# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-brokered-trust-grant-as-non-transitive-across-a-federation-hop-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-brokered-trust-grant-as-non-transitive-across-a-federation-hop-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   abe16b9ff7cad65924b6c5cf3b124921cd8014985532418ee024bf8393b3ad87
# Code AST SHA-256:   f7dc7679375352fd9347046524d1f4a4873ec03bfb8b08123a9159dcdce782f8
# Verified Classes:   DelegationBudgetViolation, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DelegationBudgetViolation(RuntimeError):
    """Raised when a spent warrant nonce is presented with a novel request id,
    or when the signed chain cannot be recomputed to a trusted root."""


@dataclass(frozen=True)
class Warrant:
    root_nonce: str
    parent_nonce: str
    request_id: str
    depth_remaining: int
    signature: str


def derive_child(parent: Warrant, request_id: str, key: str) -> Warrant:
    # Deterministic: same (parent, request_id) always yields the same child nonce,
    # so a retried handoff returns the cached child instead of a sibling.
    child_nonce = hashlib.sha256(
        f"{parent.root_nonce}:{parent.parent_nonce}:{request_id}".encode()
    ).hexdigest()
    if parent.depth_remaining <= 0:
        raise DelegationBudgetViolation(
            f"cannot derive from {parent.parent_nonce}: depth exhausted"
        )
    sig = hashlib.sha256(f"{child_nonce}:{key}".encode()).hexdigest()
    return Warrant(
        root_nonce=parent.root_nonce,
        parent_nonce=child_nonce,
        request_id=request_id,
        depth_remaining=parent.depth_remaining - 1,
        signature=sig,
    )


def re_delegate(
    parent: Warrant,
    request_id: str,
    spent_nonces: set[str],
    minted: dict[tuple[str, str], Warrant],
    key: str,
) -> Warrant:
    cache_key = (parent.parent_nonce, request_id)
    if cache_key in minted:
        # Idempotent replay: return the prior child, do not mint a sibling.
        return minted[cache_key]
    if parent.parent_nonce in spent_nonces:
        # Spent nonce + unseen request id: cannot distinguish retry-loss from forgery.
        raise DelegationBudgetViolation(
            f"nonce {parent.parent_nonce} already spent; novel request {request_id} "
            "cannot be proven to be a retry"
        )
    child = derive_child(parent, request_id, key)
    spent_nonces.add(parent.parent_nonce)
    minted[cache_key] = child
    return child
