# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-speculative-tool-call-pre-execution-when-speculative-memory-writes-can-outlive-a-rolled-back-consistency-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-speculative-tool-call-pre-execution-when-speculative-memory-writes-can-outlive-a-rolled-back-consistency-window.warrant.json
# Markdown SHA-256:   d9c800c5c1dd84d447d77c095bda9cc92faab1cbddf265e6d3400e051695d811
# Code AST SHA-256:   62bea9d0c713bc665d12b3d1956bb7ebfd33b79f39d8c90eeeaeedb3fb90f4a3
# Verified Classes:   SpeculativeWriteError, WindowStatus, SpeculativeWrite, Window, SpeculativeMemoryStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Optional


class SpeculativeWriteError(RuntimeError):
    """Raised when a speculative memory write would violate window provenance
    or be read before its consistency window is committed."""


class WindowStatus(Enum):
    OPEN = "open"
    COMMITTED = "committed"
    ROLLED_BACK = "rolled_back"


@dataclass(frozen=True)
class SpeculativeWrite:
    window_id: str
    call_id: str
    key: str
    predicted_value: object
    observed: bool = False


@dataclass
class Window:
    id: str
    status: WindowStatus = WindowStatus.OPEN
    writes: Dict[str, SpeculativeWrite] = field(default_factory=dict)


class SpeculativeMemoryStore:
    def __init__(self) -> None:
        self._windows: Dict[str, Window] = {}
        self._writes: Dict[str, SpeculativeWrite] = {}

    def open_window(self, window_id: str) -> Window:
        if window_id in self._windows:
            raise SpeculativeWriteError(
                f"window {window_id} already exists; ids must be unique"
            )
        w = Window(id=window_id)
        self._windows[window_id] = w
        return w

    def prewrite(self, window_id: str, call_id: str, key: str, value: object) -> None:
        if window_id not in self._windows:
            raise SpeculativeWriteError(
                f"prewrite for unknown window {window_id}; "
                f"speculative writes must be enrolled in an open window"
            )
        win = self._windows[window_id]
        if win.status is not WindowStatus.OPEN:
            raise SpeculativeWriteError(
                f"prewrite into window {window_id} with status {win.status.value}; "
                f"only OPEN windows accept speculative writes"
            )
        # Provenance is stamped at creation and is immutable thereafter.
        w = SpeculativeWrite(window_id=window_id, call_id=call_id, key=key,
                             predicted_value=value)
        win.writes[key] = w
        self._writes[key] = w

    def _restamp(self, key: str, new_window_id: str) -> None:
        # Simulates a batching/flush layer that tries to re-stamp provenance.
        existing = self._writes[key]
        if existing.window_id != new_window_id:
            raise SpeculativeWriteError(
                f"flush would re-stamp {key} from window {existing.window_id} "
                f"to {new_window_id}; provenance is immutable"
            )

    def commit(self, window_id: str) -> None:
        win = self._windows[window_id]
        if win.status is not WindowStatus.OPEN:
            raise SpeculativeWriteError(
                f"cannot commit window {window_id} in status {win.status.value}"
            )
        win.status = WindowStatus.COMMITTED

    def rollback(self, window_id: str) -> None:
        # Reachability operation: flips status atomically; every dependent
        # write becomes unreadable in one step, including in-flight copies.
        win = self._windows[window_id]
        win.status = WindowStatus.ROLLED_BACK

    def read(self, key: str) -> Optional[object]:
        w = self._writes.get(key)
        if w is None:
            return None
        win = self._windows[w.window_id]
        if win.status is not WindowStatus.COMMITTED:
            # Presence is not permission.
            return None
        return w.predicted_value


def demonstrate_failure() -> None:
    store = SpeculativeMemoryStore()
    store.open_window("W1")
    store.prewrite("W1", "call-3", "balance", 0.00)

    # A batching layer tries to fold the prewrite into the next window's flush.
    store.open_window("W2")
    try:
        store._restamp("balance", "W2")
    except SpeculativeWriteError:
        pass  # correctly rejected; provenance held

    # Transport timeout on call-3 rolls back W1.
    store.rollback("W1")

    # The poisoned belief must now be unreadable by every path.
    if store.read("balance") is not None:
        raise SpeculativeWriteError(
            "rolled-back speculative write remained addressable; "
            "window gating is broken"
        )


if __name__ == "__main__":
    demonstrate_failure()
