ReMe/plugins/home/tests/test_evaluation_repetition.py
xyf2020 b3a5eac4a8
fix(home): continue optimization after baseline question errors (#751)
* 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>
2026-11-24 10:29:25 +08:00

506 lines
22 KiB
Python

"""Tree-based repetition checks through real Jobs with fake Docker/model boundaries."""
# pylint: disable=missing-function-docstring,redefined-outer-name,unused-argument
# pylint: disable=protected-access
import asyncio
import json
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
from agentscope.state import AgentState
from reme_home.agent import optimizer
from reme_home.evaluation import repetition
from reme_home.evaluation.artifacts import write_json
from reme_home.evaluation.repetition import retryable_result
from test_evaluation import ( # noqa: F401 # pylint: disable=unused-import
FakeFactory,
commit_candidate,
command,
home_application,
preparation_inputs,
prepared_home,
rebuild_review,
)
def artifacts(home):
return {path.relative_to(home): path.read_bytes() for path in home.rglob("*") if path.is_file()}
@pytest.mark.asyncio
@pytest.mark.parametrize("change", ["init_to_candidate", "candidate_to_init", "branch", "commit"])
async def test_optimizer_rejects_checkout_changes_before_admission(app, prepared, monkeypatch, change):
from reme_home.agent import candidate_gate
repo = prepared / "code/repo"
if change != "init_to_candidate":
commit_candidate(prepared)
expected = optimizer.evaluation_checkout(prepared)
review = AsyncMock(side_effect=AssertionError("Stale requests must not invoke an admission model"))
monkeypatch.setattr(candidate_gate, "review_candidate", review)
evaluate_job = app.context.jobs["home_evaluate"]
class SwitchingJob:
"""Switch after the optimizer binds its request, before the real Job starts."""
enabled = is_started = True
async def __call__(self, **kwargs):
assert kwargs["expected_commit"] == expected["expected_commit"]
assert kwargs["expected_branch"] == expected["expected_branch"]
assert kwargs["sampling"] == expected["sampling"]
if change in {"init_to_candidate", "commit"}:
commit_candidate(prepared)
else:
if change == "candidate_to_init":
command(repo, "switch", "init")
else:
command(repo, "switch", "-c", "other")
return await evaluate_job(**kwargs)
wrapper = SimpleNamespace(app_context=SimpleNamespace(jobs={"home_evaluate": SwitchingJob()}))
tool = optimizer.evaluation_tool(
wrapper,
{"sampling_policy": {"max_cases": 1}},
home=prepared,
)
response = await tool._func(_agent_state=AgentState())
assert not response["success"]
assert "Checkout changed before evaluation" in str(response["answer"])
review.assert_not_called()
assert not FakeFactory.instances
assert not list((prepared / "evaluations").glob("*/*/*/manifest.json"))
@pytest.mark.asyncio
async def test_bound_checkout_is_rechecked_when_snapshot_is_fixed(app, prepared, monkeypatch):
from reme_home.evaluation import component
expected = optimizer.evaluation_checkout(prepared)
original = component.snapshot_code
def switch_before_snapshot(*args, **kwargs):
# The early check passed; simulate a switch before the snapshot lock was acquired.
commit_candidate(prepared)
return original(*args, **kwargs)
monkeypatch.setattr(component, "snapshot_code", switch_before_snapshot)
response = await app.run_job("home_evaluate", **expected, max_evaluations=10)
assert not response.success
assert "Checkout changed before evaluation" in str(response.answer)
assert not FakeFactory.instances
@pytest.mark.parametrize("binding", [{"expected_commit": "abc"}, {"expected_branch": "init"}])
def test_checkout_binding_requires_both_commit_and_branch(binding):
from reme_home.evaluation.inputs import EvaluationSpec
with pytest.raises(ValueError, match="must be supplied together"):
EvaluationSpec(**binding)
@pytest.mark.asyncio
@pytest.mark.usefixtures("rebuild_review")
async def test_bound_checkout_preserves_init_full_and_candidate_sampled(app, prepared):
initial = optimizer.evaluation_checkout(prepared)
assert not initial["sampling"] and initial["expected_branch"] == "init"
response = await app.run_job("home_evaluate", **initial, sampling_policy={"max_cases": 1})
assert response.success, response.answer
assert len(json.loads((Path(response.answer["result_dir"]) / "manifest.json").read_text())["case_ids"]) == 2
commit_candidate(prepared)
candidate = optimizer.evaluation_checkout(prepared)
assert candidate["sampling"]
response = await app.run_job("home_evaluate", **candidate, sampling_policy={"max_cases": 1})
assert response.success, response.answer
assert len(json.loads((Path(response.answer["result_dir"]) / "manifest.json").read_text())["case_ids"]) == 1
@pytest.mark.asyncio
@pytest.mark.parametrize("direct", [False, True])
@pytest.mark.parametrize("alias", [False, True])
@pytest.mark.parametrize(
"options",
[
{"sampling": True},
{"case_ids": ["1"]},
{"case_ids": ["1"], "query_ids": {"1": ["fact:1"]}},
{"reuse_construction_from": "evaluations/init/old/1"},
],
)
async def test_init_rejects_partial_formal_evaluation_before_sandbox(app, prepared, options, direct, alias):
if alias:
response = await app.run_job("home_create_candidate_branch", branch_name="initial-alias")
assert response.success, response.answer
before = len(FakeFactory.instances)
if direct:
with pytest.raises(ValueError, match="init requires all training cases and queries"):
await app.context.components["home.evaluation"]["default"].evaluate(**options)
else:
response = await app.run_job("home_evaluate", **options)
assert not response.success
assert "init requires all training cases and queries" in str(response.answer)
assert len(FakeFactory.instances) == before
assert not list((prepared / "evaluations").glob("*/*/*/manifest.json"))
@pytest.mark.asyncio
@pytest.mark.parametrize("infra_error", [False, True])
async def test_legacy_init_subset_cannot_block_or_narrow_full_baseline(app, prepared, infra_error):
response = await app.run_job("home_evaluate")
assert response.success, response.answer
run = Path(response.answer["result_dir"])
manifest = json.loads((run / "manifest.json").read_text())
full_queries = manifest["query_ids"]
manifest["case_ids"] = ["1"]
manifest["query_ids"] = {"1": full_queries["1"]}
write_json(run / "manifest.json", manifest)
if infra_error:
summary = json.loads((run / "summary.json").read_text())
summary["case_status_counts"]["infra_error"] = 1
write_json(run / "summary.json", summary)
response = await app.run_job("home_evaluate")
assert response.success, response.answer
new_manifest = json.loads((Path(response.answer["result_dir"]) / "manifest.json").read_text())
assert new_manifest["query_ids"] == full_queries
assert new_manifest["case_ids"] == list(full_queries)
@pytest.mark.asyncio
async def test_init_rejects_partial_queries_even_when_all_cases_are_selected(app, inputs):
source = Path(inputs[0]["benchmark"]["source"])
for path in source.glob("chats/*/*/probing_questions/probing_questions.json"):
raw = json.loads(path.read_text())
raw["fact"].append(dict(raw["fact"][0], question="second question", rubric=["says hello"]))
path.write_text(json.dumps(raw))
assert (await app.run_job("home_prepare", spec=inputs[0])).success
response = await app.run_job("home_evaluate", query_ids={"1": ["fact:1"]})
assert not response.success
assert "init requires all training cases and queries" in str(response.answer)
def test_tree_lookup_is_cached_without_skipping_attempts(tmp_path, monkeypatch):
repo = tmp_path / "code/repo"
repo.mkdir(parents=True)
runs = {
commit: [tmp_path / f"evaluations/{commit}/{commit}/{attempt}" for attempt in (1, 2)]
for commit in ("current", "other")
}
for commit, attempts in runs.items():
for run in attempts:
write_json(run / "manifest.json", {"commit_sha": commit})
lookups = []
def git_tree(repository, *args):
assert repository == repo and args[:3] == ("rev-parse", "--verify", "--end-of-options")
lookups.append(args[-1])
return args[-1]
monkeypatch.setattr(repetition, "git", git_tree)
assert repetition.previous_candidate_result(tmp_path, "current") == runs["current"][1]
assert lookups == ["current^{tree}", "other^{tree}"]
completed = runs["current"][0]
write_json(completed / "summary.json", {"cases": {"1": {"status": "completed"}}})
with pytest.raises(repetition.UnchangedCandidateError) as error:
repetition.previous_candidate_result(tmp_path, "current")
assert error.value.path == completed
def test_recovery_order_uses_attempt_ids_within_branch_and_start_time_across_branches(tmp_path, monkeypatch):
(tmp_path / "code/repo").mkdir(parents=True)
monkeypatch.setattr(repetition, "git", lambda _repo, *args: args[-1])
def attempt(branch, number, started_at):
run = tmp_path / f"evaluations/{branch}/current/{number}"
write_json(run / "manifest.json", {"commit_sha": "current", "started_at": started_at})
return run
attempt("z", 9, "2026-11-20T00:00:00+00:00")
tenth = attempt("z", 10, "2026-11-20T00:00:00+00:00")
assert repetition.previous_candidate_result(tmp_path, "current") == tenth
other_branch = attempt("a", 1, "2026-11-20T01:00:00+00:00")
assert repetition.previous_candidate_result(tmp_path, "current") == other_branch
@pytest.mark.asyncio
@pytest.mark.parametrize("options", [{}, {"sampling": True}, {"record_history": False}, {"case_ids": ["1"]}])
async def test_completed_tree_rejected_before_pool_allocation_or_history_changes(app, prepared, options):
commit_candidate(prepared)
baseline = await app.run_job("home_evaluate")
assert baseline.success
before = artifacts(prepared)
repeat = await app.run_job("home_evaluate", **options)
assert not repeat.success and "already been evaluated" in str(repeat.answer)
assert repeat.answer == {
"status": "rejected",
"error_code": "UNCHANGED_CANDIDATE",
"error": repeat.answer["error"],
"result_dir": baseline.answer["result_dir"],
}
assert "already been evaluated" in repeat.answer["error"]
assert repeat.metadata["result_dir"] == baseline.answer["result_dir"]
assert "reme.job_error" not in repeat.metadata
assert len(FakeFactory.instances) == 1 and artifacts(prepared) == before
@pytest.mark.asyncio
@pytest.mark.parametrize("change", ["empty_commit", "branch", "code"])
async def test_tree_identity_across_commits_and_branches(app, prepared, change):
baseline = await app.run_job("home_evaluate", record_history=False)
assert baseline.success
repo = prepared / "code/repo"
assert (await app.run_job("home_create_candidate_branch", branch_name="next")).success
if change == "code":
path = repo / "plugins/beam/src/reme_beam/__init__.py"
path.write_text("value = 2\n")
command(repo, "add", ".")
if change != "branch":
command(
repo,
"-c",
"user.name=Fixture",
"-c",
"user.email=test@localhost",
"commit",
"--allow-empty",
"-m",
change,
)
response = await app.run_job("home_evaluate")
assert response.success is (change == "code")
assert len(FakeFactory.instances) == (2 if change == "code" else 1)
@pytest.mark.asyncio
@pytest.mark.parametrize("fail_fast", [False, True])
async def test_candidate_failures_block_retry_including_partial_results(app, prepared, monkeypatch, fail_fast):
monkeypatch.setattr(FakeFactory, "fail_build", "2")
failed = await app.run_job("home_evaluate", fail_fast=fail_fast, concurrency=1)
assert failed.success is (not fail_fast)
before = artifacts(prepared)
retry = await app.run_job("home_evaluate")
assert not retry.success and "already been evaluated" in str(retry.answer)
assert len(FakeFactory.instances) == 1 and artifacts(prepared) == before
@pytest.mark.asyncio
@pytest.mark.parametrize("fail_fast", [False, True])
async def test_infrastructure_retry_gets_new_id_and_retains_prior_artifacts(app, prepared, monkeypatch, fail_fast):
monkeypatch.setattr(FakeFactory, "bad_export", True)
failed = await app.run_job("home_evaluate", fail_fast=fail_fast)
assert not failed.success
manifests = list((prepared / "evaluations").glob("*/*/*/manifest.json"))
run = manifests[0].parent
before = artifacts(run)
monkeypatch.setattr(FakeFactory, "bad_export", False)
recovered = await app.run_job("home_evaluate")
assert recovered.success, recovered.answer
assert Path(recovered.answer["result_dir"]).name == "2"
assert artifacts(run) == before and len(FakeFactory.instances) == 2
repeat = await app.run_job("home_evaluate")
assert not repeat.success and len(FakeFactory.instances) == 2
@pytest.mark.asyncio
async def test_interrupted_run_retries_but_empty_commit_cannot_relabel_failure(app, prepared, monkeypatch):
original = FakeFactory.create_cases
async def fail(*args, **kwargs):
raise ConnectionError("Docker unavailable before startup")
monkeypatch.setattr(FakeFactory, "create_cases", fail)
assert not (await app.run_job("home_evaluate")).success
repo = prepared / "code/repo"
assert (await app.run_job("home_create_candidate_branch", branch_name="retry")).success
command(
repo,
"-c",
"user.name=Fixture",
"-c",
"user.email=test@localhost",
"commit",
"--allow-empty",
"-m",
"empty",
)
rejected = await app.run_job("home_evaluate")
assert not rejected.success and "already been evaluated" in str(rejected.answer)
command(repo, "reset", "--hard", "HEAD~1")
monkeypatch.setattr(FakeFactory, "create_cases", original)
recovered = await app.run_job("home_evaluate")
assert recovered.success, recovered.answer
# Switching branches does not overwrite the first attempt.
assert len(list((prepared / "evaluations").glob("*/*/*/manifest.json"))) == 2
@pytest.mark.asyncio
async def test_debug_can_repeat_and_does_not_block_scored_baseline(app, prepared):
assert (await app.run_job("home_evaluate", debug=True)).success
assert (await app.run_job("home_evaluate", debug=True)).success
assert (await app.run_job("home_evaluate")).success
assert (await app.run_job("home_evaluate", debug=True)).success
@pytest.mark.asyncio
async def test_cancelled_evaluation_retries_after_pool_cleanup(app, prepared, monkeypatch):
monkeypatch.setattr(FakeFactory, "block", asyncio.Event())
task = asyncio.create_task(app.run_job("home_evaluate", concurrency=1))
try:
async with asyncio.timeout(5):
while not FakeFactory.instances:
await asyncio.sleep(0.01)
await FakeFactory.instances[0].entered.wait()
finally:
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert all(worker.closed for worker in FakeFactory.instances[0].workers)
run = next((prepared / "evaluations").glob("*/*/*/manifest.json")).parent
before = artifacts(run)
monkeypatch.setattr(FakeFactory, "block", None)
recovered = await app.run_job("home_evaluate")
assert recovered.success and Path(recovered.answer["result_dir"]).name == "2"
assert artifacts(run) == before
@pytest.mark.asyncio
async def test_replay_and_corrupt_sampling_cache_cannot_bypass_guard(app, prepared):
commit_candidate(prepared)
baseline = await app.run_job("home_evaluate")
assert baseline.success
(prepared / "sampling/state.json").write_text("invalid cache")
for options in ({"sampling": True}, {"reuse_construction_from": baseline.answer["result_dir"]}):
repeat = await app.run_job("home_evaluate", **options)
assert not repeat.success and "already been evaluated" in str(repeat.answer)
assert len(FakeFactory.instances) == 1
@pytest.mark.asyncio
@pytest.mark.parametrize("record_history", [True, False])
@pytest.mark.parametrize("retry_sampling", [True, False])
async def test_sampled_recovery_preserves_cases_queries_and_order(
app,
inputs,
monkeypatch,
record_history,
retry_sampling,
):
source = Path(inputs[0]["benchmark"]["source"])
for path in source.glob("chats/*/*/probing_questions/probing_questions.json"):
raw = json.loads(path.read_text())
raw["fact"] = [dict(raw["fact"][0], question=f"question {i}", rubric=["says hello"]) for i in range(4)]
path.write_text(json.dumps(raw))
assert (await app.run_job("home_prepare", spec=inputs[0])).success
commit_candidate(Path(app.config.workspace_dir) / "home")
monkeypatch.setattr("reme_home.evaluation.component.DockerReMeSandboxFactory", FakeFactory)
FakeFactory.instances = []
monkeypatch.setattr(
app.context.components["agent_wrapper"]["judge"],
"reply",
AsyncMock(return_value={"result": '{"score": 0.5}', "status": "completed", "error": None}),
)
monkeypatch.setattr("reme_home.sampling.time.time_ns", lambda: 1)
monkeypatch.setattr(FakeFactory, "bad_export", True)
first = await app.run_job(
"home_evaluate",
sampling=True,
sampling_policy={"max_cases": 1, "max_queries": 2},
record_history=record_history,
)
assert not first.success
run = Path(first.answer["result_dir"])
original = artifacts(run)
old = json.loads((run / "manifest.json").read_text())
assert len(old["case_ids"]) == 1 and len(next(iter(old["query_ids"].values()))) == 2
home = Path(app.config.workspace_dir) / "home"
state_path = home / "sampling/state.json"
state_before = state_path.read_bytes() if state_path.exists() else None
def no_draw(*args, **kwargs):
raise AssertionError("Recovery must not redraw or consult sampling observations")
monkeypatch.setattr("reme_home.evaluation.component.create_sampling_plan", no_draw)
monkeypatch.setattr(app.context.components["home.evaluation_history"]["default"], "sampling_state", no_draw)
monkeypatch.setattr("reme_home.sampling.time.time_ns", lambda: 2)
monkeypatch.setattr(FakeFactory, "bad_export", False)
options = {} if retry_sampling else {"case_ids": list({"1", "2"} - set(old["case_ids"]))}
retry = await app.run_job(
"home_evaluate",
sampling=retry_sampling,
sampling_policy={"max_cases": 2, "max_queries": 1},
record_history=record_history,
**options,
)
assert retry.success, retry.answer
new_run = Path(retry.answer["result_dir"])
new = json.loads((new_run / "manifest.json").read_text())
assert new_run.name == "2" and artifacts(run) == original
assert new["case_ids"] == old["case_ids"] and new["query_ids"] == old["query_ids"]
worker = FakeFactory.instances[-1].workers[0]
assert [query.query_id for query in worker.queries] == old["query_ids"][worker.case_id]
plan = json.loads((home / new["sampling"]["plan_path"]).read_text()) if record_history else new["selection_plan"]
assert plan["case_ids"] == old["case_ids"] and plan["query_ids"] == old["query_ids"]
assert plan["mode"] == "explicit" and plan["recovery_from"] == run.relative_to(home).as_posix()
assert "seed" not in plan
if not record_history:
assert (state_path.read_bytes() if state_path.exists() else None) == state_before
@pytest.mark.asyncio
async def test_recovery_before_sandbox_start_keeps_original_explicit_selection(app, prepared, monkeypatch):
commit_candidate(prepared)
original = FakeFactory.create_cases
async def fail(*args, **kwargs):
raise ConnectionError("Docker unavailable")
monkeypatch.setattr(FakeFactory, "create_cases", fail)
first = await app.run_job("home_evaluate", case_ids=["2", "1"])
assert not first.success
old = json.loads(next((prepared / "evaluations").glob("*/*/*/manifest.json")).read_text())
assert "sampling" not in old and "selection_plan" not in old
monkeypatch.setattr(FakeFactory, "create_cases", original)
retry = await app.run_job("home_evaluate", case_ids=["1"])
assert retry.success
new = json.loads((Path(retry.answer["result_dir"]) / "manifest.json").read_text())
assert new["case_ids"] == ["2", "1"] and new["query_ids"] == old["query_ids"]
@pytest.mark.asyncio
@pytest.mark.parametrize(
"mutation",
[{"case_ids": None}, {"query_ids": None}, {"query_ids": {}}, {"query_ids": {"1": ["missing"]}}],
)
async def test_invalid_saved_recovery_selection_fails_before_allocation(app, prepared, monkeypatch, mutation):
commit_candidate(prepared)
monkeypatch.setattr(FakeFactory, "bad_export", True)
assert not (await app.run_job("home_evaluate", case_ids=["1"])).success
path = next((prepared / "evaluations").glob("*/*/*/manifest.json"))
manifest = json.loads(path.read_text())
path.write_text(json.dumps({**manifest, **mutation}))
before = artifacts(path.parent)
retry = await app.run_job("home_evaluate")
assert not retry.success
assert len(FakeFactory.instances) == 1 and artifacts(path.parent) == before
assert len(list((prepared / "evaluations").glob("*/*/*/manifest.json"))) == 1
@pytest.mark.parametrize(
"payload,expected",
[
({"cases": {"a": {"status": "completed"}}}, False),
({"cases": [{"status": "candidate_failure"}]}, False),
({"cases": [{"status": "infra_error"}]}, True),
({"cases": []}, True),
({"cases": {"a": {}}, "case_status_counts": {"completed": 0, "candidate_failure": 0}}, True),
],
)
def test_legacy_and_incomplete_summaries(tmp_path, payload, expected):
(tmp_path / "summary.json").write_text(json.dumps(payload))
assert retryable_result(tmp_path) is expected