From 7e3ec0e7ff86e77265ea99bc2a44c1d6cd551799 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:22:44 +0800 Subject: [PATCH 1/3] Bind managed sessions and context delivery to the frozen ranking policy Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/apps/cli/__init__.py | 2 + src/inferrsi/apps/cli/arguments.py | 4 + src/inferrsi/apps/workflows/campaign.py | 9 +- src/inferrsi/harness/README.md | 25 +++ src/inferrsi/harness/optimization.py | 43 ++++- src/inferrsi/harness/optimization_session.py | 20 +- src/inferrsi/knowledge/ranking_policy.py | 14 ++ tests/apps/test_session_ranking_policy.py | 186 +++++++++++++++++++ 8 files changed, 297 insertions(+), 6 deletions(-) create mode 100644 tests/apps/test_session_ranking_policy.py diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index 69ed0180c..c76418009 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -34,6 +34,7 @@ def _round_provider(plan): def _optimization_session(args, *, task_source=None, report_metadata=None): from ...harness.optimization_session import session_command + from ...knowledge.ranking_policy import managed_ranking_policy settings = None external_project = None @@ -46,6 +47,7 @@ def _optimization_session(args, *, task_source=None, report_metadata=None): external_project = freeze_project(args.repo if args.project_task else None) return session_command( args, task_source=task_source, retain_context=capture_context, + ranking_policy_for=managed_ranking_policy, knowledge_reader=KnowledgeReader() if args.session_action == "knowledge" else None, external_knowledge=settings, external_project=external_project, external_provider_for=_round_provider, diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index 5842128f2..a46b86171 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -216,6 +216,10 @@ def _optimization_actions(stages, *, project=False): start.add_argument("--condition", default="current-agent" if project else None, required=not project) start.add_argument("--knowledge", choices=("on", "off"), default="on") + from ...knowledge.ranking_policy import MANAGED_RANKING_POLICIES + + start.add_argument("--ranking-policy", choices=tuple(MANAGED_RANKING_POLICIES), + default="default", help="Freeze the Knowledge ranking rule for this session") from ..integrations.cannbot.project import PLATFORMS start.add_argument("--cannbot-platform", choices=PLATFORMS, diff --git a/src/inferrsi/apps/workflows/campaign.py b/src/inferrsi/apps/workflows/campaign.py index 5ecff1add..3340eca2d 100644 --- a/src/inferrsi/apps/workflows/campaign.py +++ b/src/inferrsi/apps/workflows/campaign.py @@ -39,6 +39,7 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "", backend: str | None = None, scenario: str | None = None, limit: int = 5, context_bytes: int = 65536, sources: tuple[str, ...] = ("package",), + ranking_policy=None, diagnosis_binding: dict | None = None) -> tuple[Path, str]: """Run ``collect`` with a context budget and keep its complete envelope. @@ -55,10 +56,11 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "", if backend is None: backend = campaign.get("backend") pins = {"revisions": revisions} if revisions else {} + ranking = {"ranking_policy": ranking_policy} if ranking_policy is not None else {} result = reader.collect( query, ids=ids, kind=kind, repo=repo, tier=tier, backend=backend, scenario=scenario, limit=limit, relevance=relevance, - relevance_method=relevance_method, context_bytes=context_bytes, **pins, + relevance_method=relevance_method, context_bytes=context_bytes, **pins, **ranking, ) observation = result.get("retrieval") source_types = list(sources) @@ -72,6 +74,11 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "", "backend": backend, "scenario": scenario, "limit": limit, "context_bytes": context_bytes, "sources": source_types, **pins, } + if ranking_policy is not None: + effective = ranking_policy.receipt() + if (observation or {}).get("selection", {}).get("ranking_policy") != effective: + raise ValueError("Delivered ranking policy differs from the frozen session") + request["ranking_policy"] = effective if _supplies_no_observation(result): # Such a reader gets the record this entry wrote before observations # existed: the same fields, order and bytes, with no empty provenance. diff --git a/src/inferrsi/harness/README.md b/src/inferrsi/harness/README.md index d754478c3..32cebbeb9 100644 --- a/src/inferrsi/harness/README.md +++ b/src/inferrsi/harness/README.md @@ -29,6 +29,31 @@ measurement and assessment rules. receipts and budget accounting in the shared RunStore. See the [speculative search design](../../../docs/guides/speculative-search.md) for recovery rules. +## Managed optimization loop + +`campaign` and `benchmarks session` enter through [session_command](optimization_session.py). +The agent chooses a hypothesis and edits a candidate between rounds. + +- **Analyzer.** The agent supplies the measured bottleneck and its evidence. + [record_diagnosis](optimization.py) retains that evidence and binds later deliveries + and rounds to the diagnosis. +- **Indexer.** Knowledge [ranks matches](../knowledge/knowledge_find.py) and assembles + context within the requested byte budget. Inspect the capture for delivered material, + source revisions and omissions. Start a fresh session with `--ranking-policy applicability` + to raise the applicability weight from 2 to 3. The default keeps the original six weights. +- **Executor.** [The round controller](optimization.py) owns attempts, time and round + budgets, pending work, recovery and final retests. It dispatches the retained candidate + to the task runner or the [service lifecycle](project_service.py). +- **Evaluator.** [_session_assess](optimization_session.py) dispatches packaged tasks to + their frozen assessment protocol and projects to [the AB/BA assessor](project.py). + In service mode, the optional screening report is diagnostic. Formal performance + and quality measurements in [evaluate](project_service.py) determine acceptance. + +New plans freeze the ranking ID, scoring version and all effective weights. Ordinary +plans and delivery receipts include a configuration digest. Service plans, manifests +and deliveries retain the values directly. Use the original runtime to continue a +historical plan without these fields or a session whose installed rule has changed. + ## Evaluate retained runs With the Apps saved-request CLI, a trusted caller allocates the attempt before diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index 8908ac270..ad17bf214 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -57,6 +57,36 @@ def initialize(root: Path, plan: dict) -> dict: return status(root) +def _require_ranking_policy(recorded, effective): + if (not isinstance(recorded, dict) or not isinstance(effective, dict) + or type(recorded.get("version")) is not int + or not isinstance(recorded.get("weights"), dict) + or any(type(value) not in (int, float) for value in recorded["weights"].values()) + or recorded != effective): + raise ValueError("Frozen ranking policy changed or is incomplete, use its original runtime") + + +def resolve_frozen_ranking(plan, ranking_policy_for, *, read_only=False): + if read_only and "ranking_policy" not in plan: + return None + recorded = plan.get("ranking_policy") + if not isinstance(recorded, dict) or not isinstance(recorded.get("id"), str): + raise ValueError("Missing frozen ranking policy, use the original runtime to resume") + if ranking_policy_for is None: + raise ValueError("A resolver for the frozen ranking policy is required") + policy = ranking_policy_for(recorded["id"]) + effective = (policy.configuration() if plan.get("evaluation_mode") == "service_reuse" + else policy.receipt()) + _require_ranking_policy(recorded, effective) + return policy + + +def _check_context_ranking(plan, context): + if "ranking_policy" in plan: + _require_ranking_policy(context.get("request", {}).get("ranking_policy"), + plan["ranking_policy"]) + + def _control(root): plan = json.loads((root / "plan.json").read_text(encoding="utf-8")) state = json.loads((root / "state.json").read_text(encoding="utf-8")) @@ -82,6 +112,8 @@ def _control(root): ) ): raise ValueError("Incompatible service campaign records") + if "ranking_policy" in manifest or "ranking_policy" in plan: + _require_ranking_policy(manifest.get("ranking_policy"), plan.get("ranking_policy")) service.no_fingerprints(plan) service.no_fingerprints(state) return plan, state @@ -129,6 +161,7 @@ def _load(root, *, read_only=False): retained = _read_context(root, context) if context.get("kind") not in ("external_search", "external_read"): _check_context_diagnosis(plan, diagnoses, context, retained) + _check_context_ranking(plan, retained) contexts[context["path"]] = context for record in [*state["rounds"], *([state["final"]] if state["final"] else [])]: directory = root / record["path"] @@ -806,6 +839,7 @@ def _service_initialize(root, plan): "evaluation_mode": "service_reuse", "protocol_id": state["protocol_id"], "diagnosis_required": plan.get("diagnosis_required", False), + **({"ranking_policy": plan["ranking_policy"]} if "ranking_policy" in plan else {}), }, ) atomic_write_json(root / "state.json", state) @@ -838,6 +872,7 @@ def _service_load(root, plan, state, *, read_only=False): _check_activity_diagnosis(plan, diagnoses, attempt) for context in state["contexts"]: retained = service.read(service.safe_path(root, context["path"])) + _check_context_ranking(plan, retained) _check_context_diagnosis(plan, diagnoses, context, retained) for event in state["recovery_events"]: if event["kind"] == "cleanup_inspection": @@ -1330,7 +1365,7 @@ def _service_cleanup_receipt(root, state, path): atomic_write_json(root / "state.json", state) -def service_command(root, args, *, knowledge_reader=None): +def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=None): """Service-mode operations inside the shared controller's lock and control record.""" from . import project_service as service from . import service_evidence @@ -1340,8 +1375,12 @@ def service_command(root, args, *, knowledge_reader=None): if action == "profile": from . import service_backfill + plan, _ = _control(root) + resolve_frozen_ranking(plan, ranking_policy_for) return service_backfill.run(root, args) plan, state = _load(root, read_only=action == "status") + ranking_policy = resolve_frozen_ranking(plan, ranking_policy_for, + read_only=action == "status") if getattr(args, "cleanup_receipt", None) is not None: _service_cleanup_receipt(root, state, args.cleanup_receipt) if action == "status": @@ -1416,7 +1455,9 @@ def service_command(root, args, *, knowledge_reader=None): relevance_method=args.relevance_method, limit=args.limit, context_bytes=args.context_bytes, + ranking_policy=ranking_policy, ) + _check_context_ranking(plan, context) if binding: context["diagnosis_binding"] = binding service.no_fingerprints(context) diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/optimization_session.py index ad4e379ab..111e592e1 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/optimization_session.py @@ -123,11 +123,13 @@ def _runtime_identity(): "harness/protocol_child.py", "harness/candidates.py", "harness/project.py", "harness/measurement.py", "harness/records/knowledge_capture.py", "apps/workflows/campaign.py", - "knowledge/context_projection.py") + "knowledge/context_projection.py", "knowledge/knowledge_find.py", + "knowledge/ranking_policy.py") return {name: sha256(root / name) for name in names} -def session_command(args, *, task_source: Path | None = None, knowledge_reader=None, +def session_command(args, *, ranking_policy_for, task_source: Path | None = None, + knowledge_reader=None, retain_context=None, external_knowledge=None, external_provider=None, external_project=None, external_provider_for=None, report_metadata=None) -> dict: @@ -148,6 +150,7 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N raise ValueError("A positive round/time budget and condition label are required") if root.exists(): raise ValueError("Session directory must be new") + ranking_policy = ranking_policy_for(args.ranking_policy) reserve = (args.final_reserve_seconds if args.final_reserve_seconds is not None else args.evaluation_timeout_seconds) if not math.isfinite(reserve) or not 0 < reserve < args.max_minutes * 60: @@ -195,6 +198,7 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N "round_mode": args.round_mode, "final_reserve_seconds": reserve, "knowledge_allowed": args.knowledge == "on", + "ranking_policy": ranking_policy.configuration(), "evaluation_timeout_seconds": args.evaluation_timeout_seconds, "evaluation_prefix": evaluation_prefix, "python": args.python, @@ -258,6 +262,7 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N "round_limit": args.rounds, "max_seconds": args.max_minutes * 60, "round_mode": args.round_mode, "final_reserve_seconds": reserve, "knowledge_allowed": args.knowledge == "on", + "ranking_policy": ranking_policy.receipt(), "evaluation_timeout_seconds": args.evaluation_timeout_seconds, "evaluation_prefix": evaluation_prefix, "python": args.python, "runtime_identity": _runtime_identity(), **candidate, **settings} @@ -295,7 +300,9 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N ): if args.session_action == "profile": try: - return optimization.service_command(root, args) + return optimization.service_command( + root, args, ranking_policy_for=ranking_policy_for, + ) except (ValueError, OSError) as exc: message = "Campaign lock is busy" if isinstance(exc, BlockingIOError) else str(exc) return { @@ -312,7 +319,8 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N if getattr(args, "alternative", None) is not None or getattr( args, "selection_reason", None) is not None: raise ValueError("Round decision declarations require a benchmark or AB/BA campaign") - return optimization.service_command(root, args, knowledge_reader=knowledge_reader) + return optimization.service_command(root, args, knowledge_reader=knowledge_reader, + ranking_policy_for=ranking_policy_for) if ( args.session_action in ("baseline", "refresh-references", "resume", "profile") or getattr(args, "retry_of", None) @@ -323,6 +331,9 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N raise ValueError("Service lifecycle/retry operations require a service-reuse campaign") if plan["runtime_identity"] != _runtime_identity(): raise ValueError("Optimization runtime changed, use its frozen runtime to resume") + ranking_policy = optimization.resolve_frozen_ranking( + plan, ranking_policy_for, read_only=args.session_action == "status", + ) if args.session_action == "status": return optimization.status(root) if args.session_action == "diagnose": @@ -334,6 +345,7 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N root, knowledge_reader, retain_context=retain_context, + ranking_policy=ranking_policy, external_provider=external_provider, external_provider_for=external_provider_for, query="", diff --git a/src/inferrsi/knowledge/ranking_policy.py b/src/inferrsi/knowledge/ranking_policy.py index bfbd7c5f1..c2ddacc3a 100644 --- a/src/inferrsi/knowledge/ranking_policy.py +++ b/src/inferrsi/knowledge/ranking_policy.py @@ -50,3 +50,17 @@ def receipt(self) -> dict: DEFAULT_RANKING_POLICY = RankingPolicy() + +MANAGED_RANKING_POLICIES = MappingProxyType({ + "default": DEFAULT_RANKING_POLICY, + "applicability": RankingPolicy("applicability", {"applicability": 3}), +}) + + +def managed_ranking_policy(name: str) -> RankingPolicy: + try: + return MANAGED_RANKING_POLICIES[name] + except KeyError: + raise ValueError( + f"Unknown frozen ranking policy {name!r}, use its original runtime" + ) from None diff --git a/tests/apps/test_session_ranking_policy.py b/tests/apps/test_session_ranking_policy.py new file mode 100644 index 000000000..667b7a736 --- /dev/null +++ b/tests/apps/test_session_ranking_policy.py @@ -0,0 +1,186 @@ +"""Exercise frozen ranking through each managed CLI and its real delivery or assessor.""" + +import json +import sys + +import pytest + +from inferrsi.apps.cli import main +from inferrsi.harness import project_service, task_protocol +from inferrsi.knowledge import ranking_policy +from tests.apps import test_optimization_session as benchmark +from tests.apps import test_project_optimization as project_cli +from tests.apps.test_optimization_session import task as task +from tests.apps.test_project_optimization import project as project +from tests.fixtures import service_reuse as service +from tests.fixtures.service_reuse import campaign as campaign + + +def read(path): + return json.loads(path.read_text(encoding="utf-8")) + + +@pytest.mark.parametrize("lane", ["abba", "service_reuse"]) +def test_managed_policy_binds_delivery_and_guards_resume(lane, request, capsys, monkeypatch): + rule = ranking_policy.managed_ranking_policy("applicability") + if lane == "abba": + project = request.getfixturevalue("project") + root = project[-1] + project_cli.start(project, capsys, extra=("--ranking-policy", rule.policy_id)) + expected = rule.receipt() + operation = ["campaign", "round", "--session", str(root), "--candidate", str(project[0]), + "--hypothesis", "fixed candidate"] + else: + campaign = request.getfixturevalue("campaign") + root = campaign["root"] + campaign["start"] += ["--ranking-policy", rule.policy_id] + service.call(campaign, "start") + service.diagnose(campaign) + expected = rule.configuration() + operation = ["campaign", "baseline", "--session", str(root)] + + plan_path = root / "plan.json" + plan = read(plan_path) + assert plan["ranking_policy"] == expected + assert main(["campaign", "knowledge", "--session", str(root), "--query", "cgroupv2", + "--limit", "1", "--context-bytes", "65536"]) == 0 + context = json.loads(capsys.readouterr().out)["context"] + assert context["request"]["ranking_policy"] == expected + assert context["contexts"] + retained = read(root / read(root / "state.json")["contexts"][0]["path"]) + assert retained["request"]["ranking_policy"] == expected + if lane == "abba": + assert retained["retrieval"]["selection"]["ranking_policy"] == expected + else: + assert read(root / "campaign.json")["ranking_policy"] == expected + project_service.no_fingerprints(retained) + + def refused_without_writes(): + before = {p: p.read_bytes() for p in root.rglob("*") if p.is_file()} + with pytest.raises(SystemExit) as error: + main(operation) + assert error.value.code == 2 + assert "ranking policy" in capsys.readouterr().err.lower() + assert {p: p.read_bytes() for p in root.rglob("*") if p.is_file()} == before + + # JSON field order is immaterial to either integrity scheme. + plan["ranking_policy"]["weights"] = dict(reversed(expected["weights"].items())) + plan_path.write_text(json.dumps(plan), encoding="utf-8") + assert main(["campaign", "status", "--session", str(root)]) == 0 + capsys.readouterr() + with monkeypatch.context() as runtime: + changed = ranking_policy.RankingPolicy(rule.policy_id, {"applicability": 4}) + runtime.setattr(ranking_policy, "MANAGED_RANKING_POLICIES", {rule.policy_id: changed}) + refused_without_writes() + with monkeypatch.context() as runtime: + runtime.setattr(ranking_policy, "RANKING_VERSION", expected["version"] + 1) + refused_without_writes() + for incomplete in ( + {k: v for k, v in expected.items() if k != "version"}, + {**expected, "weights": {k: v for k, v in expected["weights"].items() if k != "body"}}, + {**expected, "version": True}, + ): + plan["ranking_policy"] = incomplete + plan_path.write_text(json.dumps(plan), encoding="utf-8") + refused_without_writes() + + # A historical plan with no binding requires its original runtime. + del plan["ranking_policy"] + plan_path.write_text(json.dumps(plan), encoding="utf-8") + if lane == "service_reuse": + manifest = read(root / "campaign.json") + del manifest["ranking_policy"] + (root / "campaign.json").write_text(json.dumps(manifest), encoding="utf-8") + refused_without_writes() + + +def test_packaged_assessor_receives_identical_evidence_across_policies(task, tmp_path, capsys, + monkeypatch): + calls = [] + real_run = task_protocol.run + + def observe(frozen, source_hash, operation, **inputs): + if operation == "assess": + assert set(inputs) == {"directory", "settings", "execution"} + directory = inputs["directory"] + calls.append((source_hash, inputs["settings"], inputs["execution"]["status"], + (directory / "candidate.py").read_bytes(), + read(directory / "measurement/result.json"))) + return real_run(frozen, source_hash, operation, **inputs) + + monkeypatch.setattr(task_protocol, "run", observe) + outcomes = [] + for name in ("default", "applicability"): + root = tmp_path / name + options = [] if name == "default" else ["--ranking-policy", name] + assert main(["benchmarks", "session", "start", task.name, "--session", str(root), + "--rounds", "1", "--max-minutes", "5", "--evaluation-timeout-seconds", "15", + "--condition", "same CPU fixture", "--evaluation-args", "", *options]) == 0 + capsys.readouterr() + assert read(root / "plan.json")["ranking_policy"] == ( + ranking_policy.managed_ranking_policy(name).receipt() + ) + benchmark.diagnose(root, capsys) + benchmark.submit(root, 2, capsys) + outcomes.append(read(root / "state.json")["rounds"][0]["assessment"]) + assert len(calls) == 2 and calls[0] == calls[1] + assert outcomes[0] == outcomes[1] + assert outcomes[0]["verdict"] == "PASS" + + +def test_project_assessor_uses_the_same_measurements_quality_and_threshold(project, capsys): + arms = [] + for name in ("default", "applicability"): + arm = (*project[:3], project[-1].parent / name) + project_cli.start(arm, capsys, extra=("--ranking-policy", name)) + arms.append(arm) + + evidence = [] + for arm in arms: + code, result = project_cli.submit(arm, capsys, 20) + assert code == 0 + observation = result["latest_observation"] + assessment = observation["assessment"] + assert assessment["verdict"] == "PASS" and assessment["quality_passed"] + directory = arm[-1] / read(arm[-1] / "state.json")["rounds"][0]["path"] + samples = {p.parent.name: read(p) for p in (directory / "execution").glob("*/result.json")} + assert {"metric": 20} in samples.values() and {"correct": True} in samples.values() + evidence.append((read(arm[-1] / "plan.json")["evaluation_settings"], samples, + assessment["verdict"], assessment["score"], assessment["quality_passed"])) + assert evidence[0] == evidence[1] + + +@pytest.mark.skipif(sys.platform == "win32", reason="service fixture needs POSIX process ownership") +def test_service_screening_and_formal_gates_across_policies(campaign): + config = service.settings() + config["screening"] = { + "command": [arg.replace("measure", "screening") for arg in config["commands"]["measure"]], + "estimated_gain": 50, + } + campaign["config"].write_text(json.dumps(config), encoding="utf-8") + arms = [] + for name in ("default", "applicability"): + root = campaign["root"].parent / name + start = [str(root) if arg == str(campaign["root"]) else arg for arg in campaign["start"]] + arm = {**campaign, "root": root, "start": [*start, "--ranking-policy", name]} + service.begin(arm) + arms.append(arm) + + service.commit(campaign["repo"], version="fixed", a=90, screen_reject=True) + evidence = [] + for arm in arms: + result = service.call(arm, "round", "--candidate", campaign["repo"], + "--hypothesis", "fixed CPU fixture") + attempt = result["latest_observation"] + assert attempt["execution"]["screening"]["passed"] is False + steps = attempt["execution"]["steps"] + measured = [s["result"]["scenarios"] for s in steps if s["id"].startswith("measure-")] + quality, = [s["result"] for s in steps if s["id"] == "quality"] + assert len(measured) == 2 and attempt["assessment"]["verdict"] == "PASS" + reference = read(arm["root"] / "state.json")["initial_reference"] + quality_inputs = {key: quality[key] for key in ("dataset", "scorer", "samples", "quality")} + evidence.append((read(arm["root"] / "frozen/evaluation.json"), measured, + quality["binding"]["revision"], quality["binding"]["conditions"], + quality_inputs, reference["measurements"], reference["quality_score"], + attempt["assessment"])) + assert evidence[0] == evidence[1] From 6e22fe51373908f06f516b76e0cc672f0c2d600d Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:40:09 +0800 Subject: [PATCH 2/3] Cover benchmark recovery and both directions of service assessment Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- tests/apps/test_session_ranking_policy.py | 46 ++++++++++++++++++----- 1 file changed, 37 insertions(+), 9 deletions(-) diff --git a/tests/apps/test_session_ranking_policy.py b/tests/apps/test_session_ranking_policy.py index 667b7a736..3ef5438a3 100644 --- a/tests/apps/test_session_ranking_policy.py +++ b/tests/apps/test_session_ranking_policy.py @@ -20,9 +20,11 @@ def read(path): return json.loads(path.read_text(encoding="utf-8")) -@pytest.mark.parametrize("lane", ["abba", "service_reuse"]) -def test_managed_policy_binds_delivery_and_guards_resume(lane, request, capsys, monkeypatch): +@pytest.mark.parametrize("lane", ["abba", "benchmark", "service_reuse"]) +def test_managed_policy_binds_delivery_and_guards_resume(lane, request, tmp_path, capsys, + monkeypatch): rule = ranking_policy.managed_ranking_policy("applicability") + command = ["campaign"] if lane == "abba": project = request.getfixturevalue("project") root = project[-1] @@ -30,6 +32,18 @@ def test_managed_policy_binds_delivery_and_guards_resume(lane, request, capsys, expected = rule.receipt() operation = ["campaign", "round", "--session", str(root), "--candidate", str(project[0]), "--hypothesis", "fixed candidate"] + elif lane == "benchmark": + task = request.getfixturevalue("task") + root = tmp_path / "session" + command = ["benchmarks", "session"] + assert main([*command, "start", task.name, "--session", str(root), "--rounds", "1", + "--max-minutes", "5", "--evaluation-timeout-seconds", "15", "--condition", + "same CPU fixture", "--evaluation-args", "", "--ranking-policy", + rule.policy_id]) == 0 + capsys.readouterr() + benchmark.diagnose(root, capsys) + expected = rule.receipt() + operation = [*command, "recover", "--session", str(root)] else: campaign = request.getfixturevalue("campaign") root = campaign["root"] @@ -42,14 +56,14 @@ def test_managed_policy_binds_delivery_and_guards_resume(lane, request, capsys, plan_path = root / "plan.json" plan = read(plan_path) assert plan["ranking_policy"] == expected - assert main(["campaign", "knowledge", "--session", str(root), "--query", "cgroupv2", + assert main([*command, "knowledge", "--session", str(root), "--query", "cgroupv2", "--limit", "1", "--context-bytes", "65536"]) == 0 context = json.loads(capsys.readouterr().out)["context"] assert context["request"]["ranking_policy"] == expected assert context["contexts"] retained = read(root / read(root / "state.json")["contexts"][0]["path"]) assert retained["request"]["ranking_policy"] == expected - if lane == "abba": + if lane != "service_reuse": assert retained["retrieval"]["selection"]["ranking_policy"] == expected else: assert read(root / "campaign.json")["ranking_policy"] == expected @@ -66,7 +80,7 @@ def refused_without_writes(): # JSON field order is immaterial to either integrity scheme. plan["ranking_policy"]["weights"] = dict(reversed(expected["weights"].items())) plan_path.write_text(json.dumps(plan), encoding="utf-8") - assert main(["campaign", "status", "--session", str(root)]) == 0 + assert main([*command, "status", "--session", str(root)]) == 0 capsys.readouterr() with monkeypatch.context() as runtime: changed = ranking_policy.RankingPolicy(rule.policy_id, {"applicability": 4}) @@ -75,10 +89,19 @@ def refused_without_writes(): with monkeypatch.context() as runtime: runtime.setattr(ranking_policy, "RANKING_VERSION", expected["version"] + 1) refused_without_writes() + if lane == "service_reuse": + manifest_path = root / "campaign.json" + manifest = read(manifest_path) + drifted_manifest = {**manifest, "ranking_policy": changed.configuration()} + manifest_path.write_text(json.dumps(drifted_manifest), encoding="utf-8") + refused_without_writes() + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") for incomplete in ( {k: v for k, v in expected.items() if k != "version"}, {**expected, "weights": {k: v for k, v in expected["weights"].items() if k != "body"}}, {**expected, "version": True}, + {**expected, "id": "unavailable"}, + {**expected, "weights": {**expected["weights"], "unknown": 1}}, ): plan["ranking_policy"] = incomplete plan_path.write_text(json.dumps(plan), encoding="utf-8") @@ -151,7 +174,10 @@ def test_project_assessor_uses_the_same_measurements_quality_and_threshold(proje @pytest.mark.skipif(sys.platform == "win32", reason="service fixture needs POSIX process ownership") -def test_service_screening_and_formal_gates_across_policies(campaign): +@pytest.mark.parametrize(("screen_reject", "quality_score", "verdict"), + [(True, 1, "PASS"), (False, 0, "FAIL")]) +def test_service_screening_and_formal_gates_across_policies(campaign, screen_reject, quality_score, + verdict): config = service.settings() config["screening"] = { "command": [arg.replace("measure", "screening") for arg in config["commands"]["measure"]], @@ -166,17 +192,19 @@ def test_service_screening_and_formal_gates_across_policies(campaign): service.begin(arm) arms.append(arm) - service.commit(campaign["repo"], version="fixed", a=90, screen_reject=True) + service.commit(campaign["repo"], version="fixed", a=90, screen_reject=screen_reject, + quality=quality_score) evidence = [] for arm in arms: result = service.call(arm, "round", "--candidate", campaign["repo"], "--hypothesis", "fixed CPU fixture") attempt = result["latest_observation"] - assert attempt["execution"]["screening"]["passed"] is False + assert attempt["execution"]["screening"]["passed"] is (not screen_reject) steps = attempt["execution"]["steps"] measured = [s["result"]["scenarios"] for s in steps if s["id"].startswith("measure-")] quality, = [s["result"] for s in steps if s["id"] == "quality"] - assert len(measured) == 2 and attempt["assessment"]["verdict"] == "PASS" + assert len(measured) == 2 and attempt["assessment"]["verdict"] == verdict + assert attempt["assessment"]["quality_passed"] is bool(quality_score) reference = read(arm["root"] / "state.json")["initial_reference"] quality_inputs = {key: quality[key] for key in ("dataset", "scorer", "samples", "quality")} evidence.append((read(arm["root"] / "frozen/evaluation.json"), measured, From 048110cbdc525bf573d864938a358287b8b3ffc0 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:53:23 +0800 Subject: [PATCH 3/3] Pin the complete ranking fixture and check corpus drift against a retained delivery Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/harness/README.md | 7 +++ tests/apps/test_indexer_deliveries.py | 50 +++++++++++++------ .../indexer/ranking-corpus/demo/SKILL.md | 6 +++ .../ranking-corpus/demo/cases/alpha.json | 1 + .../ranking-corpus/demo/cases/alpha.md | 1 + .../ranking-corpus/demo/cases/bravo.json | 1 + .../ranking-corpus/demo/cases/bravo.md | 1 + 7 files changed, 52 insertions(+), 15 deletions(-) create mode 100644 tests/fixtures/indexer/ranking-corpus/demo/SKILL.md create mode 100644 tests/fixtures/indexer/ranking-corpus/demo/cases/alpha.json create mode 100644 tests/fixtures/indexer/ranking-corpus/demo/cases/alpha.md create mode 100644 tests/fixtures/indexer/ranking-corpus/demo/cases/bravo.json create mode 100644 tests/fixtures/indexer/ranking-corpus/demo/cases/bravo.md diff --git a/src/inferrsi/harness/README.md b/src/inferrsi/harness/README.md index 32cebbeb9..1e7bc4658 100644 --- a/src/inferrsi/harness/README.md +++ b/src/inferrsi/harness/README.md @@ -54,6 +54,13 @@ plans and delivery receipts include a configuration digest. Service plans, manif and deliveries retain the values directly. Use the original runtime to continue a historical plan without these fields or a session whose installed rule has changed. +To reproduce a ranking experiment, pin the scoring runtime revision and the complete +eligible corpus alongside the query, filters and policy. Document frequency and median +body length depend on entries outside the delivered context. The [ranking regression](../../../tests/apps/test_indexer_deliveries.py) +runs both policies against the same [complete corpus](../../../tests/fixtures/indexer/ranking-corpus) +at that Git revision. It also verifies an old capture after an undelivered entry changes +the score in a fresh search. + ## Evaluate retained runs With the Apps saved-request CLI, a trusted caller allocates the attempt before diff --git a/tests/apps/test_indexer_deliveries.py b/tests/apps/test_indexer_deliveries.py index 160e59821..a9014ce03 100644 --- a/tests/apps/test_indexer_deliveries.py +++ b/tests/apps/test_indexer_deliveries.py @@ -1,5 +1,7 @@ import hashlib import json +import shutil +from pathlib import Path import pytest @@ -11,25 +13,12 @@ CUE = "qxrankprobe" A, B = "case.qxrankprobe", "case.alternate" ALTERNATE = RankingPolicy("applicability", {"applicability": 3}) +FROZEN_CORPUS = Path(__file__).resolve().parents[1] / "fixtures" / "indexer" / "ranking-corpus" @pytest.fixture() def library(tmp_path): - root = tmp_path / "library" - owner = root / "demo" - cases = owner / "cases" - cases.mkdir(parents=True) - (owner / "SKILL.md").write_bytes(b"---\nname: demo\ndescription: Demo owner\n---\n\nbody\n") - for name, identity, applicability in [("alpha", A, []), ("bravo", B, [CUE] * 4)]: - (cases / f"{name}.md").write_bytes(f"source {name}\n".encode()) - record = { - "id": identity, "kind": "case", "content": f"{name}.md", - "state": "historical_observation", "backend": "ascend", - "applicability": applicability, "limitations": [], "attribution": "Demo", - "sources": [{"type": "internal", "issue": "local", "artifact": "fixture"}], - } - (cases / f"{name}.json").write_text(json.dumps(record), encoding="utf-8") - return root + return shutil.copytree(FROZEN_CORPUS, tmp_path / "library") @pytest.mark.parametrize(("options", "order", "scores", "source"), [ @@ -76,6 +65,37 @@ def test_find_collect_and_retained_context(library, tmp_path, options, order, sc assert (omission["ref"], omission["reason"]) == (ref, "context_limit") +def test_undelivered_corpus_change_preserves_capture_but_changes_ranking(library, tmp_path): + def collect(): + reader = KnowledgeReader(skill_root=library) + return reader.collect(f"{CUE} alpha", kind="case", limit=1, context_bytes=2048) + + original = collect() + campaign = tmp_path / "run" + create_campaign(campaign, "replay") + path, _ = save_retrieval(campaign, context_id="original", result=original) + + cases = library / "demo" / "cases" + extra = json.loads((cases / "alpha.json").read_text(encoding="utf-8")) + extra.update(id="case.extra", content="extra.md") + (cases / "extra.json").write_text(json.dumps(extra), encoding="utf-8") + (cases / "extra.md").write_bytes(f"{CUE}\n".encode()) + changed = collect() + + saved, state = verify_capture(path.read_bytes()) + assert state == "verified" + assert saved["retrieval"]["items"] == original["retrieval"]["items"] + before, = saved["retrieval"]["items"] + after, = changed["retrieval"]["items"] + assert before["ref"] == after["ref"] == "checkout:" + A + assert before["revision"] == after["revision"] + assert before["score"] != after["score"] + assert original["contexts"] == changed["contexts"] + assert "source alpha\n" in saved["assembled_text"] + assert saved["retrieval"]["counts"]["excluded"]["item_limit"] == 1 + assert changed["retrieval"]["counts"]["excluded"]["item_limit"] == 2 + + def test_explicit_ids_keep_caller_order_under_alternative_policy(library): reader = KnowledgeReader(skill_root=library) refs = ["checkout:" + A, "checkout:" + B] diff --git a/tests/fixtures/indexer/ranking-corpus/demo/SKILL.md b/tests/fixtures/indexer/ranking-corpus/demo/SKILL.md new file mode 100644 index 000000000..a84904970 --- /dev/null +++ b/tests/fixtures/indexer/ranking-corpus/demo/SKILL.md @@ -0,0 +1,6 @@ +--- +name: demo +description: Demo owner +--- + +body diff --git a/tests/fixtures/indexer/ranking-corpus/demo/cases/alpha.json b/tests/fixtures/indexer/ranking-corpus/demo/cases/alpha.json new file mode 100644 index 000000000..adbf62baf --- /dev/null +++ b/tests/fixtures/indexer/ranking-corpus/demo/cases/alpha.json @@ -0,0 +1 @@ +{"id": "case.qxrankprobe", "kind": "case", "content": "alpha.md", "state": "historical_observation", "backend": "ascend", "applicability": [], "limitations": [], "attribution": "Demo", "sources": [{"type": "internal", "issue": "local", "artifact": "fixture"}]} \ No newline at end of file diff --git a/tests/fixtures/indexer/ranking-corpus/demo/cases/alpha.md b/tests/fixtures/indexer/ranking-corpus/demo/cases/alpha.md new file mode 100644 index 000000000..49f44eca9 --- /dev/null +++ b/tests/fixtures/indexer/ranking-corpus/demo/cases/alpha.md @@ -0,0 +1 @@ +source alpha diff --git a/tests/fixtures/indexer/ranking-corpus/demo/cases/bravo.json b/tests/fixtures/indexer/ranking-corpus/demo/cases/bravo.json new file mode 100644 index 000000000..ad72817e6 --- /dev/null +++ b/tests/fixtures/indexer/ranking-corpus/demo/cases/bravo.json @@ -0,0 +1 @@ +{"id": "case.alternate", "kind": "case", "content": "bravo.md", "state": "historical_observation", "backend": "ascend", "applicability": ["qxrankprobe", "qxrankprobe", "qxrankprobe", "qxrankprobe"], "limitations": [], "attribution": "Demo", "sources": [{"type": "internal", "issue": "local", "artifact": "fixture"}]} \ No newline at end of file diff --git a/tests/fixtures/indexer/ranking-corpus/demo/cases/bravo.md b/tests/fixtures/indexer/ranking-corpus/demo/cases/bravo.md new file mode 100644 index 000000000..850060102 --- /dev/null +++ b/tests/fixtures/indexer/ranking-corpus/demo/cases/bravo.md @@ -0,0 +1 @@ +source bravo