# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-envelope-whose-nonce-is-valid-but-whose-causal-predecessor-is-missing-the-orphaned-nonce-gap-in-replay-resistant-a.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-envelope-whose-nonce-is-valid-but-whose-causal-predecessor-is-missing-the-orphaned-nonce-gap-in-replay-resistant-a.warrant.json
# Markdown SHA-256:   e2addc3087ef8350cbf6576e4b6a8e0484fa56f69bb7155423c4967eeaadbb3d
# Code AST SHA-256:   10050b02200373d97e3494f1c9af8c77d24a9476458b6658207852a4f22cfc31
# Verified Classes:   OrphanedNonceError, ReplayRejectedError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class OrphanedNonceError(RuntimeError):
    """Raised when an envelope's nonce is fresh and signature valid, but its
    declared causal_parent is absent from the receiver's committed chain.
    Must NOT be silently promoted to a chain root."""
    pass


class ReplayRejectedError(RuntimeError):
    """Raised when an envelope's nonce is already in the seen-set."""
    pass


def commit_envelope(envelope, committed_chain, seen_set, pending_buffer,
                    max_pending=1024):
    """
    Ternary decision over an inbound A2A envelope.
    envelope: {sender_id, nonce, causal_parent, payload_hash, signature}
    committed_chain: set of nonces already committed for this sender
    seen_set: set of nonces ever observed (committed or rejected-replay)
    pending_buffer: dict nonce -> envelope awaiting its parent
    """
    nonce = envelope["nonce"]
    parent = envelope["causal_parent"]

    if not verify_signature(envelope):
        raise OrphanedNonceError(
            f"signature invalid for nonce={nonce}; refusing commit"
        )

    # 1. Freshness check (anti-replay).
    if nonce in seen_set:
        raise ReplayRejectedError(
            f"nonce={nonce} already seen; replay rejected, "
            f"last_committed unchanged"
        )

    # 2. Causal-continuity check (the invariant most schemes omit).
    if parent is not None and parent not in committed_chain:
        if len(pending_buffer) >= max_pending:
            # Fail closed: do not promote orphan to root.
            raise OrphanedNonceError(
                f"nonce={nonce} orphaned on parent={parent}; "
                f"pending buffer full ({max_pending}); escalate to chain-reset"
            )
        pending_buffer[nonce] = envelope
        raise OrphanedNonceError(
            f"nonce={nonce} orphaned on parent={parent}; held pending, "
            f"requesting re-transmit of predecessor"
        )

    # 3. Joint commit: nonce AND parent both grounded.
    committed_chain.add(nonce)
    seen_set.add(nonce)
    drain_pending(pending_buffer, committed_chain, seen_set)
    return "COMMITTED"


def drain_pending(pending_buffer, committed_chain, seen_set):
    """After a commit, promote any pending envelopes whose parent now exists."""
    progressed = True
    while progressed:
        progressed = False
        for n, env in list(pending_buffer.items()):
            if env["causal_parent"] in committed_chain:
                committed_chain.add(n)
                seen_set.add(n)
                del pending_buffer[n]
                progressed = True
