"""Target-scoped API recovery with exact accounting and replay-checked state.""" from __future__ import annotations from copy import deepcopy import json from typing import Any, Mapping import jsonschema from . import adapter as _adapter from . import recovery_policy as _policy from . import stream_runtime as _stream from .snapshot import validate_snapshot from .spec import ( BUSINESS_BUDGET, DRIFT_EVENT_ID, EXACT_IDENTITY_READ_COST, EXACT_RULE_READ_COST, INITIAL_BUDGET, RATE_READ_COST, RETRY_COST, SNAPSHOT_SCHEMA, TARGETS, TOOL_BY_NAME, provider_tools, ) def _canonical(value: Any) -> str: return json.dumps( value, ensure_ascii=True, sort_keys=True, separators=(",", ":"), allow_nan=False, ) def _is_int(value: Any) -> bool: return type(value) is int def _source_cell(source: Mapping[str, Any]) -> tuple[str, str]: return ( _policy.failure_signal_for(dict(source)), _policy.operation_class_for(str(source.get("operation") or "")), ) class ApiReliabilityWorld(_stream.PersistentApiReliabilityAdapter): """One released world; capability evidence and business state persist together.""" def __init__(self, budget: int = INITIAL_BUDGET, *, snapshot: dict[str, Any] | None = None) -> None: self.capability_observations: list[dict[str, Any]] = [] super().__init__(budget=budget) if snapshot is not None: self.restore(snapshot) def snapshot(self) -> dict[str, Any]: value = super().snapshot() value["schema"] = SNAPSHOT_SCHEMA value["capability_observations"] = deepcopy(self.capability_observations) return value def activate_task(self, task_id: str, allowance: int = BUSINESS_BUDGET, *, apply_boundary_drift: bool = True) -> dict[str, Any]: if task_id != "T09" or apply_boundary_drift: return super().activate_task(task_id, allowance=allowance) # A researcher-only counterfactual uses the same activation without drift. already_applied = DRIFT_EVENT_ID in self.applied_boundary_events self.applied_boundary_events.add(DRIFT_EVENT_ID) try: receipt = super().activate_task(task_id, allowance=allowance) finally: if not already_applied: self.applied_boundary_events.remove(DRIFT_EVENT_ID) receipt["boundary_event_applied"] = False return receipt def public_tool_schemas(self, actor: str = _adapter.ROLE) -> list[dict[str, Any]]: return provider_tools() if actor == _adapter.ROLE else [] def _cost(self, tool: str, arguments: Any) -> int: if tool in {"list_api_credentials", "list_retry_budgets"}: return EXACT_IDENTITY_READ_COST if tool == "inspect_rate_limit_status": return RATE_READ_COST if tool == "search_recovery_evidence": return EXACT_RULE_READ_COST if tool in {"list_service_integrations", "list_fault_policies", "search_audit_events"}: return 4 return super()._cost(tool, arguments) def _observation_is_visible(self, observation: Mapping[str, Any]) -> bool: if self.active_task_id is None: return False targets = TARGETS[self.active_task_id] kind = observation.get("kind") if kind in {"credential", "retry_budget"}: return any( target["integration_id"] == observation.get("integration_id") for target in targets ) if kind == "rate_bucket": return any( target["integration_id"] == observation.get("integration_id") and target["operation"] == observation.get("operation") for target in targets ) if kind == "recovery_profile": return any( target["failure_signal"] == observation.get("failure_signal") and target["operation_class"] == observation.get("operation_class") for target in targets ) return False def _scope_matches_active_target( self, tool: str, arguments: Mapping[str, Any] ) -> bool: if self.active_task_id is None: return False targets = TARGETS[self.active_task_id] if tool == "list_api_credentials": return any( target["integration_id"] == arguments.get("integration_id") and target["operation"] == arguments.get("scope_contains") for target in targets ) if tool == "list_retry_budgets": return any( target["integration_id"] == arguments.get("integration_id") for target in targets ) if tool == "inspect_rate_limit_status": return any( target["integration_id"] == arguments.get("integration_id") and target["operation"] == arguments.get("operation") for target in targets ) if tool == "search_recovery_evidence": return any( target["failure_signal"] == arguments.get("failure_signal") and target["operation_class"] == arguments.get("operation_class") for target in targets ) return True def _append_observation(self, observation: dict[str, Any]) -> None: if not self._observation_is_visible(observation): return self.capability_observations.append( { **deepcopy(observation), "task_id": self.active_task_id, } ) def _record_public_observations(self, result: Mapping[str, Any]) -> None: content = result.get("content") if not isinstance(content, Mapping) or content.get("status") != "success": return data = content.get("data") receipt_index = result.get("receipt_index") if not isinstance(data, Mapping) or not _is_int(receipt_index): return tool = result.get("tool") if tool == "list_api_credentials": for row in data.get("items", []): if not isinstance(row, Mapping): continue self._append_observation( { "kind": "credential", "credential_id": row.get("credential_id"), "integration_id": row.get("integration_id"), "operations": deepcopy(row.get("scope")), "receipt_index": receipt_index, } ) elif tool == "list_retry_budgets": for row in data.get("items", []): if not isinstance(row, Mapping): continue self._append_observation( { "kind": "retry_budget", "retry_budget_id": row.get("budget_id"), "integration_id": row.get("integration_id"), "receipt_index": receipt_index, } ) elif tool == "inspect_rate_limit_status": for row in data.get("buckets", []): if not isinstance(row, Mapping): continue self._append_observation( { "kind": "rate_bucket", "rate_limit_bucket_id": row.get("bucket_id"), "integration_id": row.get("integration_id"), "operation": row.get("operation"), "receipt_index": receipt_index, } ) elif tool == "search_recovery_evidence": for row in data.get("evidence", []): if not isinstance(row, Mapping): continue self._append_observation( { "kind": "recovery_profile", "recovery_profile_id": row.get("recovery_profile_id"), "failure_signal": row.get("failure_signal"), "operation_class": row.get("operation_class"), "receipt_index": receipt_index, } ) def _has_credential(self, source: Mapping[str, Any], capability_id: str) -> bool: return any( row.get("kind") == "credential" and row.get("credential_id") == capability_id and row.get("integration_id") == source.get("integration_id") and source.get("operation") in row.get("operations", []) for row in self.capability_observations ) def _has_retry_budget(self, source: Mapping[str, Any], capability_id: str) -> bool: return any( row.get("kind") == "retry_budget" and row.get("retry_budget_id") == capability_id and row.get("integration_id") == source.get("integration_id") for row in self.capability_observations ) def _has_rate_bucket(self, source: Mapping[str, Any], capability_id: str) -> bool: return any( row.get("kind") == "rate_bucket" and row.get("rate_limit_bucket_id") == capability_id and row.get("integration_id") == source.get("integration_id") and row.get("operation") == source.get("operation") for row in self.capability_observations ) def _has_recovery_profile( self, source: Mapping[str, Any], capability_id: str ) -> bool: failure_signal, operation_class = _source_cell(source) return any( row.get("kind") == "recovery_profile" and row.get("recovery_profile_id") == capability_id and row.get("failure_signal") == failure_signal and row.get("operation_class") == operation_class for row in self.capability_observations ) def _provenance_error( self, arguments: dict[str, Any], code: str, message: str, ) -> dict[str, Any]: cost = self._cost("retry_api_call", arguments) before = self.business_hash() self.remaining -= cost result = self._error("retry_api_call", code, message, cost) return self._finish("retry_api_call", arguments, result, cost, before) @classmethod def _replay_snapshot(cls, snapshot: Mapping[str, Any]) -> "ApiReliabilityWorld": replay = cls() receipts = list(snapshot["receipts"]) cursor = 0 while cursor < len(receipts) and receipts[cursor]["task_id"] is None: receipt = receipts[cursor] replay.dispatch(receipt["tool"], deepcopy(receipt["arguments"]), receipt["actor"]) cursor += 1 for task_id in snapshot["activated_tasks"]: replay.activate_task(task_id) while cursor < len(receipts) and receipts[cursor]["task_id"] == task_id: receipt = receipts[cursor] replay.dispatch( receipt["tool"], deepcopy(receipt["arguments"]), receipt["actor"] ) cursor += 1 if cursor != len(receipts): raise ValueError("API Reliability v8 receipt ledger cannot be replayed") return replay def _dispatch_business( self, tool: str, arguments: Mapping[str, Any], actor: str = _adapter.ROLE, ) -> dict[str, Any]: if ( tool == "retry_api_call" and isinstance(arguments, Mapping) and "incident_id" in arguments and actor == _adapter.ROLE and self.active_task_id is not None ): cost = self._cost(tool, arguments) if self.remaining < cost: return self._error( tool, "WORK_QUOTA_EXHAUSTED", "insufficient API-work quota" ) before = self.business_hash() self.remaining -= cost result = self._error( tool, "INVALID_ARGUMENTS", "unsupported argument(s): incident_id", cost, ) return self._finish(tool, dict(arguments), result, cost, before) return super().dispatch(tool, arguments, actor) def _dispatch_observed( self, tool: str, arguments: Mapping[str, Any], actor: str = _adapter.ROLE, ) -> dict[str, Any]: if tool == "retry_api_call" and actor == _adapter.ROLE: if self.remaining < self._cost(tool, arguments): return self._dispatch_business(tool, arguments, actor) if ( isinstance(arguments, dict) and "incident_id" not in arguments and _adapter._validate_arguments(tool, arguments) is None ): source = self.manager.get_entity( "api_call_attempt", arguments["call_id"], id_field="call_id" ) if source is not None: checks = ( ( self._has_credential(source, arguments["credential_id"]), "UNOBSERVED_CREDENTIAL", "credential was not returned by a public capability read for this source scope", ), ( self._has_retry_budget(source, arguments["retry_budget_id"]), "UNOBSERVED_RETRY_BUDGET", "retry budget was not returned by a public capability read for this source scope", ), ( self._has_rate_bucket( source, arguments["rate_limit_bucket_id"] ), "UNOBSERVED_RATE_BUCKET", "rate bucket was not returned by a public capability read for this source scope", ), ( self._has_recovery_profile( source, arguments["recovery_profile_id"] ), "UNOBSERVED_RECOVERY_PROFILE", "recovery profile was not observed for the exact failure and operation cell", ), ) for observed, code, message in checks: if not observed: return self._provenance_error(dict(arguments), code, message) result = self._dispatch_business(tool, arguments, actor) if actor == _adapter.ROLE: self._record_public_observations(result) return result def _scoped_error( self, tool: str, arguments: dict[str, Any], code: str, message: str, ) -> dict[str, Any]: cost = self._cost(tool, arguments) if self.remaining < cost: return self._dispatch_observed(tool, arguments, _adapter.ROLE) before = self.business_hash() self.remaining -= cost result = self._error(tool, code, message, cost) return self._finish(tool, arguments, result, cost, before) def dispatch( self, tool: str, arguments: Mapping[str, Any], actor: str = _adapter.ROLE, ) -> dict[str, Any]: if actor != _adapter.ROLE: return self._dispatch_observed(tool, arguments, actor) if tool not in TOOL_BY_NAME: if tool in _adapter.ALLOWED_TOOLS: prepared = dict(arguments) if isinstance(arguments, Mapping) else {} return self._scoped_error( tool, prepared, "TOOL_FORBIDDEN", "tool is outside the target-scoped API recovery surface", ) return self._dispatch_observed(tool, arguments, actor) if not isinstance(arguments, Mapping): return self._dispatch_observed(tool, arguments, actor) prepared = dict(arguments) if tool in { "list_api_credentials", "list_retry_budgets", "search_recovery_evidence", }: prepared.setdefault("limit", 1) try: jsonschema.validate(prepared, TOOL_BY_NAME[tool]["input_schema"]) except jsonschema.ValidationError: return self._scoped_error( tool, prepared, "INVALID_ARGUMENTS", "arguments do not match the target-scoped public schema", ) if tool in { "list_api_credentials", "list_retry_budgets", "inspect_rate_limit_status", "search_recovery_evidence", } and not self._scope_matches_active_target(tool, prepared): return self._scoped_error( tool, prepared, "TARGET_SCOPE_REQUIRED", "capability discovery must match one exact target in the active task", ) return self._dispatch_observed(tool, prepared, actor) def restore(self, snapshot: dict[str, Any]) -> None: validate_snapshot(snapshot) replay = self._replay_snapshot(snapshot) canonical = replay.snapshot() if _canonical(canonical) != _canonical(snapshot): raise ValueError("API Reliability v8 snapshot differs from canonical public replay") inherited = deepcopy(canonical) observations = inherited.pop("capability_observations") inherited["schema"] = _stream.SNAPSHOT_SCHEMA super().restore(inherited) self.capability_observations = observations if _canonical(self.snapshot()) != _canonical(canonical): raise ValueError("API Reliability v8 snapshot did not round trip exactly") def grade(self, task_id: str | None = None) -> dict[str, Any]: diagnostic = super().grade(task_id) rows = [] for row in diagnostic["targets"]: item = deepcopy(row) item["diagnostic_milestone_score"] = item["score"] complete = all(bool(value) for value in item["milestones"].values()) item["score"] = 25.0 if complete else 0.0 item["complete"] = complete rows.append(item) complete_artifacts = sum(int(row["complete"]) for row in rows) return { "task_id": diagnostic["task_id"], "score": 25.0 * complete_artifacts, "complete_artifacts": complete_artifacts, "completed_artifacts": complete_artifacts, "remaining_budget": self.remaining, "work_units_used": self.initial_budget - self.remaining, "targets": rows, }