# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-warrant-depth-collapse-in-transitive-agent-attestation-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-warrant-depth-collapse-in-transitive-agent-attestation-chains.warrant.json
# Markdown SHA-256:   2c3cba5de4ed1face19aa4d3f0701da5028711da988bbb5ab5821cb860587c23
# Code AST SHA-256:   ceb3165a308525bb47af914d7139fdc918424a5664a5b90bfe1163180b370880
# Verified Classes:   WarrantMonotonicityError, Constraint, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class WarrantMonotonicityError(RuntimeError):
    """Raised when a child warrant is not a provable restriction of its parent."""


@dataclass(frozen=True)
class Constraint:
    resource: str
    ops: frozenset
    byte_cap: Optional[int]      # None means UNBOUNDED -> never a valid restriction target
    expiry_abs: float            # absolute epoch seconds, inherited from root


@dataclass
class Warrant:
    subject: str
    constraint: Constraint
    parent: Optional["Warrant"] = None
    signature: bytes = b""       # assumed valid; we are testing monotonicity, not crypto


def verify_restriction(child: Warrant, parent: Warrant) -> None:
    c, p = child.constraint, parent.constraint

    if c.resource != p.resource and not c.resource.startswith(p.resource + "/"):
        raise WarrantMonotonicityError(
            f"resource {c.resource!r} not within parent {p.resource!r}"
        )
    if not c.ops.issubset(p.ops):
        raise WarrantMonotonicityError(
            f"ops {set(c.ops)} exceed parent {set(p.ops)}"
        )
    # The observed failure: leaf byte_cap parsed to None (unbounded) from prose.
    if c.byte_cap is None and p.byte_cap is not None:
        raise WarrantMonotonicityError(
            "child byte_cap is unbounded but parent is capped; "
            "constraint was likely lossily re-serialized (prose round-trip)"
        )
    if c.byte_cap is not None and p.byte_cap is not None and c.byte_cap > p.byte_cap:
        raise WarrantMonotonicityError(
            f"child byte_cap {c.byte_cap} exceeds parent {p.byte_cap}"
        )
    if c.expiry_abs > p.expiry_abs:
        raise WarrantMonotonicityError(
            f"child expiry {c.expiry_abs} extends parent {p.expiry_abs}; "
            "expiry must be inherited absolutely, not re-derived from receipt time"
        )


def walk_chain(leaf: Warrant) -> None:
    node = leaf
    while node.parent is not None:
        verify_restriction(node, node.parent)
        node = node.parent


def verify_chain_or_root_rederive(leaf: Warrant, root_reachable: bool) -> str:
    try:
        walk_chain(leaf)
        return "transitive-ok"
    except WarrantMonotonicityError:
        if not root_reachable:
            raise WarrantMonotonicityError(
                "chain fails monotonicity and root is unreachable; fail closed"
            )
        return "root-rederive-required"
