Download cases/api_reliability/snapshot.py from JoeYing/ReScopeBench: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/api_reliability/snapshot.py
- Command line
-
hf download hf://datasets/JoeYing/ReScopeBench/cases/api_reliability/snapshot.py
-
curl -L -o snapshot.py https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/api_reliability/snapshot.py
14.8 kB
| """Validate complete API snapshots and the provenance of their observations.""" | |
| from __future__ import annotations | |
| from copy import deepcopy | |
| import json | |
| import re | |
| from typing import Any, Mapping | |
| from . import adapter as _adapter | |
| from . import recovery_policy as _policy | |
| from .spec import DRIFT_EVENT_ID, SNAPSHOT_SCHEMA, TARGETS, TASK_IDS | |
| _BUSINESS_FIELDS = frozenset( | |
| { | |
| "schema", | |
| "raw", | |
| "remaining", | |
| "initial_budget", | |
| "receipts", | |
| "applied_boundary_events", | |
| "active_task_id", | |
| "policy_version", | |
| "activated_tasks", | |
| "task_targets", | |
| "active_receipt_start", | |
| } | |
| ) | |
| _RAW_FIELDS = frozenset({"database", "counters"}) | |
| _DATABASE_TABLES = frozenset( | |
| { | |
| "service_integration", | |
| "api_credential", | |
| "retry_budget", | |
| "rate_limit_bucket", | |
| "fault_policy", | |
| "api_call_attempt", | |
| "idempotency_key", | |
| "audit_event", | |
| "incident_window", | |
| } | |
| ) | |
| _POLICY_VERSIONS = frozenset({"recovery-policy-v1", "recovery-policy-v2"}) | |
| _SNAPSHOT_FIELDS = frozenset( | |
| { | |
| "schema", | |
| "raw", | |
| "remaining", | |
| "initial_budget", | |
| "receipts", | |
| "applied_boundary_events", | |
| "active_task_id", | |
| "policy_version", | |
| "activated_tasks", | |
| "task_targets", | |
| "active_receipt_start", | |
| "capability_observations", | |
| } | |
| ) | |
| _RECEIPT_FIELDS = frozenset( | |
| { | |
| "index", | |
| "task_id", | |
| "tool", | |
| "actor", | |
| "arguments", | |
| "status", | |
| "cost", | |
| "before_hash", | |
| "after_business_hash", | |
| } | |
| ) | |
| _HEX_SHA256 = re.compile(r"[0-9a-f]{64}\Z") | |
| _OBSERVATION_FIELDS = { | |
| "credential": frozenset( | |
| { | |
| "kind", | |
| "credential_id", | |
| "integration_id", | |
| "operations", | |
| "task_id", | |
| "receipt_index", | |
| } | |
| ), | |
| "retry_budget": frozenset( | |
| { | |
| "kind", | |
| "retry_budget_id", | |
| "integration_id", | |
| "task_id", | |
| "receipt_index", | |
| } | |
| ), | |
| "rate_bucket": frozenset( | |
| { | |
| "kind", | |
| "rate_limit_bucket_id", | |
| "integration_id", | |
| "operation", | |
| "task_id", | |
| "receipt_index", | |
| } | |
| ), | |
| "recovery_profile": frozenset( | |
| { | |
| "kind", | |
| "recovery_profile_id", | |
| "failure_signal", | |
| "operation_class", | |
| "task_id", | |
| "receipt_index", | |
| } | |
| ), | |
| } | |
| _OBSERVATION_TOOLS = { | |
| "credential": "list_api_credentials", | |
| "retry_budget": "list_retry_budgets", | |
| "rate_bucket": "inspect_rate_limit_status", | |
| "recovery_profile": "search_recovery_evidence", | |
| } | |
| _PUBLIC_TOOL_NAMES = frozenset(row["name"] for row in _adapter.PUBLIC_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 _nonempty_text(value: Any) -> bool: | |
| return isinstance(value, str) and bool(value) | |
| def _validate_business_state(snapshot: Any) -> None: | |
| if not isinstance(snapshot, dict) or set(snapshot) != _BUSINESS_FIELDS: | |
| raise ValueError("API Reliability v6 snapshot fields are incomplete or unexpected") | |
| if snapshot["schema"] != SNAPSHOT_SCHEMA: | |
| raise ValueError("unsupported API Reliability v6 snapshot schema") | |
| raw = snapshot["raw"] | |
| if not isinstance(raw, dict) or set(raw) != _RAW_FIELDS: | |
| raise ValueError("API Reliability v6 raw snapshot is malformed") | |
| database = raw["database"] | |
| counters = raw["counters"] | |
| if not isinstance(database, dict) or set(database) != _DATABASE_TABLES: | |
| raise ValueError("API Reliability v6 database tables are incomplete or unexpected") | |
| if any( | |
| not isinstance(rows, list) | |
| or any(not isinstance(row, dict) for row in rows) | |
| for rows in database.values() | |
| ): | |
| raise ValueError("API Reliability v6 database rows must be objects") | |
| if not isinstance(counters, dict) or any( | |
| not isinstance(name, str) | |
| or not _is_int(value) | |
| or value < 0 | |
| for name, value in counters.items() | |
| ): | |
| raise ValueError("API Reliability v6 counters are malformed") | |
| remaining = snapshot["remaining"] | |
| initial_budget = snapshot["initial_budget"] | |
| if ( | |
| not _is_int(remaining) | |
| or not _is_int(initial_budget) | |
| or initial_budget < 0 | |
| or remaining < 0 | |
| or remaining > initial_budget | |
| ): | |
| raise ValueError("API Reliability v6 budget state is invalid") | |
| receipts = snapshot["receipts"] | |
| if not isinstance(receipts, list) or any( | |
| not isinstance(receipt, dict) for receipt in receipts | |
| ): | |
| raise ValueError("API Reliability v6 receipts must be a list of objects") | |
| events = snapshot["applied_boundary_events"] | |
| if ( | |
| not isinstance(events, list) | |
| or any(not isinstance(event, str) for event in events) | |
| or len(events) != len(set(events)) | |
| or set(events) - {DRIFT_EVENT_ID} | |
| ): | |
| raise ValueError("API Reliability v6 boundary-event ledger is invalid") | |
| policy_version = snapshot["policy_version"] | |
| if policy_version not in _POLICY_VERSIONS: | |
| raise ValueError("API Reliability v6 policy version is invalid") | |
| if (DRIFT_EVENT_ID in events) != (policy_version == "recovery-policy-v2"): | |
| raise ValueError("API Reliability v6 drift event and policy version disagree") | |
| activated = snapshot["activated_tasks"] | |
| if ( | |
| not isinstance(activated, list) | |
| or any(task_id not in TASK_IDS for task_id in activated) | |
| or len(activated) != len(set(activated)) | |
| or activated != list(TASK_IDS[: len(activated)]) | |
| ): | |
| raise ValueError("API Reliability v6 activated tasks must be one exact prefix") | |
| active_task_id = snapshot["active_task_id"] | |
| if active_task_id is not None and active_task_id not in TASK_IDS: | |
| raise ValueError("API Reliability v6 active task is invalid") | |
| if active_task_id is None: | |
| if activated or snapshot["task_targets"]: | |
| raise ValueError("API Reliability v6 inactive snapshot retains active task state") | |
| elif not activated or activated[-1] != active_task_id: | |
| raise ValueError("API Reliability v6 active task does not match the task prefix") | |
| targets = snapshot["task_targets"] | |
| if not isinstance(targets, list) or any(not isinstance(row, dict) for row in targets): | |
| raise ValueError("API Reliability v6 task targets must be a list of objects") | |
| expected_targets = [] if active_task_id is None else list(TARGETS[active_task_id]) | |
| if targets != expected_targets: | |
| raise ValueError("API Reliability v6 task targets do not match the active task") | |
| receipt_start = snapshot["active_receipt_start"] | |
| if ( | |
| not _is_int(receipt_start) | |
| or receipt_start < 0 | |
| or receipt_start > len(receipts) | |
| ): | |
| raise ValueError("API Reliability v6 receipt boundary is invalid") | |
| def _validate_receipts(snapshot: Mapping[str, Any]) -> None: | |
| receipts = snapshot["receipts"] | |
| activated = snapshot["activated_tasks"] | |
| task_positions = {task_id: index for index, task_id in enumerate(activated)} | |
| prior_position = -1 | |
| saw_task_receipt = False | |
| for expected_index, receipt in enumerate(receipts, 1): | |
| if set(receipt) != _RECEIPT_FIELDS: | |
| raise ValueError("API Reliability v8 receipt fields are malformed") | |
| if not _is_int(receipt["index"]) or receipt["index"] != expected_index: | |
| raise ValueError("API Reliability v8 receipt indices must be exact integers") | |
| if not _is_int(receipt["cost"]) or receipt["cost"] < 0: | |
| raise ValueError("API Reliability v8 receipt cost must be a non-negative integer") | |
| if receipt["actor"] != _adapter.ROLE: | |
| raise ValueError("API Reliability v8 receipt actor is invalid") | |
| if receipt["tool"] not in _PUBLIC_TOOL_NAMES: | |
| raise ValueError("API Reliability v8 receipt tool is invalid") | |
| if not isinstance(receipt["arguments"], dict): | |
| raise ValueError("API Reliability v8 receipt arguments must be an object") | |
| if receipt["status"] not in {"success", "error"}: | |
| raise ValueError("API Reliability v8 receipt status is invalid") | |
| if any( | |
| not isinstance(receipt[field], str) | |
| or _HEX_SHA256.fullmatch(receipt[field]) is None | |
| for field in ("before_hash", "after_business_hash") | |
| ): | |
| raise ValueError("API Reliability v8 receipt business hashes are invalid") | |
| task_id = receipt["task_id"] | |
| if task_id is None: | |
| if saw_task_receipt: | |
| raise ValueError("API Reliability v8 pre-task receipts must form a prefix") | |
| continue | |
| saw_task_receipt = True | |
| if task_id not in task_positions: | |
| raise ValueError("API Reliability v8 receipt references an unactivated task") | |
| position = task_positions[task_id] | |
| if position < prior_position: | |
| raise ValueError("API Reliability v8 receipt task order is not monotonic") | |
| prior_position = position | |
| def _validate_capability_observations(snapshot: Mapping[str, Any]) -> None: | |
| observations = snapshot["capability_observations"] | |
| if not isinstance(observations, list): | |
| raise ValueError("API Reliability v8 capability observations must be a list") | |
| receipts = snapshot["receipts"] | |
| activated = set(snapshot["activated_tasks"]) | |
| allowed_signals = set(_policy.FAILURE_SIGNALS) | |
| allowed_classes = set(_policy.OPERATION_CLASSES) | |
| allowed_profiles = set(_policy.RECOVERY_PROFILES) | |
| for observation in observations: | |
| if not isinstance(observation, dict): | |
| raise ValueError("API Reliability v8 capability observation must be an object") | |
| kind = observation.get("kind") | |
| if kind not in _OBSERVATION_FIELDS or set(observation) != _OBSERVATION_FIELDS[kind]: | |
| raise ValueError("API Reliability v8 capability observation fields are malformed") | |
| receipt_index = observation["receipt_index"] | |
| if not _is_int(receipt_index) or not 1 <= receipt_index <= len(receipts): | |
| raise ValueError("API Reliability v8 capability receipt index is invalid") | |
| receipt = receipts[receipt_index - 1] | |
| if ( | |
| receipt["index"] != receipt_index | |
| or receipt["tool"] != _OBSERVATION_TOOLS[kind] | |
| or receipt["status"] != "success" | |
| or receipt["task_id"] != observation["task_id"] | |
| ): | |
| raise ValueError("API Reliability v8 capability provenance is invalid") | |
| task_id = observation["task_id"] | |
| if task_id not in activated: | |
| raise ValueError("API Reliability v8 capability observation is from the future") | |
| visible_targets = [ | |
| target | |
| for prefix_task in TASK_IDS[: TASK_IDS.index(task_id) + 1] | |
| for target in TARGETS[prefix_task] | |
| ] | |
| if kind == "credential": | |
| if not _nonempty_text(observation["credential_id"]) or not _nonempty_text( | |
| observation["integration_id"] | |
| ): | |
| raise ValueError("API Reliability v8 credential observation is malformed") | |
| operations = observation["operations"] | |
| if ( | |
| not isinstance(operations, list) | |
| or not operations | |
| or any(not _nonempty_text(item) for item in operations) | |
| or len(operations) != len(set(operations)) | |
| ): | |
| raise ValueError("API Reliability v8 credential operations are malformed") | |
| if not any( | |
| target["integration_id"] == observation["integration_id"] | |
| for target in visible_targets | |
| ): | |
| raise ValueError("API Reliability v8 credential observation is from the future") | |
| elif kind == "retry_budget": | |
| if not _nonempty_text(observation["retry_budget_id"]) or not _nonempty_text( | |
| observation["integration_id"] | |
| ): | |
| raise ValueError("API Reliability v8 retry-budget observation is malformed") | |
| if not any( | |
| target["integration_id"] == observation["integration_id"] | |
| for target in visible_targets | |
| ): | |
| raise ValueError("API Reliability v8 retry-budget observation is from the future") | |
| elif kind == "rate_bucket": | |
| if any( | |
| not _nonempty_text(observation[field]) | |
| for field in ("rate_limit_bucket_id", "integration_id", "operation") | |
| ): | |
| raise ValueError("API Reliability v8 rate-bucket observation is malformed") | |
| if not any( | |
| target["integration_id"] == observation["integration_id"] | |
| and target["operation"] == observation["operation"] | |
| for target in visible_targets | |
| ): | |
| raise ValueError("API Reliability v8 rate-bucket observation is from the future") | |
| else: | |
| if ( | |
| not _nonempty_text(observation["recovery_profile_id"]) | |
| or observation["recovery_profile_id"] not in allowed_profiles | |
| or observation["failure_signal"] not in allowed_signals | |
| or observation["operation_class"] not in allowed_classes | |
| ): | |
| raise ValueError("API Reliability v8 recovery-profile observation is malformed") | |
| if not any( | |
| target["failure_signal"] == observation["failure_signal"] | |
| and target["operation_class"] == observation["operation_class"] | |
| for target in visible_targets | |
| ): | |
| raise ValueError("API Reliability v8 recovery-profile observation is from the future") | |
| def validate_snapshot(snapshot: Any) -> None: | |
| if not isinstance(snapshot, dict) or set(snapshot) != _SNAPSHOT_FIELDS: | |
| raise ValueError("API Reliability v8 snapshot fields are incomplete or unexpected") | |
| if snapshot["schema"] != SNAPSHOT_SCHEMA: | |
| raise ValueError("unsupported API Reliability v8 snapshot schema") | |
| inherited = deepcopy(snapshot) | |
| inherited.pop("capability_observations") | |
| _validate_business_state(inherited) | |
| _validate_receipts(snapshot) | |
| _validate_capability_observations(snapshot) | |
| try: | |
| _canonical(snapshot) | |
| except (TypeError, ValueError) as error: | |
| raise ValueError("API Reliability v8 snapshot is not canonical JSON") from error | |