# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-brokered-capability-grant-whose-attestation-chain-validates-but-whose-delegation-depth-exceeds-the-trust-anchor-s-re-at.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-brokered-capability-grant-whose-attestation-chain-validates-but-whose-delegation-depth-exceeds-the-trust-anchor-s-re-at.warrant.json
# Markdown SHA-256:   febf6269fd4ed8d7a271c2907f4461575e21fc7dadd273186855bfa4be711f84
# Code AST SHA-256:   13b7451dbe838457aaa08b446d4081701d3597b17539cef023bfa39d257e7d89
# Verified Classes:   StaleRootAttestation, AttestationLink, BrokeredGrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class StaleRootAttestation(RuntimeError):
    """Raised when a brokered grant's root attestation has aged past its horizon."""
    pass


@dataclass
class AttestationLink:
    issuer: str
    issued_at: float
    horizon: float          # seconds; origin-declared, brokers may only narrow
    is_broker_countersign: bool = False


@dataclass
class BrokeredGrant:
    capability: str
    chain: List[AttestationLink] = field(default_factory=list)
    max_depth: int = 0

    def root(self) -> AttestationLink:
        if not self.chain:
            raise StaleRootAttestation("empty attestation chain")
        return self.chain[0]


def effective_freshness(grant: BrokeredGrant, now: float) -> float:
    """Minimum remaining freshness across all links. Broker links cannot widen
    upstream horizons; the root's horizon is the binding constraint."""
    remaining = []
    for link in grant.chain:
        rem = link.horizon - (now - link.issued_at)
        remaining.append(rem)
    return min(remaining)


def execute_brokered_capability(
    grant: BrokeredGrant,
    now: float,
    rpa_queue_estimate: float = 0.0,
) -> str:
    root = grant.root()

    # Rule 1: root-anchored freshness. Broker countersignatures do not reset
    # the origin clock.
    if now - root.issued_at > root.horizon:
        raise StaleRootAttestation(
            f"root attestation from {root.issuer} aged "
            f"{now - root.issued_at:.1f}s > horizon {root.horizon:.1f}s; "
            f"broker countersignatures do not renew it"
        )

    # Rule 2: latency-budgeted delegation. Worst-case transit plus RPA queue
    # must fit inside the tightest horizon in the chain.
    tightest = min(link.horizon for link in grant.chain)
    worst_case_transit = sum(
        (now - link.issued_at) for link in grant.chain
    ) + rpa_queue_estimate
    if worst_case_transit >= tightest:
        raise StaleRootAttestation(
            f"delegation latency budget {worst_case_transit:.1f}s exceeds "
            f"tightest horizon {tightest:.1f}s; chain structurally unsound"
        )

    # Rule 3: safety-margin gate. Near-expiry grants require fresh origin
    # re-attestation, not a broker countersignature.
    if effective_freshness(grant, now) < 0.1 * root.horizon:
        raise StaleRootAttestation(
            f"effective freshness {effective_freshness(grant, now):.1f}s "
            f"below safety margin; demand origin re-attestation before execute"
        )

    return f"executed {grant.capability}"


# --- demonstration of the boundary ---
t0 = 1_000_000.0
grant = BrokeredGrant(
    capability="write:ledger",
    max_depth=3,
    chain=[
        AttestationLink("alpha-attest", t0, 900.0),                 # root
        AttestationLink("beta-broker", t0 + 460, 900.0, True),
        AttestationLink("gamma-broker", t0 + 920, 900.0, True),
    ],
)

# At t0+1400: all signatures valid, newest link 480s old, but root is stale.
execute_brokered_capability(grant, now=t0 + 1400)
