diff --git a/loopx/capabilities/manager_context/tracking.py b/loopx/capabilities/manager_context/tracking.py index b2cba8ac54..3a9a5c861f 100644 --- a/loopx/capabilities/manager_context/tracking.py +++ b/loopx/capabilities/manager_context/tracking.py @@ -5,6 +5,7 @@ from __future__ import annotations +import json from typing import Any from . import _read, _root, evidence_goal_scope @@ -16,6 +17,8 @@ controlled_request_readback, ) from ...control_plane.collaboration.goal_instance_scope import ( + CollaborationGoalScope, + CollaborationLifecycleRejected, collaboration_goal_scope, decide_collaboration_lifecycle, scope_for_caller_goal_ref, @@ -24,7 +27,110 @@ from ...control_plane.content_digest import ( BARE_SHA256_PATTERN, ) +from ...control_plane.effect_runtime import effect_runtime_request_scope +_LifecycleDecisionCache = dict[ + tuple[Any, str, str, str], tuple[bool, dict[str, Any] | None] +] + + +def _lifecycle_cache_key( + scope: Any, + record: dict[str, Any], +) -> tuple[Any, str, str, str] | None: + """Build a canonical cache key for pure `history_inspect` lifecycle checks.""" + if not isinstance(scope, CollaborationGoalScope): + return None + try: + caller_key = json.dumps( + scope.caller_goal_ref, + ensure_ascii=False, + sort_keys=True, + allow_nan=False, + ) + current_key = json.dumps( + scope.current_goal_ref, + ensure_ascii=False, + sort_keys=True, + allow_nan=False, + ) + record_key = json.dumps( + record.get("goal_ref") if isinstance(record, dict) else None, + ensure_ascii=False, + sort_keys=True, + allow_nan=False, + ) + except (TypeError, ValueError): + return None + return (scope.profile_id, caller_key, current_key, record_key) + + +def _decide_history_inspect( + scope: Any, + record: dict[str, Any], + cache: _LifecycleDecisionCache, +) -> None: + """Reuse `history_inspect` decisions across entries sharing exact Goal refs.""" + # TS `collaboration.goal_instance.decide` for `history_inspect` depends solely + # on `(profile_id, caller_goal_ref, current_goal_ref, record_goal_ref)`. + key = _lifecycle_cache_key(scope, record) + if key is not None and key in cache: + allowed, rejected_decision = cache[key] + if not allowed: + assert rejected_decision is not None + raise CollaborationLifecycleRejected(rejected_decision) + return + try: + decide_collaboration_lifecycle( + scope, + operation="history_inspect", + record=record, + ) + except CollaborationLifecycleRejected as exc: + if key is not None: + cache[key] = (False, exc.decision) + raise + if key is not None: + cache[key] = (True, None) + + +def _verify_goal_group( + root: Any, + registry_path: Any, + gid: str, + group_rows: list[tuple[int, dict[str, Any]]], + lifecycle_cache: _LifecycleDecisionCache, +) -> tuple[list[tuple[int, dict[str, Any]]], int]: + """Validate matching entries for one `goal_id` under one Goal lifetime fence.""" + verified: list[tuple[int, dict[str, Any]]] = [] + unreadable = 0 + try: + with collaboration_goal_scope( + registry_path, + goal_id=gid, + agents=(), + caller_goal_ref=None, + ) as base_scope: + for scan_index, row in group_rows: + try: + goal_scope = scope_for_caller_goal_ref( + base_scope, + row.get("goal_ref"), + ) + entry = _entry( + root, + row["goal_id"], + row["agent_id"], + row["request_id"], + scope=goal_scope, + ) + _decide_history_inspect(goal_scope, entry, lifecycle_cache) + verified.append((scan_index, row)) + except (OSError, ValueError, KeyError, TypeError): + unreadable += 1 + except (OSError, ValueError, KeyError, TypeError): + return [], len(group_rows) + return verified, unreadable def query( @@ -53,24 +159,34 @@ def query( raise ValueError("invalid context page") # Legacy entries have no channel. Recover only provider-owned provenance, # never infer audience from Goal identity or a model-authored field. - legacy_channels = {} - ingress_paths = sorted((_root(root) / "ingress").glob("*.json")) - for path in ingress_paths[:2000] if not owner_scope else []: - try: - item = _read(path) - legacy_channels.setdefault(item.get("source_id"), set()).add( - item.get("channel") - ) - except (OSError, ValueError, TypeError): - continue - rows, unreadable = [], 0 - candidates_by_goal: dict[str, list[dict[str, Any]]] = {} + ingress_paths = ( + [] if owner_scope else sorted((_root(root) / "ingress").glob("*.json")) + ) + legacy_channels: dict[Any, set[Any]] | None = None + + def _legacy_channels() -> dict[Any, set[Any]]: + nonlocal legacy_channels + if legacy_channels is None: + loaded: dict[Any, set[Any]] = {} + for ingress_path in ingress_paths[:2000]: + try: + item = _read(ingress_path) + loaded.setdefault(item.get("source_id"), set()).add( + item.get("channel") + ) + except (OSError, ValueError, TypeError): + continue + legacy_channels = loaded + return legacy_channels + + unreadable = 0 + candidates_by_goal: dict[str, list[tuple[int, dict[str, Any]]]] = {} paths = sorted( (_root(root) / "entries").glob( "*/" + (request_id + ".json" if request_id else "*.json") ) ) - for path in paths[:2000]: + for scan_index, path in enumerate(paths[:2000]): try: row = _read(path) gid = row.get("goal_id") @@ -85,112 +201,95 @@ def query( if audience != channel_id and not ( audience is None and len(ingress_paths) <= 2000 - and legacy_channels.get(row.get("source_id")) == {channel_id} + and _legacy_channels().get(row.get("source_id")) == {channel_id} ): continue - candidates_by_goal.setdefault(gid, []).append(row) + if not isinstance(gid, str): + raise TypeError("invalid context goal id") + candidates_by_goal.setdefault(gid, []).append((scan_index, row)) except (OSError, ValueError, KeyError, TypeError): unreadable += 1 - # Hold each Goal's lifetime fence once per matched Goal rather than once per - # handoff entry so lock contention cannot amplify into O(N * timeout) stalls. - for gid, group_rows in candidates_by_goal.items(): - try: - with collaboration_goal_scope( - registry_path, - goal_id=gid, - agents=(), - caller_goal_ref=None, - ) as base_scope: - for row in group_rows: - try: - goal_scope = scope_for_caller_goal_ref( - base_scope, - row.get("goal_ref"), - ) - entry = _entry( - root, - row["goal_id"], - row["agent_id"], - row["request_id"], - scope=goal_scope, - ) - decide_collaboration_lifecycle( - goal_scope, - operation="history_inspect", - record=entry, - ) - rows.append(row) - except (OSError, ValueError, KeyError, TypeError): - unreadable += 1 - except (OSError, ValueError, KeyError, TypeError): - unreadable += len(group_rows) - rows.sort( - key=lambda row: (row.get("delivered_at") or "", row["request_id"]), reverse=True - ) - projected, todos_cache = [], {} - core_read_goals = set(evidence_goal_scope(root, channel_id, registry_path=registry_path) or []) if not owner_scope else set() - for row in rows[offset : offset + limit]: - read, read_error = _receipt(root, "reads", row) - decision, decision_error = _receipt(root, "decisions", row) - work = read_linked_work(root, registry_path, row, todos_cache, - include_core_details=owner_scope or row["goal_id"] in core_read_goals) - warnings = [x for x in (read_error, decision_error) if x] + work["warnings"] - item = { - key: row[key] - for key in ("request_id", "goal_id", "agent_id", "source_id", "goal_ref") - if key in row - } - if row.get("source_kind") == "peer": - item.update(source_kind="peer", source_agent_id=row["source_agent_id"], parent_request_id=row.get("parent_request_id")) - if owner_scope and row.get("brief"): - item["brief"] = row["brief"] - item.update( - delivery={"status": "delivered", "at": row.get("delivered_at")}, - read={ - "status": "supplied_to_receiver" - if read - else "decision_exists_read_receipt_missing" - if decision - else "not_recorded", - "at": read.get("read_at"), - }, - decision={ - "status": decision.get("decision", "not_recorded"), - "at": decision.get("decided_at"), - }, - linked_todos=work["linked_todos"], - evidence_refs=work["evidence_refs"], - evidence_verification="receiver_linked_reference_not_independent_verification", - warnings=warnings, + + matched_rows: list[tuple[int, dict[str, Any]]] = [] + lifecycle_cache: _LifecycleDecisionCache = {} + with effect_runtime_request_scope(): + # Hold each Goal's lifetime fence once per matched Goal and reuse pure + # history_inspect decisions so lock-hold time stays bounded to O(unique refs). + for gid, group_rows in candidates_by_goal.items(): + verified, group_unreadable = _verify_goal_group( + root, registry_path, gid, group_rows, lifecycle_cache + ) + matched_rows.extend(verified) + unreadable += group_unreadable + matched_rows.sort(key=lambda item: item[0]) + rows = [row for _, row in matched_rows] + rows.sort( + key=lambda row: (row.get("delivered_at") or "", row["request_id"]), reverse=True ) - from .roundtrip import reply_status - item["return_replies"] = reply_status(root, row) - if owner_scope: - item["decision"]["reason"] = decision.get("reason") - else: - item["decision"]["reason_visibility"] = "owner_only" - controlled = controlled_request_readback(root, row) - if controlled is not None: - item["warnings"] += controlled["warnings"] - current = controlled.get("readback") - if current is not None: - item.update(request_revision=current["request_revision"], read=current["read"], decision=dict(current["decision"])) - if owner_scope: - item["brief"] = current["brief"] - item["request_control"] = controlled["request_control_view"] - else: - item["decision"].pop("reason", None) - item["decision"]["reason_visibility"] = "owner_only" - item["request_control"] = {"control_state": controlled["request_control_view"]["control_state"]} + projected, todos_cache = [], {} + core_read_goals = set(evidence_goal_scope(root, channel_id, registry_path=registry_path) or []) if not owner_scope else set() + for row in rows[offset : offset + limit]: + read, read_error = _receipt(root, "reads", row) + decision, decision_error = _receipt(root, "decisions", row) + work = read_linked_work(root, registry_path, row, todos_cache, + include_core_details=owner_scope or row["goal_id"] in core_read_goals) + warnings = [x for x in (read_error, decision_error) if x] + work["warnings"] + item = { + key: row[key] + for key in ("request_id", "goal_id", "agent_id", "source_id", "goal_ref") + if key in row + } + if row.get("source_kind") == "peer": + item.update(source_kind="peer", source_agent_id=row["source_agent_id"], parent_request_id=row.get("parent_request_id")) + if owner_scope and row.get("brief"): + item["brief"] = row["brief"] + item.update( + delivery={"status": "delivered", "at": row.get("delivered_at")}, + read={ + "status": "supplied_to_receiver" + if read + else "decision_exists_read_receipt_missing" + if decision + else "not_recorded", + "at": read.get("read_at"), + }, + decision={ + "status": decision.get("decision", "not_recorded"), + "at": decision.get("decided_at"), + }, + linked_todos=work["linked_todos"], + evidence_refs=work["evidence_refs"], + evidence_verification="receiver_linked_reference_not_independent_verification", + warnings=warnings, + ) + from .roundtrip import reply_status + item["return_replies"] = reply_status(root, row) + if owner_scope: + item["decision"]["reason"] = decision.get("reason") else: - item["request_control"] = None - item["read"] = {"status": "unavailable", "at": None} - item["decision"] = {"status": "unavailable", "at": None} - revisions = controlled.get("result_revisions") - for reply in item["return_replies"]: - key = reply.get("result_key", reply["phase"]) - reply["request_revision"] = next((value["request_revision"] for value in revisions or [] if value["result_key"] == key), None) - projected.append(item) + item["decision"]["reason_visibility"] = "owner_only" + controlled = controlled_request_readback(root, row) + if controlled is not None: + item["warnings"] += controlled["warnings"] + current = controlled.get("readback") + if current is not None: + item.update(request_revision=current["request_revision"], read=current["read"], decision=dict(current["decision"])) + if owner_scope: + item["brief"] = current["brief"] + item["request_control"] = controlled["request_control_view"] + else: + item["decision"].pop("reason", None) + item["decision"]["reason_visibility"] = "owner_only" + item["request_control"] = {"control_state": controlled["request_control_view"]["control_state"]} + else: + item["request_control"] = None + item["read"] = {"status": "unavailable", "at": None} + item["decision"] = {"status": "unavailable", "at": None} + revisions = controlled.get("result_revisions") + for reply in item["return_replies"]: + key = reply.get("result_key", reply["phase"]) + reply["request_revision"] = next((value["request_revision"] for value in revisions or [] if value["result_key"] == key), None) + projected.append(item) return { "source": "manager_context_receipts_and_core_todos", "observed_at": _now(), diff --git a/tests/test_manager_context_tracking.py b/tests/test_manager_context_tracking.py index d7e2a9606c..6420bae97f 100644 --- a/tests/test_manager_context_tracking.py +++ b/tests/test_manager_context_tracking.py @@ -784,3 +784,291 @@ def spy_scope(reg_path, *, goal_id, agents, caller_goal_ref=None, **kwargs): assert scope_calls == ["delivery"] assert {row["request_id"] for row in result["rows"]} == set(valid_ids) assert result["coverage"]["unreadable"] == 2 + + +def _write_source_registry(registry_path, goals, *, runtime_root=None): + from loopx.control_plane.projects.registry_codec import source_session_registry_transaction + + payload = { + "profile_id": "source_session_v1", + **({"common_runtime_root": str(runtime_root)} if runtime_root is not None else {}), + "goals": [ + { + "id": gid, + "repo": str(registry_path.parent), + "activation": {"schema_version": "loopx_goal_activation_v1", "state": "active"}, + "goal_instance_id": inst_id, + "coordination": {"registered_agents": ["worker"]}, + } + for gid, inst_id in goals + ], + "session_bindings": [], + "session_receipts": [], + "lifetime_receipts": [], + } + with source_session_registry_transaction( + registry_path, operation="test_create_tracking_registry", create=lambda: payload + ) as tx: + tx.commit(tx.payload_copy()) + + +def _write_tracking_entry( + root, + *, + gid, + inst_id, + idx, + channel="manager", + delivered_at=None, + include_goal_ref=True, + dir_key=None, +): + rid = f"{idx:064x}" + goal_ref = {"goal_id": gid, "goal_instance_id": inst_id} + target = ( + {"goal_ref": goal_ref, "agent_id": "worker"} + if include_goal_ref + else {"goal_id": gid, "agent_id": "worker"} + ) + row = { + "schema_version": "loopx_manager_context_entry_v2" if include_goal_ref else "loopx_manager_context_entry_v1", + "request_id": rid, + "goal_id": gid, + "agent_id": "worker", + **({"goal_ref": goal_ref} if include_goal_ref else {}), + "source_id": f"web:{gid}:{idx}", + "message": f"Tracking request {idx}", + "instruction": "Tracking instruction", + "delivered_at": delivered_at or f"2026-11-19T{(idx // 3600) % 24:02d}:{(idx // 60) % 60:02d}:{idx % 60:02d}+00:00", + **({"source_channel": channel} if channel is not None else {}), + } + folder = _root(root) / "entries" / (dir_key or _hash(target)) + folder.mkdir(parents=True, exist_ok=True) + _write(folder / f"{rid}.json", row) + return rid, row + + +def test_query_bounds_registry_loads_and_lifecycle_rpcs_across_many_entries(tmp_path, monkeypatch): + from loopx.capabilities.manager_context import tracking + from loopx.control_plane.collaboration import goal_instance_scope as gis + + inst_a = "ginst_" + "a" * 32 + inst_b = "ginst_" + "b" * 32 + inst_hist = "ginst_" + "c" * 32 + inst_ignored = "ginst_" + "d" * 32 + root = tmp_path / "runtime" + registry = tmp_path / "registry.json" + _write_source_registry( + registry, + [("goal-a", inst_a), ("goal-b", inst_b), ("goal-ignored", inst_ignored)], + ) + + expected_rows = [] + for i in range(50): + channel = "manager.external.one" if i < 10 else "manager.external.two" + _, row = _write_tracking_entry(root, gid="goal-a", inst_id=inst_a, idx=i, channel=channel) + expected_rows.append(row) + for i in range(50, 80): + if i < 55: + channel = None + _write( + _root(root) / "ingress" / f"{i:064x}.json", + {"source_id": f"web:goal-a:{i}", "channel": "manager.external.one"}, + ) + else: + channel = "manager.external.two" + _, row = _write_tracking_entry(root, gid="goal-a", inst_id=inst_hist, idx=i, channel=channel) + expected_rows.append(row) + for i in range(80, 100): + _, row = _write_tracking_entry(root, gid="goal-b", inst_id=inst_b, idx=i, channel="manager.external.two") + expected_rows.append(row) + for i in range(100, 120): + _write_tracking_entry(root, gid="goal-ignored", inst_id=inst_ignored, idx=i, channel="manager.external.one") + + orig_load = gis.load_project_registry + orig_scope = tracking.collaboration_goal_scope + orig_rpc = gis.effect_runtime_result + counts = {"load": 0, "scope": 0, "decide_rpc": 0} + + def counted_load(path): + counts["load"] += 1 + return orig_load(path) + + def counted_scope(*args, **kwargs): + counts["scope"] += 1 + return orig_scope(*args, **kwargs) + + def counted_rpc(method, params, **kwargs): + if method == "collaboration.goal_instance.decide": + counts["decide_rpc"] += 1 + return orig_rpc(method, params, **kwargs) + + monkeypatch.setattr(gis, "load_project_registry", counted_load) + monkeypatch.setattr(tracking, "collaboration_goal_scope", counted_scope) + monkeypatch.setattr(gis, "effect_runtime_result", counted_rpc) + + result = query(root, registry, goal_ids=["goal-a", "goal-b"], owner_scope=True, offset=5, limit=8) + expected_rows.sort(key=lambda r: (r["delivered_at"], r["request_id"]), reverse=True) + assert result["matched"] == 100 + assert result["coverage"] == { + "scan_complete": True, + "legacy_audience_scan_complete": True, + "unreadable": 0, + } + assert [r["request_id"] for r in result["rows"]] == [r["request_id"] for r in expected_rows[5:13]] + assert counts == {"load": 2, "scope": 2, "decide_rpc": 3} + + # Audience pre-filtering skips goal-b entirely before locks, registry, or RPCs. + counts.update(load=0, scope=0, decide_rpc=0) + external = query( + root, + registry, + goal_ids=["goal-a", "goal-b"], + owner_scope=False, + channel_id="manager.external.one", + offset=0, + limit=12, + ) + assert external["matched"] == 15 + assert len(external["rows"]) == 12 + assert counts == {"load": 1, "scope": 1, "decide_rpc": 2} + + # Legacy registry (profile_id != source_session_v1) makes zero lifecycle RPCs. + legacy_root = tmp_path / "legacy-runtime" + legacy_registry = tmp_path / "legacy-registry.json" + legacy_registry.write_text( + json.dumps( + { + "goals": [ + {"id": "goal-a", "repo": str(tmp_path), "coordination": {"registered_agents": ["worker"]}}, + {"id": "goal-b", "repo": str(tmp_path), "coordination": {"registered_agents": ["worker"]}}, + ] + } + ) + ) + for i in range(40): + gid = "goal-a" if i < 20 else "goal-b" + _write_tracking_entry(legacy_root, gid=gid, inst_id=inst_a, idx=i, include_goal_ref=False) + counts.update(load=0, scope=0, decide_rpc=0) + legacy_result = query(legacy_root, legacy_registry, goal_ids=["goal-a", "goal-b"], owner_scope=True, limit=10) + assert legacy_result["matched"] == 40 + assert len(legacy_result["rows"]) == 10 + assert counts == {"load": 2, "scope": 2, "decide_rpc": 0} + + +def test_query_preserves_unreadable_and_lifecycle_rejection_parity_in_batches(tmp_path, monkeypatch): + from loopx.capabilities.manager_context import tracking + from loopx.capabilities.manager_context.roundtrip import report + from loopx.chat_store import ChatSessionStore + from loopx.control_plane.collaboration import goal_instance_scope as gis + from loopx.control_plane.collaboration.request_control_source import execute_request_control + + inst_a = "ginst_" + "a" * 32 + inst_hist = "ginst_" + "b" * 32 + inst_mismatch = "ginst_" + "c" * 32 + inst_other = "ginst_" + "d" * 32 + root = tmp_path / "runtime" + registry = tmp_path / "registry.json" + _write_source_registry(registry, [("goal-a", inst_a)], runtime_root=root) + + store = ChatSessionStore(root) + session = store.create_session( + goal_id="loopx-manager", agent_id="codex", adapter_kind="codex_app_server", + upstream_thread_id="fixture", channel_id="manager", + ) + turn, _ = store.create_turn(session["session_id"], client_turn_id="ctrl-1", message="Check controlled", origin="web") + brief = { + "schema_version": "collaboration_brief_v0", + "purpose": "Verify controlled readback", + "context": "Keep current instance", + "constraints": [], + "inputs": [], + "acceptance": ["Readback matches"], + "return_requirement": "Return findings", + } + ctrl_receipt = deliver( + root, registry, session=session, turn=turn, + request={"goal_id": "goal-a", "agent_id": "worker", "brief": brief}, + source_store=store, + ) + ctrl_rid = ctrl_receipt["request_id"] + ctrl_view = execute_request_control( + registry_path=registry, runtime_root=root, goal_ref=ctrl_receipt["goal_ref"], + receiver_agent_id="worker", request_id=ctrl_rid, actor_agent_id=None, + operation="inspect", execute=False, + )["view"] + revised = execute_request_control( + registry_path=registry, runtime_root=root, goal_ref=ctrl_receipt["goal_ref"], + receiver_agent_id="worker", request_id=ctrl_rid, actor_agent_id=None, + operation="revise", + parameters={ + "operation_id": "rev-1", + "expected_revision": ctrl_view["revision"], + "expected_digest": ctrl_view["revision_digest"], + "brief": {**brief, "purpose": "Revised purpose"}, + "reason": "Updated requirement", + }, + execute=True, + )["view"] + acknowledge( + root, "goal-a", "worker", ctrl_rid, "adopt", "Accepted", + registry=registry, caller_goal_ref=ctrl_receipt["goal_ref"], + request_revision=2, request_revision_digest=revised["revision_digest"], + ) + report( + root, "goal-a", "worker", ctrl_rid, "conclusion", "Checked.", + registry=registry, caller_goal_ref=ctrl_receipt["goal_ref"], + request_revision=2, + ) + + valid_curr_id, _ = _write_tracking_entry(root, gid="goal-a", inst_id=inst_a, idx=1, delivered_at="2026-11-19T00:01:00+00:00") + valid_hist_id, _ = _write_tracking_entry(root, gid="goal-a", inst_id=inst_hist, idx=2, delivered_at="2026-11-19T00:02:00+00:00") + + corrupt_dir = _root(root) / "entries" / _hash({"goal_ref": {"goal_id": "goal-a", "goal_instance_id": inst_a}, "agent_id": "worker"}) + (corrupt_dir / f"{'e' * 64}.json").write_text("{damaged", encoding="utf-8") + _write(corrupt_dir / f"{'f' * 64}.json", {"goal_id": "goal-a"}) + _write(corrupt_dir / f"{'1' * 63}a.json", {"goal_id": "goal-a", "agent_id": "worker", "request_id": f"{'1' * 63}a", "goal_ref": "bad"}) + _write(corrupt_dir / f"{'1' * 63}b.json", {"goal_id": "goal-a", "agent_id": "worker", "request_id": f"{'1' * 63}b", "goal_ref": {"goal_id": "goal-a", "goal_instance_id": "invalid"}}) + _write_tracking_entry(root, gid="goal-a", inst_id=inst_a, idx=3, include_goal_ref=False) + _write_tracking_entry(root, gid="goal-a", inst_id=inst_a, idx=4, dir_key="wrongdir") + _write_tracking_entry(root, gid="unregistered-goal", inst_id=inst_a, idx=5) + _write_tracking_entry(root, gid="unregistered-goal", inst_id=inst_a, idx=6) + + mismatch_ids = set() + for i in range(10, 15): + rid, _ = _write_tracking_entry(root, gid="goal-a", inst_id=inst_mismatch, idx=i) + mismatch_ids.add(rid) + + orig_entry = tracking._entry + orig_rpc = gis.effect_runtime_result + decide_calls = 0 + + def wrapped_entry(entry_root, goal_id, agent_id, req_id, *, scope=None): + row = orig_entry(entry_root, goal_id, agent_id, req_id, scope=scope) + if req_id in mismatch_ids: + return {**row, "goal_ref": {"goal_id": "goal-a", "goal_instance_id": inst_other}} + return row + + def counted_rpc(method, params, **kwargs): + nonlocal decide_calls + if method == "collaboration.goal_instance.decide": + decide_calls += 1 + return orig_rpc(method, params, **kwargs) + + monkeypatch.setattr(tracking, "_entry", wrapped_entry) + monkeypatch.setattr(gis, "effect_runtime_result", counted_rpc) + + result = query(root, registry, goal_ids=["goal-a", "unregistered-goal"], owner_scope=True, limit=12) + assert result["matched"] == 3 + assert result["coverage"]["unreadable"] == 13 + assert {r["request_id"] for r in result["rows"]} == {ctrl_rid, valid_curr_id, valid_hist_id} + assert decide_calls == 3 + + by_id = {r["request_id"]: r for r in result["rows"]} + assert by_id[ctrl_rid]["request_revision"] == 2 + assert isinstance(by_id[ctrl_rid]["request_control"], dict) + assert by_id[ctrl_rid]["request_control"]["control_state"] + assert by_id[ctrl_rid]["brief"]["purpose"] == "Revised purpose" + assert len(by_id[ctrl_rid]["return_replies"]) == 1 + assert by_id[ctrl_rid]["return_replies"][0]["request_revision"] == 2 + assert by_id[valid_hist_id]["goal_ref"] == {"goal_id": "goal-a", "goal_instance_id": inst_hist}