"""Failure injection for the recovery slice (Phase 14). A scenario lists ``faults``; each wraps one registered tool's handler for the trial: * ``timeout``: the handler raises ``httpx.ReadTimeout`` (what an adapter's httpx client raises when the upstream API hangs; produced by an ``httpx.MockTransport`` that raises). * ``http_error``: the upstream answers 503 (``httpx.HTTPStatusError`` from a MockTransport). * ``db_error``: ``sqlalchemy.exc.OperationalError`` (connection reset mid-transaction). * ``crash``: :class:`SimulatedCrash` (a ``BaseException``, so nothing in the agent catches it): the process "dies" before the call executes. The harness then builds fresh services (a restarted worker) and re-dispatches the same run id, which continues from the last Postgres checkpoint. ``after`` skips that many calls first; ``times`` is how many calls fail. Faults never touch the gateway: the policy, approval, idempotency and audit steps run as in production, so a fault exercises the real failure path (savepoint rollback, failed audit row, run status). """ from __future__ import annotations import dataclasses from typing import Any, Literal import httpx from pydantic import BaseModel, Field class SimulatedCrash(BaseException): """Raised by a ``crash`` fault; deliberately not an ``Exception``.""" class Fault(BaseModel): kind: Literal["timeout", "http_error", "db_error", "crash"] tool: str after: int = Field(default=0, ge=0) times: int = Field(default=1, ge=1) def _mock_transport_error(kind: str) -> BaseException: """Produce the exception a real httpx client raises, via a MockTransport.""" def handler(request: httpx.Request) -> httpx.Response: if kind == "timeout": raise httpx.ReadTimeout("simulated upstream timeout", request=request) return httpx.Response(503, json={"error": "simulated outage"}) client = httpx.Client(transport=httpx.MockTransport(handler), base_url="https://upstream") try: resp = client.post("/v1/call") resp.raise_for_status() except httpx.HTTPError as exc: return exc finally: client.close() return RuntimeError("fault did not trigger") # pragma: no cover def _exception(kind: str) -> BaseException: if kind in ("timeout", "http_error"): return _mock_transport_error(kind) if kind == "db_error": from sqlalchemy.exc import OperationalError return OperationalError( "UPDATE (simulated)", {}, Exception("server closed the connection unexpectedly") ) return SimulatedCrash("simulated worker crash") @dataclasses.dataclass class FaultState: fault: Fault seen: int = 0 fired: int = 0 class FaultInjector: """Shared across the services a trial builds, so ``after``/``times`` count calls over the whole trial (a crash fault fires once, not again after the restart).""" def __init__(self, faults: list[Fault]) -> None: self.states = [FaultState(f) for f in faults] @property def fired(self) -> int: return sum(s.fired for s in self.states) def install(self, svc: Any) -> None: registry = svc.registry for st in self.states: tool = registry.get(st.fault.tool) if getattr(tool.handler, "_eval_fault", None) is st: continue inner = tool.handler async def handler(args: Any, ctx: Any, _inner: Any = inner, _st: Any = st) -> Any: _st.seen += 1 f = _st.fault if _st.seen > f.after and _st.fired < f.times: _st.fired += 1 raise _exception(f.kind) return await _inner(args, ctx) handler._eval_fault = st # type: ignore[attr-defined] registry._tools[st.fault.tool] = dataclasses.replace(tool, handler=handler)