# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-delegated-authority-at-each-hop-rather-than-trusting-the-propagated-warrant-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-delegated-authority-at-each-hop-rather-than-trusting-the-propagated-warrant-chain.warrant.json
# Markdown SHA-256:   7f35f9a1bffa925c540932d015678b62738b8a67bc7605889771461630ec8174
# Code AST SHA-256:   722cc4ab1ac002138340b04291a6791370b01542dd0ed72d56293f135a8991c2
# Verified Classes:   DelegationChainError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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

class DelegationChainError(RuntimeError):
    """Raised when a transitive delegation chain cannot be soundly re-derived."""
    pass

@dataclass
class Warrant:
    principal: str
    scope: str
    predicates: tuple[Callable[[dict], bool], ...]
    parent_hash: str | None = None

    def predicate_hash(self) -> str:
        # Hash the *identity* of the predicate set, not its truth value.
        names = "|".join(sorted(p.__name__ for p in self.predicates))
        return hashlib.sha256(f"{self.scope}::{names}".encode()).hexdigest()

def rederive_effective_authority(chain: list[Warrant], action: dict) -> bool:
    """
    Re-derive effective authority by evaluating the full ordered predicate
    conjunction at the executing hop. Refuses chains that elided an ancestor
    predicate, even if scope subsetting and signatures are intact.
    """
    if not chain:
        raise DelegationChainError("empty chain")

    for i, w in enumerate(chain):
        if i == 0:
            continue
        parent = chain[i - 1]
        # Invariant 2: child must carry forward all ancestor predicates.
        parent_preds = set(id(p) for p in parent.predicates)
        child_preds = set(id(p) for p in w.predicates)
        if not parent_preds.issubset(child_preds):
            raise DelegationChainError(
                f"hop {i} ({w.principal}) elided ancestor predicates from "
                f"{parent.principal}; chain is unverifiable and must be refused"
            )
        # Invariant 3: parent binding must match.
        if w.parent_hash != parent.predicate_hash():
            raise DelegationChainError(
                f"hop {i} ({w.principal}) parent binding mismatch; "
                f"delegation was not derived from the presented parent"
            )

    # Invariant 4: evaluate the concrete action against the full conjunction.
    for w in chain:
        for pred in w.predicates:
            if not pred(action):
                return False
    return True

def execute_delegated(chain: list[Warrant], action: dict) -> str:
    if not rederive_effective_authority(chain, action):
        raise DelegationChainError(
            f"effective authority at executing hop does not authorize {action}"
        )
    return f"executed {action['op']} on {action['resource']}"
