# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-capability-token-as-void-after-a-mid-chain-re-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-delegated-capability-token-as-void-after-a-mid-chain-re-delegation.warrant.json
# Markdown SHA-256:   979666bf54f32f88d3dff280b34b04ac4a213e7c0c65924b3e4465b7fe65560c
# Code AST SHA-256:   a2821d11819608bc2067dcba32d8a88a4ce465daefd9fb8570bb38fb0d33bc6b
# Verified Classes:   AttenuationChainDiscontinuity, AttenuationEntry, CapabilityToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class AttenuationChainDiscontinuity(RuntimeError):
    """Raised when a delegated capability token's proof chain does not
    account for every hop implied by the issuer's depth budget, or when
    a proof entry's parent_hash does not match the preceding token_hash."""
    pass


@dataclass
class AttenuationEntry:
    token_hash: str
    parent_hash: Optional[str]
    constraints: dict


@dataclass
class CapabilityToken:
    root_constraints: dict
    max_depth: int
    remaining_depth: int
    proof: list[AttenuationEntry] = field(default_factory=list)

    def token_hash(self) -> str:
        h = hashlib.sha256()
        h.update(repr(sorted(self.root_constraints.items())).encode())
        for e in self.proof:
            h.update(e.token_hash.encode())
        return h.hexdigest()


def verify_lineage(token: CapabilityToken) -> None:
    hops_consumed = token.max_depth - token.remaining_depth
    if hops_consumed < 0:
        raise AttenuationChainDiscontinuity(
            f"remaining_depth {token.remaining_depth} exceeds max_depth "
            f"{token.max_depth}; token is malformed"
        )
    if len(token.proof) != hops_consumed:
        raise AttenuationChainDiscontinuity(
            f"proof chain has {len(token.proof)} entries but {hops_consumed} "
            f"hops were consumed; an intermediate attenuation is missing "
            f"(likely a re-delegation from a stale pre-attenuation snapshot)"
        )
    prev_hash = None
    for i, entry in enumerate(token.proof):
        if i > 0 and entry.parent_hash != prev_hash:
            raise AttenuationChainDiscontinuity(
                f"proof entry {i} parent_hash {entry.parent_hash!r} does not "
                f"match preceding token_hash {prev_hash!r}; chain forked"
            )
        prev_hash = entry.token_hash
    composed = dict(token.root_constraints)
    for entry in token.proof:
        for k, v in entry.constraints.items():
            composed[k] = v
    for k, v in token.root_constraints.items():
        if k in composed and composed[k] != v and not _narrows(composed[k], v):
            raise AttenuationChainDiscontinuity(
                f"composed constraint {k}={composed[k]!r} is not a narrowing "
                f"of root constraint {v!r}"
            )


def _narrows(child, parent) -> bool:
    if isinstance(parent, int) and isinstance(child, int):
        return child <= parent
    if isinstance(parent, (list, tuple)) and isinstance(child, (list, tuple)):
        return set(child).issubset(set(parent))
    return child == parent


# Reproduces the observed failure: W1 caches T1 pre-attenuation, re-delegates
# from the snapshot, producing a token with remaining_depth=2 but proof length 1.
t2_prime = CapabilityToken(
    root_constraints={"tenant": "acme", "rows": 1000, "columns": ["a", "b", "c"]},
    max_depth=3,
    remaining_depth=1,
    proof=[AttenuationEntry(token_hash="h_O_W1", parent_hash=None, constraints={"rows": 1000})],
)
verify_lineage(t2_prime)  # raises AttenuationChainDiscontinuity
