# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-revocation-epoch-gap-in-federated-agent-identity-propagation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-revocation-epoch-gap-in-federated-agent-identity-propagation.warrant.json
# Markdown SHA-256:   59b233a672281bd96cacb84464b6ddf37cbef85ea963f8d5842de143d9174136
# Code AST SHA-256:   8a09611997628118107ccb18567a538c26590e3b63d2c05ac41d841c8b2e2823
# Verified Classes:   RevocationInvariantViolation, Warrant, TrustGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class RevocationInvariantViolation(RuntimeError):
    """Raised when a revoked identity is authorized to act past the tolerance window."""
    pass


@dataclass
class Warrant:
    identity: str
    epoch: int
    trust_0: float
    last_attestation_ts: float
    revoked: bool = False
    revoked_ts: float | None = None


class TrustGate:
    """
    Enforces: effective_trust = 0.0 if identity in revoked_set else decayed(cached).
    The revoked_set check is synchronous at read time; cached trust is advisory only.
    """

    def __init__(self, threshold: float, tolerance_s: float, trust_max: float = 1.0):
        self.threshold = threshold
        self.tolerance_s = tolerance_s
        # Decay rate derived from tolerance, not tuned for smoothness.
        # lambda such that trust_max -> threshold in exactly tolerance_s.
        import math
        self.lam = math.log(trust_max / threshold) / tolerance_s
        self.revoked_set: set[str] = set()
        self.warrants: dict[str, Warrant] = {}

    def register(self, w: Warrant) -> None:
        self.warrants[w.identity] = w

    def revoke(self, identity: str, epoch: int) -> None:
        w = self.warrants[identity]
        w.revoked = True
        w.revoked_ts = time.monotonic()
        # Synchronous insertion: gate reads this set, so effect is immediate.
        self.revoked_set.add(identity)

    def _decayed_trust(self, w: Warrant, now: float) -> float:
        import math
        dt = now - w.last_attestation_ts
        return w.trust_0 * math.exp(-self.lam * dt)

    def evaluate(self, identity: str, now: float | None = None) -> tuple[bool, float]:
        now = now if now is not None else time.monotonic()
        w = self.warrants[identity]

        # Hard floor at read path. Membership test is the only non-eventual-consistent step.
        if identity in self.revoked_set:
            effective = 0.0
        else:
            effective = self._decayed_trust(w, now)

        allow = effective >= self.threshold

        # Invariant check: if revoked, the post-revocation window must be bounded.
        if w.revoked and allow:
            elapsed = now - (w.revoked_ts or now)
            if elapsed > self.tolerance_s:
                raise RevocationInvariantViolation(
                    f"identity {identity} authorized {elapsed:.3f}s after revocation "
                    f"(tolerance {self.tolerance_s}s); revoked_set floor failed to bind"
                )
        return allow, effective


def attest(gate: TrustGate, attester: str, subject: str, now: float) -> None:
    """
    Positive attestation must come from a signer independent of the subject.
    Self-attestation is rejected to break the feedback loop.
    """
    if attester == subject:
        raise RevocationInvariantViolation(
            f"self-attestation rejected: {attester} cannot attest {subject}"
        )
    w = gate.warrants[subject]
    w.last_attestation_ts = now
