File size: 24,939 Bytes
f726fd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 | """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",
]
|