# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-cluster-draft-token-equivocation-from-silently-corrupting-verifiable-speculative-decoding.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-cluster-draft-token-equivocation-from-silently-corrupting-verifiable-speculative-decoding.warrant.json
# Markdown SHA-256:   57360fe0ce3c038765aac31792b47629f1effc783acae7eeebc310ed877a4325
# Code AST SHA-256:   d3281c9332bc6c923ccb3b721329249f9d794cb0af7756ae9e77c5ac301200e4
# Verified Classes:   EquivocationDetected
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class EquivocationDetected(RuntimeError):
    """Raised when a step has two commitment receipts with differing roots
    in the same commitment slot. Must halt the step; must NOT fall back
    to target-model sampling or arrival-time tiebreak."""
    pass


def resolve_draft_commitment(
    step_index: int,
    receipts: list[dict],
    commitment_order: dict[int, int] | None,
) -> dict:
    """
    receipts: list of {"slot": int, "root": str, "verifier": str, "sig": str}
    commitment_order: map slot -> total-order rank; None if sequencer unavailable.
    Returns the single accepted receipt, or raises EquivocationDetected.
    """
    if not receipts:
        raise EquivocationDetected(f"step {step_index}: no receipts to resolve")

    by_slot: dict[int, list[dict]] = {}
    for r in receipts:
        by_slot.setdefault(r["slot"], []).append(r)

    for slot, group in by_slot.items():
        roots = {r["root"] for r in group}
        if len(roots) > 1:
            raise EquivocationDetected(
                f"step {step_index}: slot {slot} has {len(roots)} distinct roots "
                f"{sorted(roots)} across verifiers {[r['verifier'] for r in group]}"
            )

    if len(by_slot) == 1:
        return next(iter(by_slot.values()))[0]

    # Multiple distinct slots: need a total order to pick the superseding one.
    if commitment_order is None:
        raise EquivocationDetected(
            f"step {step_index}: multiple slots {sorted(by_slot)} but no "
            f"commitment total order available; refusing arrival-time tiebreak"
        )

    ordered = sorted(by_slot, key=lambda s: commitment_order[s])
    return by_slot[ordered[-1]][0]
