# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-equivocation-evidence-against-a-peer-whose-reputation-weight-was-earned-under-a-different-quorum-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-equivocation-evidence-against-a-peer-whose-reputation-weight-was-earned-under-a-different-quorum-epoch.warrant.json
# Markdown SHA-256:   78073b42b4f868ca1b1d0c45d5d90e7342dca74f0633b9d55238a30b3de98cee
# Code AST SHA-256:   d74580d5cdeebd3a74d46a6b2798f04d670489fdcc8896f253aa7b2288f94139
# Verified Classes:   RetroactiveQuorumInvalidation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class RetroactiveQuorumInvalidation(RuntimeError):
    """Raised when slashing would mutate a weight snapshot referenced by a finalized decision."""
    pass

def reconcile_equivocation(proof, local_log, live_weights, snapshots):
    """
    proof:        EquivocationProof(view, seq, peer_id, principal_id, sig_pair)
    local_log:    finalized decisions keyed by seq -> {value, weight_snapshot_hash}
    live_weights: mutable current-epoch weight table
    snapshots:    seq -> immutable WeightSnapshot
    """
    last_finalized = max(local_log.keys()) if local_log else -1

    # Identity binding must resolve to a single reputation principal.
    if proof.principal_id is None:
        return {"action": "freeze", "peer": proof.peer_id,
                "reason": "unresolved_principal"}

    if proof.seq > last_finalized:
        # Forward-only slash: safe to mutate live weights.
        live_weights[proof.principal_id] = 0.0
        return {"action": "slash", "peer": proof.peer_id,
                "scope": "live_only", "epoch_floor": proof.view}

    # Evidence at or before a finalized seq: do NOT recompute quorum.
    snap = snapshots.get(proof.seq)
    if snap is None:
        raise RetroactiveQuorumInvalidation(
            f"equivocation proof at seq={proof.seq} references finalized "
            f"decision with no retained snapshot; cannot reconcile without "
            f"rewriting history for peer {proof.peer_id}"
        )

    # Verify the snapshot still matches what justified the decision.
    recorded = local_log[proof.seq]["weight_snapshot_hash"]
    if snap.hash != recorded:
        raise RetroactiveQuorumInvalidation(
            f"snapshot hash mismatch at seq={proof.seq}: recorded "
            f"{recorded[:12]} != retained {snap.hash[:12]}; replay would fork"
        )

    # Halt finalization and request full signed history; never slash retroactively.
    return {"action": "halt_and_reconcile", "peer": proof.peer_id,
            "seq_range": (proof.seq, last_finalized),
            "freeze_principal": proof.principal_id}
