# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-speculative-execution-when-two-byzantine-replicas-return-byte-identical-results-but-divergent-witness-trac.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-speculative-execution-when-two-byzantine-replicas-return-byte-identical-results-but-divergent-witness-trac.warrant.json
# Markdown SHA-256:   fa003ea6e9f939e11a689dd4ae23d9b8597211a28ed2841c66ddb22b5fee1bdc
# Code AST SHA-256:   aaf4eb2d102c92ef82c06b4adc152d6fe2192e860016c5c4095485e0a04388fc
# Verified Classes:   EquivocationError, Trace
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Sequence


class EquivocationError(RuntimeError):
    """Raised when result-hash quorum is satisfied but trace-replay agreement is not."""


@dataclass(frozen=True)
class Trace:
    replica_id: str
    result_hash: str
    step_roots: tuple[str, ...]

    def replay(self) -> str:
        # Deterministic re-execution of the recorded step-root chain.
        h = hashlib.sha256()
        for root in self.step_roots:
            h.update(root.encode())
        return h.hexdigest()


def reconcile(
    traces: Sequence[Trace],
    quorum: int,
    durable: bool,
) -> str:
    """
    Reconcile speculative replica traces.

    Invariant: durable promotion requires trace-replay quorum, not merely
    result-hash quorum. Ephemeral acceptance may rely on result-hash quorum.
    """
    by_result: dict[str, list[Trace]] = {}
    for t in traces:
        by_result.setdefault(t.result_hash, []).append(t)

    # Find the result hash with the largest result-level quorum.
    winner_hash, winner_traces = max(by_result.items(), key=lambda kv: len(kv[1]))
    if len(winner_traces) < quorum:
        raise EquivocationError(
            f"result quorum not met: {len(winner_traces)} < {quorum}"
        )

    # Trace-replay verification: re-execute each winning trace and confirm
    # it reproduces the claimed result hash AND that step roots agree pairwise.
    replay_ok: list[Trace] = []
    for t in winner_traces:
        if t.replay() != t.result_hash:
            # Trace does not reproduce its own claimed result: forged trace.
            continue
        replay_ok.append(t)

    if durable:
        if len(replay_ok) < quorum:
            raise EquivocationError(
                f"trace-replay quorum not met: {len(replay_ok)} < {quorum}; "
                f"result {winner_hash} is unauditable and cannot be promoted"
            )
        # Pairwise step-root agreement across the replay-verified set.
        reference = replay_ok[0].step_roots
        for t in replay_ok[1:]:
            if t.step_roots != reference:
                locus = next(
                    (i for i, (a, b) in enumerate(zip(reference, t.step_roots)) if a != b),
                    min(len(reference), len(t.step_roots)),
                )
                raise EquivocationError(
                    f"equivocation at step {locus}: replicas "
                    f"{replay_ok[0].replica_id} vs {t.replica_id} diverge on "
                    f"step root while agreeing on result {winner_hash}"
                )

    return winner_hash
