# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-warrant-whose-trust-score-has-silently-decayed-below-the-issuing-registry-s-own-revocation-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-warrant-whose-trust-score-has-silently-decayed-below-the-issuing-registry-s-own-revocation-horizon.warrant.json
# Markdown SHA-256:   23d084d3f15ed1c15b2e19a76817c2b5e7c83ba4d3a4d79f8b5be30399f0f872
# Code AST SHA-256:   6724e42ed76b12c7699d9a20a4f96ffb1f8c2d22e92958298fbd197694e5c346
# Verified Classes:   StaleWarrantError, Warrant, CalleeView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleWarrantError(RuntimeError):
    """Raised when a capability warrant's trust score cannot be proven fresh at decision time."""


@dataclass
class Warrant:
    subject: str
    capability: str
    stamped_score: float
    issued_at: float
    ttl: float
    issuer_horizon: float
    issuer_propagation_bound: float
    issuer_sequence: int


@dataclass
class CalleeView:
    local_threshold: float
    horizon_margin_delta: float
    processed_sequence: int
    now: float


def admit_caller(
    warrant: Warrant,
    view: CalleeView,
    synchronous_rescore: Optional[float] = None,
) -> bool:
    # Effective admission TTL is the tighter of issuer TTL and propagation bound.
    effective_ttl = min(warrant.ttl, warrant.issuer_propagation_bound)

    # Freshness proof: callee must have processed the issuer's current revocation sequence.
    if view.processed_sequence < warrant.issuer_sequence:
        raise StaleWarrantError(
            f"revocation stream stale: processed seq {view.processed_sequence} "
            f"< issuer seq {warrant.issuer_sequence} for {warrant.subject}"
        )

    age = view.now - warrant.issued_at
    if age >= effective_ttl:
        raise StaleWarrantError(
            f"warrant age {age:.1f}s exceeds effective_ttl {effective_ttl:.1f}s "
            f"for {warrant.subject}"
        )

    # Thin horizon margin requires a synchronous re-score bound into the transaction.
    horizon_margin = warrant.stamped_score - warrant.issuer_horizon
    if horizon_margin < view.horizon_margin_delta:
        if synchronous_rescore is None:
            raise StaleWarrantError(
                f"horizon margin {horizon_margin:.3f} below delta "
                f"{view.horizon_margin_delta:.3f}; synchronous re-score required "
                f"for {warrant.subject}"
            )
        if synchronous_rescore <= warrant.issuer_horizon:
            return False
        if synchronous_rescore <= view.local_threshold:
            return False
        return True

    return warrant.stamped_score > view.local_threshold
