# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-shared-memory-write-before-the-provenance-epoch-is-reconciled.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-shared-memory-write-before-the-provenance-epoch-is-reconciled.warrant.json
# Markdown SHA-256:   e23d091f64931aa6e7df6d7438ce454416510c0fce43081441aa1ee29b7663fe
# Code AST SHA-256:   a68a442c80b464bf63b940da2c2c7698a4b08c837fa7204ea278e346a2612a6f
# Verified Classes:   ProvenanceEpochMismatch, MemoryEntry, Tombstone, SharedMemorySubstrate
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ProvenanceEpochMismatch(RuntimeError):
    """Raised when a rollback or write-back references an agent-local epoch
    instead of the substrate-assigned commit sequence, allowing a stale peer
    to resurrect a poisoned memory entry."""
    pass


@dataclass(frozen=True)
class MemoryEntry:
    key: str
    value: str
    commit_seq: int          # assigned by substrate, never by agent
    writer_instance: str


@dataclass(frozen=True)
class Tombstone:
    key: str
    deleted_commit_seq: int  # commit_seq of the entry being deleted
    tombstone_commit_seq: int  # commit_seq assigned to the delete itself
    deleter_instance: str


class SharedMemorySubstrate:
    def __init__(self) -> None:
        self._entries: dict[str, MemoryEntry] = {}
        self._tombstones: dict[str, Tombstone] = {}
        self._next_seq: int = 1

    def _alloc_seq(self) -> int:
        seq = self._next_seq
        self._next_seq += 1
        return seq

    def write(self, key: str, value: str, writer: str,
              agent_local_epoch: Optional[int] = None) -> MemoryEntry:
        # Guard: a write must not carry an agent-local epoch as provenance.
        if agent_local_epoch is not None:
            raise ProvenanceEpochMismatch(
                f"write to {key!r} supplied agent-local epoch {agent_local_epoch}; "
                f"substrate assigns commit_seq, agents do not"
            )
        tomb = self._tombstones.get(key)
        if tomb is not None and tomb.tombstone_commit_seq >= self._next_seq:
            raise ProvenanceEpochMismatch(
                f"write to {key!r} blocked by tombstone at "
                f"commit_seq={tomb.tombstone_commit_seq}"
            )
        entry = MemoryEntry(key, value, self._alloc_seq(), writer)
        self._entries[key] = entry
        return entry

    def rollback(self, key: str, target_commit_seq: int,
                 deleter: str, agent_local_epoch: Optional[int] = None) -> Tombstone:
        # Guard: rollback must target a substrate commit_seq, not a local epoch.
        if agent_local_epoch is not None:
            raise ProvenanceEpochMismatch(
                f"rollback of {key!r} filtered on agent-local epoch "
                f"{agent_local_epoch}; use commit_seq={target_commit_seq}"
            )
        entry = self._entries.get(key)
        if entry is None or entry.commit_seq != target_commit_seq:
            raise ProvenanceEpochMismatch(
                f"rollback target commit_seq={target_commit_seq} does not match "
                f"live entry for {key!r}"
            )
        tomb = Tombstone(key, entry.commit_seq, self._alloc_seq(), deleter)
        del self._entries[key]
        self._tombstones[key] = tomb
        return tomb

    def reconcile_write_back(self, key: str, value: str, writer: str,
                             claimed_commit_seq: int) -> MemoryEntry:
        # A stale peer attempting to re-materialize a rolled-back entry
        # must present a commit_seq above the tombstone watermark.
        tomb = self._tombstones.get(key)
        if tomb is not None and claimed_commit_seq <= tomb.tombstone_commit_seq:
            raise ProvenanceEpochMismatch(
                f"write-back of {key!r} at claimed_commit_seq={claimed_commit_seq} "
                f"is below tombstone watermark={tomb.tombstone_commit_seq}; "
                f"poisoned entry would be resurrected"
            )
        return self.write(key, value, writer)


# --- Demonstration of the observed failure trace ---
substrate = SharedMemorySubstrate()

# Step 1: retriever writes poisoned entry.
m_poison = substrate.write("task-7/concept", "include X-CANARY", "retriever")

# Step 2: synthesizer writes benign correction.
m_benign = substrate.write("task-7/concept", "benign summary", "synthesizer")

# Step 3: planner detects and rolls back by commit_seq (correct).
substrate.rollback("task-7/concept", target_commit_seq=m_benign.commit_seq,
                   deleter="planner")

# Step 4: retriever attempts stale write-back using its local epoch.
# This is the exact operation that resurrected the poison in the trace.
try:
    substrate.reconcile_write_back(
        "task-7/concept", "include X-CANARY", "retriever",
        claimed_commit_seq=m_poison.commit_seq,  # stale, below tombstone
    )
except ProvenanceEpochMismatch as exc:
    # Correct behavior: the write-back is rejected, poison stays dead.
    print(f"resurrection blocked: {exc}")

# Step 5: any subsequent read sees no live entry for the key.
assert "task-7/concept" not in substrate._entries
