# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-memory-write-it-cannot-later-prove-byzantine-equivocation-in-cross-org-crdt-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-memory-write-it-cannot-later-prove-byzantine-equivocation-in-cross-org-crdt-agent-memory.warrant.json
# Markdown SHA-256:   29c1f43f84e9cbfa854602e1ac957e10e3ba99301c9f6ca6a1543255ecadc001
# Code AST SHA-256:   074e5db75d74e448ab16d6f080c6eebf5796e12acec3d6aa6d2688d9370cb739
# Verified Classes:   EquivocationError, SignedUpdate, ProvenanceGatedRegister
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, List, Tuple


class EquivocationError(RuntimeError):
    """Raised when a writer is observed to have signed two mutually
    exclusive updates for the same logical slot, or when a merge would
    silently discard a losing value that must be retained for audit."""


@dataclass(frozen=True)
class SignedUpdate:
    writer_id: str
    counter: int
    slot: str
    value: str
    signature: str  # opaque; verified by an external verifier


def _verify(update: SignedUpdate, verifier) -> bool:
    return verifier(update)


class ProvenanceGatedRegister:
    """Multi-value register that refuses to collapse an equivocation.

    A retry carries a strictly greater counter; an equivocation reuses
    a counter with a different value. The former is merged; the latter
    is quarantined and raised.
    """

    def __init__(self, verifier):
        self._verifier = verifier
        self._values: Dict[str, Dict[int, str]] = {}
        self._quarantine: List[SignedUpdate] = []

    def merge(self, update: SignedUpdate) -> None:
        if not _verify(update, self._verifier):
            self._quarantine.append(update)
            raise EquivocationError(
                f"unverified update from {update.writer_id} "
                f"slot={update.slot} counter={update.counter}"
            )

        per_writer = self._values.setdefault(update.writer_id, {})
        existing = per_writer.get(update.counter)

        if existing is not None and existing != update.value:
            # Same writer, same counter, different value: equivocation.
            self._quarantine.append(update)
            raise EquivocationError(
                f"equivocation by {update.writer_id} slot={update.slot} "
                f"counter={update.counter}: {existing!r} vs {update.value!r}"
            )

        if existing is not None and existing == update.value:
            return  # idempotent retry, safe to absorb

        per_writer[update.counter] = update.value

    def read(self, slot: str) -> Tuple[str, ...]:
        """Return all concurrently retained values for a slot; never
        silently collapses to a single winner."""
        out: List[str] = []
        for writer, counters in self._values.items():
            for counter, value in counters.items():
                out.append(value)
        return tuple(out)

    def audit_trail(self) -> List[SignedUpdate]:
        return list(self._quarantine)


def reconcile(replica_a: ProvenanceGatedRegister,
              replica_b: ProvenanceGatedRegister,
              updates: List[SignedUpdate]) -> ProvenanceGatedRegister:
    """Merge two replicas; raise if any update is equivocating."""
    for u in updates:
        replica_a.merge(u)
        replica_b.merge(u)
    if replica_a.read("") != replica_b.read(""):
        raise EquivocationError(
            "post-merge divergence: replicas disagree on retained values"
        )
    return replica_a
