# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-negotiate-trust-after-a-federated-capability-grant-silently-outlives-its-issuing-policy-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-negotiate-trust-after-a-federated-capability-grant-silently-outlives-its-issuing-policy-epoch.warrant.json
# Markdown SHA-256:   f26c6bff3dfe13bd42fd905a0ec7c726a43ab1d87d44872532235d72a5ea11a5
# Code AST SHA-256:   a165b451213dfb48b70d42947cce2d33d54daca08333b16a7614e79d2f327af7
# Verified Classes:   StaleEpochWarrantError, MissingStabilityAssertionError, Warrant, StabilityAssertion
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleEpochWarrantError(RuntimeError):
    """Raised when a warrant is presented under an epoch the issuer has superseded."""


class MissingStabilityAssertionError(RuntimeError):
    """Raised when a checkpointed warrant lacks proof it was safe to cache."""


@dataclass(frozen=True)
class Warrant:
    capability: str
    subject: str
    issuer: str
    epoch: int
    ttl_seconds: float
    minted_at: float
    delegation_depth: int


@dataclass(frozen=True)
class StabilityAssertion:
    issuer: str
    epoch: int
    immutable_for_ttl: bool
    assertion_expiry: float


def admit(
    warrant: Warrant,
    assertion: StabilityAssertion | None,
    issuer_current_epoch: int,
    issuer_policy: dict,
    now: float | None = None,
) -> bool:
    now = now if now is not None else time.time()

    if now > warrant.minted_at + warrant.ttl_seconds:
        raise StaleEpochWarrantError(
            f"warrant for {warrant.capability} expired at "
            f"{warrant.minted_at + warrant.ttl_seconds:.0f}"
        )

    if assertion is None:
        raise MissingStabilityAssertionError(
            f"warrant epoch={warrant.epoch} checkpointed without stability assertion; "
            f"cannot prove it was safe to cache"
        )

    if assertion.issuer != warrant.issuer or assertion.epoch != warrant.epoch:
        raise StaleEpochWarrantError(
            f"assertion (issuer={assertion.issuer}, epoch={assertion.epoch}) "
            f"does not match warrant (issuer={warrant.issuer}, epoch={warrant.epoch})"
        )

    if now > assertion.assertion_expiry:
        raise StaleEpochWarrantError(
            f"stability assertion for epoch={assertion.epoch} expired at "
            f"{assertion.assertion_expiry:.0f}; re-negotiate before admission"
        )

    if warrant.epoch != issuer_current_epoch:
        raise StaleEpochWarrantError(
            f"warrant epoch={warrant.epoch} != issuer current epoch={issuer_current_epoch}; "
            f"policy predicates may have changed, re-negotiate"
        )

    policy = issuer_policy.get(issuer_current_epoch)
    if policy is None:
        raise StaleEpochWarrantError(
            f"no policy published for epoch={issuer_current_epoch}"
        )

    max_depth = policy.get("max_delegation_depth", 0)
    if warrant.delegation_depth > max_depth:
        raise StaleEpochWarrantError(
            f"warrant delegation_depth={warrant.delegation_depth} exceeds "
            f"epoch={issuer_current_epoch} max={max_depth}"
        )

    return True


# Example of the observed failure: E=7 warrant admitted under E=8 policy.
if __name__ == "__main__":
    w = Warrant(
        capability="summarize_ledger",
        subject="B-sub",
        issuer="org-a-broker",
        epoch=7,
        ttl_seconds=86400,
        minted_at=time.time() - 1800,
        delegation_depth=1,
    )
    a = StabilityAssertion(
        issuer="org-a-broker",
        epoch=7,
        immutable_for_ttl=False,
        assertion_expiry=time.time() - 60,
    )
    try:
        admit(w, a, issuer_current_epoch=8, issuer_policy={8: {"max_delegation_depth": 0}})
    except StaleEpochWarrantError as exc:
        print(f"rejected (correct): {exc}")
