mirror of
https://github.com/agentscope-ai/ReMe.git
synced 2026-11-27 23:58:47 +00:00
* Add sandboxed Python execution and home AutoBash plugin * Harden read-only shell commands and filesystem sandboxes * Group file sandbox backends in one package * Fix macOS file sandbox isolation and runtime access * Refine file sandbox limits and executor checks * Harden AutoBash policy and macOS sandbox supervision * fix(home): require ReMe release with file sandbox * refactor(home): simplify sandbox calls and redundant tests * fix(execution): bound output and clean up cancelled sandbox startup * fix(tests): mock Seatbelt platform requirements on Linux * fix(home): block Git help helpers and harden sandbox cleanup * Fix sandbox runtime links and subprocess cleanup * ci: cover Home plugin tests * test: wait for pipeline descendants to exit after cancellation * fix: align Home dependencies and preserve cleanup cancellation Require ReMe 0.4.2.1 and verify isolated Home wheel installation in package CI. Share cancellation-safe cleanup with thread calls, retain AnyIO cancellation semantics, and record Bubblewrap mount targets during argument construction. * feat(home): prepare self-evolution workspaces and benchmark inputs * fix(home): load only selected cases for debug derivation * feat(home): evaluate candidates with benchmark judges and prepare workspace docs * refactor(home): organize workflows and unify debug evaluation mode * fix(home): align Docker runtime and preserve evaluation failures * refactor(home): align evaluation summaries with dev_meta * feat(home): migrate agent, sampling and evidence inspection tooling * feat(home): add case-study agent and query evidence tracing tools - Add home_case_study job with CaseStudyAgentWrapper and a read-only sandboxed investigation step for per-case diagnostic reports - Add home_trace_query_evidence job/step to locate a query's source evidence sessions, memory checkpoints and answer/score previews - Compact evaluation summaries: record per-query failure errors, round scores to four decimals, expose scoring_enabled and observed means - Slim run manifests: drop schema_version and trusted_judge fingerprint, exclude debug/sampling_policy options, keep construction_source only for query-only replay - Simplify history index internals and update guide docs and tests * feat(home): support multi-case case-study runs with dedicated LLM and Git sandbox - Allow home_case_study to investigate up to eight ordered cases per invocation with a shared focus, one isolated agent per case, while keeping the legacy single-case selector as a deprecated alias - Configure a dedicated home_case_study LLM component instead of the shared judge backend - Wrap ReMe's OS file sandbox with a Home-specific Git runtime grant (developer directory on macOS) and argv-based child environment - Tighten case-study prompts around evidence certainty, code-tool path scoping, citation form, and unresolved-cause reporting - Extend evidence tracing and expand case-study/sandbox tests and docs * feat(home): run case studies with bounded concurrency and fix sandbox test * feat(home): guard repeated evaluations and preserve retry selections * feat(home): migrate optimization workflows and evaluation budgets * feat(home): add candidate admission gate and construction-equivalence replay Add host-side candidate gate agent that reviews committed changes before sampling, and construction-equivalence agent that compares a candidate against its nearest reusable ancestor to select query-only replay with 60% probability when construction is unchanged. Wire both into plugin.yaml application defaults, update optimizer prompt to explain the new host behaviors, extend snapshot/evaluation components with reuse support, and add focused tests. * feat(home): add structured-report agent and gate/equivalence test coverage Add StructuredReportAgent wrapper selectable via the _structured_report_model option in BoundedAgentWrapper, plus its dedicated unit tests. Extend candidate gate, construction equivalence, evaluation history, sampling, and validation budget tests, and document the new behavior in the plugin README. * feat(home): add standalone benchmark test evaluation and fix compression recovery * fix(home): preserve top-level answer failure classification * refactor(home): rename max_validations to max_evaluations * refactor(home): extract shared review_report workflow helper and bump version to 0.4.2.2 * fix(home): load runner credentials and localize dataset evaluation * fix(benchmark): propagate Home sandbox memory limits * refactor(home): consolidate Git exports and candidate validation * fix(home): clarify branch and diff tool parameter contracts * feat(home): bound case-study reports and migrate draft tools * fix(home): align benchmark report limits with plugin defaults * Fix Home evaluation recovery and cancellation boundaries * fix(home): tolerate fenced optimizer results and finalize exhausted budgets * fix(benchmark): align Docker runtime with AgentScope 2.0.11 * fix(home): unify history writes and cancellation cleanup * refactor(home): reuse structured report parsing * ci: remove redundant Home compatibility install check * fix(home): preserve literal formatting in structured reports * fix(home): continue optimization after baseline question errors * fix(sandbox): require explicit file write grants * test(home): verify host network isolation with connection probes * fix(sandbox): write to the validated canonical target * refactor(home): simplify optimizer evidence validation * feat(home): add targeted evaluation and controlled memory replay Expose optional case/question targets with bounded sampling and ignored invalid IDs. Reuse reviewed memory per case, preserve paired replay without targets, and sample every direct child of init. Restore the persistent optimizer overview and document optional targeted checks. Add regression coverage for selection, partial reuse, provenance, and frozen retries. * feat(home): preserve evaluated commits and compare validation evidence Add compact paired score and token comparisons, protected evaluated branches, and unique commit-prefix selection. Reveal comparison guidance during final selection and update optimizer tools, documentation, and regression tests. * feat(home): expand debug cases and diversify smoke questions * feat(home): prioritize reusable memory in targeted evaluation * fix(ci): limit coverage collection to repository sources * chore(home): remove legacy Meta-ReMe references * fix(home): harden evaluation and bound targeted reuse Normalize benchmark inputs while preserving standalone judge contracts. Protect initial baselines and completed evaluations, and scope targeted memory reuse to the selected sample. Simplify HoMe usage and agent documentation. * docs(home): explain how to use custom datasets * fix(home): validate explicit replay artifacts before sampling * fix(home): validate replay inputs before selection * fix(home): pin candidate admission and compact replay metadata * fix(home): address evaluation and preparation review findings Select baseline retries by attempt order and keep archive preflight outside the workspace lock. Base candidate admission on usable budgeted ancestors and validate normalized dataset IDs before publishing preparation. * docs(home): consolidate benchmark experiment guides Document the shared HoMe workflow and keep dataset setup, splits, and results in the BEAM and LongMemEval guides. * fix(home): resolve release and evaluation review findings Validate artifact IDs against the published runtime contract, cover the minimum ReMe wheel and Docker backend in CI, and keep sampling budgets and observations consistent when evaluation results are archived or restored. * test(home): seed durable validation history in optimizer fixtures * fix(ci): align Home wheel smoke test with minimum ReMe release * fix(ci): resolve unreleased minimum runtime from built wheels * fix(home): enforce full init baselines and retain replay evidence * docs: reorganize bilingual BEAM and LME benchmark guides * fix(home): bind optimizer sampling to the evaluated checkout * Validate retained replay configuration and pin explicit snapshots * docs(home): clarify final replay validation requirements --------- Co-authored-by: jinli.yl <jinli.yl@alibaba-inc.com>
830 lines
35 KiB
Python
830 lines
35 KiB
Python
"""One-time preparation through the real application lifecycle and Git objects."""
|
|
|
|
import asyncio
|
|
import copy
|
|
from threading import Event
|
|
from importlib.metadata import EntryPoint
|
|
from importlib.resources import files as resource_files
|
|
import json
|
|
from pathlib import Path
|
|
import subprocess
|
|
import shutil
|
|
|
|
import pytest
|
|
import pytest_asyncio
|
|
import yaml
|
|
from reme_home.preparation.spec import PreparationSpec
|
|
from reme_home.preparation.code import tree_fingerprint
|
|
from reme_home.preparation.transaction import OUTPUTS, TRANSACTION, recover_preparation
|
|
from reme_home.workspace import _initialization_lock
|
|
|
|
from reme import Application
|
|
|
|
|
|
def command(root, *args):
|
|
"""Git fixtures never depend on a developer's identity or hooks."""
|
|
return subprocess.check_output(
|
|
["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgSign=false", "-C", str(root), *args],
|
|
text=True,
|
|
).strip()
|
|
|
|
|
|
@pytest.fixture(name="inputs")
|
|
def preparation_inputs(tmp_path):
|
|
"""A committed tiny ReMe project plus both benchmark formats."""
|
|
repository = tmp_path / "source"
|
|
repository.mkdir()
|
|
files = {
|
|
"pyproject.toml": '[project]\nname="fixture-reme"\nversion="0.0.1"\n',
|
|
"reme/__init__.py": '"""Fixture."""\n',
|
|
"reme/config/benchmark.yaml": "jobs: {}\n",
|
|
"reme/candidate.py": "baseline = 1\n",
|
|
"plugins/beam/pyproject.toml": '[project.entry-points."reme.plugins"]\nbeam="reme_beam"\n',
|
|
"plugins/beam/src/reme_beam/plugin.yaml": "backends: {}\n",
|
|
"plugins/beam/src/reme_beam/__init__.py": "value = 1\n",
|
|
"plugins/beam/README.md": "Plugin installation instructions\n",
|
|
"plugins/beam/config/default.yaml": "enabled: true\n",
|
|
}
|
|
for name, value in files.items():
|
|
path = repository / name
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(value)
|
|
command(repository, "init", "--initial-branch=main", "--template=")
|
|
command(repository, "add", ".")
|
|
command(repository, "-c", "user.name=Fixture", "-c", "user.email=fixture@localhost", "commit", "-m", "fixture")
|
|
revision = command(repository, "rev-parse", "HEAD")
|
|
beam = tmp_path / "beam"
|
|
for case_id in ("1", "2"):
|
|
directory = beam / "chats/100K" / case_id
|
|
(directory / "probing_questions").mkdir(parents=True)
|
|
(directory / "chat.json").write_text(
|
|
json.dumps(
|
|
[
|
|
{
|
|
"batch_number": 1,
|
|
"time_anchor": "January-1-2024",
|
|
"turns": [[{"id": 1, "role": "user", "content": "hello"}]],
|
|
},
|
|
],
|
|
),
|
|
)
|
|
(directory / "probing_questions/probing_questions.json").write_text(
|
|
json.dumps(
|
|
{
|
|
"fact": [
|
|
{
|
|
"question": "What?",
|
|
"ideal_answer": "hello",
|
|
"rubric": ["says hello"],
|
|
"source_chat_ids": [1],
|
|
},
|
|
],
|
|
},
|
|
),
|
|
)
|
|
lme = tmp_path / "lme.json"
|
|
lme.write_text(
|
|
json.dumps(
|
|
[
|
|
{
|
|
"question_id": "q1",
|
|
"question": "What?",
|
|
"answer": "hello",
|
|
"question_type": "single-session-user",
|
|
"question_date": "2024/01/02 (Tue) 00:00",
|
|
"haystack_dates": ["2024/01/01 (Mon) 00:00"],
|
|
"haystack_session_ids": ["s1"],
|
|
"haystack_sessions": [[{"role": "user", "content": "hello"}]],
|
|
},
|
|
],
|
|
),
|
|
)
|
|
spec = {
|
|
"benchmark": {"name": "beam", "source": str(beam), "variant": "100K", "case_ids": ["2", "1"]},
|
|
"runtime": {"source_repo": str(repository), "source_ref": revision, "plugins": ["beam"]},
|
|
"candidate": {"paths": ["plugins/beam/src"]},
|
|
}
|
|
return spec, lme
|
|
|
|
|
|
@pytest_asyncio.fixture(name="app")
|
|
async def home_application(tmp_path, monkeypatch, request):
|
|
"""Enable Home by entry point, as an installed plugin would be enabled."""
|
|
judge_name = getattr(request, "param", "beam-judge")
|
|
for name in ("beam-judge", "lme-judge"):
|
|
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2] / name / "src"))
|
|
entries = {
|
|
name: EntryPoint(name=name, value=value, group="reme.plugins")
|
|
for name, value in [("home", "reme_home"), ("beam-judge", "judge_beam"), ("lme-judge", "judge_lme")]
|
|
}
|
|
monkeypatch.setattr("reme.plugin.manager.find_entry_points", lambda group, name: [entries[name]])
|
|
monkeypatch.setenv("LLM_API_KEY", "test")
|
|
application = Application(
|
|
workspace_dir=str(tmp_path / "workspace"),
|
|
plugins=["home", judge_name],
|
|
service={"backend": "cli"},
|
|
enable_logo=False,
|
|
log_to_console=False,
|
|
log_to_file=False,
|
|
)
|
|
await application.start()
|
|
try:
|
|
yield application
|
|
finally:
|
|
await application.close()
|
|
|
|
|
|
def snapshot(root):
|
|
"""Compare durable paths, bytes and modes, ignoring atime/mtime bookkeeping."""
|
|
return {
|
|
path.relative_to(root).as_posix(): (path.stat().st_mode, path.read_bytes() if path.is_file() else None)
|
|
for path in root.rglob("*")
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_python_job_prepares_once(app, inputs):
|
|
"""Dict input prepares selected cases and only committed source bytes."""
|
|
spec, _ = inputs
|
|
root = Path(app.config.workspace_dir)
|
|
(Path(spec["runtime"]["source_repo"]) / "plugins/beam/src/reme_beam/__init__.py").write_text("dirty = True")
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert response.success, response.answer
|
|
assert response.answer["dataset"]["case_ids"] == ["2", "1"]
|
|
assert response.answer["dataset"]["query_count"] == 2
|
|
assert response.answer["dataset"]["converter_version"] == 3
|
|
assert (root / "home/code/repo/plugins/beam/src/reme_beam/__init__.py").read_text() == "value = 1\n"
|
|
case = json.loads((root / "home/datasets/training-set/cases/000000.json").read_text())
|
|
assert case["sessions"][0]["messages"][0]["id"] == "1"
|
|
assert case["queries"][0]["metadata"]["evidence_session_ids"] == ["beam_100K_2_batch1"]
|
|
assert case["queries"][0]["groundtruth"] == {"golden_answer": "hello", "rubric": ["says hello"]}
|
|
assert "rubric" not in case["queries"][0]["metadata"]
|
|
assert not (root / "home/datasets/debug-cases/derivation.json").exists()
|
|
docs = root / "home/docs"
|
|
resources = resource_files("reme_home").joinpath("runtime_docs")
|
|
assert sorted(path.name for path in docs.iterdir()) == ["architecture-guide.md", "evaluation-artifact-guide.md"]
|
|
for path in docs.iterdir():
|
|
assert path.read_bytes() == resources.joinpath(path.name).read_bytes()
|
|
assert command(root / "home/code/repo", "branch", "--show-current") == "init"
|
|
assert not command(root / "home/code/repo", "status", "--porcelain")
|
|
before = snapshot(root)
|
|
again = await app.run_job("home_prepare", spec=spec)
|
|
assert not again.success
|
|
assert "already prepared" in str(again.answer)
|
|
assert snapshot(root) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_beam_missing_rubric_is_rejected_during_preparation(app, inputs):
|
|
"""A missing BEAM rubric fails preparation without writing workspace state."""
|
|
spec, _ = inputs
|
|
source = Path(spec["benchmark"]["source"]) / "chats/100K/2/probing_questions/probing_questions.json"
|
|
data = json.loads(source.read_text())
|
|
del data["fact"][0]["rubric"]
|
|
source.write_text(json.dumps(data))
|
|
home = Path(app.config.workspace_dir) / "home"
|
|
before = snapshot(home)
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert not response.success
|
|
assert "BEAM case 2 query fact:1 requires a non-empty list of rubric strings" in str(response.answer)
|
|
assert snapshot(home) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_beam_unsafe_query_id_fails_before_publication(app, inputs):
|
|
"""Normalized query IDs must be usable as evaluation artifact paths."""
|
|
spec, _ = inputs
|
|
source = Path(spec["benchmark"]["source"]) / "chats/100K/2/probing_questions/probing_questions.json"
|
|
data = json.loads(source.read_text())
|
|
data["invalid/group"] = data.pop("fact")
|
|
source.write_text(json.dumps(data))
|
|
home = Path(app.config.workspace_dir) / "home"
|
|
before = snapshot(home)
|
|
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
|
|
assert not response.success
|
|
assert "Invalid query_id 'invalid/group:1' in case '2'" in str(response.answer)
|
|
assert snapshot(home) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("app", ["lme-judge"], indirect=True)
|
|
@pytest.mark.parametrize("answer", [" ", None, True, False, [], {}, float("nan"), float("inf"), -float("inf")])
|
|
async def test_lme_invalid_answer_is_rejected_during_preparation(app, inputs, answer):
|
|
"""Invalid LongMemEval answers fail preparation without writing workspace state."""
|
|
spec, lme_source = inputs
|
|
data = json.loads(lme_source.read_text())
|
|
data[0]["answer"] = answer
|
|
lme_source.write_text(json.dumps(data))
|
|
spec["benchmark"] = {"name": "longmemeval", "source": str(lme_source), "all_cases": True}
|
|
home = Path(app.config.workspace_dir) / "home"
|
|
before = snapshot(home)
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert not response.success
|
|
assert "LongMemEval case q1 query q1 requires a non-empty reference answer" in str(response.answer)
|
|
assert snapshot(home) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("app", ["lme-judge"], indirect=True)
|
|
@pytest.mark.parametrize(
|
|
"invalid_id, field",
|
|
[("support/42", "case_id"), ("support 42", "case_id"), ("summary.json", "query_id"), ("result.json", "query_id")],
|
|
)
|
|
async def test_lme_invalid_id_fails_preparation_and_allows_retry(app, inputs, invalid_id, field):
|
|
"""Preparation must roll back IDs that cannot be evaluated."""
|
|
spec, source = inputs
|
|
spec["benchmark"] = {"name": "longmemeval", "source": str(source), "all_cases": True}
|
|
items = json.loads(source.read_text())
|
|
items[0]["question_id"] = invalid_id
|
|
source.write_text(json.dumps(items))
|
|
home = Path(app.config.workspace_dir) / "home"
|
|
before = snapshot(home)
|
|
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
|
|
assert not response.success
|
|
assert f"Invalid {field} {invalid_id!r}" in str(response.answer)
|
|
assert snapshot(home) == before
|
|
|
|
items[0]["question_id"] = "support-42"
|
|
source.write_text(json.dumps(items))
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert response.success, response.answer
|
|
assert response.answer["dataset"]["case_ids"] == ["support-42"]
|
|
case = json.loads((home / "datasets/training-set/cases/000000.json").read_text())
|
|
assert case["queries"][0]["query_id"] == "support-42"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("questions", [{}, {"fact": []}])
|
|
async def test_beam_case_without_questions_fails_preparation(app, inputs, questions):
|
|
"""A selected BEAM case must contain at least one probing question."""
|
|
spec, _ = inputs
|
|
source = Path(spec["benchmark"]["source"]) / "chats/100K/1/probing_questions/probing_questions.json"
|
|
source.write_text(json.dumps(questions))
|
|
home = Path(app.config.workspace_dir) / "home"
|
|
before = snapshot(home)
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert not response.success
|
|
assert "BEAM case 1 has no probing questions" in str(response.answer)
|
|
assert snapshot(home) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_beam_variant_without_cases_fails_preparation(app, inputs):
|
|
"""Selecting an empty BEAM variant fails preparation."""
|
|
spec, _ = inputs
|
|
source = spec["benchmark"]["source"]
|
|
(Path(source) / "chats/500K").mkdir()
|
|
spec["benchmark"] = {"name": "beam", "source": source, "variant": "500K", "all_cases": True}
|
|
home = Path(app.config.workspace_dir) / "home"
|
|
before = snapshot(home)
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert not response.success
|
|
assert "BEAM variant 500K has no cases" in str(response.answer)
|
|
assert snapshot(home) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_beam_import_accepts_legacy_list_of_criteria(app, inputs):
|
|
"""BEAM imports use legacy ideal-answer criteria as the rubric."""
|
|
spec, _ = inputs
|
|
source = Path(spec["benchmark"]["source"]) / "chats/100K/2/probing_questions/probing_questions.json"
|
|
data = json.loads(source.read_text())
|
|
query = data["fact"][0]
|
|
query["ideal_answer"] = query.pop("rubric")
|
|
source.write_text(json.dumps(data))
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert response.success, response.answer
|
|
case = Path(app.config.workspace_dir) / "home/datasets/training-set/cases/000000.json"
|
|
assert json.loads(case.read_text())["queries"][0]["groundtruth"] == {
|
|
"golden_answer": None,
|
|
"rubric": ["says hello"],
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"candidate_path",
|
|
["plugins/beam/src", "plugins/beam", "plugins/beam/src/reme_beam/__init__.py"],
|
|
)
|
|
async def test_complete_plugins_live_only_in_candidate(app, inputs, tmp_path, candidate_path):
|
|
"""An editable subset still yields an installable plugin and a Git baseline."""
|
|
spec, _ = inputs
|
|
spec["candidate"]["paths"] = [candidate_path, "reme/candidate.py"]
|
|
source = Path(spec["runtime"]["source_repo"])
|
|
(source / "plugins/beam/README.md").write_text("uncommitted documentation")
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert response.success, response.answer
|
|
root = Path(app.config.workspace_dir)
|
|
runtime, candidate = root / "home/code/runtime", root / "home/code/repo"
|
|
assert not (runtime / "plugins").exists()
|
|
for relative in (
|
|
"pyproject.toml",
|
|
"README.md",
|
|
"config/default.yaml",
|
|
"src/reme_beam/plugin.yaml",
|
|
"src/reme_beam/__init__.py",
|
|
):
|
|
name = f"plugins/beam/{relative}"
|
|
committed = command(source, "show", f"{spec['runtime']['source_ref']}:{name}")
|
|
assert (candidate / name).read_text().strip() == committed
|
|
assert command(candidate, "show", f"init:{name}") == committed
|
|
assert (candidate / "reme/candidate.py").read_bytes() == (runtime / "reme/candidate.py").read_bytes()
|
|
code = response.answer["code"]
|
|
assert code["candidate_paths"] == spec["candidate"]["paths"]
|
|
assert code["runtime_fingerprint"] == tree_fingerprint(runtime)
|
|
assert code["candidate_fingerprint"] == tree_fingerprint(candidate)
|
|
# Future evaluators combine these trees; plugin installation uses repo bytes.
|
|
evaluation = tmp_path / "evaluation"
|
|
shutil.copytree(runtime, evaluation)
|
|
shutil.copytree(candidate, evaluation, dirs_exist_ok=True, ignore=shutil.ignore_patterns(".git"))
|
|
for project in code["install_projects"]:
|
|
assert (evaluation / project / "pyproject.toml").is_file()
|
|
assert not command(candidate, "status", "--porcelain")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("spec_path", ["prepare.yaml", "home/prepare.yaml"])
|
|
@pytest.mark.parametrize("app", ["lme-judge"], indirect=True)
|
|
async def test_yaml_lme_core_candidate(app, inputs, spec_path):
|
|
"""Workspace YAML and core candidates use the same job as Python dictionaries."""
|
|
spec, lme = inputs
|
|
spec["benchmark"] = {"name": "longmemeval", "source": str(lme), "all_cases": True}
|
|
spec["runtime"]["plugins"] = []
|
|
spec["candidate"]["paths"] = ["reme/candidate.py"]
|
|
spec["debug"] = {"enabled": False}
|
|
root = Path(app.config.workspace_dir)
|
|
(root / spec_path).write_text(yaml.safe_dump(spec))
|
|
response = await app.run_job("home_prepare", spec_path=spec_path)
|
|
assert response.success, response.answer
|
|
domain = yaml.safe_load((root / "home/domain_spec.yaml").read_text())
|
|
assert domain["benchmark"]["case_ids"] == ["q1"]
|
|
assert not domain["benchmark"]["all_cases"]
|
|
assert (root / "home/code/repo/reme/candidate.py").is_file()
|
|
case = json.loads((root / "home/datasets/training-set/cases/000000.json").read_text())
|
|
assert case["queries"][0]["metadata"]["question_date"] == "2024/01/02 (Tue) 00:00"
|
|
assert case["sessions"][0]["messages"][0]["created_at"] == "2024-01-01T00:00:00"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_relative_inputs_still_resolve_against_outer_workspace(app, inputs):
|
|
"""Nesting outputs must not change existing source-path configuration."""
|
|
spec, _ = inputs
|
|
root = Path(app.config.workspace_dir)
|
|
shutil.copytree(spec["benchmark"]["source"], root / "inputs/beam")
|
|
shutil.copytree(spec["runtime"]["source_repo"], root / "inputs/source")
|
|
spec["benchmark"]["source"] = "inputs/beam"
|
|
spec["runtime"]["source_repo"] = "inputs/source"
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert response.success, response.answer
|
|
domain = yaml.safe_load((root / "home/domain_spec.yaml").read_text())
|
|
assert domain["benchmark"]["source"] == str(root / "inputs/beam")
|
|
assert domain["runtime"]["source_repo"] == str(root / "inputs/source")
|
|
assert not (root / "code").exists()
|
|
assert not (root / "datasets").exists()
|
|
assert not (root / "metadata/home").exists()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"failure",
|
|
[
|
|
"convert",
|
|
"code",
|
|
"docs",
|
|
"absent-outputs",
|
|
*[f"publish-{i}" for i in range(len(OUTPUTS) + 1)],
|
|
*[f"after-{i}" for i in range(len(OUTPUTS) + 1)],
|
|
],
|
|
)
|
|
async def test_failures_restore_original_workspace_and_allow_retry(app, inputs, monkeypatch, failure):
|
|
"""Failures during conversion, code export, and every publication phase roll back."""
|
|
spec, _ = inputs
|
|
root = Path(app.config.workspace_dir)
|
|
(root / "daily/keep.md").write_text("user memory")
|
|
if failure == "absent-outputs":
|
|
for relative in ("code/runtime", "code/repo", "datasets/training-set", "datasets/debug-cases", "docs"):
|
|
shutil.rmtree(root / "home" / relative)
|
|
failure = "after-5"
|
|
before = snapshot(root)
|
|
with monkeypatch.context() as patch:
|
|
if failure == "convert":
|
|
patch.setattr(
|
|
"reme_home.preparation.component.prepare_dataset",
|
|
lambda *a, **kw: (_ for _ in ()).throw(OSError("test")),
|
|
)
|
|
elif failure == "code":
|
|
patch.setattr(
|
|
"reme_home.preparation.component.prepare_code",
|
|
lambda *a, **kw: (_ for _ in ()).throw(OSError("test")),
|
|
)
|
|
elif failure == "docs":
|
|
original_read = Path.read_bytes
|
|
|
|
def read_bytes(path):
|
|
if path.name == "evaluation-artifact-guide.md":
|
|
raise FileNotFoundError("missing packaged document")
|
|
return original_read(path)
|
|
|
|
patch.setattr(Path, "read_bytes", read_bytes)
|
|
else:
|
|
original = __import__("os").replace
|
|
|
|
def replace(source, destination):
|
|
if Path(source).name == failure.replace("publish-", "output-"):
|
|
raise OSError("test publication failure")
|
|
result = original(source, destination)
|
|
if failure.startswith("after-") and Path(source).name == failure.replace("after-", "output-"):
|
|
raise OSError("test failure after rename")
|
|
return result
|
|
|
|
patch.setattr("reme_home.preparation.transaction.os.replace", replace)
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert not response.success
|
|
assert snapshot(root) == before
|
|
assert (await app.run_job("home_prepare", spec=spec)).success
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_preparation_preserves_existing_docs(app, inputs):
|
|
"""Existing user documentation is a conflict, never overwritten or removed."""
|
|
root = Path(app.config.workspace_dir)
|
|
(root / "home/docs/architecture-guide.md").write_text("user-owned documentation")
|
|
before = snapshot(root)
|
|
response = await app.run_job("home_prepare", spec=inputs[0])
|
|
assert not response.success
|
|
assert "not empty" in str(response.answer)
|
|
assert snapshot(root) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_legacy_preparation_journal_recovery_preserves_docs(app):
|
|
"""Version 1 recovery uses the original output indices and leaves docs alone."""
|
|
root = Path(app.config.workspace_dir) / "home"
|
|
state = root / "metadata"
|
|
(root / "docs/keep.md").write_text("existing documentation")
|
|
before = snapshot(root)
|
|
transaction = state / TRANSACTION
|
|
transaction.mkdir()
|
|
(transaction / "journal.json").write_text(
|
|
json.dumps({"schema_version": 1, "existed": [True, True, True, True, False, False]}),
|
|
)
|
|
(root / "code/runtime").rename(transaction / "backup-0")
|
|
(root / "code/runtime").mkdir()
|
|
(root / "code/runtime/partial.py").write_text("partial runtime")
|
|
(root / "code/repo").rename(transaction / "backup-1")
|
|
(transaction / "output-1").mkdir()
|
|
recover_preparation(root, state)
|
|
assert snapshot(root) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_interrupted_publication_recovers_at_startup(app, inputs, monkeypatch):
|
|
"""A durable journal survives process interruption and is recovered on startup."""
|
|
spec, _ = inputs
|
|
root = Path(app.config.workspace_dir)
|
|
before = snapshot(root)
|
|
preparation = app.context.components["home.preparation"]["default"]
|
|
with monkeypatch.context() as patch:
|
|
original = __import__("os").replace
|
|
|
|
def replace(source, destination):
|
|
if Path(source).name == "output-3":
|
|
raise RuntimeError("simulated crash")
|
|
return original(source, destination)
|
|
|
|
patch.setattr("reme_home.preparation.transaction.os.replace", replace)
|
|
patch.setattr("reme_home.preparation.component.rollback", lambda *args: None)
|
|
with pytest.raises(RuntimeError, match="simulated crash"):
|
|
await preparation.prepare(spec=spec)
|
|
workspace = app.context.components["home.workspace"]["default"]
|
|
await workspace.close()
|
|
await workspace.start()
|
|
assert snapshot(root) == before
|
|
assert (await app.run_job("home_prepare", spec=spec)).success
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_success_survives_cleanup_failure_and_restart(app, inputs, monkeypatch):
|
|
"""Committed completion is retained when cleanup was interrupted."""
|
|
spec, _ = inputs
|
|
root = Path(app.config.workspace_dir)
|
|
original = __import__("shutil").rmtree
|
|
with monkeypatch.context() as patch:
|
|
|
|
def remove(path, *args, **kwargs):
|
|
if Path(path).name == TRANSACTION:
|
|
raise OSError("cleanup")
|
|
return original(path, *args, **kwargs)
|
|
|
|
patch.setattr("reme_home.preparation.component.shutil.rmtree", remove)
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert response.success
|
|
assert (root / "home/metadata" / TRANSACTION).exists()
|
|
workspace = app.context.components["home.workspace"]["default"]
|
|
await workspace.close()
|
|
await workspace.start()
|
|
assert not (root / "home/metadata" / TRANSACTION).exists()
|
|
assert not (await app.run_job("home_prepare", spec=spec)).success
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_upgrade_restores_renamed_guide_and_preserves_prepared_workspace(app, inputs):
|
|
"""Restart restores the missing guide and preserves existing workspace files."""
|
|
spec, _ = inputs
|
|
assert (await app.run_job("home_prepare", spec=spec)).success
|
|
home = Path(app.config.workspace_dir) / "home"
|
|
guide = home / "docs/evaluation-artifact-guide.md"
|
|
legacy = home / "docs/validation-artifact-guide.md"
|
|
guide.rename(legacy)
|
|
legacy.write_text("Previous guide with local edits\n", encoding="utf-8")
|
|
summary = home / "evaluations/init/initial/1/summary.json"
|
|
summary.parent.mkdir(parents=True)
|
|
summary.write_text('{"mean_query_score": 0.5}\n', encoding="utf-8")
|
|
before = snapshot(home)
|
|
|
|
workspace = app.context.components["home.workspace"]["default"]
|
|
await workspace.close()
|
|
await workspace.start()
|
|
expected = resource_files("reme_home").joinpath("runtime_docs", guide.name).read_bytes()
|
|
assert guide.read_bytes() == expected
|
|
restored = snapshot(home)
|
|
restored.pop("docs/evaluation-artifact-guide.md")
|
|
assert restored == before
|
|
assert not (await app.run_job("home_prepare", spec=spec)).success
|
|
|
|
guide.write_text("Local edits to the new guide\n", encoding="utf-8")
|
|
after = snapshot(home)
|
|
await workspace.close()
|
|
await workspace.start()
|
|
assert snapshot(home) == after
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_conflicts_and_lock_preserve_user_content(app, inputs):
|
|
"""Competing jobs and user-owned output directories cannot be overwritten."""
|
|
spec, _ = inputs
|
|
root = Path(app.config.workspace_dir)
|
|
before = snapshot(root)
|
|
with _initialization_lock(root / "home/metadata/workspace.lock"):
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert not response.success
|
|
assert snapshot(root) == before
|
|
(root / "home/code/repo/keep.py").write_text("keep")
|
|
before = snapshot(root)
|
|
assert not (await app.run_job("home_prepare", spec=spec)).success
|
|
assert snapshot(root) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"kwargs",
|
|
[
|
|
{},
|
|
{"spec": {}, "spec_path": "prepare.yaml"},
|
|
{"spec_path": "../outside.yaml"},
|
|
{"spec_path": "~/prepare.yaml"},
|
|
{"spec": {}, "_allowed_paths": []},
|
|
],
|
|
)
|
|
async def test_bad_job_inputs_do_not_mutate_workspace(app, kwargs):
|
|
"""Path escape and restricted invocation fail closed."""
|
|
root = Path(app.config.workspace_dir)
|
|
before = snapshot(root)
|
|
assert not (await app.run_job("home_prepare", **kwargs)).success
|
|
assert snapshot(root) == before
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"change",
|
|
[
|
|
{"case_ids": []},
|
|
{"case_ids": ["1", "1"]},
|
|
{"case_ids": [1]},
|
|
{"case_ids": None},
|
|
{"all_cases": True},
|
|
{"variant": "bad"},
|
|
{"evidence_source": "annotations.jsonl"},
|
|
],
|
|
)
|
|
def test_strict_case_selection(inputs, change):
|
|
"""Do not silently select everything or accept misspelled dataset options."""
|
|
spec, _ = inputs
|
|
spec = copy.deepcopy(spec)
|
|
spec["benchmark"].update(change)
|
|
with pytest.raises(ValueError):
|
|
PreparationSpec.model_validate(spec)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("mutation", ["unknown-case", "unknown-plugin", "bad-ref", "bad-candidate", "symlink"])
|
|
async def test_invalid_sources_roll_back(app, inputs, mutation):
|
|
"""Input and revision failures leave no partially prepared dataset."""
|
|
spec, _ = inputs
|
|
if mutation == "unknown-case":
|
|
spec["benchmark"]["case_ids"] = ["missing"]
|
|
elif mutation == "unknown-plugin":
|
|
spec["runtime"]["plugins"] = ["missing"]
|
|
elif mutation == "bad-ref":
|
|
spec["runtime"]["source_ref"] = "--bad-ref"
|
|
elif mutation == "bad-candidate":
|
|
spec["candidate"]["paths"] = ["../outside"]
|
|
else:
|
|
repository = Path(spec["runtime"]["source_repo"])
|
|
(repository / "reme/link").symlink_to("__init__.py")
|
|
command(repository, "add", ".")
|
|
command(repository, "-c", "user.name=Fixture", "-c", "user.email=fixture@localhost", "commit", "-m", "link")
|
|
spec["runtime"]["source_ref"] = "HEAD"
|
|
root = Path(app.config.workspace_dir)
|
|
before = snapshot(root)
|
|
assert not (await app.run_job("home_prepare", spec=spec)).success
|
|
assert snapshot(root) == before
|
|
|
|
|
|
def test_bad_recovery_journal_does_not_remove_outside_paths(tmp_path):
|
|
"""Recovery accepts no path names from disk."""
|
|
state = tmp_path / "home/metadata"
|
|
transaction = state / TRANSACTION
|
|
transaction.mkdir(parents=True)
|
|
(transaction / "journal.json").write_text('{"existed": [], "paths": ["../../outside"]}')
|
|
with pytest.raises(ValueError):
|
|
recover_preparation(tmp_path / "home", state)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("cancellations", [1, 3])
|
|
@pytest.mark.parametrize("fail_stage", [False, True])
|
|
async def test_cancellation_waits_for_rollback(app, inputs, monkeypatch, cancellations, fail_stage):
|
|
"""The event loop stays available, and cancellation waits for the worker to restore state."""
|
|
spec, _ = inputs
|
|
root = Path(app.config.workspace_dir)
|
|
before = snapshot(root)
|
|
component = app.context.components["home.preparation"]["default"]
|
|
stage = component._stage # pylint: disable=protected-access
|
|
entered = Event()
|
|
proceed = Event()
|
|
|
|
def blocked(*args):
|
|
entered.set()
|
|
if not proceed.wait(10):
|
|
raise RuntimeError("test worker timed out")
|
|
result = stage(*args)
|
|
if fail_stage:
|
|
raise OSError("injected stage failure after cancellation")
|
|
return result
|
|
|
|
monkeypatch.setattr(component, "_stage", blocked)
|
|
task = asyncio.create_task(app.run_job("home_prepare", spec=spec))
|
|
try:
|
|
assert await asyncio.to_thread(entered.wait, 10)
|
|
for index in range(cancellations):
|
|
task.cancel(f"cancellation-{index}")
|
|
await asyncio.sleep(0)
|
|
assert not task.done()
|
|
assert component._pending # pylint: disable=protected-access
|
|
proceed.set()
|
|
with pytest.raises(asyncio.CancelledError, match="cancellation-0"):
|
|
await task
|
|
finally:
|
|
proceed.set()
|
|
await asyncio.gather(task, return_exceptions=True)
|
|
assert snapshot(root) == before
|
|
assert not component._pending # pylint: disable=protected-access
|
|
monkeypatch.setattr(component, "_stage", stage)
|
|
assert (await app.run_job("home_prepare", spec=spec)).success
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("cancellations", [1, 3])
|
|
async def test_cancellation_after_preparation_commit_retains_success(app, inputs, monkeypatch, cancellations):
|
|
"""A stop request after the last published target must not undo a completed transaction."""
|
|
from reme_home.preparation import component as preparation
|
|
|
|
entered, release = Event(), Event()
|
|
original = preparation.publish
|
|
|
|
def committed(*args):
|
|
original(*args)
|
|
entered.set()
|
|
assert release.wait(5)
|
|
|
|
monkeypatch.setattr(preparation, "publish", committed)
|
|
task = asyncio.create_task(app.run_job("home_prepare", spec=inputs[0]))
|
|
try:
|
|
assert await asyncio.to_thread(entered.wait, 5)
|
|
for index in range(cancellations):
|
|
task.cancel(f"cancellation-{index}")
|
|
await asyncio.sleep(0)
|
|
assert not task.done()
|
|
release.set()
|
|
response = await task
|
|
assert response.success, response.answer
|
|
home = Path(app.config.workspace_dir) / "home"
|
|
assert json.loads((home / "metadata/preparation.json").read_text())["preparation_id"]
|
|
assert not (home / "metadata" / TRANSACTION).exists()
|
|
assert not app.context.components["home.preparation"]["default"]._pending # pylint: disable=protected-access
|
|
finally:
|
|
release.set()
|
|
await asyncio.gather(task, return_exceptions=True)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("app", ["lme-judge"], indirect=True)
|
|
async def test_duplicate_lme_ids_fail_without_mutation(app, inputs):
|
|
"""Upstream duplicate IDs cannot silently replace selected cases."""
|
|
spec, lme = inputs
|
|
items = json.loads(lme.read_text())
|
|
lme.write_text(json.dumps(items + items))
|
|
spec["benchmark"] = {"name": "longmemeval", "source": str(lme), "all_cases": True}
|
|
root = Path(app.config.workspace_dir)
|
|
before = snapshot(root)
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert not response.success
|
|
assert "Duplicate LongMemEval" in str(response.answer)
|
|
assert snapshot(root) == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("app", ["lme-judge"], indirect=True)
|
|
async def test_lme_evidence_and_time_cutoff_debug_cases(app, inputs):
|
|
"""Evidence survives conversion and debug data obeys question-time cutoffs."""
|
|
spec, lme = inputs
|
|
items = json.loads(lme.read_text())
|
|
item = items[0]
|
|
item["haystack_dates"].append("2024/01/03 (Wed) 00:00")
|
|
item["haystack_session_ids"].append("future")
|
|
item["haystack_sessions"].append([{"role": "user", "content": "future information"}])
|
|
lme.write_text(json.dumps(items))
|
|
evidence = lme.with_suffix(".jsonl")
|
|
evidence.write_text(json.dumps({"case_id": "q1", "evidence_sessions": ["s1"], "is_certain": True}) + "\n")
|
|
spec["benchmark"] = {
|
|
"name": "longmemeval",
|
|
"source": str(lme),
|
|
"case_ids": ["q1"],
|
|
"evidence_source": str(evidence),
|
|
}
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
assert response.success, response.answer
|
|
root = Path(app.config.workspace_dir)
|
|
case = json.loads((root / "home/datasets/training-set/cases/000000.json").read_text())
|
|
assert case["queries"][0]["metadata"]["evidence_session_ids"] == ["s1"]
|
|
assert case["construction_cutoff"] == case["queries"][0]["query_time"] == "2024-01-02T00:00:00"
|
|
assert [session["session_id"] for session in case["sessions"]] == ["s1", "future"]
|
|
debug = json.loads((root / "home/datasets/debug-cases/cases/000000.json").read_text())
|
|
assert [session["session_id"] for session in debug["sessions"]] == ["s1"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("app", ["lme-judge"], indirect=True)
|
|
async def test_lme_preparation_derives_debug_cases_for_long_ids(app, inputs):
|
|
"""The default debug dataset preserves provenance for every valid training ID."""
|
|
spec, source = inputs
|
|
item = json.loads(source.read_text())[0]
|
|
case_ids = ["x" * 122, "x" * 123, "x" * 128, "long-1"]
|
|
source.write_text(json.dumps([{**item, "question_id": case_id} for case_id in case_ids]))
|
|
spec["benchmark"] = {"name": "longmemeval", "source": str(source), "all_cases": True}
|
|
|
|
response = await app.run_job("home_prepare", spec=spec)
|
|
|
|
assert response.success, response.answer
|
|
assert response.answer["dataset"]["case_ids"] == case_ids
|
|
folder = Path(app.config.workspace_dir) / "home/datasets/debug-cases/cases"
|
|
cases = [json.loads(path.read_text()) for path in sorted(folder.glob("*.json"))]
|
|
assert [case["metadata"]["source_case_id"] for case in cases] == case_ids
|
|
debug_ids = [case["case_id"] for case in cases]
|
|
assert len(set(debug_ids)) == 4
|
|
assert all(len(case_id) <= 128 for case_id in debug_ids)
|
|
assert debug_ids[0] == f"debug-{case_ids[0]}"
|
|
assert debug_ids[-1] == "debug-long-1"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_concurrent_preparation_rejects_second_writer(app, inputs, monkeypatch):
|
|
"""Two active Jobs share the process lock rather than racing to publish."""
|
|
spec, _ = inputs
|
|
component = app.context.components["home.preparation"]["default"]
|
|
stage = component._stage # pylint: disable=protected-access
|
|
entered = Event()
|
|
proceed = Event()
|
|
|
|
def blocked(*args):
|
|
entered.set()
|
|
if not proceed.wait(10):
|
|
raise RuntimeError("test worker timed out")
|
|
return stage(*args)
|
|
|
|
monkeypatch.setattr(component, "_stage", blocked)
|
|
first = asyncio.create_task(app.run_job("home_prepare", spec=spec))
|
|
try:
|
|
assert await asyncio.to_thread(entered.wait, 10)
|
|
second = await app.run_job("home_prepare", spec=spec)
|
|
assert not second.success
|
|
assert "already in progress" in str(second.answer)
|
|
proceed.set()
|
|
assert (await first).success
|
|
finally:
|
|
proceed.set()
|
|
await asyncio.gather(first, return_exceptions=True)
|