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

349 lines
14 KiB
Python

"""Test optimizer cycle timing with fake clocks and isolated evaluation evidence."""
# pylint: disable=missing-function-docstring,missing-class-docstring,protected-access
# pylint: disable=redefined-outer-name,unused-argument
import asyncio
import copy
from types import SimpleNamespace
import pytest
from agentscope.agent import ModelConfig, ReActConfig
from agentscope.message import HintBlock, TextBlock, UserMsg
from agentscope.model import ChatResponse, ChatUsage
from agentscope.state import AgentState
from reme_home.agent import optimizer
from reme_home.agent.bounded import BoundedReActAgent
from reme_home.evaluation.artifacts import write_json
from reme_home.evaluation.history import rebuild_sampling_state
from test_bounded_agent import RecordingModel
@pytest.fixture(autouse=True)
def candidate_checkout(monkeypatch):
monkeypatch.setattr(
optimizer,
"evaluation_checkout",
lambda _home: {"sampling": True, "expected_commit": "candidate-sha", "expected_branch": "candidate"},
)
def make_agent(timer, model=None):
return optimizer.OptimizerAgent(
name="optimizer",
system_prompt="Improve general memory mechanisms.",
model=model or RecordingModel(),
validation_cycle_timer=timer,
model_config=ModelConfig(max_retries=0),
react_config=ReActConfig(max_iters=100),
)
def cycle_hints(messages, source="meta_reme_validation_timer"):
return [
block
for message in messages
for block in message.content
if isinstance(block, HintBlock) and block.source == source
]
@pytest.mark.asyncio
@pytest.mark.parametrize("debug", [False, True])
async def test_evaluation_tool_forwards_formal_targets_and_ignores_debug_targets(tmp_path, debug):
write_history(tmp_path, [])
calls = []
class EvaluationJob:
enabled = is_started = True
async def __call__(self, **kwargs):
calls.append(kwargs)
return SimpleNamespace(
success=False,
answer={"status": "rejected", "paired_comparisons": {"path": "private-until-selection"}},
metadata={},
)
wrapper = SimpleNamespace(app_context=SimpleNamespace(jobs={"home_evaluate": EvaluationJob()}))
tool = optimizer.evaluation_tool(wrapper, {}, home=tmp_path)
targets = {"1": [], "2": None, "3": ["fact:1"]}
result = await tool._func(debug=debug, target_queries=targets, _agent_state=AgentState())
assert "paired_comparisons" not in result["answer"]
assert ("target_queries" in calls[0]) is not debug
if not debug:
assert calls[0]["target_queries"] == targets
assert calls[0]["sampling"] is True
assert calls[0]["expected_commit"] == "candidate-sha"
assert calls[0]["expected_branch"] == "candidate"
else:
assert "expected_commit" not in calls[0] and "expected_branch" not in calls[0]
@pytest.mark.asyncio
async def test_early_selection_reveals_guidance_and_stops_timer():
timer = optimizer.ValidationCycleTimer(10)
hint = await optimizer.final_selection_tool(timer)._func()
assert hint == optimizer.FINAL_SELECTION_HINT
assert "home_compare_validations" in hint
assert "historical finalists" in hint
assert timer.next_reminder() is None
assert hint in optimizer.VALIDATION_BUDGET_EXHAUSTED_HINT
@pytest.mark.parametrize("budget", [True, 0, -1, float("nan"), float("inf"), "10"])
def test_cycle_rejects_invalid_budget(budget):
with pytest.raises(ValueError, match="positive"):
optimizer.ValidationCycleTimer(budget)
@pytest.mark.asyncio
async def test_cycle_injects_dev_meta_reminders_and_resets():
now = [0.0]
timer = optimizer.ValidationCycleTimer(100, clock=lambda: now[0])
class SnapshotModel(RecordingModel):
async def __call__(self, **kwargs):
return await super().__call__(**copy.deepcopy(kwargs))
agent = make_agent(timer, SnapshotModel())
timer.record_context_compression()
timer.record_context_compression()
delivered = []
for minute in (49, 50, 74, 75, 90, 100, 109, 110, 120):
now[0] = minute * 60
_ = [item async for item in agent._reasoning()]
reminders = [block.hint for block in cycle_hints(agent.model.calls[-1]["messages"])]
if minute in (50, 75, 90, 100, 110, 120):
delivered.append(reminders[-1])
assert timer.next_reminder() is None
for percentage, text in zip((50, 75, 90, 100, 110, 120), delivered):
assert f"({percentage}% of its 100 minutes soft time budget)" in text
assert "2 context compressions since the last scored validation" in text
assert "start validation within 50 minutes" in delivered[0]
assert "start validation within 10 minutes" in delivered[2]
assert "starting validation as soon as possible" in delivered[3]
persistent = cycle_hints(agent.state.context)
assert len(persistent) == 3
for percentage, message in zip((75, 100, 120), persistent):
assert f"({percentage}%" in message.hint
timer.reset()
assert timer.context_compression_count == 0
now[0] += 60
assert timer.next_reminder() is None
# Reset keeps historical persistent messages and restarts alternation.
assert cycle_hints(agent.state.context) == persistent
now[0] = 170 * 60
assert timer.next_reminder().persistent is False
def test_cycle_skips_old_thresholds_and_formats_seconds():
now = [0.0]
timer = optimizer.ValidationCycleTimer(1, clock=lambda: now[0])
now[0] = 59
reminder = timer.next_reminder()
assert "(90%" in reminder.content
assert "within 1 second." in reminder.content
now[0] = 101
assert "(160%" in timer.next_reminder().content
assert timer.next_reminder() is None
@pytest.mark.asyncio
@pytest.mark.parametrize("failure", [RuntimeError("model unavailable"), asyncio.CancelledError()])
async def test_cycle_ephemeral_cleanup_on_error_and_cancellation(monkeypatch, failure):
now = [0.0]
timer = optimizer.ValidationCycleTimer(1, clock=lambda: now[0])
agent = make_agent(timer)
async def fail(*args, **kwargs):
raise failure
yield # pylint: disable=unreachable
monkeypatch.setattr(BoundedReActAgent, "_reasoning", fail)
now[0] = 30
with pytest.raises(type(failure)):
_ = [item async for item in agent._reasoning()]
assert not cycle_hints(agent.state.context)
now[0] = 45
with pytest.raises(type(failure)):
_ = [item async for item in agent._reasoning()]
assert len(cycle_hints(agent.state.context)) == 1 # The second reminder is persistent.
@pytest.mark.asyncio
async def test_cycle_counts_only_completed_context_replacements(monkeypatch):
timer = optimizer.ValidationCycleTimer(1)
agent = make_agent(timer)
async def unchanged(self):
pass
monkeypatch.setattr(BoundedReActAgent, "compress_context", unchanged)
await agent.compress_context()
assert timer.context_compression_count == 0
async def compressed(self):
self.state.summary = "Retained previous evidence."
self.state.context = []
monkeypatch.setattr(BoundedReActAgent, "compress_context", compressed)
await agent.compress_context()
assert timer.context_compression_count == 1
async def failed(self):
raise RuntimeError("compression unavailable")
monkeypatch.setattr(BoundedReActAgent, "compress_context", failed)
with pytest.raises(RuntimeError, match="unavailable"):
await agent.compress_context()
assert timer.context_compression_count == 1
def write_history(home, started):
# Started plans are durable evidence; state.json is only a rebuildable cache.
for index, key in enumerate(started, 1):
write_json(
home / "sampling/plans" / f"{key}.json",
{
"round": index,
"validation_key": key,
"sandbox_started_at": "2026-10-31T00:00:00Z",
},
)
rebuild_sampling_state(home)
@pytest.mark.asyncio
@pytest.mark.parametrize("timed", [False, True])
@pytest.mark.parametrize(
"outcome,reset",
[
("completed", True),
("success", True),
("candidate_failure", True),
("completed_infra_error", True),
("debug", False),
("rejected", False),
("failed", False),
("partial", False),
("not_started", False),
("preexisting", False),
("cancelled", False),
],
)
async def test_evaluation_reset_boundary_matches_dev_meta(tmp_path, outcome, reset, timed):
home = tmp_path
previous = ["init/initial/1", "candidate/previous/1"]
key = "candidate/current/1"
if outcome == "preexisting":
previous.append(key)
write_history(home, previous)
now = [0.0]
timer = optimizer.ValidationCycleTimer(1, clock=lambda: now[0])
timer.record_context_compression()
now[0] = 45
timer.next_reminder() # First reminder is ephemeral.
state = AgentState()
old = UserMsg(name="meta_reme_validation_timer", content="Previous persistent reminder.")
state.context.append(old)
class EvaluationJob:
enabled = is_started = True
async def __call__(self, **kwargs):
assert kwargs["debug"] is (outcome == "debug")
# Tool execution time remains part of the previous cycle until completion.
now[0] = 90
if outcome == "cancelled":
raise asyncio.CancelledError()
if outcome not in {"debug", "rejected", "not_started", "preexisting"}:
write_history(home, [*previous, key])
manifest = {
"commit_sha": "1b2cdcc" + "0" * 33,
"status": "failed" if outcome in {"failed", "partial"} else "completed",
"mode": "debug" if outcome == "debug" else "scored",
"dataset_kind": "training-set",
"sandbox_started_at": None if outcome == "not_started" else "2026-10-31T00:00:00Z",
}
run = home / "evaluations" / key
write_json(run / "manifest.json", manifest)
status = outcome if outcome in {"success", "rejected", "failed", "partial"} else "completed"
return SimpleNamespace(
success=outcome not in {"completed_infra_error", "rejected", "failed", "partial"},
answer={"status": status, "result_dir": str(run), "mean_query_score": 0.0},
metadata={},
)
wrapper = SimpleNamespace(app_context=SimpleNamespace(jobs={"home_evaluate": EvaluationJob()}))
tool = optimizer.evaluation_tool(wrapper, {}, home=home, timer=timer if timed else None)
assert set(tool.input_schema["properties"]) == {"debug", "target_queries"}
if outcome == "cancelled":
with pytest.raises(asyncio.CancelledError):
await tool._func(debug=False, _agent_state=state)
else:
await tool._func(debug=outcome == "debug", _agent_state=state)
assert len(state.context) == 1 # The tool cannot insert anything before its result is written.
pending = state.middle_context.get(optimizer.PENDING_CYCLE_TRANSITIONS, [])
assert len(pending) == int(reset)
agent = make_agent(None)
agent.state = state
_ = [item async for item in agent._reasoning()]
transitions = cycle_hints(state.context, "meta_reme_validation_cycle_transition")
assert len(transitions) == int(reset)
assert state.context[0] is old
if reset:
assert transitions[0].hint == (
"<system-reminder>Formal validation 2 completed successfully for commit 1b2cdcc. "
"The previous cycle timer has been reset, and all timer reminders for cycle 2 are now expired. "
"Remaining formal validations: 8. Start cycle 3.</system-reminder>"
)
if reset and timed:
assert timer.context_compression_count == 0
assert timer.next_reminder() is None
now[0] += 30
assert timer.next_reminder().persistent is False
else:
assert timer.context_compression_count == 1
assert "(150%" in timer.next_reminder().content
def test_wrapper_owns_fresh_cycle_timers_and_supports_disabling():
wrapper = optimizer.OptimizerAgentWrapper(name="optimizer", validation_cycle_time_budget_minutes=150)
first, second = wrapper.create_cycle_timer(), wrapper.create_cycle_timer()
assert first is not second
assert first.time_budget_minutes == 150
first.record_context_compression()
assert second.context_compression_count == 0
assert wrapper.create_cycle_timer({"validation_cycle_time_budget_minutes": None}) is None
legacy = optimizer.OptimizerAgentWrapper(name="optimizer", time_budget_minutes=75)
assert legacy.create_cycle_timer().time_budget_minutes == 75
assert legacy.create_cycle_timer({"validation_cycle_time_budget_minutes": 30}).time_budget_minutes == 30
@pytest.mark.asyncio
async def test_temporary_and_persistent_reminders_preserve_total_reply_usage():
now = [0.0]
class AdvancingModel(RecordingModel):
async def __call__(self, **kwargs):
result = await super().__call__(**kwargs)
now[0] = 30 if len(self.calls) == 1 else 45
return result
model = AdvancingModel(
final=ChatResponse(
content=[TextBlock(text="final report")],
is_last=True,
usage=ChatUsage(input_tokens=2, output_tokens=3, time=0),
),
)
agent = make_agent(optimizer.ValidationCycleTimer(1, clock=lambda: now[0]), model)
agent.react_config.max_iters = 2
reply = await agent.reply(UserMsg(name="user", content="Investigate"))
assert len(model.calls) == 3
assert reply.usage.input_tokens == 6
assert reply.usage.output_tokens == 9
retained = cycle_hints(agent.state.context)
assert len(retained) == 1
assert "(75%" in retained[0].hint