mirror of
https://github.com/agentscope-ai/ReMe.git
synced 2026-11-27 23:58:47 +00:00
* Add sandboxed Python execution and home AutoBash plugin * Harden read-only shell commands and filesystem sandboxes * Group file sandbox backends in one package * Fix macOS file sandbox isolation and runtime access * Refine file sandbox limits and executor checks * Harden AutoBash policy and macOS sandbox supervision * fix(home): require ReMe release with file sandbox * refactor(home): simplify sandbox calls and redundant tests * fix(execution): bound output and clean up cancelled sandbox startup * fix(tests): mock Seatbelt platform requirements on Linux * fix(home): block Git help helpers and harden sandbox cleanup * Fix sandbox runtime links and subprocess cleanup * ci: cover Home plugin tests * test: wait for pipeline descendants to exit after cancellation * fix: align Home dependencies and preserve cleanup cancellation Require ReMe 0.4.2.1 and verify isolated Home wheel installation in package CI. Share cancellation-safe cleanup with thread calls, retain AnyIO cancellation semantics, and record Bubblewrap mount targets during argument construction. * feat(home): prepare self-evolution workspaces and benchmark inputs * fix(home): load only selected cases for debug derivation * feat(home): evaluate candidates with benchmark judges and prepare workspace docs * refactor(home): organize workflows and unify debug evaluation mode * fix(home): align Docker runtime and preserve evaluation failures * refactor(home): align evaluation summaries with dev_meta * feat(home): migrate agent, sampling and evidence inspection tooling * feat(home): add case-study agent and query evidence tracing tools - Add home_case_study job with CaseStudyAgentWrapper and a read-only sandboxed investigation step for per-case diagnostic reports - Add home_trace_query_evidence job/step to locate a query's source evidence sessions, memory checkpoints and answer/score previews - Compact evaluation summaries: record per-query failure errors, round scores to four decimals, expose scoring_enabled and observed means - Slim run manifests: drop schema_version and trusted_judge fingerprint, exclude debug/sampling_policy options, keep construction_source only for query-only replay - Simplify history index internals and update guide docs and tests * feat(home): support multi-case case-study runs with dedicated LLM and Git sandbox - Allow home_case_study to investigate up to eight ordered cases per invocation with a shared focus, one isolated agent per case, while keeping the legacy single-case selector as a deprecated alias - Configure a dedicated home_case_study LLM component instead of the shared judge backend - Wrap ReMe's OS file sandbox with a Home-specific Git runtime grant (developer directory on macOS) and argv-based child environment - Tighten case-study prompts around evidence certainty, code-tool path scoping, citation form, and unresolved-cause reporting - Extend evidence tracing and expand case-study/sandbox tests and docs * feat(home): run case studies with bounded concurrency and fix sandbox test * feat(home): guard repeated evaluations and preserve retry selections * feat(home): migrate optimization workflows and evaluation budgets * feat(home): add candidate admission gate and construction-equivalence replay Add host-side candidate gate agent that reviews committed changes before sampling, and construction-equivalence agent that compares a candidate against its nearest reusable ancestor to select query-only replay with 60% probability when construction is unchanged. Wire both into plugin.yaml application defaults, update optimizer prompt to explain the new host behaviors, extend snapshot/evaluation components with reuse support, and add focused tests. * feat(home): add structured-report agent and gate/equivalence test coverage Add StructuredReportAgent wrapper selectable via the _structured_report_model option in BoundedAgentWrapper, plus its dedicated unit tests. Extend candidate gate, construction equivalence, evaluation history, sampling, and validation budget tests, and document the new behavior in the plugin README. * feat(home): add standalone benchmark test evaluation and fix compression recovery * fix(home): preserve top-level answer failure classification * refactor(home): rename max_validations to max_evaluations * refactor(home): extract shared review_report workflow helper and bump version to 0.4.2.2 * fix(home): load runner credentials and localize dataset evaluation * fix(benchmark): propagate Home sandbox memory limits * refactor(home): consolidate Git exports and candidate validation * fix(home): clarify branch and diff tool parameter contracts * feat(home): bound case-study reports and migrate draft tools * fix(home): align benchmark report limits with plugin defaults * Fix Home evaluation recovery and cancellation boundaries * fix(home): tolerate fenced optimizer results and finalize exhausted budgets * fix(benchmark): align Docker runtime with AgentScope 2.0.11 * fix(home): unify history writes and cancellation cleanup * refactor(home): reuse structured report parsing * ci: remove redundant Home compatibility install check * fix(home): preserve literal formatting in structured reports * fix(home): continue optimization after baseline question errors * fix(sandbox): require explicit file write grants * test(home): verify host network isolation with connection probes * fix(sandbox): write to the validated canonical target * refactor(home): simplify optimizer evidence validation * feat(home): add targeted evaluation and controlled memory replay Expose optional case/question targets with bounded sampling and ignored invalid IDs. Reuse reviewed memory per case, preserve paired replay without targets, and sample every direct child of init. Restore the persistent optimizer overview and document optional targeted checks. Add regression coverage for selection, partial reuse, provenance, and frozen retries. * feat(home): preserve evaluated commits and compare validation evidence Add compact paired score and token comparisons, protected evaluated branches, and unique commit-prefix selection. Reveal comparison guidance during final selection and update optimizer tools, documentation, and regression tests. * feat(home): expand debug cases and diversify smoke questions * feat(home): prioritize reusable memory in targeted evaluation * fix(ci): limit coverage collection to repository sources * chore(home): remove legacy Meta-ReMe references * fix(home): harden evaluation and bound targeted reuse Normalize benchmark inputs while preserving standalone judge contracts. Protect initial baselines and completed evaluations, and scope targeted memory reuse to the selected sample. Simplify HoMe usage and agent documentation. * docs(home): explain how to use custom datasets * fix(home): validate explicit replay artifacts before sampling * fix(home): validate replay inputs before selection * fix(home): pin candidate admission and compact replay metadata * fix(home): address evaluation and preparation review findings Select baseline retries by attempt order and keep archive preflight outside the workspace lock. Base candidate admission on usable budgeted ancestors and validate normalized dataset IDs before publishing preparation. * docs(home): consolidate benchmark experiment guides Document the shared HoMe workflow and keep dataset setup, splits, and results in the BEAM and LongMemEval guides. * fix(home): resolve release and evaluation review findings Validate artifact IDs against the published runtime contract, cover the minimum ReMe wheel and Docker backend in CI, and keep sampling budgets and observations consistent when evaluation results are archived or restored. * test(home): seed durable validation history in optimizer fixtures * fix(ci): align Home wheel smoke test with minimum ReMe release * fix(ci): resolve unreleased minimum runtime from built wheels * fix(home): enforce full init baselines and retain replay evidence * docs: reorganize bilingual BEAM and LME benchmark guides * fix(home): bind optimizer sampling to the evaluated checkout * Validate retained replay configuration and pin explicit snapshots * docs(home): clarify final replay validation requirements --------- Co-authored-by: jinli.yl <jinli.yl@alibaba-inc.com>
289 lines
12 KiB
Python
289 lines
12 KiB
Python
"""Compact evidence tracing against real, isolated evaluation and Git artifacts."""
|
|
|
|
# pylint: disable=missing-function-docstring,redefined-outer-name,unused-argument,protected-access
|
|
|
|
import json
|
|
import shutil
|
|
|
|
import pytest
|
|
from pydantic import ValidationError
|
|
from reme_home.evaluation import evidence_step as evidence_tools
|
|
from reme_home.evaluation.artifacts import write_json
|
|
from reme_home.preparation.code import git
|
|
|
|
from test_memory_inspection import ( # noqa: F401 # pylint: disable=unused-import
|
|
FakeFactory,
|
|
commit,
|
|
evidence,
|
|
home_application,
|
|
preparation_inputs,
|
|
prepared_home,
|
|
)
|
|
from test_evaluation_inspection import call, snapshot, write_run
|
|
|
|
|
|
@pytest.fixture
|
|
def query_evidence(evidence): # noqa: F811
|
|
home, run, repo, first, second = evidence
|
|
manifest = json.loads((run / "manifest.json").read_text())
|
|
manifest["query_ids"] = {"case1": ["q1"]}
|
|
write_json(run / "manifest.json", manifest)
|
|
case = {
|
|
"case_id": "case1",
|
|
"sessions": [{"session_id": "session1", "messages": [{"content": "source transcript"}]}],
|
|
"queries": [
|
|
{
|
|
"query_id": "q1",
|
|
"question": "What is the fact?",
|
|
"groundtruth": {"golden_answer": "old fact", "rubric": []},
|
|
"metadata": {"evidence_session_ids": ["session1", "session1"], "evidence_is_certain": False},
|
|
},
|
|
],
|
|
}
|
|
source = home / "datasets/training-set/cases/000000.json"
|
|
write_json(source, case)
|
|
write_json(
|
|
run / "cases/case1/queries/result.json",
|
|
{"queries": [{"query_id": "q1", "answer": "new fact", "score": 0, "judge_result": {"large": "hidden"}}]},
|
|
)
|
|
return home, run, repo, first, second, source, case
|
|
|
|
|
|
def trace(home, run, **kwargs):
|
|
spec = evidence_tools.TraceQueryEvidenceInput(validation_path=str(run), case_id="case1", query_id="q1", **kwargs)
|
|
return evidence_tools.trace_query_evidence(home, spec)
|
|
|
|
|
|
def test_compact_annotation_root_checkpoint_and_read_only(query_evidence):
|
|
home, run, repo, first, _second, source, _case = query_evidence
|
|
(repo / "memory/note.md").write_text("dirty ignored")
|
|
before = snapshot(home)
|
|
# Independent annotations take precedence, even over nonexistent inferred IDs.
|
|
result = trace(home, run, evidence_session_ids=["unknown"])
|
|
assert result["query"] == {
|
|
"question": "What is the fact?",
|
|
"expected": "old fact",
|
|
"expected_kind": "reference_answer",
|
|
"actual": "new fact",
|
|
"score": 0,
|
|
"error": None,
|
|
"result_missing": False,
|
|
}
|
|
assert result["evidence_source"] == "independent_annotation"
|
|
assert result["evidence_is_certain"] is False and result["memory_status"] == "available"
|
|
assert result["sessions"] == [
|
|
{
|
|
"id": "session1",
|
|
"source_pointer": "/sessions/0",
|
|
"checkpoint": first,
|
|
"changed_files": ["memory/note.md", "removed.txt"],
|
|
},
|
|
]
|
|
assert result["paths"]["source_case"] == str(source)
|
|
assert result["paths"]["memory_repository"] == str(repo)
|
|
assert result["locations"] == {"source_query": "/queries/0", "saved_query": "/queries/0"}
|
|
assert "criteria" not in result
|
|
assert "source transcript" not in json.dumps(result) and "judge_result" not in json.dumps(result)
|
|
assert snapshot(home) == before
|
|
|
|
|
|
def test_inference_missing_checkpoint_and_debug_dataset(query_evidence):
|
|
home, run, _repo, _first, second, source, case = query_evidence
|
|
case["sessions"] += [{"session_id": "session2"}, {"session_id": "not-constructed"}]
|
|
case["queries"][0]["metadata"] = {}
|
|
debug_source = home / "datasets/debug-cases/cases/000001.json"
|
|
write_json(debug_source, case)
|
|
source.unlink()
|
|
manifest = json.loads((run / "manifest.json").read_text())
|
|
manifest["dataset_kind"] = "debug-cases"
|
|
write_json(run / "manifest.json", manifest)
|
|
result = trace(home, run, evidence_session_ids=["session2", "not-constructed", "session2"])
|
|
assert result["evidence_source"] == "diagnostician_inference"
|
|
assert result["paths"]["source_case"] == str(debug_source)
|
|
assert result["sessions"][0]["checkpoint"] == second
|
|
assert result["sessions"][0]["changed_files"] == ["added.bin", "memory/note.md", "removed.txt"]
|
|
assert result["sessions"][1] == {
|
|
"id": "not-constructed",
|
|
"source_pointer": "/sessions/2",
|
|
"checkpoint": None,
|
|
"changed_files": [],
|
|
}
|
|
assert trace(home, run)["evidence_source"] == "unavailable"
|
|
with pytest.raises(ValueError, match="not present"):
|
|
trace(home, run, evidence_session_ids=["unknown"])
|
|
|
|
|
|
@pytest.mark.parametrize("annotation", [[], [""], "session1", [123]])
|
|
def test_empty_and_invalid_annotations(query_evidence, annotation):
|
|
home, run, _repo, _first, _second, source, case = query_evidence
|
|
case["queries"][0]["metadata"]["evidence_session_ids"] = annotation
|
|
write_json(source, case)
|
|
if not annotation:
|
|
result = trace(home, run, evidence_session_ids=["session1"])
|
|
assert not result["sessions"] and result["evidence_source"] == "independent_annotation"
|
|
else:
|
|
with pytest.raises(ValidationError):
|
|
trace(home, run)
|
|
|
|
|
|
@pytest.mark.parametrize("state", ["workspace_missing", "history_missing", "history_empty"])
|
|
def test_missing_history_and_results(query_evidence, state):
|
|
home, run, repo, _first, _second, _source, _case = query_evidence
|
|
shutil.rmtree(repo if state == "workspace_missing" else repo / ".git")
|
|
if state == "history_empty":
|
|
git(repo, "init")
|
|
(run / "cases/case1/queries/result.json").unlink()
|
|
result = trace(home, run)
|
|
assert result["memory_status"] == state and result["sessions"][0]["checkpoint"] is None
|
|
assert result["locations"]["saved_query"] is None and "criteria" not in result
|
|
assert result["query"]["result_missing"] and result["query"]["score"] is None
|
|
assert result["query"]["actual"] is None and result["query"]["expected"] == "old fact"
|
|
|
|
|
|
def test_large_fields_and_lists_are_bounded(query_evidence):
|
|
home, run, repo, _first, _second, source, case = query_evidence
|
|
for index in range(55):
|
|
(repo / f"file-{index:03}").write_text("fact")
|
|
checkpoint = commit(repo, "session: session1")
|
|
case["sessions"] = [{"session_id": f"s{index}"} for index in range(55)] + case["sessions"]
|
|
case["queries"][0]["metadata"]["evidence_session_ids"] = ["session1"] + [f"s{i}" for i in range(55)]
|
|
case["queries"][0]["question"] = "x" * 100_000
|
|
write_json(source, case)
|
|
result = trace(home, run)
|
|
assert len(result["sessions"]) == 50 and result["omitted_session_count"] == 6
|
|
assert result["sessions"][0]["checkpoint"] == checkpoint
|
|
assert len(result["sessions"][0]["changed_files"]) == 50
|
|
assert result["sessions"][0]["omitted_changed_file_count"] == 5
|
|
assert len(result["query"]["question"]) < 2100
|
|
assert len(json.dumps(result)) < 15_000
|
|
|
|
|
|
def test_reject_unselected_queries_and_external_sources(query_evidence, tmp_path):
|
|
home, run, _repo, _first, _second, source, _case = query_evidence
|
|
manifest = json.loads((run / "manifest.json").read_text())
|
|
manifest["query_ids"] = {"case1": []}
|
|
write_json(run / "manifest.json", manifest)
|
|
with pytest.raises(ValueError, match="not selected"):
|
|
trace(home, run)
|
|
manifest["query_ids"] = {"case1": ["q1"]}
|
|
write_json(run / "manifest.json", manifest)
|
|
source.unlink()
|
|
source.symlink_to(tmp_path / "external.json")
|
|
with pytest.raises(ValueError, match="Symbolic link"):
|
|
trace(home, run)
|
|
source.unlink()
|
|
with pytest.raises(ValueError, match="case is missing"):
|
|
trace(home, run)
|
|
|
|
|
|
def test_missing_query_invalid_dataset_and_corrupt_history(query_evidence):
|
|
home, run, repo, _first, _second, source, case = query_evidence
|
|
case["queries"] = []
|
|
write_json(source, case)
|
|
with pytest.raises(ValueError, match="has no query"):
|
|
trace(home, run)
|
|
manifest = json.loads((run / "manifest.json").read_text())
|
|
manifest["dataset_kind"] = "../outside"
|
|
write_json(run / "manifest.json", manifest)
|
|
with pytest.raises(ValueError, match="dataset_kind"):
|
|
trace(home, run)
|
|
manifest["dataset_kind"] = "training-set"
|
|
write_json(run / "manifest.json", manifest)
|
|
case["queries"] = [{"query_id": "q1"}]
|
|
write_json(source, case)
|
|
(repo / ".git/objects/info/alternates").write_text("/external/objects")
|
|
with pytest.raises(ValueError, match="indirect"):
|
|
trace(home, run)
|
|
|
|
|
|
def test_run_and_case_scope(query_evidence):
|
|
home, run, _repo, _first, _second, _source, _case = query_evidence
|
|
with pytest.raises(ValueError, match="case_id"):
|
|
evidence_tools.trace_query_evidence(
|
|
home,
|
|
evidence_tools.TraceQueryEvidenceInput(validation_path=str(run), case_id="unknown", query_id="q1"),
|
|
)
|
|
with pytest.raises(ValueError, match="escapes"):
|
|
trace(home, home.parent / "outside")
|
|
|
|
|
|
@pytest.mark.parametrize("kwargs", [{"query_id": "../q"}, {"case_id": "../c"}, {"evidence_session_ids": [""]}])
|
|
def test_invalid_inputs(kwargs):
|
|
with pytest.raises(ValidationError):
|
|
evidence_tools.TraceQueryEvidenceInput.model_validate(
|
|
{"validation_path": "run", "case_id": "case1", "query_id": "q1", **kwargs},
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_registered_job_and_restricted_scope(app, prepared, query_evidence):
|
|
home, source_run, _repo, _first, _second, _source, _case = query_evidence
|
|
run = write_run(prepared, case_ids=["case1"], query_ids={"case1": ["q1"]})
|
|
shutil.copytree(home / "datasets/training-set", prepared / "datasets/training-set", dirs_exist_ok=True)
|
|
shutil.copytree(source_run / "cases", run / "cases")
|
|
before = snapshot(prepared)
|
|
result = await call(app, "home_trace_query_evidence", validation_path=str(run), case_id="case1", query_id="q1")
|
|
assert result["query"]["score"] == 0 and result["sessions"][0]["checkpoint"]
|
|
response = await app.run_job(
|
|
"home_trace_query_evidence",
|
|
validation_path=str(run),
|
|
case_id="case1",
|
|
query_id="q1",
|
|
_allowed_paths=[str(run)],
|
|
)
|
|
assert not response.success and "unrestricted" in str(response.answer)
|
|
assert snapshot(prepared) == before
|
|
|
|
|
|
@pytest.mark.parametrize("count", [2, 1, 25])
|
|
def test_rubric_judgments_and_independent_source_pointers(query_evidence, count):
|
|
home, run, _repo, _first, _second, source, case = query_evidence
|
|
case["queries"].insert(0, {"query_id": "other"})
|
|
case["sessions"].insert(0, {"session_id": "other-session"})
|
|
case["queries"][1]["groundtruth"]["rubric"] = ["required" + str(i) for i in range(25 if count == 25 else 2)]
|
|
write_json(source, case)
|
|
result_path = run / "cases/case1/queries/result.json"
|
|
judged = [{"score": 0.5, "reason": "r" * 1000} for _ in range(count)]
|
|
write_json(
|
|
result_path,
|
|
{
|
|
"queries": [
|
|
{
|
|
"query_id": "q1",
|
|
"judge_result": {
|
|
"metadata": {"llm_judge_responses": judged},
|
|
},
|
|
},
|
|
],
|
|
},
|
|
)
|
|
result = trace(home, run)
|
|
assert result["locations"] == {
|
|
"source_query": "/queries/1",
|
|
"saved_query": "/queries/0",
|
|
"rubric": "/queries/1/groundtruth/rubric",
|
|
}
|
|
assert result["sessions"][0]["source_pointer"] == "/sessions/1"
|
|
if count == 1:
|
|
assert "criteria" not in result # Do not silently pair incomplete judgments.
|
|
else:
|
|
assert len(result["criteria"]) == min(count, 20)
|
|
item = result["criteria"][0]
|
|
assert item["requirement"] == "required0" and len(item["reason"]) < 700
|
|
value = json.loads(result_path.read_text())
|
|
for segment in item["pointer"].strip("/").split("/"):
|
|
value = value[int(segment)] if isinstance(value, list) else value[segment]
|
|
assert value == judged[0]
|
|
if count == 25:
|
|
assert result["omitted_criterion_count"] == 5
|
|
|
|
|
|
def test_rubric_without_reference_answer_is_shown_as_expected_evidence(query_evidence):
|
|
home, run, _repo, _first, _second, source, case = query_evidence
|
|
case["queries"][0]["groundtruth"] = {"golden_answer": None, "rubric": ["required fact"]}
|
|
write_json(source, case)
|
|
result = trace(home, run)
|
|
assert result["query"]["expected_kind"] == "rubric"
|
|
assert result["query"]["expected"] == ["required fact"]
|
|
assert result["locations"]["rubric"] == "/queries/0/groundtruth/rubric"
|
|
assert "criteria" not in result # A rubric is not a saved judgment.
|