# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-stale-capability-warrants-during-cross-org-federation-handoff-through-a-trust-broker.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-stale-capability-warrants-during-cross-org-federation-handoff-through-a-trust-broker.warrant.json
# Markdown SHA-256:   4ee792749f36388d7625ad031fb19151a20d440b8af3aa6552e7080bc29ebfbe
# Code AST SHA-256:   18163cbcc7a442909a6875d367d66fd25bc3c5ca181c7b760c423c8a1372f962
# Verified Classes:   WarrantDriftError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class WarrantDriftError(RuntimeError):
    """Raised when a cached capability warrant's semantics no longer match
    the remote agent's live manifest. Signature validity is irrelevant here:
    the warrant is cryptographically sound but semantically stale."""


@dataclass(frozen=True)
class Warrant:
    capability: str
    semantics_hash: str
    side_effect: str          # "idempotent" | "at-most-once" | "exactly-once"
    issued_at: float
    ttl: float


def compute_manifest_hash(manifest: dict) -> str:
    # Covers side-effect class, units, and error taxonomy -- NOT just params.
    payload = "|".join(
        f"{k}={manifest[k]}"
        for k in sorted(("capability", "side_effect", "units", "error_taxonomy"))
    )
    return hashlib.sha256(payload.encode()).hexdigest()


def resolve_retry_policy(
    warrant: Warrant,
    live_manifest: dict | None,
    feed_staleness_bound: float,
    now: float | None = None,
) -> str:
    """Return the retry policy to use for this call.

    The policy is derived from the *live manifest observed at call time*,
    never from the cached warrant's side_effect field. If the live manifest
    is unavailable, drift is unbounded and we must assume the most
    conservative policy.
    """
    now = time.time() if now is None else now

    if live_manifest is None:
        # Missing manifest is not "no drift" -- it is unbounded drift.
        return "at-most-once"

    if now - warrant.issued_at > feed_staleness_bound:
        raise WarrantDriftError(
            f"warrant for {warrant.capability!r} is older than the feed "
            f"staleness bound ({now - warrant.issued_at:.0f}s > "
            f"{feed_staleness_bound:.0f}s); re-negotiate through broker"
        )

    live_hash = compute_manifest_hash(live_manifest)
    if live_hash != warrant.semantics_hash:
        raise WarrantDriftError(
            f"semantic drift on {warrant.capability!r}: warrant says "
            f"{warrant.semantics_hash[:12]} ({warrant.side_effect}), remote "
            f"manifest says {live_hash[:12]} "
            f"({live_manifest.get('side_effect')}); re-negotiate, do not retry"
        )

    # Warrant and live manifest agree; trust the warrant's side_effect.
    return warrant.side_effect


def execute_with_retry(
    call_fn,
    warrant: Warrant,
    live_manifest: dict | None,
    feed_staleness_bound: float,
    max_attempts: int = 3,
) -> object:
    policy = resolve_retry_policy(warrant, live_manifest, feed_staleness_bound)
    attempts = 0
    last_error: Exception | None = None

    while attempts < max_attempts:
        attempts += 1
        try:
            return call_fn()
        except TimeoutError as exc:
            last_error = exc
            if policy != "idempotent":
                # At-most-once / exactly-once: do not retry on timeout.
                raise WarrantDriftError(
                    f"timeout on non-idempotent capability "
                    f"{warrant.capability!r} under policy {policy!r}; "
                    f"refusing to retry"
                ) from exc
            continue

    raise WarrantDriftError(
        f"exhausted {max_attempts} attempts on {warrant.capability!r} "
        f"under policy {policy!r}: {last_error}"
    )
