# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-shared-state-mutation-before-peer-agents-have-acknowledged-the-dependency-graph.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-shared-state-mutation-before-peer-agents-have-acknowledged-the-dependency-graph.warrant.json
# Markdown SHA-256:   b9e0b01be11319cc1f4c22a71f0263d9c26a0fe2d010b1903aa2f498d06e6689
# Code AST SHA-256:   2959abc0f00c8aef1ee5358139005deeaaaf094b00165bbf845c09ca7bfa677d
# Verified Classes:   RollbackEchoError, Retraction, RetractionLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Any


class RollbackEchoError(RuntimeError):
    """Raised when a write re-asserts a value that was retracted by a rollback."""
    pass


@dataclass
class Retraction:
    key: str
    retracted_value: Any
    store_version: int
    timestamp: float


@dataclass
class RetractionLedger:
    records: list[Retraction] = field(default_factory=list)
    horizon_seconds: float = 30.0

    def record(self, key: str, value: Any, version: int) -> None:
        self.records.append(Retraction(key, value, version, time.time()))

    def is_echo(self, key: str, value: Any) -> bool:
        now = time.time()
        for r in self.records:
            if r.key == key and r.retracted_value == value and (now - r.timestamp) < self.horizon_seconds:
                return True
        return False


def reconcile_write(
    ledger: RetractionLedger,
    key: str,
    value: Any,
    justification_independent_of_retraction: bool,
) -> None:
    """Apply a reconciled write, rejecting rollback echoes."""
    if ledger.is_echo(key, value) and not justification_independent_of_retraction:
        raise RollbackEchoError(
            f"Write {key}={value!r} re-asserts a retracted value without "
            f"independent justification; likely stale-context echo from a peer "
            f"that read during the speculative window."
        )
    # ... apply write to store ...


def handle_conflict(
    ledger: RetractionLedger,
    key: str,
    speculative_value: Any,
    store_version: int,
    peer_read_sets: dict[str, set[str]],
) -> set[str]:
    """Roll back a speculative write and return peers whose context is now poisoned."""
    ledger.record(key, speculative_value, store_version)
    # Any peer that read this key during the window must be quarantined.
    return {peer for peer, reads in peer_read_sets.items() if key in reads}
