# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-equivocating-commitment-receipts-as-a-liveness-hazard-rather-than-a-safety-violation-in-byzantine-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-equivocating-commitment-receipts-as-a-liveness-hazard-rather-than-a-safety-violation-in-byzantine-consensus.warrant.json
# Markdown SHA-256:   00a08ff3a0201ef49b8cef2a4f51c1f25f00731686250772f0f16d803b7f28b8
# Code AST SHA-256:   cbb52c110141ca28ea33b30dc2c4b4b3212f30bfad77c57af897eedc1a13fc72
# Verified Classes:   EquivocationSpanError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class EquivocationSpanError(RuntimeError):
    """Raised when an equivocation receipt pair cannot be classified
    as same-epoch (safety fault) or cross-epoch (supersession) because
    the epoch watermark chain is broken."""
    pass


def classify_receipt_pair(r_early, r_late, watermark_chain):
    """
    r_early, r_late: signed receipts for the same task_id, same signer.
    watermark_chain: dict mapping epoch -> prior_epoch_quorum_hash.
    Returns 'SAFETY_FAULT' or 'SUPERSESSION'.
    """
    if r_early.task_id != r_late.task_id:
        raise EquivocationSpanError("receipts reference different tasks")

    delta = r_late.epoch - r_early.epoch

    if delta == 0:
        # Provable double-sign within one epoch: genuine safety fault.
        return "SAFETY_FAULT"

    if delta < 0:
        raise EquivocationSpanError(
            f"epoch ordering violated: late epoch {r_late.epoch} < "
            f"early epoch {r_early.epoch}"
        )

    # Cross-epoch: must verify causal linkage before declaring supersession.
    for e in range(r_early.epoch + 1, r_late.epoch + 1):
        if e not in watermark_chain:
            raise EquivocationSpanError(
                f"watermark chain broken at epoch {e}; cannot distinguish "
                f"supersession from genuine fork"
            )
        if watermark_chain[e] != r_early.task_id:
            raise EquivocationSpanError(
                f"watermark at epoch {e} does not descend from task "
                f"{r_early.task_id}"
            )

    # Chain intact across the span: later receipt legitimately supersedes.
    return "SUPERSESSION"


def reconcile(receipts_by_signer, watermark_chain):
    supersessions = []
    for signer, (r_early, r_late) in receipts_by_signer.items():
        verdict = classify_receipt_pair(r_early, r_late, watermark_chain)
        if verdict == "SAFETY_FAULT":
            raise EquivocationSpanError(
                f"signer {signer} double-signed within epoch {r_early.epoch}; "
                f"exclusion required"
            )
        supersessions.append((signer, r_late.epoch))
    return supersessions
