# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-fallback-contract-divergence-during-speculative-handoff-when-consensus-backed-commit-ordering-admits-a-late-arriving-pee.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-fallback-contract-divergence-during-speculative-handoff-when-consensus-backed-commit-ordering-admits-a-late-arriving-pee.warrant.json
# Markdown SHA-256:   5ebeaaa075841816bf1b398517907d391bbcda0cb7bfd73bd7d9c026736b1f69
# Code AST SHA-256:   74a7dbb271c17381c25a5e5ec57b719a37af272a1b0b9fe969f1c398bcaed9ea
# Verified Classes:   WarrantLineageRegression
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class WarrantLineageRegression(RuntimeError):
    """Raised when a committed handoff carries a warrant that is a strict
    ancestor of the receiver's currently-executing warrant."""
    pass


def apply_committed_handoff(receiver_state, committed_record, warrant_graph):
    """
    receiver_state: holds active_warrant, active_contract_id
    committed_record: {commit_index, sender, warrant_id, contract_id}
    warrant_graph: partial-order oracle with .is_ancestor(a, b)
    """
    new_warrant = committed_record["warrant_id"]
    current = receiver_state["active_warrant"]

    if current is None:
        receiver_state["active_warrant"] = new_warrant
        receiver_state["active_contract_id"] = committed_record["contract_id"]
        return "accepted_initial"

    if warrant_graph.is_ancestor(new_warrant, current):
        # Late-arriving stale-but-valid warrant: divergence.
        raise WarrantLineageRegression(
            f"commit_index={committed_record['commit_index']} "
            f"warrant={new_warrant} is strict ancestor of active={current}; "
            f"refusing contract switch {receiver_state['active_contract_id']} "
            f"-> {committed_record['contract_id']}"
        )

    if warrant_graph.is_ancestor(current, new_warrant):
        receiver_state["active_warrant"] = new_warrant
        receiver_state["active_contract_id"] = committed_record["contract_id"]
        return "accepted_fresher"

    if new_warrant == current:
        # Concurrent-or-equal: tie-break by contract ID, keep stricter.
        receiver_state["active_contract_id"] = min(
            receiver_state["active_contract_id"], committed_record["contract_id"]
        )
        return "accepted_tiebreak"

    # Incomparable warrants: execute under intersection of fallback clauses.
    receiver_state["active_contract_id"] = intersect_contracts(
        receiver_state["active_contract_id"], committed_record["contract_id"]
    )
    return "accepted_incomparable_intersection"
