ReMe/plugins/home/tests/test_benchmark_runner.py
xyf2020 fa6d8fcef7
Some checks are pending
CI / macOS sandbox / Seatbelt - clt (push) Waiting to run
CI / macOS sandbox / Seatbelt - xcode (push) Waiting to run
CI / Python packages / Build and verify distributions (push) Waiting to run
CI / Python quality / GitHub Actions (push) Waiting to run
CI / Python quality / Pre-commit (push) Waiting to run
CI / Python tests / Unit Tests - py3.11 (push) Waiting to run
CI / Python tests / Unit Tests - py3.12 (push) Waiting to run
CI / Python tests / Unit Tests - py3.13 (push) Waiting to run
CI / Python tests / Unit Tests - py3.14 (push) Waiting to run
CI / ReMe Studio / Studio checks (push) Waiting to run
CI / Windows / CLI smoke - py3.11 (push) Waiting to run
Deploy / Documentation / Build documentation (push) Waiting to run
Deploy / Documentation / deploy (push) Blocked by required conditions
CI and Release / Docker / Build and test / amd64 (push) Waiting to run
CI and Release / Docker / Build and test / arm64 (push) Waiting to run
CI and Release / Docker / Publish multi-platform tags (push) Blocked by required conditions
Security / CodeQL / Analyze javascript-typescript (push) Waiting to run
Security / CodeQL / Analyze python (push) Waiting to run
feat(home): add reproducible benchmark preparation and candidate evaluation (#693)
* 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

---------

Co-authored-by: jinli.yl <jinli.yl@alibaba-inc.com>
2026-11-05 14:54:31 +08:00

413 lines
18 KiB
Python

"""Benchmark Home defaults and lifecycle wiring, without models or dataset writes."""
import hashlib
import json
import os
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 reme.schema import Response
from benchmark.beam import run_home as beam_runner
from benchmark.longmemeval import run_home as lme_runner
ROOT = Path(__file__).resolve().parents[3]
@pytest.fixture(autouse=True)
def isolated_runner_environment(tmp_path, monkeypatch):
"""Never load developer credentials while exercising benchmark lifecycles."""
for benchmark in ("beam", "longmemeval"):
for runner in ("run_home", "run_home_eval"):
module = import_module(f"benchmark.{benchmark}.{runner}")
monkeypatch.setattr(module, "PROJECT_ROOT", tmp_path)
@pytest.mark.asyncio
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
@pytest.mark.parametrize("runner", ["run_home", "run_home_eval"])
@pytest.mark.parametrize("env_file", [True, False])
async def test_credentials_loaded_before_application(tmp_path, monkeypatch, benchmark, runner, env_file):
"""Load repository .env without overriding exports, independently of cwd."""
module = import_module(f"benchmark.{benchmark}.{runner}")
monkeypatch.delenv("EMBEDDING_API_KEY", raising=False)
monkeypatch.setenv("LLM_API_KEY", "exported-key")
if env_file:
(tmp_path / ".env").write_text("LLM_API_KEY=file-key\nEMBEDDING_API_KEY=embedding-key\n")
cwd = tmp_path / "elsewhere"
cwd.mkdir()
monkeypatch.chdir(cwd)
if runner == "run_home_eval":
config = SimpleNamespace(benchmark=SimpleNamespace(name=benchmark))
monkeypatch.setattr(module, "load_request", lambda *args, **kwargs: (config, tmp_path, None, None))
class ApplicationReached(Exception):
"""Stop before creating any application resources."""
def factory(**_kwargs):
assert os.environ["LLM_API_KEY"] == "exported-key"
assert os.environ.get("EMBEDDING_API_KEY") == ("embedding-key" if env_file else None)
raise ApplicationReached
monkeypatch.setattr(module, "Application", factory)
with pytest.raises(ApplicationReached):
await module.run()
def test_preserved_lme_split_and_evidence():
"""Retain dev_meta's exact reviewed partition and annotations."""
directory = ROOT / "benchmark/longmemeval"
assert hashlib.sha256((directory / "home_evidence_sessions.jsonl").read_bytes()).hexdigest() == (
"35655c51210a96b595910923576fa97b93c81abd82e3cfcda801180007c23a7d"
)
workspace, spec = lme_runner.load_config(directory / "config_home.yaml")
selected = spec["benchmark"]["case_ids"]
assert len(selected) == len(set(selected)) == 250
# Hash the original first-five-group sequence to preserve both IDs and order.
assert hashlib.sha256("\n".join(selected).encode()).hexdigest() == (
"f4bee54f5afe9e0b6c6be8f95c7e1a803a3c2ba8183a77c5f8188e1875818e67"
)
assert spec["runtime"]["plugins"] == ["lme"]
assert spec["candidate"]["paths"] == ["plugins/lme/src"]
assert workspace == directory / "workspaces/home-groups-1-5"
def test_beam_defaults_use_all_100k_cases_from_any_cwd(tmp_path, monkeypatch):
"""Paths and selection do not depend on where Python was launched."""
monkeypatch.chdir(tmp_path)
workspace, spec = beam_runner.load_config(ROOT / "benchmark/beam/config_home.yaml")
assert spec["benchmark"]["variant"] == "100K"
assert spec["benchmark"]["all_cases"] is True
assert spec["benchmark"]["case_ids"] is None
assert spec["benchmark"]["source"] == str(ROOT / "benchmark/beam/dataset/BEAM")
assert spec["runtime"]["source_repo"] == str(ROOT)
assert spec["runtime"]["plugins"] == ["beam"]
assert spec["candidate"]["paths"] == ["plugins/beam/src"]
assert workspace == ROOT / "benchmark/beam/workspaces/home-100K"
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
def test_runner_preserves_explicit_candidate_paths(tmp_path, benchmark):
"""Runner defaults preserve custom scopes from existing configurations."""
module = import_module(f"benchmark.{benchmark}.run_home")
config = yaml.safe_load(module.DEFAULT_CONFIG.read_text())
config["preparation"]["candidate"] = {"paths": ["reme/steps"]}
path = tmp_path / "home.yaml"
path.write_text(yaml.safe_dump(config))
_, spec = module.load_config(path)
assert spec["candidate"]["paths"] == ["reme/steps"]
@pytest.mark.asyncio
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
async def test_python_runner_starts_prepares_and_closes(tmp_path, monkeypatch, benchmark):
"""Both Python entry points invoke only home_prepare through a local application."""
module = import_module(f"benchmark.{benchmark}.run_home")
application = AsyncMock()
application.run_job.return_value = Response(answer={"dataset": {"case_count": 1}})
observed = {}
def factory(**kwargs):
observed.update(kwargs)
return application
monkeypatch.setattr(module, "Application", factory)
result = await module.run(workspace_dir=str(tmp_path / "experiment"))
assert observed["plugins"] == ["home", "beam-judge" if benchmark == "beam" else "lme-judge"]
assert observed["service"] == {"backend": "cli"}
assert observed["workspace_dir"] == str(tmp_path / "experiment")
assert observed["components"]["home.evaluation"]["default"]["sampling_policy"] == {
"max_cases": 5,
"max_queries": None,
"temperature": 1.0,
"ewma_alpha": 0.3,
"uniform_exploration": 0.2,
}
assert observed["components"]["agent_wrapper"]["home_optimizer"] == {
"validation_cycle_time_budget_minutes": 150,
"max_evaluations": 10,
}
application.start.assert_awaited_once()
application.close.assert_awaited_once()
assert application.run_job.await_count == 1
assert application.run_job.call_args.args == ("home_prepare",)
assert result["workspace_dir"] == str(tmp_path / "experiment")
@pytest.mark.asyncio
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
async def test_runner_validates_and_passes_custom_sampling_policy(tmp_path, monkeypatch, benchmark):
"""Partial policies merge typed defaults and never leak into preparation inputs."""
module = import_module(f"benchmark.{benchmark}.run_home")
config = yaml.safe_load(module.DEFAULT_CONFIG.read_text())
config["sampling_policy"] = {"max_cases": 2, "max_queries": 7}
path = tmp_path / "home.yaml"
path.write_text(yaml.safe_dump(config))
application = AsyncMock()
application.run_job.return_value = Response(answer={})
observed = {}
def factory(**kwargs):
observed.update(kwargs)
return application
monkeypatch.setattr(module, "Application", factory)
await module.prepare(path)
policy = observed["components"]["home.evaluation"]["default"]["sampling_policy"]
assert policy["max_cases"] == 2 and policy["max_queries"] == 7 and policy["ewma_alpha"] == 0.3
assert "sampling_policy" not in application.run_job.call_args.kwargs["spec"]
for invalid in ({"max_cases": 0}, {"unknown": 1}, {"max_queries": "7"}):
config["sampling_policy"] = invalid
path.write_text(yaml.safe_dump(config))
with pytest.raises(ValueError):
await module.prepare(path)
assert application.start.await_count == 1
assert application.run_job.await_count == 1
assert application.run_job.call_args.args == ("home_prepare",)
@pytest.mark.asyncio
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
@pytest.mark.parametrize("budget", ["omitted", 45.5, None])
async def test_runner_passes_cycle_budget_to_optimizer(tmp_path, monkeypatch, benchmark, budget):
"""Both local runners apply the default, custom duration and explicit disable value."""
module = import_module(f"benchmark.{benchmark}.run_home")
config = yaml.safe_load(module.DEFAULT_CONFIG.read_text())
if budget == "omitted":
config.pop("validation_cycle_time_budget_minutes", None)
else:
config["validation_cycle_time_budget_minutes"] = budget
path = tmp_path / "home.yaml"
path.write_text(yaml.safe_dump(config))
application = AsyncMock()
application.run_job.return_value = Response(answer={})
observed = {}
def factory(**kwargs):
observed.update(kwargs)
return application
monkeypatch.setattr(module, "Application", factory)
await module.run(path)
expected = 150 if budget == "omitted" else budget
assert observed["components"]["agent_wrapper"]["home_optimizer"] == {
"validation_cycle_time_budget_minutes": expected,
"max_evaluations": 10,
}
assert "validation_cycle_time_budget_minutes" not in application.run_job.call_args.kwargs["spec"]
application.close.assert_awaited_once()
@pytest.mark.asyncio
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
@pytest.mark.parametrize("budget", [0, -1, True, "150", float("nan"), float("inf")])
async def test_runner_rejects_invalid_cycle_budget_before_start(tmp_path, monkeypatch, benchmark, budget):
"""Reject nonpositive, nonnumeric and nonfinite durations without creating an application."""
module = import_module(f"benchmark.{benchmark}.run_home")
config = yaml.safe_load(module.DEFAULT_CONFIG.read_text())
config["validation_cycle_time_budget_minutes"] = budget
path = tmp_path / "home.yaml"
path.write_text(yaml.safe_dump(config))
created = []
monkeypatch.setattr(module, "Application", lambda **kwargs: created.append(kwargs))
with pytest.raises(ValueError):
await module.run(path)
assert not created
@pytest.mark.asyncio
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
@pytest.mark.parametrize("failure", ["startup", "preparation"])
async def test_runner_propagates_failure_and_closes(monkeypatch, failure, benchmark):
"""A failed preparation is never printed or returned as success."""
application = AsyncMock()
if failure == "startup":
application.start.side_effect = RuntimeError("startup failed")
else:
application.run_job.return_value = Response(success=False, answer="already prepared")
module = import_module(f"benchmark.{benchmark}.run_home")
monkeypatch.setattr(module, "Application", lambda **kwargs: application)
with pytest.raises(RuntimeError):
await module.prepare(module.DEFAULT_CONFIG)
application.close.assert_awaited_once()
@pytest.mark.asyncio
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
@pytest.mark.parametrize("limit", ["omitted", 3, 0, -1, True, "10", 1.5, None])
async def test_runner_formal_budget_configuration(tmp_path, monkeypatch, benchmark, limit):
"""Validate host count budgets and pass them only to the optimizer wrapper."""
module = import_module(f"benchmark.{benchmark}.run_home")
config = yaml.safe_load(module.DEFAULT_CONFIG.read_text())
if limit == "omitted":
config.pop("max_evaluations", None)
else:
config["max_evaluations"] = limit
path = tmp_path / "home.yaml"
path.write_text(yaml.safe_dump(config))
application = AsyncMock()
application.run_job.return_value = Response(answer={})
observed = {}
def factory(**kwargs):
observed.update(kwargs)
return application
monkeypatch.setattr(module, "Application", factory)
if limit in ("omitted", 3):
await module.prepare(path)
assert observed["components"]["agent_wrapper"]["home_optimizer"]["max_evaluations"] == (
10 if limit == "omitted" else limit
)
assert "max_evaluations" not in application.run_job.call_args.kwargs["spec"]
else:
with pytest.raises(ValueError):
await module.prepare(path)
assert not observed
@pytest.mark.asyncio
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
@pytest.mark.parametrize("limit", ["omitted", None, 0, 1024, -1, True, "0", 1.5])
async def test_runner_sandbox_memory_policy(tmp_path, monkeypatch, benchmark, limit):
"""Keep zero explicit across every host sandbox and preserve platform defaults when unset."""
module = import_module(f"benchmark.{benchmark}.run_home")
config = yaml.safe_load(module.DEFAULT_CONFIG.read_text())
if limit == "omitted":
config.pop("memory_limit_mib", None)
else:
config["memory_limit_mib"] = limit
path = tmp_path / "home.yaml"
path.write_text(yaml.safe_dump(config))
application = AsyncMock()
application.run_job.return_value = Response(answer={})
observed = {}
def factory(**kwargs):
observed.update(kwargs)
return application
monkeypatch.setattr(module, "Application", factory)
if isinstance(limit, bool) or limit in (-1, "0", 1.5):
with pytest.raises(ValueError):
await module.optimize(path)
assert not observed
return
await module.optimize(path)
evaluation = observed["components"]["home.evaluation"]["default"]
if limit in ("omitted", None):
assert observed["jobs"] == {}
assert "candidate_gate_memory_limit_mib" not in evaluation
assert "construction_equivalence_memory_limit_mib" not in evaluation
else:
assert evaluation["candidate_gate_memory_limit_mib"] == limit
assert evaluation["construction_equivalence_memory_limit_mib"] == limit
defaults = yaml.safe_load((ROOT / "plugins/home/src/reme_home/plugin.yaml").read_text())[
"application_defaults"
]["jobs"]
assert set(observed["jobs"]) == {"home_optimize", "home_diagnose", "home_case_study"}
for name, job in observed["jobs"].items():
assert job["steps"] == [{**defaults[name]["steps"][0], "memory_limit_mib": limit}]
application.run_job.assert_awaited_once_with("home_optimize")
application.close.assert_awaited_once()
@pytest.mark.parametrize("module", [beam_runner, lme_runner])
def test_runner_rejects_old_budget_name(module):
"""Reject obsolete config keys instead of using the default budget."""
config = yaml.safe_load(module.DEFAULT_CONFIG.read_text())
config["max_validations"] = config.pop("max_evaluations")
with pytest.raises(ValueError):
module.RunHomeConfig.model_validate(config)
@pytest.mark.asyncio
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
@pytest.mark.parametrize("minutes", [30, None])
async def test_optimizer_lifecycle_uses_same_config_and_does_not_prepare(tmp_path, monkeypatch, benchmark, minutes):
"""A separate optimization launch consumes the same count, timer and sampling settings."""
module = import_module(f"benchmark.{benchmark}.run_home")
config = yaml.safe_load(module.DEFAULT_CONFIG.read_text())
config.update(max_evaluations=3, validation_cycle_time_budget_minutes=minutes)
path = tmp_path / "home.yaml"
path.write_text(yaml.safe_dump(config))
application = AsyncMock()
application.run_job.return_value = Response(answer={"status": "completed"})
observed = {}
def factory(**kwargs):
observed.update(kwargs)
return application
monkeypatch.setattr(module, "Application", factory)
result = await module.optimize(path, workspace_dir=str(tmp_path / "existing"), instruction="Improve retrieval")
assert result["status"] == "completed"
assert observed["components"]["agent_wrapper"]["home_optimizer"] == {
"max_evaluations": 3,
"validation_cycle_time_budget_minutes": minutes,
}
application.run_job.assert_awaited_once_with("home_optimize", instruction="Improve retrieval")
application.close.assert_awaited_once()
@pytest.mark.asyncio
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
async def test_optimizer_failure_closes_application(monkeypatch, benchmark):
"""Failed optimization retains the normal cleanup and error contract."""
module = import_module(f"benchmark.{benchmark}.run_home")
application = AsyncMock()
application.run_job.return_value = Response(success=False, answer="optimization failed")
monkeypatch.setattr(module, "Application", lambda **kwargs: application)
with pytest.raises(RuntimeError, match="optimization failed"):
await module.optimize()
application.run_job.assert_awaited_once_with("home_optimize")
application.close.assert_awaited_once()
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
def test_optimizer_cli_forwards_configuration_and_focus(tmp_path, monkeypatch, capsys, benchmark):
"""The explicit CLI mode reaches optimization and preserves the preparation default."""
module = import_module(f"benchmark.{benchmark}.run_home")
config = tmp_path / "home.yaml"
optimize = AsyncMock(return_value={"status": "completed"})
prepare = AsyncMock()
monkeypatch.setattr(module, "optimize", optimize)
monkeypatch.setattr(module, "prepare", prepare)
monkeypatch.setattr(
sys,
"argv",
[
"run_home.py",
"--optimize",
"--config",
str(config),
"--workspace-dir",
str(tmp_path / "existing"),
"--instruction",
"Improve retrieval",
],
)
module.main()
optimize.assert_awaited_once_with(
config,
workspace_dir=str(tmp_path / "existing"),
instruction="Improve retrieval",
)
prepare.assert_not_called()
assert json.loads(capsys.readouterr().out) == {"status": "completed"}
@pytest.mark.parametrize("benchmark", ["beam", "longmemeval"])
def test_cli_rejects_optimization_focus_in_preparation_mode(monkeypatch, benchmark):
"""Do not silently discard an instruction when the caller forgot --optimize."""
module = import_module(f"benchmark.{benchmark}.run_home")
monkeypatch.setattr(sys, "argv", ["run_home.py", "--instruction", "Improve retrieval"])
with pytest.raises(SystemExit) as error:
module.main()
assert error.value.code == 2