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>
826 lines
36 KiB
Python
826 lines
36 KiB
Python
"""Host-selected query-only replay, construction evidence and sandbox isolation."""
|
|
|
|
# pylint: disable=missing-function-docstring,missing-class-docstring,unused-argument,protected-access
|
|
|
|
import asyncio
|
|
import os
|
|
import shutil
|
|
from pathlib import Path
|
|
import sys
|
|
from threading import Event
|
|
from types import MethodType, SimpleNamespace
|
|
from unittest.mock import AsyncMock
|
|
|
|
import pytest
|
|
from agentscope.model import ChatUsage, StructuredResponse
|
|
from reme_home.agent import candidate_gate, construction_equivalence, optimizer, workflow_common
|
|
from reme_home.code.snapshot import read_code_file
|
|
from reme_home.evaluation import reuse
|
|
from reme_home.evaluation.artifacts import file_sha256, read_json, write_json
|
|
from reme_home.evaluation.budget import validation_budget_status
|
|
from reme_home.evaluation.inputs import EvaluationSpec, load_inputs
|
|
|
|
from test_evaluation import ( # noqa: F401 # pylint: disable=unused-import
|
|
FakeFactory,
|
|
command,
|
|
commit_candidate,
|
|
home_application,
|
|
preparation_inputs,
|
|
prepared_home,
|
|
os_sandbox_available,
|
|
host_network_probe_fixture,
|
|
)
|
|
from test_workflows import ScriptedModel, final_report, set_model
|
|
|
|
from reme.utils.local_backend import LocalProcessBackend
|
|
|
|
|
|
@pytest.fixture(name="sandbox")
|
|
def review_sandbox(monkeypatch):
|
|
policies = []
|
|
|
|
def create(**kwargs):
|
|
policies.append(kwargs)
|
|
local = LocalProcessBackend()
|
|
return SimpleNamespace(backend=local, exec_shell=local.exec_shell)
|
|
|
|
monkeypatch.setattr(workflow_common, "create_case_study_sandbox", create)
|
|
return policies
|
|
|
|
|
|
@pytest.fixture(name="reviewer")
|
|
def real_reviewer(app, prepared, monkeypatch):
|
|
wrapper = app.context.components["agent_wrapper"]["home_construction_equivalence"]
|
|
monkeypatch.setattr(wrapper, "reply", MethodType(type(wrapper).reply, wrapper))
|
|
gate = app.context.components["agent_wrapper"]["home_candidate_gate"]
|
|
monkeypatch.setattr(
|
|
gate,
|
|
"reply",
|
|
AsyncMock(
|
|
return_value={"result": '{"decision":"accept","reason":"Mechanism"}', "status": "completed", "error": None},
|
|
),
|
|
)
|
|
return wrapper
|
|
|
|
|
|
def force_draw(monkeypatch, draw):
|
|
monkeypatch.setattr(reuse.random, "SystemRandom", lambda: SimpleNamespace(random=lambda: draw))
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_corrected_equivalence_authorizes_replay(app, prepared, reviewer, sandbox, monkeypatch):
|
|
assert (await app.run_job("home_evaluate")).success
|
|
commit_candidate(prepared)
|
|
model = ScriptedModel(final="Construction is unchanged: only query behavior changes.")
|
|
model.generate_structured_output = AsyncMock(
|
|
return_value=StructuredResponse(
|
|
content={"decision": "construction_unchanged", "reason": "Only query behavior changes"},
|
|
usage=ChatUsage(input_tokens=7, output_tokens=11, time=0),
|
|
),
|
|
)
|
|
set_model(app, "home_construction_equivalence", model)
|
|
force_draw(monkeypatch, 0.1)
|
|
response = await app.run_job("home_evaluate", sampling=True)
|
|
assert response.success, response.answer
|
|
assert response.answer["execution_mode"] == "query_only_replay"
|
|
report = response.answer["automatic_construction_reuse"]["equivalence_report"]
|
|
assert report["decision"] == "construction_unchanged" and "review_failed" not in report
|
|
assert report["usage"]["input_tokens"] == 9 and report["usage"]["output_tokens"] == 14
|
|
assert read_json(Path(report["review_path"]))["session_id"]
|
|
assert not Path(report["source_path"]).exists()
|
|
model.generate_structured_output.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("stage", ["before_export", "after_review", "final_validation"])
|
|
async def test_replay_binds_reviewed_archive(app, prepared, reviewer, sandbox, monkeypatch, stage):
|
|
baseline = await app.run_job("home_evaluate")
|
|
source = Path(baseline.answer["result_dir"])
|
|
commit_candidate(prepared)
|
|
force_draw(monkeypatch, 0.1)
|
|
set_model(
|
|
app,
|
|
"home_construction_equivalence",
|
|
ScriptedModel(final='{"decision":"construction_unchanged","reason":"Query only"}'),
|
|
)
|
|
|
|
def replace_snapshot(run):
|
|
target = run / "cases/1/memory_construction"
|
|
shutil.copyfile(run / "cases/2/memory_construction/reme_workspace.tar.gz", target / "reme_workspace.tar.gz")
|
|
result = read_json(target / "result.json")
|
|
result["workspace_sha256"] = file_sha256(target / "reme_workspace.tar.gz")
|
|
if "source_workspace_sha256" in result:
|
|
result["source_workspace_sha256"] = result["workspace_sha256"]
|
|
write_json(target / "result.json", result)
|
|
|
|
if stage == "before_export":
|
|
prepare = construction_equivalence.prepare_equivalence_scope
|
|
|
|
def changed(*args, **kwargs):
|
|
replace_snapshot(source)
|
|
return prepare(*args, **kwargs)
|
|
|
|
monkeypatch.setattr(construction_equivalence, "prepare_equivalence_scope", changed)
|
|
elif stage == "after_review":
|
|
review = reuse._review_source
|
|
|
|
async def changed(*args, **kwargs):
|
|
report = await review(*args, **kwargs)
|
|
replace_snapshot(source)
|
|
return report
|
|
|
|
monkeypatch.setattr(reuse, "_review_source", changed)
|
|
launches = len(FakeFactory.instances)
|
|
response = await app.run_job("home_evaluate", sampling=True)
|
|
if stage == "final_validation":
|
|
assert response.success, response.answer
|
|
run = Path(response.answer["result_dir"])
|
|
optimizer.verify_evaluation(prepared, run, response.answer["commit_sha"])
|
|
replace_snapshot(run)
|
|
with pytest.raises(ValueError, match="snapshot provenance"):
|
|
optimizer.verify_evaluation(prepared, run, response.answer["commit_sha"])
|
|
else:
|
|
assert not response.success
|
|
assert "changed" in str(response.answer)
|
|
assert len(FakeFactory.instances) == launches
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("changed", [False, True])
|
|
async def test_large_resources_export_for_both_reviewers(app, prepared, reviewer, sandbox, monkeypatch, changed):
|
|
assert (await app.run_job("home_evaluate")).success
|
|
commit_candidate(prepared)
|
|
repo = prepared / "code/repo"
|
|
relative = "plugins/beam/src/reme_beam/large_resource.bin"
|
|
resource = repo / relative
|
|
resource.write_bytes(b"\0" * 5_000_001)
|
|
command(repo, "add", ".")
|
|
command(repo, "-c", "user.name=Fixture", "-c", "user.email=test@localhost", "commit", "-m", "Large resource")
|
|
source_sha = file_sha256(resource)
|
|
assert (await app.run_job("home_evaluate")).success
|
|
commit_candidate(prepared)
|
|
if changed:
|
|
with resource.open("ab") as output:
|
|
output.write(b"updated")
|
|
command(repo, "add", ".")
|
|
command(repo, "-c", "user.name=Fixture", "-c", "user.email=test@localhost", "commit", "-m", "Update resource")
|
|
candidate_sha = file_sha256(resource)
|
|
# Browsing retains its existing output guard; only complete exports bypass it.
|
|
with pytest.raises(ValueError, match="Code file exceeds 5 MB"):
|
|
read_code_file(repo, {}, path=relative)
|
|
inspected = []
|
|
|
|
def inspect_export(category):
|
|
root = next((prepared / "tmp").glob(f"{category}-*"))
|
|
assert file_sha256(root / "base" / relative) == source_sha
|
|
assert file_sha256(root / "candidate" / relative) == candidate_sha
|
|
inspected.append(category)
|
|
|
|
async def accept(*args, **kwargs):
|
|
inspect_export("candidate-gate")
|
|
return {"result": '{"decision":"accept","reason":"Fixture export check"}', "status": "completed", "error": None}
|
|
|
|
def finish():
|
|
inspect_export("construction-equivalence")
|
|
return '{"decision":"construction_unchanged","reason":"Fixture export check"}'
|
|
|
|
gate = app.context.components["agent_wrapper"]["home_candidate_gate"]
|
|
monkeypatch.setattr(gate, "reply", accept)
|
|
set_model(
|
|
app,
|
|
"home_construction_equivalence",
|
|
ScriptedModel(final=finish),
|
|
)
|
|
force_draw(monkeypatch, 0.1)
|
|
response = await app.run_job("home_evaluate", sampling=True, max_evaluations=10)
|
|
assert response.success, response.answer
|
|
assert response.answer["execution_mode"] == "query_only_replay"
|
|
for report in (
|
|
response.answer["candidate_gate"],
|
|
response.answer["automatic_construction_reuse"]["equivalence_report"],
|
|
):
|
|
assert not Path(report["source_path"]).exists()
|
|
assert inspected == ["candidate-gate", "construction-equivalence"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("draw,selected", [(0.0, True), (0.599999, True), (0.6, False), (0.99, False)])
|
|
async def test_equivalent_candidate_uses_host_probability(
|
|
app,
|
|
prepared,
|
|
reviewer,
|
|
sandbox,
|
|
monkeypatch,
|
|
draw,
|
|
selected,
|
|
):
|
|
baseline = await app.run_job("home_evaluate")
|
|
source = Path(baseline.answer["result_dir"])
|
|
commit_candidate(prepared)
|
|
|
|
def finish():
|
|
evidence = next((prepared / "tmp").glob("construction-equivalence-*"))
|
|
assert (evidence / "runtime/reme/__init__.py").is_file()
|
|
assert not list(evidence.rglob(".git"))
|
|
assert not list(evidence.rglob("queries"))
|
|
assert not (evidence / "manifest.json").exists()
|
|
for case in ["1", "2"]:
|
|
assert (evidence / f"construction/{case}/workspace/daily/note.md").read_text() == case
|
|
assert (evidence / f"construction/{case}/build.log").is_file()
|
|
return '{"decision":"construction_unchanged","reason":"Only query behavior changes"}'
|
|
|
|
model = ScriptedModel(
|
|
[("Read", lambda: {"file_path": str(next((prepared / "tmp").glob("construction-equivalence-*/diff.patch")))})],
|
|
final=finish,
|
|
)
|
|
set_model(app, "home_construction_equivalence", model)
|
|
force_draw(monkeypatch, draw)
|
|
result = await app.run_job("home_evaluate", sampling=True, max_evaluations=10)
|
|
assert result.success, result.answer
|
|
decision = result.answer["automatic_construction_reuse"]
|
|
assert decision["selected"] == selected and decision["draw"] == draw and decision["probability"] == 0.6
|
|
assert decision["source_validation"] == str(source)
|
|
report = decision["equivalence_report"]
|
|
assert read_json(Path(report["review_path"]))["decision"] == "construction_unchanged"
|
|
assert report["session_id"] and report["usage"]["input_tokens"] == 4
|
|
assert report["base_commit"] == baseline.answer["commit_sha"]
|
|
assert report["candidate_commit"] == result.answer["commit_sha"]
|
|
assert {tool["function"]["name"] for tool in model.calls[0]["tools"]} == {"Read", "Glob", "Grep", "AutoBash"}
|
|
assert sandbox and all(policy["writable_paths"] == [] for policy in sandbox)
|
|
review_policies = [policy for policy in sandbox if "construction-equivalence-" in policy["cwd"]]
|
|
assert review_policies and all(policy["read_only_paths"] == [report["source_path"]] for policy in review_policies)
|
|
assert not Path(report["source_path"]).exists()
|
|
events = {event[1] for event in FakeFactory.instances[-1].events}
|
|
assert ("upload" in events) == selected and ("build" in events) != selected
|
|
assert result.answer["execution_mode"] == ("query_only_replay" if selected else "full_validation")
|
|
run = Path(result.answer["result_dir"])
|
|
manifest = read_json(run / "manifest.json")
|
|
saved = manifest["automatic_construction_reuse"]
|
|
derived = {"equivalence_report", "probability_scope", "reuse_reasons"}
|
|
assert derived.isdisjoint(saved)
|
|
assert saved["source_reviews"][saved["source_validation"]]["equivalence_report"] == report
|
|
assert saved == {key: value for key, value in decision.items() if key not in derived}
|
|
assert decision["probability_scope"] == "all_cases"
|
|
assert decision["reuse_reasons"] == {case_id: "60_percent_policy" for case_id in saved["case_sources"]}
|
|
assert validation_budget_status(prepared, 10)["used_validations"] == 1
|
|
optimizer.verify_evaluation(prepared, run, result.answer["commit_sha"])
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"output",
|
|
[
|
|
'{"decision":"construction_changed","reason":"Construction storage changes"}',
|
|
"malformed",
|
|
'{"decision":"construction_unchanged","reason":"x","extra":true}',
|
|
"error",
|
|
],
|
|
)
|
|
async def test_changed_or_failed_review_rebuilds_without_drawing(app, prepared, reviewer, sandbox, monkeypatch, output):
|
|
assert (await app.run_job("home_evaluate")).success
|
|
commit_candidate(prepared)
|
|
set_model(app, "home_construction_equivalence", ScriptedModel(final=output))
|
|
if output == "error":
|
|
monkeypatch.setattr(reviewer, "reply", AsyncMock(side_effect=RuntimeError("model offline")))
|
|
monkeypatch.setattr(reuse, "select_query_only", lambda: pytest.fail("Cannot draw without equivalence"))
|
|
response = await app.run_job("home_evaluate", sampling=True)
|
|
assert response.success, response.answer
|
|
decision = response.answer["automatic_construction_reuse"]
|
|
assert decision["selected"] is False and decision["reason"] == "construction_not_equivalent"
|
|
assert decision["equivalence_report"]["decision"] == "construction_changed"
|
|
if output != '{"decision":"construction_changed","reason":"Construction storage changes"}':
|
|
assert decision["equivalence_report"]["review_failed"]
|
|
assert not list((prepared / "tmp").glob("construction-equivalence-*"))
|
|
assert any(event[1] == "build" for event in FakeFactory.instances[-1].events)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_skip_baseline_debug_plain_calls_and_missing_ancestor(app, prepared, monkeypatch):
|
|
async def unexpected(*args, **kwargs):
|
|
pytest.fail("No reviewer expected")
|
|
|
|
monkeypatch.setattr(construction_equivalence, "review_construction", unexpected)
|
|
commit_candidate(prepared)
|
|
response = await app.run_job("home_evaluate", sampling=True)
|
|
assert response.success and response.answer["automatic_construction_reuse"]["reason"] == "no_reusable_ancestor"
|
|
commit_candidate(prepared)
|
|
assert (await app.run_job("home_evaluate", debug=True, sampling=True)).success
|
|
response = await app.run_job("home_evaluate")
|
|
assert response.success and "automatic_construction_reuse" not in response.answer
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("invalid", ["checksum", "failed_construction", "answer", "config", "unfinished", "debug"])
|
|
async def test_invalid_nearest_source_falls_back_to_older_ancestor(
|
|
app,
|
|
prepared,
|
|
reviewer,
|
|
sandbox,
|
|
monkeypatch,
|
|
invalid,
|
|
):
|
|
baseline = await app.run_job("home_evaluate")
|
|
commit_candidate(prepared)
|
|
recent = await app.run_job("home_evaluate", case_ids=["1"])
|
|
source = Path(recent.answer["result_dir"])
|
|
if invalid == "checksum":
|
|
(source / "cases/1/memory_construction/reme_workspace.tar.gz").write_bytes(b"bad")
|
|
elif invalid == "failed_construction":
|
|
path = source / "cases/1/memory_construction/result.json"
|
|
write_json(path, {**read_json(path), "success": False})
|
|
elif invalid == "answer":
|
|
write_json(source / "cases/1/queries/result.json", {"queries": [{"answer": "", "error": "failed"}]})
|
|
else:
|
|
manifest = read_json(source / "manifest.json")
|
|
if invalid == "config":
|
|
manifest["fingerprints"]["construction_config"] = "different"
|
|
elif invalid == "debug":
|
|
manifest["mode"] = "debug"
|
|
else:
|
|
manifest["status"] = "failed"
|
|
write_json(source / "manifest.json", manifest)
|
|
commit_candidate(prepared)
|
|
set_model(
|
|
app,
|
|
"home_construction_equivalence",
|
|
ScriptedModel(
|
|
final=('{"decision":"construction_unchanged","reason":"Query change"}'),
|
|
),
|
|
)
|
|
force_draw(monkeypatch, 0.1)
|
|
result = await app.run_job("home_evaluate", sampling=True)
|
|
assert result.success, result.answer
|
|
assert result.answer["automatic_construction_reuse"]["source_validation"] == baseline.answer["result_dir"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_targeted_sampling_uses_nearest_source_and_older_source_fills_coverage(
|
|
app,
|
|
prepared,
|
|
reviewer,
|
|
sandbox,
|
|
monkeypatch,
|
|
):
|
|
baseline = await app.run_job("home_evaluate")
|
|
assert baseline.success
|
|
commit_candidate(prepared)
|
|
recent = await app.run_job("home_evaluate", case_ids=["1"])
|
|
commit_candidate(prepared)
|
|
set_model(
|
|
app,
|
|
"home_construction_equivalence",
|
|
ScriptedModel(
|
|
final=('{"decision":"construction_unchanged","reason":"Query only"}'),
|
|
),
|
|
)
|
|
force_draw(monkeypatch, 0.1)
|
|
replay = await app.run_job("home_evaluate", sampling=True, target_queries={"1": [], "2": []})
|
|
assert replay.success, replay.answer
|
|
assert replay.answer["automatic_construction_reuse"]["source_validation"] == recent.answer["result_dir"]
|
|
assert replay.answer["case_count"] == 2
|
|
sources = replay.answer["automatic_construction_reuse"]["case_sources"]
|
|
assert sources["1"]["result_dir"] == recent.answer["result_dir"]
|
|
assert sources["2"]["result_dir"] == baseline.answer["result_dir"]
|
|
commit_candidate(prepared)
|
|
force_draw(monkeypatch, 0.8)
|
|
rebuilt = await app.run_job("home_evaluate", sampling=True)
|
|
assert rebuilt.success and rebuilt.answer["case_count"] == 2
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_auto_memory_override_and_whitespace_only_changes(app, prepared, reviewer, sandbox, monkeypatch):
|
|
assert (await app.run_job("home_evaluate")).success
|
|
commit_candidate(prepared)
|
|
repo = prepared / "code/repo"
|
|
path = repo / "plugins/beam/src/reme_beam/auto_memory.py"
|
|
path.write_text("value = 1\n")
|
|
command(repo, "add", ".")
|
|
command(repo, "-c", "user.name=Fixture", "-c", "user.email=test@localhost", "commit", "-m", "construction")
|
|
model = ScriptedModel(final='{"decision":"construction_unchanged","reason":"Query only"}')
|
|
set_model(app, "home_construction_equivalence", model)
|
|
result = await app.run_job("home_evaluate", sampling=True)
|
|
assert result.success, result.answer
|
|
assert result.answer["automatic_construction_reuse"]["equivalence_report"]["decision"] == "construction_changed"
|
|
assert not model.calls and not sandbox
|
|
path.write_text("value = 1\n\n")
|
|
command(repo, "add", ".")
|
|
command(repo, "-c", "user.name=Fixture", "-c", "user.email=test@localhost", "commit", "-m", "spacing")
|
|
force_draw(monkeypatch, 0.1)
|
|
result = await app.run_job("home_evaluate", sampling=True)
|
|
assert result.success and result.answer["execution_mode"] == "query_only_replay"
|
|
assert len(model.calls) == 1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("draw", [0.1, 0.9])
|
|
@pytest.mark.parametrize("archive_source", [False, True])
|
|
async def test_infrastructure_retry_preserves_replay_and_selection(
|
|
app,
|
|
prepared,
|
|
reviewer,
|
|
sandbox,
|
|
monkeypatch,
|
|
draw,
|
|
archive_source,
|
|
):
|
|
baseline = await app.run_job("home_evaluate")
|
|
assert baseline.success
|
|
commit_candidate(prepared)
|
|
model = ScriptedModel(final='{"decision":"construction_unchanged","reason":"Query only"}')
|
|
set_model(app, "home_construction_equivalence", model)
|
|
force_draw(monkeypatch, draw)
|
|
monkeypatch.setattr(FakeFactory, "bad_export", True)
|
|
failed = await app.run_job("home_evaluate", sampling=True, max_evaluations=10)
|
|
assert not failed.success
|
|
failed_manifest = read_json(Path(failed.answer["result_dir"]) / "manifest.json")
|
|
if archive_source:
|
|
shutil.rmtree(Path(baseline.answer["result_dir"]))
|
|
assert (await app.run_job("home_create_candidate_branch", branch_name="retry-branch")).success
|
|
monkeypatch.setattr(FakeFactory, "bad_export", False)
|
|
monkeypatch.setattr(reuse, "select_query_only", lambda: pytest.fail("Recovery must not redraw"))
|
|
recovered = await app.run_job("home_evaluate", sampling=True, max_evaluations=10)
|
|
assert recovered.success, recovered.answer
|
|
manifest = read_json(Path(recovered.answer["result_dir"]) / "manifest.json")
|
|
saved = {
|
|
**failed_manifest["automatic_construction_reuse"],
|
|
"branch_name": "retry-branch",
|
|
}
|
|
assert manifest["automatic_construction_reuse"] == saved
|
|
report = saved["source_reviews"][saved["source_validation"]]["equivalence_report"]
|
|
decision = recovered.answer["automatic_construction_reuse"]
|
|
assert decision == {
|
|
**saved,
|
|
"equivalence_report": report,
|
|
"probability_scope": "all_cases",
|
|
"reuse_reasons": {case_id: "60_percent_policy" for case_id in saved["case_sources"]},
|
|
}
|
|
assert list(decision).index("equivalence_report") == list(decision).index("source_validation") + 1
|
|
assert manifest["case_ids"] == failed_manifest["case_ids"] and manifest["query_ids"] == failed_manifest["query_ids"]
|
|
assert recovered.answer["execution_mode"] == ("query_only_replay" if draw < 0.6 else "full_validation")
|
|
assert len(model.calls) == 1
|
|
assert validation_budget_status(prepared, 10)["used_validations"] == 2
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("mode", ["automatic", "explicit", "sampled_explicit"])
|
|
@pytest.mark.parametrize("archive_source", [False, True])
|
|
@pytest.mark.parametrize("change_image", [False, True])
|
|
async def test_replay_retry_checks_config_and_retains_pinned_sources(
|
|
app,
|
|
prepared,
|
|
reviewer,
|
|
sandbox,
|
|
monkeypatch,
|
|
mode,
|
|
archive_source,
|
|
change_image,
|
|
):
|
|
baseline = await app.run_job("home_evaluate")
|
|
assert baseline.success
|
|
commit_candidate(prepared)
|
|
set_model(
|
|
app,
|
|
"home_construction_equivalence",
|
|
ScriptedModel(final='{"decision":"construction_unchanged","reason":"Query only"}'),
|
|
)
|
|
force_draw(monkeypatch, 0.1)
|
|
options = {"sampling": mode != "explicit", "max_evaluations": 10}
|
|
if mode != "automatic":
|
|
options["reuse_construction_from"] = baseline.answer["result_dir"]
|
|
monkeypatch.setattr(FakeFactory, "bad_export", True)
|
|
failed = await app.run_job("home_evaluate", **options)
|
|
assert not failed.success
|
|
run = Path(failed.answer["result_dir"])
|
|
old = read_json(run / "manifest.json")
|
|
assert old["construction_sources"]
|
|
for case_id, source in old["construction_sources"].items():
|
|
archive = run / f"cases/{case_id}/memory_construction/reme_workspace.tar.gz"
|
|
assert source["workspace_sha256"] == file_sha256(archive)
|
|
if archive_source:
|
|
shutil.rmtree(Path(baseline.answer["result_dir"]))
|
|
monkeypatch.setattr(FakeFactory, "bad_export", False)
|
|
launches = len(FakeFactory.instances)
|
|
if change_image:
|
|
options["base_image"] = "different-image:latest"
|
|
response = await app.run_job("home_evaluate", **options)
|
|
if change_image:
|
|
assert not response.success
|
|
assert "incompatible construction_config" in str(response.answer)
|
|
assert len(FakeFactory.instances) == launches
|
|
else:
|
|
assert response.success, response.answer
|
|
current = read_json(Path(response.answer["result_dir"]) / "manifest.json")
|
|
assert current["construction_sources"] == old["construction_sources"]
|
|
assert current["case_ids"] == old["case_ids"] and current["query_ids"] == old["query_ids"]
|
|
assert not any(event[1] == "build" for factory in FakeFactory.instances[launches:] for event in factory.events)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("explicit", [False, True])
|
|
async def test_retry_rejects_corrupt_retained_snapshot(app, prepared, reviewer, sandbox, monkeypatch, explicit):
|
|
baseline = await app.run_job("home_evaluate")
|
|
assert baseline.success
|
|
commit_candidate(prepared)
|
|
set_model(
|
|
app,
|
|
"home_construction_equivalence",
|
|
ScriptedModel(final='{"decision":"construction_unchanged","reason":"Query only"}'),
|
|
)
|
|
force_draw(monkeypatch, 0.1)
|
|
monkeypatch.setattr(FakeFactory, "bad_export", True)
|
|
options = {"reuse_construction_from": baseline.answer["result_dir"]} if explicit else {}
|
|
failed = await app.run_job("home_evaluate", sampling=True, max_evaluations=10, **options)
|
|
assert not failed.success
|
|
run = Path(failed.answer["result_dir"])
|
|
manifest = read_json(run / "manifest.json")
|
|
case_id = next(iter(manifest["construction_sources"]))
|
|
(run / f"cases/{case_id}/memory_construction/reme_workspace.tar.gz").write_bytes(b"corrupt")
|
|
shutil.rmtree(Path(baseline.answer["result_dir"]))
|
|
launches = len(FakeFactory.instances)
|
|
monkeypatch.setattr(FakeFactory, "bad_export", False)
|
|
response = await app.run_job("home_evaluate", sampling=True, max_evaluations=10, **options)
|
|
assert not response.success
|
|
assert len(FakeFactory.instances) == launches
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("draw", [0.1, 0.9])
|
|
async def test_retry_with_missing_equivalence_report(app, prepared, reviewer, sandbox, monkeypatch, draw):
|
|
assert (await app.run_job("home_evaluate")).success
|
|
commit_candidate(prepared)
|
|
model = ScriptedModel(final='{"decision":"construction_unchanged","reason":"Query only"}')
|
|
set_model(app, "home_construction_equivalence", model)
|
|
force_draw(monkeypatch, draw)
|
|
monkeypatch.setattr(FakeFactory, "bad_export", True)
|
|
failed = await app.run_job("home_evaluate", sampling=True, max_evaluations=10)
|
|
assert not failed.success
|
|
path = Path(failed.answer["result_dir"]) / "manifest.json"
|
|
manifest = read_json(path)
|
|
saved = manifest["automatic_construction_reuse"]
|
|
saved["source_reviews"][saved["source_validation"]].pop("equivalence_report")
|
|
write_json(path, manifest)
|
|
|
|
monkeypatch.setattr(FakeFactory, "bad_export", False)
|
|
monkeypatch.setattr(reuse, "select_query_only", lambda: pytest.fail("Recovery must not redraw"))
|
|
launches = len(FakeFactory.instances)
|
|
recovered = await app.run_job("home_evaluate", sampling=True, max_evaluations=10)
|
|
assert len(model.calls) == 1
|
|
if draw < 0.6:
|
|
assert not recovered.success
|
|
assert "Missing construction-equivalence report for replay" in str(recovered.answer)
|
|
assert len(FakeFactory.instances) == launches
|
|
else:
|
|
assert recovered.success, recovered.answer
|
|
assert recovered.answer["execution_mode"] == "full_validation"
|
|
assert "equivalence_report" not in recovered.answer["automatic_construction_reuse"]
|
|
result = read_json(Path(recovered.answer["result_dir"]) / "manifest.json")
|
|
assert result["case_ids"] == manifest["case_ids"] and result["query_ids"] == manifest["query_ids"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_review_checkout_race_and_cancellation_do_not_sample(app, prepared, reviewer, sandbox, monkeypatch):
|
|
assert (await app.run_job("home_evaluate")).success
|
|
commit_candidate(prepared)
|
|
before = (prepared / "sampling/state.json").read_bytes()
|
|
entered, release = asyncio.Event(), asyncio.Event()
|
|
|
|
async def paused(*args, **kwargs):
|
|
entered.set()
|
|
await release.wait()
|
|
return {
|
|
"result": '{"decision":"construction_unchanged","reason":"Query only"}',
|
|
"status": "completed",
|
|
"error": None,
|
|
}
|
|
|
|
monkeypatch.setattr(reviewer, "reply", paused)
|
|
task = asyncio.create_task(app.run_job("home_evaluate", sampling=True))
|
|
await asyncio.wait_for(entered.wait(), timeout=10)
|
|
concurrent = await app.run_job("home_evaluate", sampling=True)
|
|
assert not concurrent.success
|
|
commit_candidate(prepared)
|
|
release.set()
|
|
response = await task
|
|
assert not response.success and "changed during equivalence" in str(response.answer)
|
|
assert len(FakeFactory.instances) == 1 and (prepared / "sampling/state.json").read_bytes() == before
|
|
entered.clear()
|
|
release.clear()
|
|
task = asyncio.create_task(app.run_job("home_evaluate", sampling=True))
|
|
await asyncio.wait_for(entered.wait(), timeout=10)
|
|
task.cancel()
|
|
with pytest.raises(asyncio.CancelledError):
|
|
await task
|
|
assert not list((prepared / "tmp").glob("construction-equivalence-*"))
|
|
assert (prepared / "sampling/state.json").read_bytes() == before
|
|
release.set()
|
|
assert (await app.run_job("home_evaluate", sampling=True)).success
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_sandbox_failure_stops_before_model_sampling_or_budget(app, prepared, reviewer, monkeypatch):
|
|
assert (await app.run_job("home_evaluate")).success
|
|
commit_candidate(prepared)
|
|
before = (prepared / "sampling/state.json").read_bytes()
|
|
model = ScriptedModel()
|
|
set_model(app, "home_construction_equivalence", model)
|
|
|
|
def unavailable(**kwargs):
|
|
raise RuntimeError("sandbox unavailable")
|
|
|
|
monkeypatch.setattr(workflow_common, "create_case_study_sandbox", unavailable)
|
|
response = await app.run_job("home_evaluate", sampling=True, max_evaluations=10)
|
|
assert not response.success and "sandbox unavailable" in str(response.answer)
|
|
assert not model.calls and len(FakeFactory.instances) == 1
|
|
assert not list((prepared / "tmp").glob("construction-equivalence-*"))
|
|
assert validation_budget_status(prepared, 10)["used_validations"] == 0
|
|
assert (prepared / "sampling/state.json").read_bytes() == before
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("kind", ["candidate-gate", "construction-equivalence"])
|
|
@pytest.mark.parametrize("stage", ["export", "report"])
|
|
async def test_partial_export_and_report_failures_clean_review_files(
|
|
app,
|
|
prepared,
|
|
reviewer,
|
|
sandbox,
|
|
monkeypatch,
|
|
kind,
|
|
stage,
|
|
):
|
|
assert (await app.run_job("home_evaluate")).success
|
|
commit_candidate(prepared)
|
|
if stage == "report":
|
|
|
|
def fail_report(*args, **kwargs):
|
|
raise OSError("report write failed")
|
|
|
|
monkeypatch.setattr(workflow_common, "save_record", fail_report)
|
|
elif kind == "candidate-gate":
|
|
original = candidate_gate.export_blob
|
|
|
|
def fail_blob(*args, **kwargs):
|
|
original(*args, **kwargs)
|
|
raise OSError("partial source export failed")
|
|
|
|
monkeypatch.setattr(candidate_gate, "export_blob", fail_blob)
|
|
else:
|
|
original = construction_equivalence.inspect_archive
|
|
|
|
def fail_archive(*args, **kwargs):
|
|
original(*args, **kwargs)
|
|
raise OSError("partial construction export failed")
|
|
|
|
monkeypatch.setattr(construction_equivalence, "inspect_archive", fail_archive)
|
|
response = await app.run_job(
|
|
"home_evaluate",
|
|
sampling=True,
|
|
**({"max_evaluations": 10} if kind == "candidate-gate" else {}),
|
|
)
|
|
assert not response.success and "failed" in str(response.answer)
|
|
assert not list((prepared / "tmp").glob(f"{kind}-*"))
|
|
assert len(FakeFactory.instances) == 1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cancel_during_export_waits_for_writer_and_preserves_other_scratch(tmp_path):
|
|
(tmp_path / "tmp").mkdir()
|
|
unrelated = tmp_path / "tmp/optimizer-keep"
|
|
unrelated.mkdir()
|
|
marker = unrelated / "notes.txt"
|
|
marker.write_text("keep")
|
|
started, release = Event(), Event()
|
|
roots = []
|
|
|
|
def prepare(root):
|
|
(root / "partial.txt").write_text("partial")
|
|
started.set()
|
|
if not release.wait(timeout=10):
|
|
raise TimeoutError("test writer was not released")
|
|
(root / "finished.txt").write_text("finished")
|
|
|
|
async def review():
|
|
async with candidate_gate.review_export(tmp_path, "construction-equivalence") as root:
|
|
roots.append(root)
|
|
await construction_equivalence.blocking(prepare, root)
|
|
|
|
task = asyncio.create_task(review())
|
|
try:
|
|
assert await asyncio.to_thread(started.wait, 10)
|
|
task.cancel()
|
|
await asyncio.sleep(0)
|
|
assert roots[0].is_dir() # The owned writer is still running.
|
|
finally:
|
|
release.set()
|
|
with pytest.raises(asyncio.CancelledError):
|
|
await task
|
|
assert not roots[0].exists()
|
|
assert marker.read_text() == "keep"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_optimizer_final_selection_accepts_automatic_replay(app, prepared, reviewer, sandbox, monkeypatch):
|
|
baseline = await app.run_job("home_evaluate")
|
|
assert baseline.success
|
|
set_model(
|
|
app,
|
|
"home_construction_equivalence",
|
|
ScriptedModel(
|
|
final=('{"decision":"construction_unchanged","reason":"Query only"}'),
|
|
),
|
|
)
|
|
target = prepared / "code/repo/plugins/beam/src/reme_beam/__init__.py"
|
|
model = ScriptedModel(
|
|
[
|
|
("home_create_candidate_branch", {"branch_name": "retrieval"}),
|
|
("Read", {"file_path": str(target)}),
|
|
("Edit", {"file_path": str(target), "old_string": "value = 1", "new_string": "value = 2"}),
|
|
("home_commit_candidate", {"message": "Improve retrieval"}),
|
|
("home_evaluate", {"debug": False}),
|
|
],
|
|
final=lambda: final_report(prepared, "retrieval"),
|
|
)
|
|
set_model(app, "home_optimizer", model)
|
|
force_draw(monkeypatch, 0.1)
|
|
result = await app.run_job("home_optimize")
|
|
assert result.success, result.answer
|
|
manifest = read_json(Path(result.answer["evaluation_path"]) / "manifest.json")
|
|
assert manifest["execution_mode"] == "query_only_replay"
|
|
schema = next(tool for tool in model.calls[0]["tools"] if tool["function"]["name"] == "home_evaluate")
|
|
assert set(schema["function"]["parameters"]["properties"]) == {"debug", "target_queries"}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.usefixtures("os_sandbox_available")
|
|
async def test_real_equivalence_sandbox_allows_only_copied_construction_and_source(
|
|
app,
|
|
prepared,
|
|
tmp_path,
|
|
monkeypatch,
|
|
host_network_probe,
|
|
):
|
|
source = await app.run_job("home_evaluate")
|
|
assert source.success
|
|
commit_candidate(prepared)
|
|
spec = EvaluationSpec(sampling=True)
|
|
record, dataset, cases = load_inputs(prepared, spec)
|
|
fingerprints = reuse.construction_fingerprints(
|
|
record,
|
|
dataset,
|
|
spec,
|
|
{**os.environ, **app.context.app_config.environment},
|
|
)
|
|
context = {
|
|
"source_validation": source.answer["result_dir"],
|
|
"base_commit": source.answer["commit_sha"],
|
|
"candidate_commit": command(prepared / "code/repo", "rev-parse", "HEAD"),
|
|
}
|
|
root = tmp_path / "review-export"
|
|
root.mkdir()
|
|
scope = construction_equivalence.prepare_equivalence_scope(
|
|
prepared,
|
|
context,
|
|
spec.model_copy(update={"reuse_construction_from": source.answer["result_dir"]}),
|
|
cases,
|
|
fingerprints,
|
|
root=root,
|
|
)
|
|
backend = workflow_common.WorkflowSandbox(scope, memory_limit_mib=0)
|
|
root = Path(scope["scratch"])
|
|
evidence = root / "construction/1/workspace/daily/note.md"
|
|
assert await backend.read_file(str(evidence)) == b"1"
|
|
assert await backend.read_file(str(root / "runtime/reme/__init__.py")) is not None
|
|
assert (await backend.stat(str(evidence))).size_bytes == 1
|
|
assert "diff.patch" in await backend.list_dir(str(root))
|
|
private = tmp_path / "private.txt"
|
|
private.write_text("private")
|
|
source_run = Path(source.answer["result_dir"])
|
|
for forbidden in [
|
|
private,
|
|
prepared / "metadata/preparation.json",
|
|
prepared / "code/repo/.git/config",
|
|
prepared / "code/runtime/reme/__init__.py",
|
|
prepared / "datasets/training-set/cases/1.json",
|
|
source_run / "summary.json",
|
|
source_run / "cases/1/queries/result.json",
|
|
source_run / "cases/1/memory_construction/build.log",
|
|
]:
|
|
with pytest.raises(OSError):
|
|
await backend.read_file(str(forbidden))
|
|
with pytest.raises(OSError):
|
|
await backend.stat(str(forbidden))
|
|
for forbidden in [evidence, root / "diff.patch", root / "new.txt", private]:
|
|
with pytest.raises(OSError):
|
|
await backend.write_file(str(forbidden), b"forbidden")
|
|
(root / "escape").symlink_to(private)
|
|
with pytest.raises(OSError):
|
|
await backend.read_file(str(root / "escape"))
|
|
assert not list(root.rglob(".git")) and not list(root.rglob("queries"))
|
|
network = await backend.exec_shell(host_network_probe, timeout=10)
|
|
assert not network.ok()
|
|
monkeypatch.setenv("HOME_REVIEW_PRIVATE_TOKEN", "private-marker")
|
|
environment = await backend.exec_shell(
|
|
[sys.executable, "-I", "-B", "-c", "import os; print(os.environ.get('HOME_REVIEW_PRIVATE_TOKEN', 'absent'))"],
|
|
timeout=10,
|
|
)
|
|
assert environment.ok() and environment.stdout.strip() == b"absent"
|