ReMe/plugins/home/tests/test_workflows.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

1009 lines
44 KiB
Python

"""Minimal Home agents exercise real Jobs, Git and AS tools with fake model/Docker boundaries."""
# pylint: disable=missing-function-docstring,missing-class-docstring,redefined-outer-name
# pylint: disable=unused-argument,protected-access
import asyncio
import json
import shutil
import sys
from importlib import import_module
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
import yaml
from agentscope.formatter import OpenAIChatFormatter
from agentscope.message import HintBlock, TextBlock, ToolCallBlock
from agentscope.model import ChatResponse, ChatUsage
from agentscope.state import AgentState
from jsonschema import Draft202012Validator
from reme_home.agent import optimizer as optimizer_module, diagnostic as diagnostic_module, workflow_common, case_study
from reme_home.evaluation.artifacts import read_json, write_json
from reme_home.preparation.code import git
from reme_home.workspace import _initialization_lock
from test_bounded_agent import RecordingModel
from test_case_study import RecordingSandbox, report_tokenizer # noqa: F401 # pylint: disable=unused-import
from test_evaluation import ( # noqa: F401 # pylint: disable=unused-import
FakeFactory,
FakeWorker,
home_application,
preparation_inputs,
prepared_home,
)
from reme.schema import Response
from reme.utils.local_backend import LocalProcessBackend
class ScriptedModel(RecordingModel):
def __init__(self, calls=(), final="Supported diagnostic report."):
super().__init__()
self.script = list(calls)
self.report = final
async def __call__(self, **kwargs):
index = len(self.calls)
self.calls.append(kwargs)
if index < len(self.script):
name, arguments = self.script[index]
arguments = arguments() if callable(arguments) else arguments
content = [ToolCallBlock(id=f"call-{index}", name=name, input=json.dumps(arguments))]
else:
final = self.report() if callable(self.report) else self.report
content = [TextBlock(text=final)]
return ChatResponse(content=content, is_last=True, usage=ChatUsage(input_tokens=2, output_tokens=3, time=0))
@pytest.fixture
def sandbox(monkeypatch):
policies = []
def create(**kwargs):
# Mock only subprocess isolation. Writes are restricted by the real
# sandbox in the dedicated OS tests below, not by this local fake.
policies.append(kwargs)
local = LocalProcessBackend()
return SimpleNamespace(backend=local, exec_shell=local.exec_shell)
monkeypatch.setattr(workflow_common, "create_case_study_sandbox", create)
monkeypatch.setattr(case_study, "create_case_study_sandbox", RecordingSandbox)
return policies
def set_model(app, name, model):
wrapper = app.context.components["agent_wrapper"][name]
wrapper.as_llm = SimpleNamespace(model=model)
return wrapper
async def baseline(app):
result = await app.run_job("home_evaluate")
assert result.success, result.answer
return result.answer["result_dir"]
@pytest.mark.asyncio
@pytest.mark.parametrize("status", ["failed", "interrupted", "waiting"])
async def test_workflow_rejects_incomplete_agent_reports(app, prepared, sandbox, monkeypatch, status):
wrapper = app.context.components["agent_wrapper"]["home_diagnostic"]
monkeypatch.setattr(
wrapper,
"reply",
AsyncMock(return_value={"result": "Unfinished diagnosis", "status": status, "error": None}),
)
with pytest.raises(RuntimeError, match=status):
await workflow_common.workflow_reply(wrapper, prepared, "diagnostic", "Diagnose this failure.")
@pytest.mark.asyncio
@pytest.mark.parametrize("role", ["optimizer", "diagnostic"])
async def test_workflow_injects_overview_only_into_optimizer(app, prepared, sandbox, monkeypatch, role):
wrapper = app.context.components["agent_wrapper"][f"home_{role}"]
reply = AsyncMock(return_value={"result": "Complete report", "status": "completed", "error": None})
monkeypatch.setattr(wrapper, "reply", reply)
await workflow_common.workflow_reply(wrapper, prepared, role, "Inspect the candidate.")
prompt = reply.call_args.kwargs["system_prompt"]
assert "{overall_structure}" not in prompt
assert str(prepared / "code/repo") in prompt
if role == "optimizer":
assert prompt.startswith("Home overview:")
assert prompt.count("Home overview:") == 1
assert prompt.count("Workspace structure:") == 1
assert prompt.count("User-owned memory files are the source of truth") == 1
assert "behavior under long or conflicting histories" in " ".join(prompt.split())
assert str(prepared / "code/runtime") in prompt
assert str(prepared / "docs/architecture-guide.md") in prompt
assert str(prepared / "datasets") in prompt
assert "Execute the optimization loop" in prompt
assert "{home}" not in prompt
else:
assert "Home overview:" not in prompt
assert "Workspace structure:" not in prompt
def final_report(home, branch="init", path=None):
repo = home / "code/repo"
if path is None:
path = sorted((home / "evaluations" / branch).glob("*/*/summary.json"))[-1].parent
return json.dumps(
{
"branch_name": branch,
"commit_sha": git(repo, "rev-parse", "HEAD"),
"evaluation_path": str(path),
"report": "Selected using matching formal evidence; sampled coverage limits confidence.",
},
)
@pytest.mark.parametrize(
"template",
[
"{}",
"```\n{}\n```",
"```json\n{}\n```",
"Completed.\n```json\n{}\n```\nSee report.",
"Completed.\r\n```JSON\r\n{}\r\n```",
"Completed. {}",
"<think>Comparing candidates.</think>\n{}",
],
)
def test_parse_optimizer_result_formats(template):
claim = {"branch_name": "candidate", "commit_sha": "a" * 40, "evaluation_path": "run", "report": "Evidence"}
assert optimizer_module.parse_result(template.format(json.dumps(claim))).model_dump() == claim
@pytest.mark.asyncio
async def test_optimizer_job_preserves_literal_formatting_in_final_report(app, prepared, sandbox):
path = await baseline(app)
claim = json.loads(final_report(prepared, path=path))
claim["report"] = "<think>Evidence from the evaluated source</think>\n```python\nexample\n```"
set_model(app, "home_optimizer", ScriptedModel(final="```json\n" + json.dumps(claim) + "\n```"))
response = await app.run_job("home_optimize")
assert response.success, response.answer
assert response.answer["report"] == claim["report"]
def test_optimizer_shared_recovery_rejects_competing_and_non_object_reports():
claim = {"branch_name": "candidate", "commit_sha": "a" * 40, "evaluation_path": "run", "report": "Evidence"}
text = json.dumps(claim)
repaired = f"Completed.\n```json\n{text[:-1]},}}\n```"
assert optimizer_module.parse_result(repaired).model_dump() == claim
for invalid in (f"[{text}]", f"```json\n{text}\n```\n{text}"):
with pytest.raises(ValueError):
optimizer_module.parse_result(invalid)
@pytest.mark.parametrize(
"text",
[
"No result",
"Completed.\n```json\n{}",
"Completed.\n```python\n{}\n```",
"Completed.\n```json\n{}\n```\n```json\n{}\n```",
"Completed.\n```text\nexample\n```\n```json\n{}\n```",
],
)
def test_parse_optimizer_result_rejects_invalid_or_multiple_fences(text):
with pytest.raises(ValueError):
optimizer_module.parse_result(text)
@pytest.mark.parametrize("changes", [{"commit_sha": "short"}, {"report": ""}, {"unexpected": True}])
def test_mixed_optimizer_result_keeps_schema_validation(changes):
claim = {"branch_name": "candidate", "commit_sha": "a" * 40, "evaluation_path": "run", "report": "Evidence"}
with pytest.raises(ValueError):
optimizer_module.parse_result(f"Completed.\n```json\n{json.dumps({**claim, **changes})}\n```")
@pytest.mark.asyncio
async def test_draft_scope_across_optimizer_diagnoses_and_invocations(app, prepared, sandbox):
path = await baseline(app)
def notebooks(messages):
return [
json.loads(block.output[0].text)["entries"]
for message in messages
for block in message.content
if block.type == "tool_result" and block.name == "read_draft"
]
class NotebookModel(ScriptedModel):
def __init__(self):
super().__init__()
self.snapshots = []
async def __call__(self, **kwargs):
index = len(self.calls) % 3
self.calls.append(kwargs)
if index == 1:
self.snapshots.append(notebooks(kwargs["messages"])[-1])
content = (
[TextBlock(text="Supported diagnostic report.")]
if index == 2
else [
ToolCallBlock(
id=f"draft-{len(self.calls)}",
name="read_draft" if index == 0 else "add_draft",
input=json.dumps({} if index == 0 else {"experience": "Pin evidence to evaluated commits"}),
),
]
)
return ChatResponse(content=content, is_last=True, usage=ChatUsage(input_tokens=2, output_tokens=3, time=0))
diagnostic = NotebookModel()
set_model(app, "home_diagnostic", diagnostic)
for _ in range(2):
model = ScriptedModel(
[
("read_draft", {}),
("add_draft", {"experience": "Compare candidates on common queries"}),
("home_diagnose", {"evaluation_paths": [path]}),
("home_diagnose", {"evaluation_paths": [path]}),
("read_draft", {}),
],
final=lambda: final_report(prepared, path=path),
)
set_model(app, "home_optimizer", model)
response = await app.run_job("home_optimize")
assert response.success, response.answer
assert notebooks(model.calls[-1]["messages"]) == [[], ["Compare candidates on common queries"]]
schemas = {tool["function"]["name"]: tool["function"]["parameters"] for tool in model.calls[0]["tools"]}
assert "_draft_store" not in schemas["home_diagnose"]["properties"]
assert diagnostic.snapshots == [
[],
["Pin evidence to evaluated commits"],
[],
["Pin evidence to evaluated commits"],
]
for _ in range(2):
response = await app.run_job("home_diagnose", evaluation_paths=[path])
assert response.success, response.answer
assert diagnostic.snapshots[-2:] == [[], []]
@pytest.mark.asyncio
@pytest.mark.parametrize("max_evaluations", [10, 1])
async def test_real_optimization_diagnoses_edits_debugs_and_evaluates(
app,
prepared,
sandbox,
monkeypatch,
max_evaluations,
):
home = prepared
now, timers = [0.0], []
timer_class = optimizer_module.ValidationCycleTimer
def create_timer(budget):
timer = timer_class(budget, clock=lambda: now[0])
timers.append(timer)
return timer
class TimedModel(ScriptedModel):
async def __call__(self, **kwargs):
formatted = await OpenAIChatFormatter().format(kwargs["messages"])
pending = set()
for message in formatted:
if pending:
assert message["role"] == "tool", formatted
pending.remove(message["tool_call_id"])
else:
assert message["role"] != "tool", formatted
pending.update(call["id"] for call in message.get("tool_calls", []))
assert not pending
response = await super().__call__(**kwargs)
now[0] += 60 * 60
return response
monkeypatch.setattr(optimizer_module, "ValidationCycleTimer", create_timer)
target = home / "code/repo/plugins/beam/src/reme_beam/__init__.py"
baseline_path = await baseline(app)
diagnostic = ScriptedModel(
[("home_case_study", {"evaluation_path": baseline_path, "case_ids": ["1"], "focus": "Trace wrong answers"})],
)
set_model(app, "home_diagnostic", diagnostic)
set_model(app, "home_case_study", ScriptedModel())
gate = ScriptedModel(final='{"decision":"accept","reason":"Changes runtime behavior."}')
set_model(app, "home_candidate_gate", gate)
optimizer = TimedModel(
[
("get_validation_budget", {}),
("home_diagnose", {"evaluation_paths": [baseline_path]}),
("home_create_candidate_branch", {"branch_name": "mechanism"}),
("Read", {"file_path": str(target)}),
("Edit", {"file_path": str(target), "old_string": "value = 1", "new_string": "value = 2"}),
("home_commit_candidate", {"message": "Change mechanism"}),
("home_evaluate", {"debug": True}),
("home_evaluate", {"debug": False}),
],
final=lambda: final_report(home, "mechanism"),
)
wrapper = set_model(app, "home_optimizer", optimizer)
monkeypatch.setattr(wrapper, "validation_limit", lambda: max_evaluations)
response = await app.run_job("home_optimize", instruction="Improve general retrieval")
assert response.success, response.answer
assert target.read_text() == "value = 2\n"
assert response.answer["branch_name"] == "mechanism"
assert response.answer["status"] == "completed"
transitions = [
block.hint
for message in optimizer.calls[-1]["messages"]
for block in message.content
if isinstance(block, HintBlock) and block.source == "meta_reme_validation_cycle_transition"
]
assert len(transitions) == 1
assert len(timers) == 1
if max_evaluations == 1:
assert transitions[0] == optimizer_module.VALIDATION_BUDGET_EXHAUSTED_HINT
assert "Start cycle" not in transitions[0]
assert not timers[0].active
assert timers[0].next_reminder() is None
else:
assert "Formal validation 1 completed successfully" in transitions[0]
assert "Remaining formal validations: 9. Start cycle 2." in transitions[0]
assert timers[0]._started_at == now[0] - 60 * 60 # Reset before the final reasoning call.
assert any(
isinstance(block, HintBlock) and block.source == "meta_reme_validation_timer"
for message in optimizer.calls[-1]["messages"]
for block in message.content
)
assert response.metadata["usage"]["input_tokens"] == 2 * len(optimizer.calls)
assert response.metadata["usage"]["output_tokens"] == 3 * len(optimizer.calls)
assert "sampled coverage" in response.answer["report"]
assert read_json(Path(response.metadata["optimization_report_path"]))["status"] == "completed"
assert len(diagnostic.calls) == 2
if max_evaluations == 1:
assert not gate.calls # A one-validation budget starts in refinement, without admission review.
else:
assert len(gate.calls) == 1
assert read_json(next((home / "logs/candidate-gates").glob("*.json")))["decision"] == "accept"
source = next((home / "logs/diagnostic-trajectories").glob("*.json"))
trace = read_json(source)
assert trace["session_id"] and any("Improve general retrieval" in str(msg) for msg in trace["messages"])
assert "permission_context" not in trace
schemas = {item["function"]["name"]: item["function"]["parameters"] for item in optimizer.calls[0]["tools"]}
assert set(schemas["home_evaluate"]["properties"]) == {"debug", "target_queries"}
assert "caller_trajectory" not in schemas["home_diagnose"]["properties"]
assert "get_validation_budget" in schemas
assert not any("equivalence" in name for name in schemas)
for manifest_path in (home / "evaluations").glob("*/*/*/manifest.json"):
manifest = read_json(manifest_path)
assert manifest["execution_mode"] == "full_validation"
assert any(read_json(path)["mode"] == "debug" for path in (home / "evaluations").glob("*/*/*/manifest.json"))
diagnostic_schemas = {item["function"]["name"] for item in diagnostic.calls[0]["tools"]}
assert "home_case_study" in diagnostic_schemas
assert not set(optimizer_module.MUTATION_JOBS) & diagnostic_schemas
assert "Edit" not in diagnostic_schemas and "home_evaluate" not in diagnostic_schemas
assert "Write" in diagnostic_schemas # Private scratch only.
assert any(str(target.parent.parent) in policy["writable_paths"] for policy in sandbox)
assert all(str(home / "code/repo") not in policy["writable_paths"] for policy in sandbox)
@pytest.mark.asyncio
@pytest.mark.parametrize("success", [True, False])
@pytest.mark.parametrize("with_timer", [True, False])
async def test_exhausted_evaluation_hint_is_once_even_after_failure(monkeypatch, success, with_timer):
job = AsyncMock(return_value=Response(success=success, answer={"status": "completed" if success else "failed"}))
monkeypatch.setattr(optimizer_module, "required_job", lambda *_args: job)
monkeypatch.setattr(optimizer_module, "read_state", lambda _home: {"started_validations": []})
monkeypatch.setattr(optimizer_module, "evaluation_checkout", lambda _home: {"sampling": True})
monkeypatch.setattr(optimizer_module, "validation_budget_status", lambda *_args: {"remaining_validations": 0})
timer = optimizer_module.ValidationCycleTimer(30) if with_timer else None
state = AgentState()
tool = optimizer_module.evaluation_tool(None, {}, home=None, timer=timer)
await tool.call(_agent_state=state)
assert state.middle_context.pop(optimizer_module.PENDING_CYCLE_TRANSITIONS) == [
optimizer_module.VALIDATION_BUDGET_EXHAUSTED_HINT,
]
await tool.call(_agent_state=state)
assert optimizer_module.PENDING_CYCLE_TRANSITIONS not in state.middle_context
if timer is not None:
assert not timer.active
assert job.await_count == 2
@pytest.mark.asyncio
async def test_optimizer_starts_with_exhausted_budget(app, prepared, sandbox, monkeypatch):
path = await baseline(app)
timer = optimizer_module.ValidationCycleTimer(30)
model = ScriptedModel(final=lambda: final_report(prepared, path=path))
wrapper = set_model(app, "home_optimizer", model)
monkeypatch.setattr(wrapper, "create_cycle_timer", lambda: timer)
monkeypatch.setattr(optimizer_module, "validation_budget_status", lambda *_args: {"remaining_validations": 0})
response = await app.run_job("home_optimize")
assert response.success, response.answer
assert not timer.active
task = "\n".join(msg.get_text_content() or "" for msg in model.calls[0]["messages"])
assert task.count(optimizer_module.VALIDATION_BUDGET_EXHAUSTED_HINT) == 1
assert len(FakeFactory.instances) == 1 # Only the baseline ran.
schemas = {item["function"]["name"] for item in model.calls[0]["tools"]}
assert set(optimizer_module.MUTATION_JOBS) <= schemas
assert "home_evaluate" in schemas
@pytest.mark.asyncio
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
async def test_benchmark_optimizer_applies_budgets_to_real_workflow(
app,
prepared,
inputs,
sandbox,
monkeypatch,
tmp_path,
benchmark,
):
baseline_path = await baseline(app)
await app.close()
module = import_module(f"benchmark.{benchmark}.run_home")
config = tmp_path / "home.yaml"
config.write_text(
yaml.safe_dump(
{
"workspace_dir": str(prepared.parent),
"preparation": inputs[0],
"max_evaluations": 3,
"validation_cycle_time_budget_minutes": 30,
},
),
)
application_class = type(app)
agents = []
model = ScriptedModel([("get_validation_budget", {})], final=lambda: final_report(prepared, path=baseline_path))
def factory(**kwargs):
application = application_class(**kwargs, log_to_console=False)
original_start = application.start
async def start():
await original_start()
wrapper = set_model(application, "home_optimizer", model)
original_create = wrapper._create_agent
def create(**options):
agent = original_create(**options)
agents.append(agent)
return agent
monkeypatch.setattr(wrapper, "_create_agent", create)
monkeypatch.setattr(application, "start", start)
return application
monkeypatch.setattr(module, "Application", factory)
result = await module.optimize(config, instruction="Keep the best existing candidate")
assert result["status"] == "completed"
assert result["branch_name"] == "init"
assert len(agents) == 1
assert agents[0].validation_cycle_timer.time_budget_minutes == 30
task = "\n".join(msg.get_text_content() or "" for msg in model.calls[0]["messages"])
assert '"max_evaluations": 3' in task
assert '"remaining_validations": 3' in task
assert len(FakeFactory.instances) == 1 # Only the earlier baseline ran.
@pytest.mark.asyncio
@pytest.mark.parametrize("template", ["{}", "```json\n{}\n```", "Completed.\n```json\n{}\n```\nSee report."])
async def test_optimizer_creates_baseline_once_and_verifies_baseline_fallback(app, prepared, sandbox, template):
model = ScriptedModel(final=lambda: template.format(final_report(prepared)))
set_model(app, "home_optimizer", model)
response = await app.run_job("home_optimize")
assert response.success, response.answer
assert len(FakeFactory.instances) == 1
assert response.answer["branch_name"] == "init"
run = response.answer["baseline_path"]
manifest = read_json(Path(run) / "manifest.json")
assert set(manifest["case_ids"]) == {"1", "2"} and not manifest["options"]["sampling"]
assert manifest["options"]["record_history"]
set_model(app, "home_optimizer", ScriptedModel(final=lambda: final_report(prepared)))
second = await app.run_job("home_optimize")
assert second.success, second.answer
assert len(FakeFactory.instances) == 1
assert second.answer["session_id"] != response.answer["session_id"]
@pytest.mark.asyncio
@pytest.mark.parametrize("change", ["dirty", "incomplete", "wrong_branch"])
async def test_new_baseline_rechecks_repository_and_evidence(app, prepared, sandbox, monkeypatch, change):
wrapper = app.context.components["agent_wrapper"]["home_optimizer"]
required_job = optimizer_module.required_job
evaluate_job = required_job(wrapper, "home_evaluate")
async def evaluate(**kwargs):
response = await evaluate_job(**kwargs)
assert response.success, response.answer
if change == "dirty":
target = prepared / "code/repo/plugins/beam/src/reme_beam/__init__.py"
target.write_text("preserve changes made during evaluation\n")
elif change == "incomplete":
path = Path(response.answer["result_dir"]) / "summary.json"
summary = read_json(path)
summary["expected_query_count"] = 0
write_json(path, summary)
else:
path = Path(response.answer["result_dir"]) / "manifest.json"
manifest = read_json(path)
manifest["branch_name"] = "candidate"
write_json(path, manifest)
return response
monkeypatch.setattr(
optimizer_module,
"required_job",
lambda wrapper, name: evaluate if name == "home_evaluate" else required_job(wrapper, name),
)
model = ScriptedModel()
set_model(app, "home_optimizer", model)
response = await app.run_job("home_optimize")
assert not response.success and not model.calls and not sandbox
expected = {
"dirty": "must be clean",
"incomplete": "incomplete case coverage",
"wrong_branch": "Initial baseline evidence must match the init branch and initial commit",
}
assert expected[change] in str(response.answer)
@pytest.mark.asyncio
@pytest.mark.parametrize("change", ["branch", "commit", "restore_init"])
async def test_new_baseline_rejects_concurrent_candidate_changes(app, prepared, sandbox, monkeypatch, change):
entered, release = asyncio.Event(), asyncio.Event()
required_job = optimizer_module.required_job
wrapper = app.context.components["agent_wrapper"]["home_optimizer"]
evaluate_job = required_job(wrapper, "home_evaluate")
async def evaluate(**kwargs):
# Pause after baseline preflight but before evaluation snapshots HEAD.
entered.set()
await release.wait()
response = await evaluate_job(**kwargs)
assert not response.success, response.answer
if change == "restore_init":
switched = await app.run_job("home_switch_candidate_branch", branch_name="init")
assert switched.success, switched.answer
return response
monkeypatch.setattr(
optimizer_module,
"required_job",
lambda wrapper, name: evaluate if name == "home_evaluate" else required_job(wrapper, name),
)
model = ScriptedModel()
set_model(app, "home_optimizer", model)
repo = prepared / "code/repo"
initial = git(repo, "rev-parse", "HEAD")
running = asyncio.create_task(app.run_job("home_optimize"))
try:
await asyncio.wait_for(entered.wait(), 10)
created = await app.run_job("home_create_candidate_branch", branch_name="concurrent")
assert created.success, created.answer
if change != "branch":
target = repo / "plugins/beam/src/reme_beam/__init__.py"
target.write_text(target.read_text() + "\n# Concurrent candidate change.\n")
committed = await app.run_job("home_commit_candidate", message="concurrent candidate")
assert committed.success, committed.answer
candidate = git(repo, "rev-parse", "HEAD")
release.set()
response = await asyncio.wait_for(running, 30)
finally:
release.set()
if not running.done():
running.cancel()
await asyncio.gather(running, return_exceptions=True)
assert not response.success, response.answer
assert not model.calls and not sandbox
assert not list((prepared / "logs/optimization-reports").glob("*.json"))
assert "Checkout changed before evaluation" in str(response.answer)
assert not list((prepared / "evaluations").glob("*/*/*/manifest.json"))
expected_branch = "init" if change == "restore_init" else "concurrent"
assert git(repo, "branch", "--show-current") == expected_branch
assert git(repo, "rev-parse", "concurrent") == candidate
if change != "branch":
assert candidate != initial
assert not list((prepared / "evaluations/init").glob("*/*/manifest.json"))
@pytest.mark.asyncio
@pytest.mark.parametrize(
"artifact,key,value,baseline_allowed",
[
("manifest", "success", False, True),
("summary", "case_status_counts", {"infra_error": 1}, True),
("summary", "query_status_counts", {"infra_error": 1}, True),
("summary", "query_status_counts", {}, True),
("manifest", "status", "failed", False),
("manifest", "sandbox_started_at", None, False),
("summary", "case_count", 0, False),
("summary", "scoring_enabled", False, False),
],
)
async def test_baseline_tolerance_preserves_final_evidence_requirements(
app,
prepared,
artifact,
key,
value,
baseline_allowed,
):
path = Path(await baseline(app))
commit = read_json(path / "manifest.json")["commit_sha"]
document = read_json(path / f"{artifact}.json")
document[key] = value
write_json(path / f"{artifact}.json", document)
for initial in (True, False):
if initial and baseline_allowed:
optimizer_module.verify_evaluation(prepared, path, commit, baseline=initial)
else:
with pytest.raises(ValueError, match="complete without infrastructure failures"):
optimizer_module.verify_evaluation(prepared, path, commit, baseline=initial)
@pytest.mark.asyncio
async def test_standalone_diagnosis_fresh_state_and_persisted_provenance(app, prepared, sandbox):
path = await baseline(app)
model = ScriptedModel()
set_model(app, "home_diagnostic", model)
first = await app.run_job("home_diagnose", evaluation_paths=[path])
second = await app.run_job("home_diagnose", evaluation_paths=[path], instruction="Compare failure clusters")
assert first.success and second.success
assert first.answer["session_id"] != second.answer["session_id"]
assert first.answer["trajectory_path"] != second.answer["trajectory_path"]
assert first.answer["evaluation_paths"] == [path]
record = read_json(Path(first.answer["diagnostic_report_path"]))
assert record["diagnosis"] == "Supported diagnostic report."
assert read_json(Path(first.answer["trajectory_path"])) == {"messages": [], "summary": None}
assert all(
len(policy["writable_paths"]) == 1 and "/tmp/diagnostic-" in policy["writable_paths"][0] for policy in sandbox
)
@pytest.mark.asyncio
@pytest.mark.parametrize("change", ["partial", "debug", "replay", "wrong_commit"])
async def test_bad_baseline_rejected_before_optimizer(app, prepared, sandbox, change):
path = Path(await baseline(app))
manifest = read_json(path / "manifest.json")
summary = read_json(path / "summary.json")
if change == "partial":
manifest["case_ids"] = ["1"]
manifest["query_ids"] = {"1": manifest["query_ids"]["1"]}
elif change == "debug":
manifest["mode"] = "debug"
elif change == "replay":
manifest["execution_mode"] = "query_only_replay"
else:
manifest["commit_sha"] = "0" * 40
write_json(path / "manifest.json", manifest)
write_json(path / "summary.json", summary)
# Missing valid baseline must not silently switch away from a candidate.
response = await app.run_job("home_create_candidate_branch", branch_name="existing")
assert response.success
model = ScriptedModel()
set_model(app, "home_optimizer", model)
response = await app.run_job("home_optimize")
assert not response.success and "baseline is missing" in str(response.answer)
assert not model.calls and not sandbox
assert git(prepared / "code/repo", "branch", "--show-current") == "existing"
@pytest.mark.asyncio
@pytest.mark.parametrize(
"change",
["dirty", "branch", "mixed_branch", "commit", "path", "infra", "debug", "replay", "invalid_json"],
)
async def test_final_claim_rejected_without_discarding_changes(app, prepared, sandbox, change):
path = Path(await baseline(app))
target = prepared / "code/repo/plugins/beam/src/reme_beam/__init__.py"
def finish():
claim = json.loads(final_report(prepared, path=path))
if change == "dirty":
target.write_text("preserve unfinished changes\n")
elif change in {"branch", "mixed_branch"}:
claim["branch_name"] = "invented"
elif change == "commit":
claim["commit_sha"] = "0" * 40
elif change == "path":
claim["evaluation_path"] = str(prepared / "tmp")
elif change == "infra":
summary = read_json(path / "summary.json")
summary["query_status_counts"]["infra_error"] = 1
write_json(path / "summary.json", summary)
elif change in {"debug", "replay"}:
manifest = read_json(path / "manifest.json")
manifest["mode" if change == "debug" else "execution_mode"] = (
"debug" if change == "debug" else "query_only_replay"
)
write_json(path / "manifest.json", manifest)
else:
return "not a structured final claim"
result = json.dumps(claim)
return f"Completed.\n```json\n{result}\n```" if change == "mixed_branch" else result
set_model(app, "home_optimizer", ScriptedModel(final=finish))
response = await app.run_job("home_optimize")
assert not response.success
record = read_json(Path(response.metadata["optimization_report_path"]))
assert record["status"] == "failed" and record["error"]
if change == "dirty":
assert target.read_text() == "preserve unfinished changes\n"
@pytest.mark.asyncio
async def test_infrastructure_baseline_failure_never_calls_optimizer(app, prepared, sandbox, monkeypatch):
async def broken(*args, **kwargs):
raise RuntimeError("Docker unavailable")
monkeypatch.setattr(FakeFactory, "create_cases", broken)
model = ScriptedModel()
set_model(app, "home_optimizer", model)
response = await app.run_job("home_optimize")
assert not response.success and not model.calls
assert "baseline failed" in str(response.answer)
@pytest.mark.asyncio
@pytest.mark.parametrize("existing_baseline", [False, True])
@pytest.mark.parametrize("failure_stage", ["answer", "answer_batch", "construction"])
async def test_baseline_infra_error_continues_optimization(
app,
prepared,
sandbox,
monkeypatch,
existing_baseline,
failure_stage,
):
method = "run_build" if failure_stage == "construction" else "run_queries"
original = getattr(FakeWorker, method)
async def execute(self, items):
failed = len(FakeFactory.instances) == 1 and self.case_id == "1"
if failed and failure_stage == "construction":
raise ConnectionError("Construction infrastructure unavailable")
if failed and failure_stage == "answer_batch":
raise ConnectionError("Answer batch disconnected")
result = await original(self, items)
if failed:
result["queries"][0].update(answer=None, error="AgentScope reply ended: exceed_max_iters")
return result
monkeypatch.setattr(FakeWorker, method, execute)
if existing_baseline:
response = await app.run_job("home_evaluate", fail_fast=False)
assert not response.success
def retry_initial_commit():
history = app.context.components["home.evaluation_history"]["default"]
assert history.sampling_state() == {"round": 0, "cases": {}, "queries": {}}
return {"debug": False}
# The optimizer receives the imperfect baseline and can retry its exact commit.
model = ScriptedModel(calls=[("home_evaluate", retry_initial_commit)], final=lambda: final_report(prepared))
set_model(app, "home_optimizer", model)
response = await app.run_job("home_optimize")
assert response.success, response.answer
assert model.calls and len(FakeFactory.instances) == 2
path = Path(response.answer["baseline_path"])
manifest = read_json(path / "manifest.json")
summary = read_json(path / "summary.json")
assert manifest["status"] == "completed" and manifest["success"] is False
assert manifest["options"]["fail_fast"] is False
assert summary["case_status_counts"] == {"completed": 1, "candidate_failure": 0, "infra_error": 1}
assert summary["query_status_counts"]["completed"] == 1
assert summary["query_status_counts"]["infra_error"] == (1 if failure_stage == "answer" else 0)
if failure_stage != "answer":
assert summary["cases"]["1"]["construction"]["status"] == (
"failure" if failure_stage == "construction" else "success"
)
assert summary["cases"]["1"]["queries"] == {}
with pytest.raises(ValueError, match="without infrastructure failures"):
optimizer_module.verify_evaluation(prepared, path, manifest["commit_sha"])
if failure_stage == "answer_batch":
failure_path = path / "cases/1/failure.json"
failure = read_json(failure_path)
for change in ({"stage": "artifacts"}, {"failure_kind": "candidate_failure"}):
write_json(failure_path, {**failure, **change})
with pytest.raises(ValueError, match="incomplete query coverage"):
optimizer_module.verify_evaluation(prepared, path, manifest["commit_sha"], baseline=True)
write_json(failure_path, failure)
assert summary["cases"]["2"]["queries"]["fact:1"]["score"] == 0.5
retry = read_json(Path(response.answer["evaluation_path"]) / "manifest.json")
assert retry["case_ids"] == manifest["case_ids"] and retry["query_ids"] == manifest["query_ids"]
assert retry["success"] is True
@pytest.mark.asyncio
async def test_baseline_state_prefers_latest_successful_numeric_attempt(app, prepared, monkeypatch):
run_build = FakeWorker.run_build
fail_build = True
async def build(self, jobs):
if fail_build and self.case_id == "1":
raise ConnectionError("Construction infrastructure unavailable")
return await run_build(self, jobs)
async def attempt(number, success):
response = await app.run_job("home_evaluate", fail_fast=False)
assert response.success is success, response.answer
assert response.answer["status"] == "completed"
path = response.answer["result_dir"]
assert Path(path).name == str(number)
return path
monkeypatch.setattr(FakeWorker, "run_build", build)
for number in range(1, 10):
diagnostic = await attempt(number, False)
assert optimizer_module.baseline_state(prepared)["evaluation_path"] == diagnostic
fail_build = False
app.context.components["agent_wrapper"]["judge"].reply.return_value = {
"result": '{"score": 0}',
"status": "completed",
"error": None,
}
successful = await attempt(10, True)
selected = optimizer_module.baseline_state(prepared)
assert selected["evaluation_path"] == successful
assert selected["summary"]["mean_query_score"] == 0
@pytest.mark.asyncio
async def test_candidate_memory_build_failure_remains_valid_baseline_evidence(app, prepared, monkeypatch):
monkeypatch.setattr(FakeFactory, "fail_build", "1")
path = await baseline(app)
evidence = optimizer_module.baseline_state(prepared)
assert evidence["evaluation_path"] == path
assert evidence["manifest"]["success"] is True
assert evidence["summary"]["case_status_counts"] == {"completed": 1, "candidate_failure": 1, "infra_error": 0}
@pytest.mark.asyncio
async def test_invalid_scope_schema_and_injected_trajectory(app, prepared, sandbox):
path = await baseline(app)
wrapper = set_model(app, "home_optimizer", ScriptedModel())
tool = diagnostic_module.diagnostic_tool(wrapper)
with pytest.raises(ValueError, match="host-owned"):
await tool._func(evaluation_paths=[path], caller_trajectory={"spoof": True})
for values in ([str(prepared / "tmp")], [path, path], [], ["../escape"]):
result = await app.run_job("home_diagnose", evaluation_paths=values)
assert not result.success
result = await app.run_job("home_diagnose", evaluation_paths=[path], _allowed_paths=[path])
assert not result.success and not sandbox
for name in ("home_optimize", "home_diagnose"):
Draft202012Validator.check_schema(app.context.jobs[name].parameters)
assert "caller_trajectory" not in app.context.jobs["home_diagnose"].parameters["properties"]
with pytest.raises(ValueError, match="execution settings"):
optimizer_module.evaluation_options({"reuse_construction_from": path})
@pytest.mark.asyncio
async def test_single_optimizer_lock_and_cancellation_cleanup(app, prepared, sandbox, monkeypatch):
await baseline(app)
entered, release = asyncio.Event(), asyncio.Event()
async def blocked(*args, **kwargs):
entered.set()
await release.wait()
monkeypatch.setattr(optimizer_module, "workflow_reply", blocked)
running = asyncio.create_task(app.run_job("home_optimize"))
await asyncio.wait_for(entered.wait(), 5)
second = await app.run_job("home_optimize")
assert not second.success and "already in progress" in str(second.answer)
running.cancel()
with pytest.raises(asyncio.CancelledError):
await running
reports = list((prepared / "logs/optimization-reports").glob("*.json"))
assert len(reports) == 1 and read_json(reports[0])["status"] == "cancelled"
with _initialization_lock(prepared / "metadata/optimization.lock"):
pass
@pytest.mark.asyncio
async def test_metadata_link_rejected_before_opening_any_lock(app, prepared, tmp_path):
outside = tmp_path / "outside"
outside.mkdir()
state = prepared / "metadata"
saved = prepared / "saved-metadata"
state.rename(saved)
state.symlink_to(outside, target_is_directory=True)
try:
result = await app.run_job("home_optimize")
assert not result.success and "real directory" in str(result.answer)
with pytest.raises(ValueError, match="real directory"):
optimizer_module.baseline_state(prepared)
with pytest.raises(ValueError, match="real directory"):
optimizer_module.verify_final(prepared, None)
assert not list(outside.iterdir())
finally:
state.unlink()
saved.rename(state)
@pytest.mark.asyncio
async def test_workflow_sandbox_enforces_read_write_and_git_boundaries(tmp_path):
if sys.platform.startswith("linux"):
sandbox_command = "bwrap"
elif sys.platform == "darwin":
sandbox_command = "sandbox-exec"
else:
pytest.skip(f"No file sandbox backend for {sys.platform}")
return
if shutil.which(sandbox_command) is None:
pytest.skip(f"Sandbox boundary test requires {sandbox_command} on PATH")
home = tmp_path / "home"
repo = home / "repo"
candidate = repo / "src"
scratch = home / "scratch"
evidence = home / "evidence"
for directory in (candidate, repo / ".git", scratch, evidence):
directory.mkdir(parents=True, exist_ok=True)
target = candidate / "module.py"
target.write_text("old\n")
secret = tmp_path / "outside.txt"
secret.write_text("outside")
(evidence / "result.json").write_text("evidence")
for role in ("optimizer", "diagnostic"):
scope = {
"scratch": str(scratch),
"read_only_paths": [str(repo), str(evidence)],
"writable_paths": [str(scratch), *([str(candidate)] if role == "optimizer" else [])],
}
backend = workflow_common.WorkflowSandbox(scope, memory_limit_mib=0)
assert (await backend.read_file(str(target))) in (b"old\n", b"new\n")
assert (await backend.stat(str(target))).size_bytes > 0
assert "module.py" in await backend.list_dir(str(candidate))
await backend.write_file(str(scratch / "analysis.py"), b"print('analysis')\n")
assert (await backend.exec_shell([sys.executable, "-I", "-B", str(scratch / "analysis.py")])).ok()
result = await case_study.python_tool(backend, str(scratch))._func(
code="import time; print('partial output', flush=True); time.sleep(20)",
timeout=0.5,
)
assert result["timed_out"] and result["stdout"].strip() == "partial output"
for path in (repo / ".git/config", evidence / "result.json", secret):
with pytest.raises(OSError):
await backend.write_file(str(path), b"forbidden")
with pytest.raises(OSError):
await backend.read_file(str(secret))
if role == "optimizer":
await backend.write_file(str(target), b"new\n")
# Replaced roots after managed Git operations must not retain stale inodes.
replacement = candidate / "replacement"
replacement.write_text("new\n")
replacement.replace(target)
assert await backend.read_file(str(target)) == b"new\n"
else:
with pytest.raises(OSError):
await backend.write_file(str(target), b"forbidden")
assert secret.read_text() == "outside" and (evidence / "result.json").read_text() == "evidence"
# A single-file candidate root must survive a managed checkout replacing
# its inode without accidentally granting writes to its containing directory.
file_scope = {
"scratch": str(scratch),
"read_only_paths": [str(repo)],
"writable_paths": [str(scratch), str(target)],
}
backend = workflow_common.WorkflowSandbox(file_scope, memory_limit_mib=0)
await backend.write_file(str(target), b"file root\n")
# Host aliases outside the mounted roots must update the granted host file.
alias = home / "alias.py"
alias.symlink_to(target)
for number, alias_path in enumerate((str(alias), "../alias.py")):
data = f"alias {number}\n".encode()
await backend.write_file(alias_path, data)
assert target.read_bytes() == data
replacement = candidate / "replacement"
replacement.write_text("replaced root\n")
replacement.replace(target)
assert await backend.read_file(str(target)) == b"replaced root\n"
with pytest.raises(OSError):
await backend.write_file(str(candidate / "sibling.py"), b"forbidden")
target.unlink()
target.symlink_to(secret)
with pytest.raises(ValueError, match="symlinks"):
await backend.read_file(str(target))