ReScopeBench / cases /api_reliability /stream_runtime.py
JoeYing
Add ReScopeBench cases and task preview
f726fd6
Raw History Blame Contribute Delete
24.9 kB
"""Persistent lifecycle runtime for the API Reliability task stream."""
from __future__ import annotations
from copy import deepcopy
import hashlib
import json
from typing import Any
from rescopebench.cases.api_reliability.adapter import (
PUBLIC_TOOLS,
REFERENCE_NOW,
RETRYABLE_STATUSES,
ROLE,
ApiReliabilityAdapter,
)
from .spec import (
CHANGED_RULE_IDS, DRIFTED_RULES, DRIFT_EVENT_ID, INITIAL_BUDGET,
OPERATION_BY_CLASS, PRE_RULES, RULE_SCHEDULE, STRUCTURE_BY_ID,
STRUCTURE_CLUSTERS, STRUCTURE_SCHEDULE, TASK_IDS, _bucket_id, stream_targets,
)
STREAM_ALLOWANCE = INITIAL_BUDGET
SNAPSHOT_SCHEMA = "rescopebench-api-reliability-stream-snapshot/v1"
def _canonical(value: Any) -> str:
return json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(",", ":"))
def _opaque(prefix: str, *parts: Any, length: int = 12) -> str:
payload = "|".join(str(part) for part in parts)
digest = hashlib.sha256(f"api-reliability-stream|{payload}".encode("utf-8")).hexdigest()
return f"{prefix}-{digest[:length]}"
def _rule_rows(*, drifted: bool) -> dict[str, dict[str, str]]:
return deepcopy(DRIFTED_RULES if drifted else PRE_RULES)
def _status_for_signal(signal: str) -> tuple[str, str]:
return {
"queued_replay": ("queued", "REPLAY_QUEUED"),
"provider_5xx": ("transient_error", "HTTP_503"),
"timeout": ("timeout", "TIMEOUT"),
"rate_limit": ("rate_limited", "HTTP_429"),
}[signal]
class _MemoryDatabase:
def __init__(self, data: dict[str, list[dict[str, Any]]]) -> None:
self._data = deepcopy(data)
def _flush(self, entity_type: str) -> None:
del entity_type
class _MemoryManager:
def __init__(self, data: dict[str, list[dict[str, Any]]]) -> None:
self.db = _MemoryDatabase(data)
self._counters: dict[str, int] = {}
def snapshot(self) -> dict[str, Any]:
return {"database": deepcopy(self.db._data), "counters": deepcopy(self._counters)}
def query_entities(self, entity_type: str, predicate: Any) -> list[dict[str, Any]]:
return [deepcopy(row) for row in self.db._data.get(entity_type, []) if predicate(row)]
def get_entity(self, entity_type: str, entity_id: str, id_field: str = "id") -> dict[str, Any] | None:
for row in self.db._data.get(entity_type, []):
if row.get(id_field) == entity_id:
return deepcopy(row)
return None
def list_entities(self, entity_type: str) -> list[dict[str, Any]]:
return deepcopy(self.db._data.get(entity_type, []))
def add_entity(self, entity_type: str, entity: dict[str, Any], id_field: str = "id") -> dict[str, Any]:
rows = self.db._data.setdefault(entity_type, [])
key = entity.get(id_field)
for index, row in enumerate(rows):
if row.get(id_field) == key:
rows[index] = deepcopy(entity)
return deepcopy(entity)
rows.append(deepcopy(entity))
return deepcopy(entity)
class _MemoryServer:
def __init__(self, manager: _MemoryManager) -> None:
self.manager = manager
@staticmethod
def _success(tool: str, data: dict[str, Any], message: str) -> dict[str, Any]:
return {
"type": "tool_result",
"tool": tool,
"content": {"status": "success", "data": data, "message": message},
}
@staticmethod
def _page(rows: list[dict[str, Any]], arguments: dict[str, Any]) -> dict[str, Any]:
offset = int(arguments.get("offset", 0))
limit = int(arguments.get("limit", 25))
return {
"total_count": len(rows),
"offset": offset,
"limit": limit,
"items": deepcopy(rows[offset : offset + limit]),
}
def cleanup_runtime(self) -> None:
return None
def call_tool(self, tool: str, state_manager: Any = None, **arguments: Any) -> dict[str, Any]:
manager = state_manager or self.manager
if tool == "list_service_integrations":
rows = manager.list_entities("service_integration")
if arguments.get("provider_type"):
rows = [row for row in rows if row.get("provider_type") == arguments["provider_type"]]
if arguments.get("status"):
rows = [row for row in rows if row.get("status") == arguments["status"]]
return self._success(tool, self._page(rows, arguments), "Integrations listed")
if tool == "list_api_credentials":
rows = manager.list_entities("api_credential")
if arguments.get("integration_id"):
rows = [row for row in rows if row.get("integration_id") == arguments["integration_id"]]
if arguments.get("status"):
rows = [row for row in rows if row.get("status") == arguments["status"]]
if arguments.get("scope_contains"):
rows = [row for row in rows if arguments["scope_contains"] in (row.get("scope") or [])]
return self._success(tool, self._page(rows, arguments), "Credentials listed")
if tool == "list_retry_budgets":
rows = manager.list_entities("retry_budget")
if arguments.get("integration_id"):
rows = [row for row in rows if row.get("integration_id") == arguments["integration_id"]]
if arguments.get("status"):
rows = [row for row in rows if row.get("status") == arguments["status"]]
if arguments.get("window_minutes"):
rows = [row for row in rows if row.get("window_minutes") == arguments["window_minutes"]]
return self._success(tool, self._page(rows, arguments), "Retry budgets listed")
if tool == "inspect_rate_limit_status":
rows = manager.query_entities(
"rate_limit_bucket",
lambda row: row.get("integration_id") == arguments["integration_id"]
and (not arguments.get("operation") or row.get("operation") == arguments["operation"]),
)
return self._success(tool, {"buckets": rows, "requested_units": arguments.get("requested_units", 1)}, "Rate capacity inspected")
if tool == "list_fault_policies":
rows = manager.list_entities("fault_policy")
if arguments.get("integration_id"):
rows = [row for row in rows if row.get("integration_id") == arguments["integration_id"]]
if "enabled" in arguments:
rows = [row for row in rows if row.get("enabled") is arguments["enabled"]]
if arguments.get("operation"):
rows = [row for row in rows if row.get("operation") == arguments["operation"]]
return self._success(tool, self._page(rows, arguments), "Fault policies listed")
if tool == "search_audit_events":
rows = manager.list_entities("audit_event")
if arguments.get("integration_id"):
rows = [row for row in rows if row.get("integration_id") == arguments["integration_id"]]
if arguments.get("related_call_id"):
rows = [row for row in rows if row.get("related_call_id") == arguments["related_call_id"]]
return self._success(tool, self._page(rows, arguments), "Audit events listed")
if tool == "execute_api_call":
digest = hashlib.sha256(
_canonical(
[
arguments["integration_id"],
arguments["operation"],
arguments["request_fingerprint"],
arguments["idempotency_key"],
]
).encode("utf-8")
).hexdigest()[:12]
call_id = f"direct-{digest}"
manager.add_entity(
"api_call_attempt",
{
"call_id": call_id,
"integration_id": arguments["integration_id"],
"credential_id": arguments["credential_id"],
"operation": arguments["operation"],
"request_hash": arguments["request_fingerprint"],
"status": "success",
"retry_attempt": 0,
"max_retry_attempts": 0,
"side_effect_committed": True,
"created_at": REFERENCE_NOW,
"updated_at": REFERENCE_NOW,
},
id_field="call_id",
)
manager.add_entity(
"idempotency_key",
{
"idempotency_id": f"idem-{digest}",
"integration_id": arguments["integration_id"],
"operation": arguments["operation"],
"key": arguments["idempotency_key"],
"request_fingerprint": arguments["request_fingerprint"],
"status": "consumed",
"associated_call_id": call_id,
},
id_field="idempotency_id",
)
return self._success(tool, {"call_id": call_id, "status": "success", "side_effect_committed": True}, "Provider call executed")
raise ValueError(f"unsupported in-memory tool: {tool}")
def _base_entities() -> dict[str, list[dict[str, Any]]]:
data: dict[str, list[dict[str, Any]]] = {
"service_integration": [],
"api_credential": [],
"retry_budget": [],
"rate_limit_bucket": [],
"fault_policy": [],
"api_call_attempt": [],
"idempotency_key": [],
"audit_event": [],
"incident_window": [],
}
for index, structure in enumerate(STRUCTURE_CLUSTERS, 1):
data["service_integration"].append(
{
"integration_id": structure["integration_id"],
"name": structure["integration_name"],
"provider_type": "external_api",
"status": "active",
"created_at": REFERENCE_NOW,
"updated_at": REFERENCE_NOW,
}
)
data["api_credential"].append(
{
"credential_id": structure["credential_id"],
"integration_id": structure["integration_id"],
"name": f"Scoped Credential {index}",
"status": "active",
"scope": list(OPERATION_BY_CLASS.values()),
"created_at": REFERENCE_NOW,
"updated_at": REFERENCE_NOW,
}
)
data["retry_budget"].append(
{
"budget_id": structure["retry_budget_id"],
"integration_id": structure["integration_id"],
"window_minutes": 60,
"status": "open",
"max_attempts": 64,
"used_attempts": 0,
"reserved_attempts": 0,
"created_at": REFERENCE_NOW,
"updated_at": REFERENCE_NOW,
}
)
for operation in OPERATION_BY_CLASS.values():
data["rate_limit_bucket"].append(
{
"bucket_id": _bucket_id(structure["atom_id"], operation),
"integration_id": structure["integration_id"],
"operation": operation,
"status": "healthy",
"limit": 64,
"remaining": 64,
"created_at": REFERENCE_NOW,
"updated_at": REFERENCE_NOW,
}
)
return data
def _task_entities(task_id: str) -> dict[str, list[dict[str, Any]]]:
data = {"api_call_attempt": [], "fault_policy": []}
for target in stream_targets(task_id):
status, error_code = _status_for_signal(target["failure_signal"])
data["api_call_attempt"].append(
{
"call_id": target["call_id"],
"integration_id": target["integration_id"],
"operation": target["operation"],
"status": status,
"http_status": 429 if error_code == "HTTP_429" else 503 if error_code == "HTTP_503" else 504 if error_code == "TIMEOUT" else None,
"error_code": error_code,
"retry_attempt": 0,
"max_retry_attempts": 3,
"request_hash": _opaque("request", task_id, target["slot"]),
"side_effect_committed": False,
"created_at": REFERENCE_NOW,
"updated_at": REFERENCE_NOW,
}
)
data["fault_policy"].append(
{
"fault_policy_id": target["fault_policy_id"],
"integration_id": target["integration_id"],
"operation": target["operation"],
"failure_signal": target["failure_signal"],
"enabled": True,
"created_at": REFERENCE_NOW,
"updated_at": REFERENCE_NOW,
}
)
return data
class PersistentApiReliabilityAdapter(ApiReliabilityAdapter):
"""In-memory persistent recovery world with sequential task activation."""
def __init__(self, budget: int = STREAM_ALLOWANCE) -> None:
self.manager = _MemoryManager(_base_entities())
self.server = _MemoryServer(self.manager)
self.initial_budget = int(budget)
self.remaining = int(budget)
self.receipts: list[dict[str, Any]] = []
self.applied_boundary_events: set[str] = set()
self.active_task_id: str | None = None
self._policy_version = "recovery-policy-v1"
self._activated_tasks: list[str] = []
self._task_targets: list[dict[str, Any]] = []
self._active_receipt_start = 0
@property
def activated_tasks(self) -> tuple[str, ...]:
return tuple(self._activated_tasks)
@property
def current_rules(self) -> dict[str, dict[str, str]]:
return _rule_rows(drifted=self._policy_version == "recovery-policy-v2")
def required_profile(self, source: dict[str, Any]) -> str:
signal = source.get("failure_signal")
operation_class = source.get("operation_class")
if not signal or not operation_class:
status = str(source.get("status") or "")
error = str(source.get("error_code") or "")
if status == "queued" or error == "REPLAY_QUEUED":
signal = "queued_replay"
elif status == "rate_limited" or error == "HTTP_429":
signal = "rate_limit"
elif status == "timeout" or error in {"TIMEOUT", "HTTP_504"}:
signal = "timeout"
else:
signal = "provider_5xx"
operation_class = next(
key for key, value in OPERATION_BY_CLASS.items() if value == source.get("operation")
)
return next(
row["recovery_profile_id"]
for row in self.current_rules.values()
if row["failure_signal"] == signal and row["operation_class"] == operation_class
)
def _retry_guard(self, arguments: dict[str, Any]) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
source = self.manager.get_entity("api_call_attempt", arguments["call_id"], id_field="call_id")
if source is None:
return None, self._error("retry_api_call", "CALL_NOT_FOUND", "source call does not exist")
if source.get("status") not in RETRYABLE_STATUSES:
return None, self._error("retry_api_call", "CALL_NOT_RETRYABLE", "source call status is not retryable")
if int(source.get("retry_attempt") or 0) >= int(source.get("max_retry_attempts") or 0):
return None, self._error("retry_api_call", "RETRY_LIMIT_REACHED", "source call has no retry attempts remaining")
prior = self.manager.query_entities(
"api_call_attempt",
lambda row: row.get("duplicate_of_call_id") == source.get("call_id")
and row.get("side_effect_committed") is True,
)
if prior:
prior.sort(key=lambda row: row.get("call_id") or "")
return source, self._success(
"retry_api_call",
{
"source_call_id": source["call_id"],
"retry_call_id": prior[0]["call_id"],
"status": prior[0].get("status"),
"side_effect_committed": True,
"idempotent_replay": True,
},
"Existing committed recovery returned without another provider call",
)
if arguments["recovery_profile_id"] != self.required_profile(source):
return None, self._error(
"retry_api_call",
"RECOVERY_PROFILE_MISMATCH",
"the selected recovery profile is not valid for the observed failure and operation class",
)
credential = self.manager.get_entity("api_credential", arguments["credential_id"], id_field="credential_id")
if credential is None:
return None, self._error("retry_api_call", "CREDENTIAL_NOT_FOUND", "credential does not exist")
if credential.get("integration_id") != source.get("integration_id"):
return None, self._error("retry_api_call", "ENTITY_SCOPE_MISMATCH", "credential belongs to another integration")
if credential.get("status") not in {"active", "rotating"}:
return None, self._error("retry_api_call", "CREDENTIAL_NOT_USABLE", "credential is not currently usable")
if source.get("operation") not in (credential.get("scope") or []):
return None, self._error("retry_api_call", "SCOPE_NOT_ALLOWED", "credential scope excludes the source operation")
budget = self.manager.get_entity("retry_budget", arguments["retry_budget_id"], id_field="budget_id")
if budget is None:
return None, self._error("retry_api_call", "BUDGET_NOT_FOUND", "retry budget does not exist")
if budget.get("integration_id") != source.get("integration_id"):
return None, self._error("retry_api_call", "ENTITY_SCOPE_MISMATCH", "retry budget belongs to another integration")
available = int(budget.get("max_attempts") or 0) - int(budget.get("used_attempts") or 0) - int(budget.get("reserved_attempts") or 0)
if budget.get("status") != "open" or available < 1:
return None, self._error("retry_api_call", "RETRY_BUDGET_EXHAUSTED", "retry budget lacks capacity")
bucket = self.manager.get_entity("rate_limit_bucket", arguments["rate_limit_bucket_id"], id_field="bucket_id")
if bucket is None:
return None, self._error("retry_api_call", "RATE_BUCKET_NOT_FOUND", "rate bucket does not exist")
if bucket.get("integration_id") != source.get("integration_id") or bucket.get("operation") != source.get("operation"):
return None, self._error("retry_api_call", "ENTITY_SCOPE_MISMATCH", "rate bucket does not match source integration and operation")
if bucket.get("status") == "disabled" or int(bucket.get("remaining") or 0) < 1:
return None, self._error("retry_api_call", "RATE_LIMIT_EXCEEDED", "rate bucket lacks capacity")
return source, None
def _search_recovery_evidence(self, arguments: dict[str, Any]) -> dict[str, Any]:
rows = list(self.current_rules.values())
if arguments.get("failure_signal"):
rows = [row for row in rows if row["failure_signal"] == arguments["failure_signal"]]
if arguments.get("operation_class"):
rows = [row for row in rows if row["operation_class"] == arguments["operation_class"]]
offset = int(arguments.get("offset", 0))
limit = int(arguments.get("limit", 16))
return self._success(
"search_recovery_evidence",
{"total_count": len(rows), "offset": offset, "limit": limit, "evidence": deepcopy(rows[offset : offset + limit])},
"Archived recovery evidence searched",
)
def apply_recovery_policy_drift(self, event_id: str = DRIFT_EVENT_ID) -> dict[str, Any]:
if event_id in self.applied_boundary_events:
return {"status": "success", "event_id": event_id, "idempotent": True}
self._policy_version = "recovery-policy-v2"
self.applied_boundary_events.add(event_id)
return {"status": "success", "event_id": event_id, "idempotent": False}
def activate_task(self, task_id: str, allowance: int = STREAM_ALLOWANCE) -> dict[str, Any]:
if task_id not in TASK_IDS:
raise ValueError(f"unknown stream task: {task_id}")
expected = TASK_IDS[len(self._activated_tasks)] if len(self._activated_tasks) < len(TASK_IDS) else None
if task_id != expected:
raise ValueError(f"expected {expected}, got {task_id}")
boundary = self.apply_recovery_policy_drift() if task_id == "T09" else None
for entity_type, rows in _task_entities(task_id).items():
id_field = "call_id" if entity_type == "api_call_attempt" else "fault_policy_id"
for row in rows:
self.manager.add_entity(entity_type, row, id_field=id_field)
self.active_task_id = task_id
self._task_targets = [deepcopy(row) for row in stream_targets(task_id)]
self.initial_budget = int(allowance)
self.remaining = int(allowance)
self._active_receipt_start = len(self.receipts)
self._activated_tasks.append(task_id)
return {
"status": "success",
"task_id": task_id,
"world_reset": False,
"budget_reset": True,
"boundary_event_applied": boundary is not None and not boundary["idempotent"],
"entry_business_hash": self.business_hash(),
"entry_lineage_hash": self.lineage_hash(),
}
def current_episode_events(self) -> list[dict[str, Any]]:
return deepcopy(self.receipts[self._active_receipt_start :])
def grade(self, task_id: str | None = None) -> dict[str, Any]:
active = task_id or self.active_task_id
if active != self.active_task_id or active not in TASK_IDS:
raise ValueError("only the active stream task can be graded")
grade_targets = []
for target in self._task_targets:
row = deepcopy(target)
row["recovery_profile_id"] = self.current_rules[target["rule_atom"]]["recovery_profile_id"]
grade_targets.append(row)
grade = self.grade_targets(grade_targets)
grade.update({"task_id": active, "remaining_budget": self.remaining})
return grade
def business_hash(self) -> str:
payload = {"database": self.manager.snapshot()["database"], "policy_version": self._policy_version}
return hashlib.sha256(_canonical(payload).encode("utf-8")).hexdigest()
def lineage_hash(self) -> str:
return hashlib.sha256(_canonical(self.snapshot()).encode("utf-8")).hexdigest()
def snapshot(self) -> dict[str, Any]:
return {
"schema": SNAPSHOT_SCHEMA,
"raw": self.manager.snapshot(),
"remaining": self.remaining,
"initial_budget": self.initial_budget,
"receipts": deepcopy(self.receipts),
"applied_boundary_events": sorted(self.applied_boundary_events),
"active_task_id": self.active_task_id,
"policy_version": self._policy_version,
"activated_tasks": list(self._activated_tasks),
"task_targets": deepcopy(self._task_targets),
"active_receipt_start": self._active_receipt_start,
}
def restore(self, snapshot: dict[str, Any]) -> None:
if snapshot.get("schema") != SNAPSHOT_SCHEMA:
raise ValueError("unsupported persistent stream snapshot schema")
self._restore_database(snapshot["raw"]["database"], snapshot["raw"].get("counters", {}))
self.remaining = int(snapshot["remaining"])
self.initial_budget = int(snapshot.get("initial_budget", STREAM_ALLOWANCE))
self.receipts = deepcopy(snapshot["receipts"])
self.applied_boundary_events = set(snapshot.get("applied_boundary_events", []))
self.active_task_id = snapshot.get("active_task_id")
self._policy_version = str(snapshot.get("policy_version") or "recovery-policy-v1")
self._activated_tasks = list(snapshot.get("activated_tasks") or [])
self._task_targets = deepcopy(snapshot.get("task_targets") or [])
self._active_receipt_start = int(snapshot.get("active_receipt_start") or 0)
__all__ = [
"CHANGED_RULE_IDS",
"DRIFTED_RULES",
"DRIFT_EVENT_ID",
"OPERATION_BY_CLASS",
"PRE_RULES",
"RULE_SCHEDULE",
"STREAM_ALLOWANCE",
"STRUCTURE_CLUSTERS",
"STRUCTURE_SCHEDULE",
"TASK_IDS",
"PersistentApiReliabilityAdapter",
"stream_targets",
]