From 6cfb1aebdef81caad4a73b8742948a68372fa56d Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:17:58 +0800 Subject: [PATCH] refactor(work-items): modularize autonomous_replan_ack with zero Any and linear writeback indexing Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../goals/goal_frontier/semantic_history.py | 5 +- .../work_items/autonomous_replan_ack.py | 653 +++++------------- .../autonomous_replan_ack_history.py | 400 +++++++++++ .../test_autonomous_replan_ack_contract.py | 341 +++++++++ 4 files changed, 921 insertions(+), 478 deletions(-) create mode 100644 loopx/control_plane/work_items/autonomous_replan_ack_history.py create mode 100644 tests/control_plane/test_autonomous_replan_ack_contract.py diff --git a/loopx/control_plane/goals/goal_frontier/semantic_history.py b/loopx/control_plane/goals/goal_frontier/semantic_history.py index f120b8406c..395ea4b7dd 100644 --- a/loopx/control_plane/goals/goal_frontier/semantic_history.py +++ b/loopx/control_plane/goals/goal_frontier/semantic_history.py @@ -262,7 +262,10 @@ def receipt_bound_replan_source_acks( if stamp is None or stamp >= cutoff: continue ack = compact_autonomous_replan_ack(row) - obligation_id = ((ack or {}).get("semantic_delta") or {}).get("obligation_id") + semantic_delta = ack.get("semantic_delta") if isinstance(ack, dict) else None + obligation_id = ( + semantic_delta.get("obligation_id") if isinstance(semantic_delta, dict) else None + ) if isinstance(obligation_id, str) and obligation_id not in seen: seen.add(obligation_id) candidates.append(ack) diff --git a/loopx/control_plane/work_items/autonomous_replan_ack.py b/loopx/control_plane/work_items/autonomous_replan_ack.py index 9c659a6e21..328416b70c 100644 --- a/loopx/control_plane/work_items/autonomous_replan_ack.py +++ b/loopx/control_plane/work_items/autonomous_replan_ack.py @@ -1,12 +1,31 @@ +"""Compact autonomous replan ACK normalization, candidate lookup, and frontier helpers.""" + from __future__ import annotations -from collections.abc import Mapping +from collections.abc import Mapping, Sequence from pathlib import Path -from typing import Any, NamedTuple +from typing import NamedTuple -from ..effect_runtime import effect_runtime_result -from ..goals.goal_ref_validation import exact_goal_ref +from ..effect_runtime import effect_runtime_result as effect_runtime_result from ..runtime.time import parse_timestamp +from .autonomous_replan_ack_history import ( + AckMapping, + AckObject, + _admission_event_index as _admission_event_index, + _attach_writeback_order_owned, + _binding_text as _binding_text, + _event_details as _event_details, + _expected_todo_receipt as _expected_todo_receipt, + _original_writeback_event_index as _original_writeback_event_index, + _owned_records as _owned_records, + _owner_goal_ref as _owner_goal_ref, + _parsed_exact_goal_ref as _parsed_exact_goal_ref, + _record_owned_by_goal_ref as _record_owned_by_goal_ref, + _source_run as _source_run, + _writeback_event_is_bound as _writeback_event_is_bound, + attach_historical_ack_writeback_order as attach_historical_ack_writeback_order, + drop_unowned_recorded_replan_acks as drop_unowned_recorded_replan_acks, +) from .progress_observation import FRESH_VISION_PATH_DISPOSITIONS AUTONOMOUS_REPLAN_ACK_MATERIAL_RUN_WINDOW = 20 @@ -18,14 +37,39 @@ # lanes also fill cannot decide one lane's material-run count. AUTONOMOUS_REPLAN_PERIODIC_LOOKBACK = AUTONOMOUS_REPLAN_ACK_MATERIAL_RUN_WINDOW * 3 +_COMPACT_SEMANTIC_DELTA_FIELDS = ( + "schema_version", + "accepted", + "outcomes", + "satisfying_outcomes", + "required_any_of", + "trigger_kinds", + "trigger_checkpoints", + "obligation_id", + "successor_todo_id", + "successor_origin_obligation_id", + "successor_binding", + "observation_fingerprint", + "reason", +) + class SettlementHistoryQualification(NamedTuple): accepted_blocked_replans: frozenset[int] active_turn_retries: frozenset[int] +def _accepted_semantic_delta(ack: object) -> AckMapping | None: + if not isinstance(ack, Mapping) or ack.get("recorded") is not True: + return None + semantic_delta = ack.get("semantic_delta") + if not isinstance(semantic_delta, Mapping) or semantic_delta.get("accepted") is not True: + return None + return semantic_delta + + def qualify_settlement_history( - runs: list[dict[str, Any]], *, observed_at: str | None = None, + runs: Sequence[AckMapping], *, observed_at: str | None = None, ) -> SettlementHistoryQualification: """Transport a history batch to its settlement owner, preserving originals. @@ -49,23 +93,28 @@ def qualify_settlement_history( "runs": [{key: runs[index][key] for key in fields if key in runs[index]} for index in candidates], }, large_local_snapshot=True) + result_map: AckMapping = result if isinstance(result, Mapping) else {} + def indexes(field: str) -> frozenset[int]: - values = result.get(field) if isinstance(result, dict) else None - if not isinstance(values, list) or any( - type(index) is not int or not 0 <= index < len(candidates) for index in values - ): + values = result_map.get(field) + if not isinstance(values, list): raise RuntimeError("TypeScript settlement history result must contain valid indexes") - return frozenset(candidates[index] for index in values) + resolved: list[int] = [] + for index in values: + if not isinstance(index, int) or type(index) is not int or not 0 <= index < len(candidates): + raise RuntimeError("TypeScript settlement history result must contain valid indexes") + resolved.append(candidates[index]) + return frozenset(resolved) return SettlementHistoryQualification(indexes("accepted_indexes"), indexes("active_retry_indexes")) -def accepted_blocked_replan_history_indexes(runs: list[dict[str, Any]]) -> frozenset[int]: +def accepted_blocked_replan_history_indexes(runs: Sequence[AckMapping]) -> frozenset[int]: """Legacy outcome reader needs administrative qualification, not a clock.""" return qualify_settlement_history(runs).accepted_blocked_replans -def ack_binds_trigger_checkpoints(ack: dict[str, Any] | None) -> bool: +def ack_binds_trigger_checkpoints(ack: AckMapping | None) -> bool: """Return whether an ACK binds exact typed trigger revisions. A checkpoint-bearing ACK is revision-gated: the typed frontier evaluator @@ -75,144 +124,112 @@ def ack_binds_trigger_checkpoints(ack: dict[str, Any] | None) -> bool: is why it stays visible for the whole scanned history instead of expiring with the material-run window. """ - - semantic_delta = ack.get("semantic_delta") if isinstance(ack, dict) else None - if not isinstance(semantic_delta, dict): + semantic_delta = ack.get("semantic_delta") if isinstance(ack, Mapping) else None + if not isinstance(semantic_delta, Mapping): return False checkpoints = semantic_delta.get("trigger_checkpoints") if not isinstance(checkpoints, list): return False return any( - isinstance(checkpoint, dict) - and str(checkpoint.get("kind") or "").strip() - and str(checkpoint.get("frontier_revision") or "").strip() + isinstance(checkpoint, Mapping) + and _binding_text(checkpoint.get("kind")) + and _binding_text(checkpoint.get("frontier_revision")) for checkpoint in checkpoints ) def normalize_projected_autonomous_replan_ack( - ack: dict[str, Any] | None, -) -> dict[str, Any] | None: + ack: AckMapping | None, +) -> AckObject | None: """Return only ACKs already carrying the current semantic contract.""" - - if not isinstance(ack, dict) or ack.get("recorded") is not True: + if _accepted_semantic_delta(ack) is None or not isinstance(ack, Mapping): return None - normalized = dict(ack) - semantic_delta = normalized.get("semantic_delta") - if not isinstance(semantic_delta, dict) or semantic_delta.get("accepted") is not True: - return None - return normalized + return dict(ack) -def autonomous_replan_ack_recorded(run: dict[str, Any]) -> bool: - ack = run.get("autonomous_replan_ack") - if not isinstance(ack, dict) or ack.get("recorded") is not True: - return False - normalized = normalize_projected_autonomous_replan_ack(ack) - return bool( - isinstance(normalized, dict) - and isinstance(normalized.get("semantic_delta"), dict) - and normalized["semantic_delta"].get("accepted") is True - ) +def autonomous_replan_ack_recorded(run: AckMapping) -> bool: + return _accepted_semantic_delta(run.get("autonomous_replan_ack")) is not None def watch_lane_continuation_todo_ids( - delta_contract: dict[str, Any] | None, + delta_contract: AckMapping | None, ) -> list[str]: """Return the exact Todo evidence carried by a validated watch delta.""" - - if not isinstance(delta_contract, dict): + if not isinstance(delta_contract, Mapping): return [] todo_ids: list[str] = [] - for item in delta_contract.get("auto_evidence") or []: - if not isinstance(item, dict) or item.get("kind") != "watch_lane_continuation": + auto_evidence = delta_contract.get("auto_evidence") + if not isinstance(auto_evidence, Sequence) or isinstance(auto_evidence, (str, bytes)): + return todo_ids + for item in auto_evidence: + if not isinstance(item, Mapping) or item.get("kind") != "watch_lane_continuation": + continue + raw_todo_ids = item.get("todo_ids") + if not isinstance(raw_todo_ids, Sequence) or isinstance(raw_todo_ids, (str, bytes)): continue - for raw_todo_id in item.get("todo_ids") or []: - todo_id = str(raw_todo_id or "").strip() + for raw_todo_id in raw_todo_ids: + todo_id = _binding_text(raw_todo_id) if todo_id and todo_id not in todo_ids: todo_ids.append(todo_id) return todo_ids -def compact_autonomous_replan_ack(run: dict[str, Any] | None) -> dict[str, Any] | None: - if not isinstance(run, dict) or not autonomous_replan_ack_recorded(run): +def compact_autonomous_replan_ack(run: AckMapping | None) -> AckObject | None: + if not isinstance(run, Mapping): return None - ack = run.get("autonomous_replan_ack") - if not isinstance(ack, dict): + raw_ack = run.get("autonomous_replan_ack") + semantic_delta = _accepted_semantic_delta(raw_ack) + if semantic_delta is None or not isinstance(raw_ack, Mapping): return None - normalized_ack = normalize_projected_autonomous_replan_ack(ack) - if normalized_ack is None: - return None - semantic_delta = normalized_ack["semantic_delta"] - result = { - "schema_version": ack.get("schema_version"), + result: AckObject = { + "schema_version": raw_ack.get("schema_version"), "recorded": True, - "source": ack.get("source"), + "source": raw_ack.get("source"), "semantic_delta": { field: semantic_delta.get(field) - for field in ( - "schema_version", - "accepted", - "outcomes", - "satisfying_outcomes", - "required_any_of", - "trigger_kinds", - "trigger_checkpoints", - "obligation_id", - "successor_todo_id", - "successor_origin_obligation_id", - "successor_binding", - "observation_fingerprint", - "reason", - ) + for field in _COMPACT_SEMANTIC_DELTA_FIELDS if semantic_delta.get(field) is not None }, } outcomes = semantic_delta.get("outcomes") - if ( - isinstance(outcomes, list) - and "fresh_vision_path_outcome" in outcomes - ): + if isinstance(outcomes, list) and "fresh_vision_path_outcome" in outcomes: raw_vision = run.get("agent_vision") - agent_vision = raw_vision if isinstance(raw_vision, dict) else {} + agent_vision: AckMapping = raw_vision if isinstance(raw_vision, Mapping) else {} raw_path = agent_vision.get("path_delta") - path_delta = raw_path if isinstance(raw_path, dict) else {} - path_disposition = str(path_delta.get("outcome") or "").strip() + path_delta: AckMapping = raw_path if isinstance(raw_path, Mapping) else {} + path_disposition = _binding_text(path_delta.get("outcome")) if path_disposition in FRESH_VISION_PATH_DISPOSITIONS: result["path_disposition"] = path_disposition - delta_contract = ack.get("delta_contract") - if isinstance(delta_contract, dict): + delta_contract = raw_ack.get("delta_contract") + if isinstance(delta_contract, Mapping): + raw_kinds = delta_contract.get("delta_kinds") + raw_evidence = delta_contract.get("auto_evidence") result["delta_contract"] = { "schema_version": delta_contract.get("schema_version"), "delta_present": bool(delta_contract.get("delta_present")), "delta_kinds": [ str(item) - for item in (delta_contract.get("delta_kinds") or []) - if str(item or "").strip() + for item in (raw_kinds if isinstance(raw_kinds, list) else ()) + if _binding_text(item) ], "auto_evidence": [ dict(item) - for item in (delta_contract.get("auto_evidence") or []) - if isinstance(item, dict) + for item in (raw_evidence if isinstance(raw_evidence, list) else ()) + if isinstance(item, Mapping) ][:6], } - goal_id = str(run.get("goal_id") or "").strip() - if goal_id: - result["goal_id"] = goal_id - agent_id = str(run.get("agent_id") or "").strip() - if agent_id: - result["agent_id"] = agent_id - turn_instance_id = str(run.get("turn_instance_id") or "").strip() - if turn_instance_id: - result["turn_instance_id"] = turn_instance_id - frontier_identity = str(ack.get("frontier_identity") or "").strip() - if frontier_identity: - result["frontier_identity"] = frontier_identity - generated_at = str(run.get("generated_at") or "").strip() - if generated_at: - result["generated_at"] = generated_at - todo_source = run.get("todo_source", normalized_ack.get("todo_source")) - if isinstance(todo_source, dict): + for key, source in ( + ("goal_id", run), + ("agent_id", run), + ("turn_instance_id", run), + ("frontier_identity", raw_ack), + ("generated_at", run), + ): + text = _binding_text(source.get(key)) + if text: + result[key] = text + todo_source = run.get("todo_source", raw_ack.get("todo_source")) + if isinstance(todo_source, Mapping): # Transport the original provider anchor, never a current-head alias. # The canonical source reader validates it before legacy ACK recovery. result["todo_source"] = dict(todo_source) @@ -220,13 +237,13 @@ def compact_autonomous_replan_ack(run: dict[str, Any] | None) -> dict[str, Any] def autonomous_replan_ack_candidates_for_obligation( - newest_first_runs: list[dict[str, Any]] | None, + newest_first_runs: Sequence[AckMapping] | None, *, goal_id: str | None, agent_id: str | None, obligation_id: str | None, limit: int = AUTONOMOUS_REPLAN_ACK_RECOVERY_CANDIDATE_LIMIT, -) -> list[dict[str, Any]]: +) -> list[AckObject]: """Project a bounded set of exact durable ACK candidates for recovery. This lookup prevents a newer unrelated ACK from hiding an older ACK for a @@ -234,20 +251,19 @@ def autonomous_replan_ack_candidates_for_obligation( the TypeScript settlement owner still validates schema, outcomes, chronology, and the distinct durable Turn before accepting any candidate. """ - - safe_goal_id = str(goal_id or "").strip() - safe_agent_id = str(agent_id or "").strip() - safe_obligation_id = str(obligation_id or "").strip() + safe_goal_id = _binding_text(goal_id) + safe_agent_id = _binding_text(agent_id) + safe_obligation_id = _binding_text(obligation_id) if not safe_goal_id or not safe_agent_id or not safe_obligation_id or limit <= 0: return [] - candidates: list[dict[str, Any]] = [] + candidates: list[AckObject] = [] seen: set[tuple[str, str, str]] = set() - for run in newest_first_runs or []: + for run in newest_first_runs or (): compact = compact_autonomous_replan_ack(run) - if not isinstance(compact, dict): + if compact is None: continue semantic_delta = compact.get("semantic_delta") - if not isinstance(semantic_delta, dict): + if not isinstance(semantic_delta, Mapping): continue if ( compact.get("goal_id") != safe_goal_id @@ -256,8 +272,8 @@ def autonomous_replan_ack_candidates_for_obligation( ): continue identity = ( - str(compact.get("turn_instance_id") or "").strip(), - str(compact.get("generated_at") or "").strip(), + _binding_text(compact.get("turn_instance_id")), + _binding_text(compact.get("generated_at")), safe_obligation_id, ) if identity in seen: @@ -269,311 +285,15 @@ def autonomous_replan_ack_candidates_for_obligation( return candidates -def _event_details(event: dict[str, Any]) -> dict[str, Any]: - details = event.get("details") - return details if isinstance(details, dict) else {} - - -def _parsed_exact_goal_ref(value: object) -> dict[str, str] | None: - """Parse one exact GoalRef, keeping the native string-only rule.""" - if not isinstance(value, Mapping): - return None - goal_id = value.get("goal_id") - instance_id = value.get("goal_instance_id") - if not isinstance(goal_id, str) or not isinstance(instance_id, str): - return None - try: - return exact_goal_ref(goal_id, instance_id) - except ValueError: - return None - - -def _owner_goal_ref( - goal_ref: Mapping[str, Any] | None, *, goal_id: str, -) -> dict[str, str] | None: - """Normalize the quota owner. None is the alias owner.""" - if goal_ref is None: - return None - owner = _parsed_exact_goal_ref(goal_ref) - if owner is None or owner["goal_id"] != str(goal_id or "").strip(): - raise ValueError("historical ACK GoalRef does not match goal_id") - return owner - - -def _record_owned_by_goal_ref( - record: Mapping[str, Any], owner: dict[str, str] | None, -) -> bool: - """Match quotaOwnerOwnsProjection for one rollout or run-index row. - - An alias owner keeps only rows with no goal_ref. An exact owner keeps - only rows whose goal_ref is that exact Goal instance. Non-string ids are - not owned, matching the strict GoalRef parser. - """ - if owner is None: - return "goal_ref" not in record - if "goal_ref" not in record: - return False - parsed = _parsed_exact_goal_ref(record.get("goal_ref")) - return parsed == owner - - -def drop_unowned_recorded_replan_acks( - runs: list[dict[str, Any]] | None, *, goal_id: str, - goal_ref: Mapping[str, Any] | None, -) -> tuple[list[dict[str, Any]], bool]: - """Drop recorded replan ACKs that belong to another Goal instance. - - Other run rows stay. Alias owners keep ACKs with no goal_ref; an exact - owner keeps only its own goal_ref. - """ - owner = _owner_goal_ref(goal_ref, goal_id=goal_id) - kept: list[dict[str, Any]] = [] - changed = False - for run in runs or []: - if not isinstance(run, dict): - continue - ack = run.get("autonomous_replan_ack") - if ( - isinstance(ack, dict) - and ack.get("recorded") is True - and not _record_owned_by_goal_ref(run, owner) - ): - changed = True - continue - kept.append(run) - return kept, changed - - -def _owned_records( - records: list[dict[str, Any]] | None, owner: dict[str, str] | None, -) -> list[dict[str, Any]]: - return [ - record for record in records or [] - if isinstance(record, dict) and _record_owned_by_goal_ref(record, owner) - ] - - -def _admission_event_index( - events: list[dict[str, Any]], *, goal_id: str, agent_id: str, - turn_instance_id: str, recorded_at: str, - owner_goal_ref: dict[str, str] | None, - event_id: str | None = None, -) -> int | None: - """Log position of the Turn's original bound admission. - - The settlement readback names that event after GoalRef filtering. Matching - the id keeps a retired Goal instance that reused this Turn id out of the - order. Callers without an id use the first row with the admission time. - """ - - if not turn_instance_id: - return None - if event_id: - for index, event in enumerate(events): - if not _record_owned_by_goal_ref(event, owner_goal_ref): - continue - if ( - event.get("event_id") == event_id - and event.get("event_kind") == "quota_should_run" - and event.get("goal_id") == goal_id - and event.get("agent_id") == agent_id - and event.get("run_id") == turn_instance_id - ): - return index - return None - if not recorded_at: - return None - for index, event in enumerate(events): - if not _record_owned_by_goal_ref(event, owner_goal_ref): - continue - if ( - event.get("event_kind") == "quota_should_run" - and event.get("goal_id") == goal_id - and event.get("agent_id") == agent_id - and event.get("run_id") == turn_instance_id - and event.get("recorded_at") == recorded_at - ): - return index - return None - - -def _binding_text(value: Any) -> str: - return str(value or "").strip() - - -def _source_run( - runs: list[dict[str, Any]] | None, *, turn_instance_id: str, obligation_id: str, - owner_goal_ref: dict[str, str] | None, -) -> dict[str, Any]: - for run in runs or []: - if not _record_owned_by_goal_ref(run, owner_goal_ref): - continue - if _binding_text(run.get("turn_instance_id")) != turn_instance_id: - continue - ack = run.get("autonomous_replan_ack") - delta = ack.get("semantic_delta") if isinstance(ack, dict) else None - if isinstance(delta, dict) and _binding_text(delta.get("obligation_id")) == obligation_id: - return run - return {} - - -def _expected_todo_receipt( - run: dict[str, Any], events: list[dict[str, Any]], *, - goal_id: str, agent_id: str, turn_instance_id: str, obligation_id: str, - owner_goal_ref: dict[str, str] | None, -) -> tuple[str, str]: - """Todo command identity for this ACK, filled from its heartbeat receipt. - - A historical index can omit the Todo and effect. The turn's existing - quota receipt still has that exact identity. A replan-bound receipt keeps - the admitted Todo as its pending action selection; that retained selection - may address the writeback without replacing the receipt's obligation. - An empty or differently bound side is not a match. - """ - - identity = run.get("settlement_identity") - identity = identity if isinstance(identity, dict) else {} - todo = _binding_text(run.get("todo_id") or identity.get("todo_id")) - effect = _binding_text(identity.get("effect_id")) - if todo and effect: - return todo, effect - for event in events: - if not _record_owned_by_goal_ref(event, owner_goal_ref): - continue - if ( - event.get("event_kind") != "quota_should_run" - or event.get("goal_id") != goal_id - or event.get("agent_id") != agent_id - or _binding_text(event.get("run_id")) != turn_instance_id - ): - continue - details = _event_details(event) - receipt_replan = _binding_text(details.get("replan_obligation_id")) - retained_todo = ( - _binding_text(details.get("pending_action_selection_todo_id")) - if receipt_replan == obligation_id - else "" - ) - todo = todo or _binding_text( - event.get("todo_id") or details.get("todo_id") or retained_todo - ) - effect = effect or _binding_text(details.get("settlement_effect_id")) - return todo, effect - - -def _writeback_event_is_bound( - event: dict[str, Any], run: dict[str, Any], events: list[dict[str, Any]], *, - goal_id: str, agent_id: str, obligation_id: str, turn_instance_id: str, - owner_goal_ref: dict[str, str] | None, -) -> bool: - """Require one positive identity shared with the accepted ACK. - - The event obligation must equal the semantic delta, or its Todo and effect - must equal the ACK receipt. Missing fields do not count as agreement. - """ - - if not _record_owned_by_goal_ref(event, owner_goal_ref): - return False - if ( - event.get("event_kind") != "refresh_state" - or event.get("goal_id") != goal_id - or event.get("agent_id") != agent_id - or _binding_text(event.get("run_id")) != turn_instance_id - ): - return False - details = _event_details(event) - if details.get("autonomous_replan_recorded") is not True: - return False - event_obligation = _binding_text(details.get("replan_obligation_id")) - if event_obligation: - return event_obligation == obligation_id - event_todo = _binding_text(event.get("todo_id")) - event_effect = _binding_text(details.get("settlement_effect_id")) - if not event_todo or not event_effect: - return False - expected_todo, expected_effect = _expected_todo_receipt( - run, events, goal_id=goal_id, agent_id=agent_id, - turn_instance_id=turn_instance_id, obligation_id=obligation_id, - owner_goal_ref=owner_goal_ref) - return bool( - expected_todo and expected_effect - and event_todo == expected_todo and event_effect == expected_effect - ) - - -def _original_writeback_event_index( - events: list[dict[str, Any]], runs: list[dict[str, Any]] | None, *, - goal_id: str, agent_id: str, obligation_id: str, turn_instance_id: str, - owner_goal_ref: dict[str, str] | None, -) -> int | None: - if not turn_instance_id or not obligation_id: - return None - run = _source_run( - runs, turn_instance_id=turn_instance_id, obligation_id=obligation_id, - owner_goal_ref=owner_goal_ref) - for index, event in enumerate(events): - if _writeback_event_is_bound( - event, run, events, goal_id=goal_id, agent_id=agent_id, - obligation_id=obligation_id, turn_instance_id=turn_instance_id, - owner_goal_ref=owner_goal_ref, - ): - return index - return None - - -def attach_historical_ack_writeback_order( - candidates: list[dict[str, Any]], events: list[dict[str, Any]], *, - goal_id: str, agent_id: str, obligation_id: str, - guard_recorded_at: str | None, guard_turn_instance_id: str | None, - runs: list[dict[str, Any]] | None = None, - goal_ref: Mapping[str, Any] | None = None, - admission_event_id: str | None = None, -) -> None: - """Copy the original refresh event order onto matching ACK candidates. - - The compact run clock is whole seconds. The decision owner compares this - event with admission; this reader only selects the bound original event. - """ - - owner = _owner_goal_ref(goal_ref, goal_id=goal_id) - owned_events = _owned_records(events, owner) - owned_runs = _owned_records(runs, owner) - admission_index = _admission_event_index( - owned_events, goal_id=goal_id, agent_id=agent_id, - turn_instance_id=str(guard_turn_instance_id or "").strip(), - recorded_at=str(guard_recorded_at or "").strip(), - event_id=str(admission_event_id or "").strip() or None, - owner_goal_ref=owner, - ) - for candidate in candidates: - turn_instance_id = _binding_text(candidate.get("turn_instance_id")) - evidence_index = _original_writeback_event_index( - owned_events, owned_runs, goal_id=goal_id, agent_id=agent_id, - obligation_id=obligation_id, turn_instance_id=turn_instance_id, - owner_goal_ref=owner, - ) - if evidence_index is None: - continue - event = owned_events[evidence_index] - candidate["writeback_recorded_at"] = event.get("recorded_at") - candidate["writeback_goal_id"] = event.get("goal_id") - candidate["writeback_agent_id"] = event.get("agent_id") - candidate["writeback_turn_instance_id"] = event.get("run_id") - candidate["writeback_obligation_id"] = obligation_id - candidate["writeback_follows_admission"] = ( - admission_index is not None and evidence_index > admission_index - ) - - def historical_ack_candidates_with_writeback_order( - newest_first_runs: list[dict[str, Any]] | None, *, + newest_first_runs: Sequence[AckMapping] | None, *, goal_id: str, agent_id: str, obligation_id: str | None, guard_scoped: bool = True, runtime_root: Path | str | None = None, - source_route: Any = None, + source_route: object = None, guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None, - goal_ref: Mapping[str, Any] | None = None, + goal_ref: AckMapping | None = None, admission_event_id: str | None = None, -) -> list[dict[str, Any]]: +) -> list[AckObject]: """Project obligation candidates and attach their original writeback order.""" from ...rollout_event_log import load_rollout_events, rollout_event_log_path @@ -582,16 +302,16 @@ def historical_ack_candidates_with_writeback_order( selected = _binding_text(obligation_id) if guard_scoped else "" candidates = autonomous_replan_ack_candidates_for_obligation( owned_runs, goal_id=goal_id, agent_id=agent_id, obligation_id=selected or None) - route = source_route if isinstance(source_route, dict) else {} + route: AckMapping = source_route if isinstance(source_route, Mapping) else {} root_text = runtime_root or route.get("runtime_root") root = Path(str(root_text)) if root_text else None if root is None or not selected: return candidates - attach_historical_ack_writeback_order( + _attach_writeback_order_owned( candidates, load_rollout_events(rollout_event_log_path(root, goal_id)), goal_id=goal_id, agent_id=agent_id, obligation_id=selected, guard_recorded_at=guard_recorded_at, guard_turn_instance_id=guard_turn_instance_id, - runs=owned_runs, goal_ref=owner, admission_event_id=admission_event_id, + owned_runs=owned_runs, owner=owner, admission_event_id=admission_event_id, ) return candidates @@ -599,9 +319,9 @@ def historical_ack_candidates_with_writeback_order( def load_receipt_replan_ack_candidates( runtime_root: Path, *, goal_id: str, agent_id: str, obligation_id: str, guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None, - goal_ref: Mapping[str, Any] | None = None, + goal_ref: AckMapping | None = None, admission_event_id: str | None = None, -) -> list[dict[str, Any]]: +) -> list[AckObject]: """Read exact recovery candidates without widening ordinary status history.""" from ...history import load_index from ..runtime.time import chronology_key @@ -618,7 +338,7 @@ def load_receipt_replan_ack_candidates( def latest_blocked_successor_frontier_identity( - latest_runs: list[dict[str, Any]] | None, + latest_runs: Sequence[AckMapping] | None, *, agent_id: str | None = None, ) -> str | None: @@ -630,13 +350,12 @@ def latest_blocked_successor_frontier_identity( def latest_monitor_replan_frontier_identity( - latest_runs: list[dict[str, Any]] | None, + latest_runs: Sequence[AckMapping] | None, *, agent_id: str | None = None, - watch_todo_ids: list[str] | None = None, + watch_todo_ids: Sequence[str] | None = None, ) -> str | None: """Return the latest monitor identity that a durable replan ACK must bind.""" - return _latest_monitor_replan_frontier_identity( latest_runs, agent_id=agent_id, @@ -646,30 +365,26 @@ def latest_monitor_replan_frontier_identity( def _latest_monitor_replan_frontier_identity( - latest_runs: list[dict[str, Any]] | None, + latest_runs: Sequence[AckMapping] | None, *, agent_id: str | None, include_generic_watch: bool, - watch_todo_ids: list[str] | None = None, + watch_todo_ids: Sequence[str] | None = None, ) -> str | None: - normalized_agent_id = str(agent_id or "").strip() + normalized_agent_id = _binding_text(agent_id) normalized_watch_todo_ids = { - str(todo_id or "").strip() - for todo_id in (watch_todo_ids or []) - if str(todo_id or "").strip() + stripped for todo_id in (watch_todo_ids or ()) if (stripped := _binding_text(todo_id)) } - evidence_linked_watch = ( - include_generic_watch and len(normalized_watch_todo_ids) == 1 - ) + evidence_linked_watch = include_generic_watch and len(normalized_watch_todo_ids) == 1 intervening_material_runs = 0 - for run in latest_runs or []: - if not isinstance(run, dict): + for run in latest_runs or (): + if not isinstance(run, Mapping): continue raw_target = run.get("monitor_target") - target = raw_target if isinstance(raw_target, dict) else {} + target: AckMapping = raw_target if isinstance(raw_target, Mapping) else {} if normalized_agent_id: - run_agent_id = str(run.get("agent_id") or "").strip() - target_agent_id = str(target.get("agent_id") or "").strip() + run_agent_id = _binding_text(run.get("agent_id")) + target_agent_id = _binding_text(target.get("agent_id")) if run_agent_id and target_agent_id and run_agent_id != target_agent_id: if normalized_agent_id in {run_agent_id, target_agent_id}: return None @@ -679,56 +394,46 @@ def _latest_monitor_replan_frontier_identity( return None if attributed_agent_id != normalized_agent_id: continue - classification = str(run.get("classification") or "").strip() + classification = _binding_text(run.get("classification")) if classification != "quota_monitor_poll": if evidence_linked_watch: intervening_material_runs += 1 - if ( - intervening_material_runs - >= AUTONOMOUS_REPLAN_ACK_MATERIAL_RUN_WINDOW - ): + if intervening_material_runs >= AUTONOMOUS_REPLAN_ACK_MATERIAL_RUN_WINDOW: return None continue return None - if target.get("monitor_mode") != ( - "blocked_successor_wait_without_material_transition" - ): + if target.get("monitor_mode") != "blocked_successor_wait_without_material_transition": if not ( include_generic_watch - and target.get("monitor_mode") - == "monitor_quiet_until_material_transition" + and target.get("monitor_mode") == "monitor_quiet_until_material_transition" ): continue - target_identity = str(target.get("target_id") or "").strip() - return target_identity or None + return _binding_text(target.get("target_id")) or None if intervening_material_runs: return None - frontier_identity = str(target.get("frontier_identity") or "").strip() - return frontier_identity or None + return _binding_text(target.get("frontier_identity")) or None return None def autonomous_replan_ack_matches_frontier( - ack: dict[str, Any] | None, - obligation: dict[str, Any] | None, + ack: AckMapping | None, + obligation: AckMapping | None, ) -> bool: - if not isinstance(obligation, dict): + if not isinstance(obligation, Mapping): return True - frontier_identity = str(obligation.get("frontier_identity") or "").strip() + frontier_identity = _binding_text(obligation.get("frontier_identity")) if not frontier_identity: return True - if not isinstance(ack, dict): + if not isinstance(ack, Mapping): return False - if str(ack.get("frontier_identity") or "").strip() != frontier_identity: + if _binding_text(ack.get("frontier_identity")) != frontier_identity: return False - - ack_generated_at = parse_timestamp( - ack.get("generated_at") or ack.get("recorded_at") - ) + ack_generated_at = parse_timestamp(ack.get("generated_at") or ack.get("recorded_at")) + raw_triggers = obligation.get("triggers") trigger_times = [ parsed - for trigger in obligation.get("triggers") or [] - if isinstance(trigger, dict) + for trigger in (raw_triggers if isinstance(raw_triggers, list) else ()) + if isinstance(trigger, Mapping) if ( parsed := parse_timestamp( trigger.get("latest_generated_at") or trigger.get("generated_at") @@ -742,24 +447,24 @@ def autonomous_replan_ack_matches_frontier( def autonomous_replan_ack_matches_agent( - ack: dict[str, Any] | None, + ack: AckMapping | None, *, agent_id: str | None, ) -> bool: - if not isinstance(ack, dict): + if not isinstance(ack, Mapping): return False - normalized_agent_id = str(agent_id or "").strip() + normalized_agent_id = _binding_text(agent_id) if not normalized_agent_id: return True - ack_agent_id = str(ack.get("agent_id") or "").strip() + ack_agent_id = _binding_text(ack.get("agent_id")) return bool(ack_agent_id and ack_agent_id == normalized_agent_id) def latest_autonomous_replan_ack_for_projection( - latest_runs: list[dict[str, Any]] | None, + latest_runs: Sequence[AckMapping] | None, *, neutral_classifications: set[str], -) -> dict[str, Any] | None: +) -> AckObject | None: """Return the newest durable replan ACK this lane may still use. A legacy ACK (one without typed trigger checkpoints) keeps the material-run @@ -768,26 +473,20 @@ def latest_autonomous_replan_ack_for_projection( the long Todo-chain rule for an unchanged frontier, which is exactly the level trigger the checkpoint contract exists to prevent. """ - material_run_count = 0 window_expired = False - for run in latest_runs or []: - if not isinstance(run, dict): + for run in latest_runs or (): + if not isinstance(run, Mapping): continue replan_ack = compact_autonomous_replan_ack(run) if replan_ack: if not window_expired or ack_binds_trigger_checkpoints(replan_ack): return replan_ack return None - classification = str(run.get("classification") or "").strip() - if not classification: - continue - if classification in neutral_classifications: - continue - if classification == "quota_monitor_poll": + classification = _binding_text(run.get("classification")) + if not classification or classification in neutral_classifications or classification == "quota_monitor_poll": continue material_run_count += 1 if material_run_count >= AUTONOMOUS_REPLAN_ACK_MATERIAL_RUN_WINDOW: window_expired = True return None - return None diff --git a/loopx/control_plane/work_items/autonomous_replan_ack_history.py b/loopx/control_plane/work_items/autonomous_replan_ack_history.py new file mode 100644 index 0000000000..afdb11df7e --- /dev/null +++ b/loopx/control_plane/work_items/autonomous_replan_ack_history.py @@ -0,0 +1,400 @@ +"""GoalRef ownership filtering and receipt-bound rollout history order helpers.""" + +from __future__ import annotations + +from collections.abc import Mapping, MutableMapping, Sequence +from typing import TypeVar + +from ..goals.goal_ref_validation import exact_goal_ref + + +AckMapping = Mapping[str, object] +AckObject = dict[str, object] +_RunT = TypeVar("_RunT", bound=Mapping[str, object]) +_MutableRecordT = TypeVar("_MutableRecordT", bound=MutableMapping[str, object]) + + +def _binding_text(value: object) -> str: + return str(value or "").strip() + + +def _event_details(event: AckMapping) -> AckMapping: + details = event.get("details") + return details if isinstance(details, Mapping) else {} + + +def _parsed_exact_goal_ref(value: object) -> dict[str, str] | None: + """Parse one exact GoalRef, keeping the native string-only rule.""" + if not isinstance(value, Mapping): + return None + goal_id = value.get("goal_id") + instance_id = value.get("goal_instance_id") + if not isinstance(goal_id, str) or not isinstance(instance_id, str): + return None + try: + return exact_goal_ref(goal_id, instance_id) + except ValueError: + return None + + +def _owner_goal_ref( + goal_ref: AckMapping | None, *, goal_id: str, +) -> dict[str, str] | None: + """Normalize the quota owner. None is the alias owner.""" + if goal_ref is None: + return None + owner = _parsed_exact_goal_ref(goal_ref) + if owner is None or owner["goal_id"] != _binding_text(goal_id): + raise ValueError("historical ACK GoalRef does not match goal_id") + return owner + + +def _record_owned_by_goal_ref( + record: AckMapping, owner: dict[str, str] | None, +) -> bool: + """Match quotaOwnerOwnsProjection for one rollout or run-index row. + + An alias owner keeps only rows with no goal_ref. An exact owner keeps + only rows whose goal_ref is that exact Goal instance. Non-string ids are + not owned, matching the strict GoalRef parser. + """ + if owner is None: + return "goal_ref" not in record + if "goal_ref" not in record: + return False + return _parsed_exact_goal_ref(record.get("goal_ref")) == owner + + +def drop_unowned_recorded_replan_acks( + runs: Sequence[_RunT] | None, *, goal_id: str, + goal_ref: AckMapping | None, +) -> tuple[list[_RunT], bool]: + """Drop recorded replan ACKs that belong to another Goal instance. + + Other run rows stay. Alias owners keep ACKs with no goal_ref; an exact + owner keeps only its own goal_ref. + """ + owner = _owner_goal_ref(goal_ref, goal_id=goal_id) + kept: list[_RunT] = [] + changed = False + for run in runs or (): + if not isinstance(run, Mapping): + continue + ack = run.get("autonomous_replan_ack") + if ( + isinstance(ack, Mapping) + and ack.get("recorded") is True + and not _record_owned_by_goal_ref(run, owner) + ): + changed = True + continue + kept.append(run) + return kept, changed + + +def _owned_records( + records: Sequence[_RunT] | None, owner: dict[str, str] | None, +) -> list[_RunT]: + return [ + record for record in records or () + if isinstance(record, Mapping) and _record_owned_by_goal_ref(record, owner) + ] + + +def _admission_event_index( + events: Sequence[AckMapping], *, goal_id: str, agent_id: str, + turn_instance_id: str, recorded_at: str, + owner_goal_ref: dict[str, str] | None, + event_id: str | None = None, +) -> int | None: + """Log position of the Turn's original bound admission. + + The settlement readback names that event after GoalRef filtering. Matching + the id keeps a retired Goal instance that reused this Turn id out of the + order. Callers without an id use the first row with the admission time. + """ + if not turn_instance_id or (not event_id and not recorded_at): + return None + for index, event in enumerate(events): + if not _record_owned_by_goal_ref(event, owner_goal_ref): + continue + if ( + event.get("event_kind") == "quota_should_run" + and event.get("goal_id") == goal_id + and event.get("agent_id") == agent_id + and event.get("run_id") == turn_instance_id + and ( + event.get("event_id") == event_id + if event_id + else event.get("recorded_at") == recorded_at + ) + ): + return index + return None + + +def _source_run( + runs: Sequence[AckMapping] | None, *, turn_instance_id: str, obligation_id: str, + owner_goal_ref: dict[str, str] | None, +) -> AckMapping: + for run in runs or (): + if not _record_owned_by_goal_ref(run, owner_goal_ref): + continue + if _binding_text(run.get("turn_instance_id")) != turn_instance_id: + continue + ack = run.get("autonomous_replan_ack") + delta = ack.get("semantic_delta") if isinstance(ack, Mapping) else None + if isinstance(delta, Mapping) and _binding_text(delta.get("obligation_id")) == obligation_id: + return run + return {} + + +def _expected_todo_receipt_from_owned_quota_events( + run: AckMapping, quota_events: Sequence[AckMapping], *, + goal_id: str, agent_id: str, turn_instance_id: str, obligation_id: str, +) -> tuple[str, str]: + identity_raw = run.get("settlement_identity") + identity: AckMapping = identity_raw if isinstance(identity_raw, Mapping) else {} + todo = _binding_text(run.get("todo_id") or identity.get("todo_id")) + effect = _binding_text(identity.get("effect_id")) + if todo and effect: + return todo, effect + for event in quota_events: + if ( + event.get("event_kind") != "quota_should_run" + or event.get("goal_id") != goal_id + or event.get("agent_id") != agent_id + or _binding_text(event.get("run_id")) != turn_instance_id + ): + continue + details = _event_details(event) + receipt_replan = _binding_text(details.get("replan_obligation_id")) + retained_todo = ( + _binding_text(details.get("pending_action_selection_todo_id")) + if receipt_replan == obligation_id + else "" + ) + todo = todo or _binding_text( + event.get("todo_id") or details.get("todo_id") or retained_todo + ) + effect = effect or _binding_text(details.get("settlement_effect_id")) + return todo, effect + + +def _expected_todo_receipt( + run: AckMapping, events: Sequence[AckMapping], *, + goal_id: str, agent_id: str, turn_instance_id: str, obligation_id: str, + owner_goal_ref: dict[str, str] | None, +) -> tuple[str, str]: + """Todo command identity for this ACK, filled from its heartbeat receipt. + + A historical index can omit the Todo and effect. The turn's existing + quota receipt still has that exact identity. A replan-bound receipt keeps + the admitted Todo as its pending action selection; that retained selection + may address the writeback without replacing the receipt's obligation. + An empty or differently bound side is not a match. + """ + return _expected_todo_receipt_from_owned_quota_events( + run, + [event for event in events if _record_owned_by_goal_ref(event, owner_goal_ref)], + goal_id=goal_id, + agent_id=agent_id, + turn_instance_id=turn_instance_id, + obligation_id=obligation_id, + ) + + +def _writeback_event_is_bound( + event: AckMapping, run: AckMapping, events: Sequence[AckMapping], *, + goal_id: str, agent_id: str, obligation_id: str, turn_instance_id: str, + owner_goal_ref: dict[str, str] | None, +) -> bool: + """Require one positive identity shared with the accepted ACK. + + The event obligation must equal the semantic delta, or its Todo and effect + must equal the ACK receipt. Missing fields do not count as agreement. + """ + if not _record_owned_by_goal_ref(event, owner_goal_ref): + return False + if ( + event.get("event_kind") != "refresh_state" + or event.get("goal_id") != goal_id + or event.get("agent_id") != agent_id + or _binding_text(event.get("run_id")) != turn_instance_id + ): + return False + details = _event_details(event) + if details.get("autonomous_replan_recorded") is not True: + return False + event_obligation = _binding_text(details.get("replan_obligation_id")) + if event_obligation: + return event_obligation == obligation_id + event_todo = _binding_text(event.get("todo_id")) + event_effect = _binding_text(details.get("settlement_effect_id")) + if not event_todo or not event_effect: + return False + expected_todo, expected_effect = _expected_todo_receipt( + run, events, goal_id=goal_id, agent_id=agent_id, + turn_instance_id=turn_instance_id, obligation_id=obligation_id, + owner_goal_ref=owner_goal_ref) + return bool( + expected_todo and expected_effect + and event_todo == expected_todo and event_effect == expected_effect + ) + + +def _original_writeback_event_index( + events: Sequence[AckMapping], runs: Sequence[AckMapping] | None, *, + goal_id: str, agent_id: str, obligation_id: str, turn_instance_id: str, + owner_goal_ref: dict[str, str] | None, +) -> int | None: + if not turn_instance_id or not obligation_id: + return None + run = _source_run( + runs, turn_instance_id=turn_instance_id, obligation_id=obligation_id, + owner_goal_ref=owner_goal_ref) + for index, event in enumerate(events): + if _writeback_event_is_bound( + event, run, events, goal_id=goal_id, agent_id=agent_id, + obligation_id=obligation_id, turn_instance_id=turn_instance_id, + owner_goal_ref=owner_goal_ref, + ): + return index + return None + + +def _attach_writeback_order_owned( + candidates: Sequence[_MutableRecordT], events: Sequence[AckMapping], *, + goal_id: str, agent_id: str, obligation_id: str, + guard_recorded_at: str | None, guard_turn_instance_id: str | None, + owned_runs: Sequence[AckMapping], + owner: dict[str, str] | None, + admission_event_id: str | None = None, +) -> None: + if not candidates: + return + guard_turn_id = _binding_text(guard_turn_instance_id) + guard_stamp = _binding_text(guard_recorded_at) + guard_event_id = _binding_text(admission_event_id) or None + candidate_turns = { + t_id for candidate in candidates + if (t_id := _binding_text(candidate.get("turn_instance_id"))) + } + + admission_index: int | None = None + quota_events_by_run: dict[str, list[AckMapping]] = {} + refresh_events_by_run: dict[str, list[tuple[int, AckMapping]]] = {} + for index, event in enumerate(events): + if not isinstance(event, Mapping) or not _record_owned_by_goal_ref(event, owner): + continue + if event.get("goal_id") != goal_id or event.get("agent_id") != agent_id: + continue + kind = event.get("event_kind") + run_id_raw = event.get("run_id") + run_id_text = _binding_text(run_id_raw) + if kind == "quota_should_run": + if ( + admission_index is None + and guard_turn_id + and (guard_event_id is not None or guard_stamp) + and run_id_raw == guard_turn_id + and ( + event.get("event_id") == guard_event_id + if guard_event_id + else event.get("recorded_at") == guard_stamp + ) + ): + admission_index = index + if obligation_id and run_id_text in candidate_turns: + quota_events_by_run.setdefault(run_id_text, []).append(event) + elif ( + kind == "refresh_state" + and obligation_id + and run_id_text in candidate_turns + and _event_details(event).get("autonomous_replan_recorded") is True + ): + refresh_events_by_run.setdefault(run_id_text, []).append((index, event)) + + if not obligation_id or not candidate_turns: + return + source_runs_by_turn: dict[str, AckMapping] = {} + for run in owned_runs: + t_id = _binding_text(run.get("turn_instance_id")) + if t_id not in candidate_turns or t_id in source_runs_by_turn: + continue + ack = run.get("autonomous_replan_ack") + delta = ack.get("semantic_delta") if isinstance(ack, Mapping) else None + if isinstance(delta, Mapping) and _binding_text(delta.get("obligation_id")) == obligation_id: + source_runs_by_turn[t_id] = run + + receipt_by_turn: dict[str, tuple[str, str]] = {} + for candidate in candidates: + turn_id = _binding_text(candidate.get("turn_instance_id")) + if not turn_id: + continue + matched: tuple[int, AckMapping] | None = None + for index, event in refresh_events_by_run.get(turn_id, ()): + details = _event_details(event) + event_obligation = _binding_text(details.get("replan_obligation_id")) + if event_obligation: + if event_obligation == obligation_id: + matched = (index, event) + break + continue + event_todo = _binding_text(event.get("todo_id")) + event_effect = _binding_text(details.get("settlement_effect_id")) + if not event_todo or not event_effect: + continue + expected = receipt_by_turn.get(turn_id) + if expected is None: + expected = _expected_todo_receipt_from_owned_quota_events( + source_runs_by_turn.get(turn_id, {}), + quota_events_by_run.get(turn_id, ()), + goal_id=goal_id, + agent_id=agent_id, + turn_instance_id=turn_id, + obligation_id=obligation_id, + ) + receipt_by_turn[turn_id] = expected + if expected[0] and expected[1] and event_todo == expected[0] and event_effect == expected[1]: + matched = (index, event) + break + if matched is None: + continue + evidence_index, matched_event = matched + candidate["writeback_recorded_at"] = matched_event.get("recorded_at") + candidate["writeback_goal_id"] = matched_event.get("goal_id") + candidate["writeback_agent_id"] = matched_event.get("agent_id") + candidate["writeback_turn_instance_id"] = matched_event.get("run_id") + candidate["writeback_obligation_id"] = obligation_id + candidate["writeback_follows_admission"] = ( + admission_index is not None and evidence_index > admission_index + ) + + +def attach_historical_ack_writeback_order( + candidates: Sequence[_MutableRecordT], events: Sequence[AckMapping], *, + goal_id: str, agent_id: str, obligation_id: str, + guard_recorded_at: str | None, guard_turn_instance_id: str | None, + runs: Sequence[AckMapping] | None = None, + goal_ref: AckMapping | None = None, + admission_event_id: str | None = None, +) -> None: + """Copy the original refresh event order onto matching ACK candidates. + + The compact run clock is whole seconds. The decision owner compares this + event with admission; this reader only selects the bound original event. + """ + owner = _owner_goal_ref(goal_ref, goal_id=goal_id) + _attach_writeback_order_owned( + candidates, + events, + goal_id=goal_id, + agent_id=agent_id, + obligation_id=obligation_id, + guard_recorded_at=guard_recorded_at, + guard_turn_instance_id=guard_turn_instance_id, + owned_runs=_owned_records(runs, owner), + owner=owner, + admission_event_id=admission_event_id, + ) diff --git a/tests/control_plane/test_autonomous_replan_ack_contract.py b/tests/control_plane/test_autonomous_replan_ack_contract.py new file mode 100644 index 0000000000..7c92f9fa01 --- /dev/null +++ b/tests/control_plane/test_autonomous_replan_ack_contract.py @@ -0,0 +1,341 @@ +"""Contract, efficiency, and origin/main parity tests for autonomous_replan_ack.""" + +from __future__ import annotations + +import ast +from collections.abc import Mapping, Sequence +import json +from pathlib import Path +import re +import subprocess +import types +from types import MappingProxyType + +import pytest + +from loopx.control_plane.work_items import ( + autonomous_replan_ack as ack_mod, + autonomous_replan_ack_history as history_mod, +) + +GOAL_ID = "goal-ack-contract" +AGENT_ID = "agent-codex" +OBLIGATION_ID = "replan-0123456789abcdef" +FRONTIER_REV = "todo_frontier_revision_v0:0123456789abcdef01234567" +GINST_A = "ginst_" + "a" * 32 +GINST_B = "ginst_" + "b" * 32 + + +def _load_baseline_ack_module() -> types.ModuleType | None: + repo_root = Path(__file__).resolve().parents[2] + proc = subprocess.run( + ["git", "show", "origin/main:loopx/control_plane/work_items/autonomous_replan_ack.py"], + cwd=repo_root, + capture_output=True, + text=True, + check=False, + ) + if proc.returncode != 0 or not proc.stdout: + return None + mod = types.ModuleType("_baseline_autonomous_replan_ack") + mod.__package__ = "loopx.control_plane.work_items" + mod.__file__ = str(repo_root / "loopx/control_plane/work_items/autonomous_replan_ack.py") + exec(compile(proc.stdout, mod.__file__, "exec"), mod.__dict__) + return mod + + +def test_autonomous_replan_ack_modules_zero_any_and_budget() -> None: + root = Path(__file__).resolve().parents[2] + limits = ( + (root / "loopx/control_plane/work_items/autonomous_replan_ack.py", 550), + (root / "loopx/control_plane/work_items/autonomous_replan_ack_history.py", 750), + (Path(__file__).resolve(), 750), + ) + for path, max_loc in limits: + source = path.read_text(encoding="utf-8") + assert len(source.splitlines()) <= max_loc, f"{path} exceeded {max_loc} LOC" + assert re.search(r"#\s*type:\s*ignore\b", source) is None, f"{path} has type: ignore" + tree = ast.parse(source) + any_refs = sum( + 1 + for node in ast.walk(tree) + if (isinstance(node, ast.Name) and node.id == "Any") + or (isinstance(node, ast.Attribute) and node.attr == "Any") + or (isinstance(node, ast.alias) and node.name == "Any") + ) + assert any_refs == 0, f"{path} has {any_refs} AST Any references" + + expected_exports = ( + "AUTONOMOUS_REPLAN_ACK_MATERIAL_RUN_WINDOW", + "AUTONOMOUS_REPLAN_ACK_RECOVERY_CANDIDATE_LIMIT", + "AUTONOMOUS_REPLAN_PERIODIC_LOOKBACK", + "SettlementHistoryQualification", + "qualify_settlement_history", + "accepted_blocked_replan_history_indexes", + "ack_binds_trigger_checkpoints", + "normalize_projected_autonomous_replan_ack", + "autonomous_replan_ack_recorded", + "watch_lane_continuation_todo_ids", + "compact_autonomous_replan_ack", + "autonomous_replan_ack_candidates_for_obligation", + "drop_unowned_recorded_replan_acks", + "attach_historical_ack_writeback_order", + "historical_ack_candidates_with_writeback_order", + "load_receipt_replan_ack_candidates", + "latest_blocked_successor_frontier_identity", + "latest_monitor_replan_frontier_identity", + "autonomous_replan_ack_matches_frontier", + "autonomous_replan_ack_matches_agent", + "latest_autonomous_replan_ack_for_projection", + "effect_runtime_result", + ) + for name in expected_exports: + assert hasattr(ack_mod, name) + assert history_mod.attach_historical_ack_writeback_order is ack_mod.attach_historical_ack_writeback_order + + +def _sample_ack( + *, + obligation_id: str = OBLIGATION_ID, + checkpoints: bool = True, + accepted: bool = True, + recorded: bool = True, + todo_source: Mapping[str, object] | None = None, +) -> dict[str, object]: + delta: dict[str, object] = { + "schema_version": "replan_semantic_delta_v0", + "accepted": accepted, + "outcomes": ["fresh_vision_path_outcome"], + "satisfying_outcomes": [], + "required_any_of": ["fresh_vision_path_outcome"], + "trigger_kinds": ["long_todo_chain"], + "obligation_id": obligation_id, + "reason": "", + } + if checkpoints: + delta["trigger_checkpoints"] = [ + {"kind": "long_todo_chain", "frontier_revision": FRONTIER_REV} + ] + ack: dict[str, object] = { + "schema_version": "autonomous_replan_ack_v0", + "recorded": recorded, + "source": "refresh_state", + "frontier_identity": "f-1", + "semantic_delta": delta, + "delta_contract": { + "schema_version": "repair_delta_v0", + "delta_present": False, + "delta_kinds": ["", "watch_lane_continuation"], + "auto_evidence": [ + {"kind": "watch_lane_continuation", "todo_ids": ["t1", " t1 ", "t2"]}, + *({"kind": f"extra_{idx}"} for idx in range(8)), + ], + }, + } + if todo_source is not None: + ack["todo_source"] = dict(todo_source) + return ack + + +def _sample_run( + index: int, + *, + goal_ref: dict[str, str] | None = None, + include_null_goal_ref: bool = False, + todo_source_present_none: bool = False, + path_outcome: str = "replan", +) -> dict[str, object]: + run: dict[str, object] = { + "goal_id": GOAL_ID, + "agent_id": AGENT_ID, + "turn_instance_id": f"turn:{index}", + "generated_at": f"2026-08-19T12:{index:02d}:00Z", + "classification": "bounded_progress", + "agent_vision": {"path_delta": {"outcome": path_outcome}}, + "autonomous_replan_ack": _sample_ack(todo_source={"provider": "ack-src"}), + } + if goal_ref is not None: + run["goal_ref"] = dict(goal_ref) + elif include_null_goal_ref: + run["goal_ref"] = None + if todo_source_present_none: + run["todo_source"] = None + return run + + +def test_paired_origin_main_behavioral_parity(tmp_path: Path) -> None: + base = _load_baseline_ack_module() + if base is None: + pytest.skip("git origin/main unavailable in this checkout") + + ack = _sample_ack() + run_plain = _sample_run(1) + run_null_source = _sample_run(2, todo_source_present_none=True) + run_unaccepted = _sample_run(3) + run_unaccepted["autonomous_replan_ack"] = _sample_ack(accepted=False) + + for r in (run_plain, run_null_source, run_unaccepted, {}): + assert ack_mod.autonomous_replan_ack_recorded(r) == base.autonomous_replan_ack_recorded(r) + assert ack_mod.compact_autonomous_replan_ack(r) == base.compact_autonomous_replan_ack(r) + assert ack_mod.compact_autonomous_replan_ack(None) == base.compact_autonomous_replan_ack(None) + assert "todo_source" in (ack_mod.compact_autonomous_replan_ack(run_plain) or {}) + assert "todo_source" not in (ack_mod.compact_autonomous_replan_ack(run_null_source) or {}) + + for a in (ack, _sample_ack(checkpoints=False), {"semantic_delta": {"trigger_checkpoints": [{"kind": " ", "frontier_revision": "x"}]}}, None): + assert ack_mod.ack_binds_trigger_checkpoints(a) == base.ack_binds_trigger_checkpoints(a) + assert ack_mod.normalize_projected_autonomous_replan_ack(a) == base.normalize_projected_autonomous_replan_ack(a) + assert ack_mod.autonomous_replan_ack_matches_agent(a, agent_id=AGENT_ID) == base.autonomous_replan_ack_matches_agent(a, agent_id=AGENT_ID) + + dc = ack.get("delta_contract") + assert isinstance(dc, dict) + assert ack_mod.watch_lane_continuation_todo_ids(dc) == base.watch_lane_continuation_todo_ids(dc) == ["t1", "t2"] + + newest_first = [_sample_run(idx) for idx in range(12, 0, -1)] + newest_first.append(_sample_run(12)) + assert ( + ack_mod.autonomous_replan_ack_candidates_for_obligation( + newest_first, goal_id=GOAL_ID, agent_id=AGENT_ID, obligation_id=OBLIGATION_ID, + ) + == base.autonomous_replan_ack_candidates_for_obligation( + newest_first, goal_id=GOAL_ID, agent_id=AGENT_ID, obligation_id=OBLIGATION_ID, + ) + ) + assert ack_mod.autonomous_replan_ack_candidates_for_obligation( + newest_first, goal_id=GOAL_ID, agent_id=AGENT_ID, obligation_id=OBLIGATION_ID, limit=0, + ) == [] + + ref_a = {"goal_id": GOAL_ID, "goal_instance_id": GINST_A} + ref_b = {"goal_id": GOAL_ID, "goal_instance_id": GINST_B} + mixed_runs = [_sample_run(1), _sample_run(2, include_null_goal_ref=True), _sample_run(3, goal_ref=ref_a), _sample_run(4, goal_ref=ref_b)] + for owner_ref in (None, ref_a): + assert ( + ack_mod.drop_unowned_recorded_replan_acks(mixed_runs, goal_id=GOAL_ID, goal_ref=owner_ref) + == base.drop_unowned_recorded_replan_acks(mixed_runs, goal_id=GOAL_ID, goal_ref=owner_ref) + ) + with pytest.raises(ValueError, match="does not match goal_id"): + ack_mod.drop_unowned_recorded_replan_acks([], goal_id="other", goal_ref=ref_a) + + # Frontier matching and monitor poll identity parity + obl = {"frontier_identity": "f-1", "triggers": [{"latest_generated_at": "2026-08-19T12:00:00Z"}]} + assert ack_mod.autonomous_replan_ack_matches_frontier({"frontier_identity": "f-1", "generated_at": "2026-08-19T12:00:00Z"}, obl) == base.autonomous_replan_ack_matches_frontier({"frontier_identity": "f-1", "generated_at": "2026-08-19T12:00:00Z"}, obl) is True + assert ack_mod.autonomous_replan_ack_matches_frontier({"frontier_identity": "f-1", "generated_at": "2026-08-19T11:59:59Z"}, obl) == base.autonomous_replan_ack_matches_frontier({"frontier_identity": "f-1", "generated_at": "2026-08-19T11:59:59Z"}, obl) is False + + poll_runs: list[dict[str, object]] = [ + {"agent_id": AGENT_ID, "classification": "bounded_progress"}, + {"agent_id": AGENT_ID, "classification": "quota_monitor_poll", "monitor_target": {"monitor_mode": "monitor_quiet_until_material_transition", "target_id": "watch-1"}}, + ] + assert ack_mod.latest_blocked_successor_frontier_identity(poll_runs, agent_id=AGENT_ID) == base.latest_blocked_successor_frontier_identity(poll_runs, agent_id=AGENT_ID) is None + assert ack_mod.latest_monitor_replan_frontier_identity(poll_runs, agent_id=AGENT_ID, watch_todo_ids=["todo-1"]) == base.latest_monitor_replan_frontier_identity(poll_runs, agent_id=AGENT_ID, watch_todo_ids=["todo-1"]) == "watch-1" + assert ack_mod.latest_monitor_replan_frontier_identity(poll_runs, agent_id=AGENT_ID, watch_todo_ids=["todo-1", "todo-2"]) is None + + # Projection lookback window parity (legacy expires at 20, checkpoint stays visible, neutral ignored) + neutral: list[dict[str, object]] = [{"classification": "quota_slot_spent", "agent_id": AGENT_ID}] * 25 + material: list[dict[str, object]] = [{"classification": f"step_{i}", "agent_id": AGENT_ID} for i in range(20)] + legacy_run = {**_sample_run(7), "autonomous_replan_ack": _sample_ack(checkpoints=False)} + for hist in ( + [*neutral, legacy_run], + [*material, legacy_run], + [*material, _sample_run(8)], + [_sample_run(9)], + ): + assert ( + ack_mod.latest_autonomous_replan_ack_for_projection(hist, neutral_classifications={"quota_slot_spent"}) + == base.latest_autonomous_replan_ack_for_projection(hist, neutral_classifications={"quota_slot_spent"}) + ) + + # Rollout index + writeback order parity via load_receipt_replan_ack_candidates + from loopx.rollout_event_log import build_rollout_event + + idx_dir = tmp_path / "goals" / GOAL_ID / "runs" + idx_dir.mkdir(parents=True) + run_row = {**_sample_run(5, goal_ref=ref_b), "todo_id": "todo-5", "settlement_identity": {"todo_id": "todo-5", "effect_id": "eff-5"}} + (idx_dir / "index.jsonl").write_text(json.dumps(run_row) + "\n", encoding="utf-8") + events = [ + build_rollout_event(goal_id=GOAL_ID, event_kind="quota_should_run", goal_ref=ref_b, agent_id=AGENT_ID, run_id="guard-1", recorded_at="2026-08-19T12:00:00Z"), + build_rollout_event(goal_id=GOAL_ID, event_kind="refresh_state", goal_ref=ref_b, agent_id=AGENT_ID, run_id="turn:5", todo_id="todo-5", recorded_at="2026-08-19T12:00:01Z", details={"autonomous_replan_recorded": True, "replan_obligation_id": None, "settlement_effect_id": "eff-5"}), + ] + (tmp_path / "goals" / GOAL_ID / "rollout-event-log.jsonl").write_text("".join(json.dumps(e) + "\n" for e in events), encoding="utf-8") + head_loaded = ack_mod.load_receipt_replan_ack_candidates(tmp_path, goal_id=GOAL_ID, agent_id=AGENT_ID, obligation_id=OBLIGATION_ID, guard_recorded_at="2026-08-19T12:00:00Z", guard_turn_instance_id="guard-1", goal_ref=ref_b) + base_loaded = base.load_receipt_replan_ack_candidates(tmp_path, goal_id=GOAL_ID, agent_id=AGENT_ID, obligation_id=OBLIGATION_ID, guard_recorded_at="2026-08-19T12:00:00Z", guard_turn_instance_id="guard-1", goal_ref=ref_b) + assert head_loaded == base_loaded and len(head_loaded) == 1 and head_loaded[0]["writeback_follows_admission"] is True + + +def test_writeback_order_linear_scan_efficiency_and_readonly_mappings() -> None: + # Single-pass indexing avoids O(candidates * events^2) ownership rescans. + proxy_run = MappingProxyType({ + "goal_id": GOAL_ID, + "agent_id": AGENT_ID, + "turn_instance_id": "turn:1", + "generated_at": "2026-08-19T12:00:00Z", + "autonomous_replan_ack": MappingProxyType(_sample_ack()), + }) + assert ack_mod.autonomous_replan_ack_recorded(proxy_run) is True + assert ack_mod.compact_autonomous_replan_ack(proxy_run) is not None + + ref = {"goal_id": GOAL_ID, "goal_instance_id": GINST_A} + + class _CountingEvent(dict[str, object]): + reads = 0 + + def get(self, key: str, default: object = None) -> object: + if key == "event_kind": + _CountingEvent.reads += 1 + return super().get(key, default) + + events: list[Mapping[str, object]] = [ + _CountingEvent({ + "event_kind": "quota_should_run", + "event_id": "evt-adm", + "goal_id": GOAL_ID, + "agent_id": AGENT_ID, + "run_id": "guard:0", + "recorded_at": "2026-08-19T12:00:00Z", + "goal_ref": ref, + "todo_id": "todo-1", + "details": {"settlement_effect_id": "eff-1"}, + }) + ] + for i in range(60): + events.append(_CountingEvent({ + "event_kind": "refresh_state", + "goal_id": GOAL_ID, + "agent_id": AGENT_ID, + "run_id": f"turn:{i % 4}", + "todo_id": f"todo-{i}", + "recorded_at": f"2026-08-19T12:01:{i:02d}Z", + "goal_ref": ref, + "details": {"autonomous_replan_recorded": True, "replan_obligation_id": None, "settlement_effect_id": f"eff-{i}"}, + })) + candidates: list[dict[str, object]] = [{"turn_instance_id": f"turn:{i}"} for i in range(4)] + runs = [{"goal_id": GOAL_ID, "agent_id": AGENT_ID, "turn_instance_id": f"turn:{i}", "goal_ref": ref, "todo_id": "todo-0", "settlement_identity": {"todo_id": "todo-0", "effect_id": "eff-0"}, "autonomous_replan_ack": {"semantic_delta": {"obligation_id": OBLIGATION_ID}}} for i in range(4)] + ack_mod.attach_historical_ack_writeback_order( + candidates, events, goal_id=GOAL_ID, agent_id=AGENT_ID, obligation_id=OBLIGATION_ID, + guard_recorded_at=None, guard_turn_instance_id="guard:0", admission_event_id="evt-adm", runs=runs, goal_ref=ref, + ) + assert _CountingEvent.reads == len(events) + assert candidates[0]["writeback_follows_admission"] is True + + +def test_settlement_qualification_and_malformed_inputs(monkeypatch: pytest.MonkeyPatch) -> None: + calls: list[str] = [] + + def fake_runtime(method: str, params: Mapping[str, object], **_: object) -> dict[str, object]: + calls.append(method) + selected_runs = params.get("runs") + assert isinstance(selected_runs, Sequence) and len(selected_runs) == 1 + return {"accepted_indexes": [0], "active_retry_indexes": []} + + monkeypatch.setattr(ack_mod, "effect_runtime_result", fake_runtime) + assert ack_mod.qualify_settlement_history([{"classification": "neutral"}]) == (frozenset(), frozenset()) + assert calls == [] + assert ack_mod.accepted_blocked_replan_history_indexes([{"replan_obligation_id": OBLIGATION_ID}]) == frozenset({0}) + assert calls == ["quota.settlement.read"] + + for bad in ([True], [-1], [1], "bad"): + monkeypatch.setattr(ack_mod, "effect_runtime_result", lambda *_a, _b=bad, **_k: {"accepted_indexes": _b, "active_retry_indexes": []}) + with pytest.raises(RuntimeError, match="valid indexes"): + ack_mod.qualify_settlement_history([{"blocked_retry": {}}], observed_at="2026-08-19T12:00:00Z") + + assert ack_mod.watch_lane_continuation_todo_ids({"auto_evidence": "not-a-list"}) == [] + assert ack_mod.latest_monitor_replan_frontier_identity([{"agent_id": AGENT_ID, "classification": "quota_monitor_poll", "monitor_target": "bad"}], agent_id=AGENT_ID) is None + assert ack_mod.autonomous_replan_ack_matches_frontier(_sample_ack(), {"frontier_identity": "f-1", "triggers": "bad"}) is True