# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-memory-write-after-a-tool-call-conflict-resolves-in-its-favor.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-memory-write-after-a-tool-call-conflict-resolves-in-its-favor.warrant.json
# Markdown SHA-256:   6ec17d562aac4f310a1e59bdc6acca101d7ba32ee40e2cc077ce38717aced096
# Code AST SHA-256:   b346f5995ed7650954189463eea27a8afd49aa6c337fd8e9742ae6ee5bf0dd39
# Verified Classes:   SpeculationRetractionError, SpeculativeWindow, SpeculationLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class SpeculationRetractionError(RuntimeError):
    """Raised when a losing speculator fails to close its reader-visibility window."""
    pass


@dataclass
class SpeculativeWindow:
    key: str
    staged_at: float
    reader_visible: bool
    readers_observed: list = field(default_factory=list)
    invalidated: bool = False


class SpeculationLedger:
    """Tracks speculative windows and enforces the retraction invariant on abort."""

    def __init__(self, store_read_audit_enabled: bool):
        self._audit = store_read_audit_enabled
        self._windows: dict[str, SpeculativeWindow] = {}
        self._open_epochs: dict[str, int] = {}

    def open(self, key: str, reader_visible: bool) -> SpeculativeWindow:
        if key in self._open_epochs:
            raise SpeculationRetractionError(
                f"cannot re-speculate on {key!r}: prior window not yet retracted"
            )
        w = SpeculativeWindow(key=key, staged_at=time.monotonic(),
                              reader_visible=reader_visible)
        self._windows[key] = w
        self._open_epochs[key] = 1
        return w

    def record_read(self, key: str, reader_id: str) -> None:
        w = self._windows.get(key)
        if w and w.reader_visible:
            w.readers_observed.append(reader_id)

    def abort(self, key: str, rolled_back_at: float) -> None:
        w = self._windows.get(key)
        if w is None:
            raise SpeculationRetractionError(f"abort for unknown window {key!r}")

        if not w.reader_visible:
            # Isolation path: rollback is genuinely local, no fan-out needed.
            w.invalidated = True
            self._close(key)
            return

        if not self._audit and not w.readers_observed:
            # Reader-visible but unenumerable: must broadcast conservatively.
            # Refuse to silently close — the window is unbounded.
            raise SpeculationRetractionError(
                f"abort on reader-visible key {key!r} during "
                f"[{w.staged_at:.3f},{rolled_back_at:.3f}] with no read audit; "
                f"cannot enumerate affected readers, must broadcast invalidation"
            )

        # Enumerable: emit scoped invalidation to observed readers.
        if not w.readers_observed:
            raise SpeculationRetractionError(
                f"abort on {key!r} with audit enabled but zero readers logged; "
                f"audit log likely stale, treat window as contaminated"
            )
        w.invalidated = True
        self._close(key)

    def _close(self, key: str) -> None:
        self._open_epochs.pop(key, None)
        self._windows.pop(key, None)
