# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-warrant-whose-attenuation-chain-exceeds-its-own-verification-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-warrant-whose-attenuation-chain-exceeds-its-own-verification-horizon.warrant.json
# Markdown SHA-256:   81903b451a80dfdfbbac203e603e86c9c1b86c0891fc1d7f39ef205091937df0
# Code AST SHA-256:   1fd4782b113d53acafa3850665dc932dddb9a68c3ac93527642190feb81b1b94
# Verified Classes:   DelegationChainUnverifiable, AttenuationViolation, Warrant, VerificationBudget
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class DelegationChainUnverifiable(RuntimeError):
    """Raised when a delegated warrant's attenuation chain cannot be fully
    verified to a local trust anchor within the agent's verification budget."""


class AttenuationViolation(DelegationChainUnverifiable):
    """Raised when a hop's scope is not a subset of its parent's scope."""


@dataclass
class Warrant:
    warrant_id: str
    issuer: str
    scope: frozenset
    issued_at: float
    expires_at: float
    parent_ref: Optional[str]
    signature: bytes


@dataclass
class VerificationBudget:
    max_chain_hops: int = 6
    max_verify_ms: int = 800


def verify_chain(
    leaf: Warrant,
    fetch_parent,                 # callable(warrant_id) -> Warrant | None
    trust_anchors: set,           # issuer ids the agent trusts as roots
    key_history,                  # callable(issuer, ts) -> set[bytes] | None
    budget: VerificationBudget,
) -> list[Warrant]:
    """Reconstruct and verify the full attenuation chain from `leaf` to a
    local trust anchor. Returns the chain root-first. Raises on any violation.
    Refuses to execute on a verified prefix — a prefix does not bound the leaf."""
    start = time.monotonic()
    chain = [leaf]
    cursor = leaf

    while cursor.issuer not in trust_anchors:
        if len(chain) > budget.max_chain_hops:
            raise DelegationChainUnverifiable(
                f"chain exceeds max_chain_hops={budget.max_chain_hops} "
                f"at warrant {cursor.warrant_id}"
            )
        if (time.monotonic() - start) * 1000 > budget.max_verify_ms:
            raise DelegationChainUnverifiable(
                f"verification exceeded max_verify_ms={budget.max_verify_ms} "
                f"at warrant {cursor.warrant_id}"
            )
        if cursor.parent_ref is None:
            raise DelegationChainUnverifiable(
                f"warrant {cursor.warrant_id} has no parent_ref and issuer "
                f"{cursor.issuer!r} is not a local trust anchor"
            )
        parent = fetch_parent(cursor.parent_ref)
        if parent is None:
            # Unreachable != absent. Refuse; do not fall back to leaf scope.
            raise DelegationChainUnverifiable(
                f"parent warrant {cursor.parent_ref} unreachable; cannot "
                f"distinguish absent from down — refusing to execute"
            )
        chain.append(parent)
        cursor = parent

    # Verify signatures against issuer key-at-issuance, not current key.
    for w in chain:
        keys = key_history(w.issuer, w.issued_at)
        if keys is None:
            raise DelegationChainUnverifiable(
                f"key history unavailable for issuer {w.issuer!r} at "
                f"{w.issued_at}; refusing current-key-only fallback"
            )
        if w.signature not in keys:
            raise DelegationChainUnverifiable(
                f"signature invalid for warrant {w.warrant_id} under "
                f"issuer {w.issuer!r} key-at-issuance"
            )

    # Attenuation monotonicity across every adjacent pair, root-first.
    chain.reverse()
    for i in range(1, len(chain)):
        child, parent = chain[i], chain[i - 1]
        if not child.scope.issubset(parent.scope):
            raise AttenuationViolation(
                f"hop {i}: scope {sorted(child.scope)} not subset of parent "
                f"{sorted(parent.scope)} at warrant {child.warrant_id}"
            )

    return chain
