# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-signed-reputation-attestation-as-void-the-moment-a-revocation-delta-arrives-out-of-band-rather-t.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-signed-reputation-attestation-as-void-the-moment-a-revocation-delta-arrives-out-of-band-rather-t.warrant.json
# Markdown SHA-256:   51f4a0db4d269bc7add8b4cf113b64b77eff6e4d36aaea217ff2cec6b05a0bd1
# Code AST SHA-256:   eea91b3743983cd6a7ea2ef1cc17b72639ce36797a0f29a77a983c857485737c
# Verified Classes:   RetroactiveRevocationError, ChainRevocationError, Attestation, RevocationDelta, TrustView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, List, Tuple


class RetroactiveRevocationError(RuntimeError):
    """Raised when a commitment was made against an attestation that a
    later-arriving revocation delta retroactively voids."""
    pass


class ChainRevocationError(RuntimeError):
    """Raised when an attestation's delegation path contains a revoked
    intermediate, even though the subject itself was never revoked."""
    pass


@dataclass(frozen=True)
class Attestation:
    subject: str
    issuer: str
    chain: Tuple[str, ...]
    score: float
    issued_at: float
    ingested_at: float
    valid_until: float


@dataclass(frozen=True)
class RevocationDelta:
    subject: str
    issuer: str
    valid_from: float
    ingested_at: float
    chain_revoked: bool = False


@dataclass
class TrustView:
    # keyed by (subject, issuer) -> list of deltas, indexed by valid_from
    revocations: Dict[Tuple[str, str], List[RevocationDelta]] = field(default_factory=dict)
    # commitments: (subject, issuer, committed_at, action_id)
    commitments: List[Tuple[str, str, float, str]] = field(default_factory=list)

    def ingest_delta(self, d: RevocationDelta) -> None:
        key = (d.subject, d.issuer)
        self.revocations.setdefault(key, []).append(d)
        self.revocations[key].sort(key=lambda x: x.valid_from)

    def _revoked_at(self, subject: str, issuer: str, t: float) -> bool:
        for d in self.revocations.get((subject, issuer), []):
            if d.valid_from <= t:
                return True
        return False

    def admit(self, a: Attestation, now: float, l_max: float) -> None:
        # Condition 1: interval contains decision instant with staleness margin.
        if not (now + l_max <= a.valid_until):
            raise RetroactiveRevocationError(
                f"attestation for {a.subject} too close to expiry; "
                f"out-of-band delta may be in flight (l_max={l_max})"
            )
        # Condition 2: retroactive void, regardless of ingestion order.
        if self._revoked_at(a.subject, a.issuer, now):
            raise RetroactiveRevocationError(
                f"attestation for {a.subject} voided by delta with valid_from <= now"
            )
        # Condition 3: chain revocation.
        for hop in a.chain:
            if self._revoked_at(hop, a.issuer, now):
                raise ChainRevocationError(
                    f"delegation path for {a.subject} passes through revoked hop {hop}"
                )

    def commit(self, a: Attestation, now: float, l_max: float, action_id: str) -> None:
        self.admit(a, now, l_max)
        self.commitments.append((a.subject, a.issuer, now, action_id))

    def reconcile(self, now: float) -> List[Tuple[str, str, float, str]]:
        """After any delta ingestion, re-validate commitments still inside
        the l_max re-validation window. Return those needing compensation."""
        bad = []
        for subject, issuer, committed_at, action_id in self.commitments:
            if self._revoked_at(subject, issuer, now):
                bad.append((subject, issuer, committed_at, action_id))
        if bad:
            raise RetroactiveRevocationError(
                f"{len(bad)} commitment(s) executed against retroactively "
                f"revoked attestations; compensating action required: {bad}"
            )
        return bad
