# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-deadlocks-on-a-federated-delegation-edge-cycle-closure-detection-and-the-lease-fencing-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-deadlocks-on-a-federated-delegation-edge-cycle-closure-detection-and-the-lease-fencing-invariant.warrant.json
# Markdown SHA-256:   cd10f7a2a6d6b1c4f68b016dbe3a27428e5366e078e1a642d985908d5fb06150
# Code AST SHA-256:   b087804c2dfb4a99b9b04816f3845f2d95dd0c6b90177a343a5760cce2ac032d
# Verified Classes:   DelegationCycleFault, DelegationEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DelegationCycleFault(RuntimeError):
    """Raised when an inbound delegation closes a cycle or exhausts its hop budget."""
    def __init__(self, root_task_id: str, hop_count: int, signature_chain: list[str]):
        self.root_task_id = root_task_id
        self.hop_count = hop_count
        self.signature_chain = signature_chain
        super().__init__(
            f"cycle/budget fault on root={root_task_id} hop={hop_count} "
            f"chain_len={len(signature_chain)}"
        )


class DelegationEnvelope:
    def __init__(self, root_task_id: str, hop_count: int,
                 max_hops: int, signature_chain: list[str]):
        self.root_task_id = root_task_id
        self.hop_count = hop_count
        self.max_hops = max_hops
        self.signature_chain = signature_chain  # append-only, never re-signed

    def child(self, signer: str) -> "DelegationEnvelope":
        # Forward the immutable root id, increment hop, append signature.
        return DelegationEnvelope(
            root_task_id=self.root_task_id,
            hop_count=self.hop_count + 1,
            max_hops=self.max_hops,
            signature_chain=self.signature_chain + [signer],
        )


def accept_inbound(env: DelegationEnvelope,
                   emitted_edges: set[tuple[str, int]]) -> None:
    """Guard invoked by every instance before queuing an inbound delegation.

    emitted_edges: set of (root_task_id, hop_count) pairs this instance has
    already emitted in the current root task. Must be pinned state that
    survives context compaction.
    """
    if env.hop_count > env.max_hops:
        raise DelegationCycleFault(env.root_task_id, env.hop_count, env.signature_chain)
    edge = (env.root_task_id, env.hop_count)
    if edge in emitted_edges:
        # This instance already emitted an edge at this depth; inbound edge
        # at the same depth closes a cycle back through us.
        raise DelegationCycleFault(env.root_task_id, env.hop_count, env.signature_chain)
    # Append-only warrant chain must not have been re-signed (nonce drift).
    if len(set(env.signature_chain)) < len(env.signature_chain) - 1:
        raise DelegationCycleFault(env.root_task_id, env.hop_count, env.signature_chain)
