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

242 lines
9.3 KiB
Python

"""Compression recovery parity with dev_meta, without model or filesystem services."""
# pylint: disable=missing-function-docstring,missing-class-docstring,protected-access
# pylint: disable=redefined-outer-name,unused-argument
import asyncio
import json
from agentscope.agent import Agent, ContextConfig
from agentscope.exception import StructuredOutputError
from agentscope.message import AssistantMsg, TextBlock, UserMsg, Usage
from agentscope.state import AgentState
import jsonschema
import openai
import pytest
from reme_home.agent import compression, optimizer
class FailingCompressionModel:
def __init__(self, ratio=0.9, failure=None):
self.context_size = 90 / ratio
self.failure = failure or RuntimeError("Failed to generate structured output for model.")
self.calls = 0
async def count_tokens(self, messages, tools=None):
return sum(10 for message in messages if (message.get_text_content() or "").startswith("message-"))
async def generate_structured_output(self, **kwargs):
self.calls += 1
raise self.failure
def make_agent(tmp_path, ratio=0.9, trigger=0.8, failure=None, summary="existing summary"):
return optimizer.OptimizerAgent(
name="optimizer",
system_prompt="system",
model=FailingCompressionModel(ratio, failure),
state=AgentState(
summary=summary,
context=[UserMsg(name="user", content=f"message-{index}") for index in range(9)],
),
context_config=ContextConfig(trigger_ratio=trigger, reserve_ratio=0.2),
fallback_directory=tmp_path / "offloads",
validation_cycle_timer=optimizer.ValidationCycleTimer(150),
)
@pytest.mark.asyncio
@pytest.mark.parametrize("failure_type", [RuntimeError, StructuredOutputError])
@pytest.mark.parametrize(
("trigger", "ratio", "expected"),
[(0.8, 0.79, False), (0.8, 0.85, False), (0.8, 0.9, True), (0.65, 0.82, False), (0.65, 0.825, True)],
)
async def test_real_compression_failure_uses_dev_meta_emergency_threshold(
tmp_path,
trigger,
ratio,
expected,
failure_type,
):
agent = make_agent(tmp_path, ratio, trigger, failure=failure_type("Invalid structured output"))
context_before, summary_before = agent.state.context, agent.state.summary
await agent.compress_context()
assert agent.validation_cycle_timer.context_compression_count == int(expected)
assert len(list(tmp_path.rglob("context-*.json"))) == int(expected)
assert agent.model.calls == int(ratio >= trigger)
assert agent.context_config.compression_fallback_to_truncation # The shared config was not mutated.
if not expected:
assert agent.state.context is context_before
assert agent.state.summary is summary_before
@pytest.mark.asyncio
@pytest.mark.parametrize("failure_type", [RuntimeError, StructuredOutputError])
@pytest.mark.parametrize("summary", ["existing summary", [TextBlock(text="existing summary")]])
@pytest.mark.parametrize("reserve_ratio", [0.2, 0])
async def test_offload_retains_full_messages_summary_usage_and_recent_context(
tmp_path,
summary,
reserve_ratio,
failure_type,
):
agent = make_agent(tmp_path, summary=summary, failure=failure_type("Invalid structured output"))
agent.context_config.reserve_ratio = reserve_ratio
agent.state.context[-1] = AssistantMsg(
id=agent.state.reply_id,
name=agent.name,
content="message-8",
usage=Usage(input_tokens=100, output_tokens=10),
)
original = [msg.model_dump(mode="json", exclude_none=False) for msg in agent.state.context]
await agent.compress_context()
(path,) = tmp_path.rglob("context-*.json")
data = json.loads(path.read_text())
assert data["messages"] == original[:7] if reserve_ratio else data["messages"] == original
if reserve_ratio:
assert [msg.get_text_content() for msg in agent.state.context] == ["message-7", "message-8"]
else:
assert len(agent.state.context) == 1
assert agent.state.context[0].content == [] # SDK usage carrier after full offload.
assert data["session_id"] == agent.state.session_id
assert data["context_ratio"] == 0.9
assert data["emergency_ratio"] == 0.9
assert data["failure"]["type"] == failure_type.__name__
text = agent.state.summary
if isinstance(text, list):
text = "\n".join(block.text for block in text)
assert "existing summary" in text
assert "without semantic summarization" in text
assert str(path) in text
assert agent._get_reply_usage().input_tokens == 100
assert not list(path.parent.glob(".result-*"))
@pytest.mark.asyncio
@pytest.mark.parametrize(
"failure",
[RuntimeError("The system prompt exceeds threshold"), ValueError("bad configuration"), asyncio.CancelledError()],
)
async def test_unrecoverable_failures_and_cancellation_propagate(tmp_path, failure):
agent = make_agent(tmp_path, failure=failure)
original = agent.state.context
with pytest.raises(type(failure)):
await agent.compress_context()
assert agent.state.context is original
assert not list(tmp_path.rglob("*.json"))
assert agent.validation_cycle_timer.context_compression_count == 0
@pytest.mark.parametrize(
("failure", "expected"),
[
(RuntimeError("provider failed"), True),
(StructuredOutputError("invalid summary"), True),
(RuntimeError("The system prompt exceeds threshold"), False),
(jsonschema.ValidationError("invalid summary"), True),
(openai.OpenAIError("provider unavailable"), True),
(ValueError("programming error"), False),
(OSError("disk full"), False),
],
)
def test_recoverable_error_classifier(failure, expected):
assert compression.RecoverableCompressionAgent._is_recoverable_compression_error(failure) is expected
@pytest.mark.asyncio
async def test_override_config_and_successful_compression_use_native_pipeline(tmp_path, monkeypatch):
agent = make_agent(tmp_path, ratio=0.85)
config = ContextConfig(trigger_ratio=0.65, reserve_ratio=0.1)
calls = []
async def compress(self, context_config=None, instructions=None):
calls.append((context_config, instructions))
self.state.summary = "semantic summary"
self.state.context = []
monkeypatch.setattr(Agent, "_compress_context_impl", compress)
await agent.compress_context(context_config=config)
assert calls[0][0].trigger_ratio == 0.65
assert calls[0][0].reserve_ratio == 0.1
assert not calls[0][0].compression_fallback_to_truncation
assert config.compression_fallback_to_truncation
assert agent.state.summary == "semantic summary"
assert agent.validation_cycle_timer.context_compression_count == 1
assert not list(tmp_path.rglob("*.json"))
@pytest.mark.asyncio
async def test_offload_write_failure_keeps_context_and_does_not_count(tmp_path, monkeypatch):
agent = make_agent(tmp_path)
original = agent.state.context
def fail(*args, **kwargs):
raise OSError("disk full")
monkeypatch.setattr(compression, "write_json", fail)
with pytest.raises(OSError, match="disk full"):
await agent.compress_context()
assert agent.state.context is original
assert agent.state.summary == "existing summary"
assert agent.validation_cycle_timer.context_compression_count == 0
@pytest.mark.asyncio
@pytest.mark.parametrize("cancellations", [1, 3])
async def test_cancellation_during_apply_finishes_consistent_offload_then_propagates(
tmp_path,
monkeypatch,
cancellations,
):
agent = make_agent(tmp_path)
started, release = asyncio.Event(), asyncio.Event()
async def clear_cache(messages):
started.set()
await release.wait()
monkeypatch.setattr(agent, "_clear_unreserved_read_cache", clear_cache)
task = asyncio.create_task(agent.compress_context())
try:
await asyncio.wait_for(started.wait(), 5)
for index in range(cancellations):
task.cancel(f"cancellation-{index}")
await asyncio.sleep(0)
assert not task.done()
release.set()
with pytest.raises(asyncio.CancelledError, match="cancellation-0"):
await task
finally:
release.set()
await asyncio.gather(task, return_exceptions=True)
assert len(list(tmp_path.rglob("context-*.json"))) == 1
assert "offloaded" in agent.state.summary
assert len(agent.state.context) == 2
@pytest.mark.asyncio
async def test_missing_directory_or_unsplittable_context_fails_explicitly(tmp_path, monkeypatch):
agent = make_agent(tmp_path)
agent.fallback_directory = None
with pytest.raises(RuntimeError, match="fallback_directory"):
await agent.compress_context()
agent.fallback_directory = tmp_path / "offloads"
async def no_old_messages(*args):
return [], agent.state.context
monkeypatch.setattr(agent, "_split_context_for_compression", no_old_messages)
with pytest.raises(RuntimeError, match="cannot remove any context"):
await agent.compress_context()
assert not list(tmp_path.rglob("*.json"))
def test_wrapper_uses_host_offload_directory(tmp_path):
wrapper = optimizer.OptimizerAgentWrapper(name="optimizer")
agent = wrapper._create_agent(
options={"_context_fallback_directory": tmp_path / "logs/context-offloads"},
name="optimizer",
system_prompt="system",
model=FailingCompressionModel(),
)
assert agent.fallback_directory == tmp_path / "logs/context-offloads"