# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-shared-memory-eviction-race-when-two-agents-hold-divergent-budget-ledgers-for-the-same-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-shared-memory-eviction-race-when-two-agents-hold-divergent-budget-ledgers-for-the-same-context-window.warrant.json
# Markdown SHA-256:   02310efd38c0fd9a194f1613873073f5308cdf92bd63dbdb1970d11ad3b9fe9c
# Code AST SHA-256:   9a30a9814fd55510f5f32e41ae44199f583fd5928ce27d5ebb49fb7b3e92386a
# Verified Classes:   StaleSnapshotError, EvictionJournalViolation, SharedStore, LocalLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StaleSnapshotError(RuntimeError):
    """Raised when an agent attempts to admit a write against a store
    version that has been superseded by a peer's write. The agent MUST
    re-snapshot and re-derive; blind retry re-enters the same race."""
    pass


class EvictionJournalViolation(RuntimeError):
    """Raised when an eviction occurs that is not debited to the
    requesting agent's ledger and not recorded in the shared journal.
    This is the load-bearing invariant: unlogged evictions are the
    silent-divergence failure mode."""
    pass


@dataclass
class SharedStore:
    capacity: int
    used: int = 0
    version: int = 0
    journal: list = field(default_factory=list)

    def snapshot(self) -> tuple[int, int]:
        return (self.used, self.version)

    def admit(self, agent_id: str, size: int, snap: tuple[int, int],
              ledger: "LocalLedger") -> None:
        snap_used, snap_version = snap
        if snap_version != self.version:
            raise StaleSnapshotError(
                f"agent {agent_id} snapshot v{snap_version} stale; "
                f"store at v{self.version}. Re-snapshot required."
            )
        free = self.capacity - snap_used
        if size > free:
            raise StaleSnapshotError(
                f"agent {agent_id} requested {size} > free {free} at "
                f"v{snap_version}. Re-snapshot required."
            )
        # Simulate eviction pressure: if write would overflow, evict.
        overflow = (snap_used + size) - self.capacity
        if overflow > 0:
            victims = self._evict(overflow)
            # INVARIANT: victims must be debited to requester and journaled.
            ledger.debit_eviction(agent_id, victims, self.journal)
            if not self.journal or self.journal[-1]["agent"] != agent_id:
                raise EvictionJournalViolation(
                    f"eviction by {agent_id} not journaled; "
                    f"unlogged victim removal is forbidden."
                )
        self.used = snap_used + size - max(overflow, 0)
        self.version += 1
        ledger.debit_write(agent_id, size)

    def _evict(self, amount: int) -> list[str]:
        victims = [f"chunk_{i}" for i in range(amount)]
        self.journal.append({"agent": None, "victims": victims})
        return victims


@dataclass
class LocalLedger:
    agent_id: str
    debits: list = field(default_factory=list)

    def debit_write(self, agent_id: str, size: int) -> None:
        self.debits.append(("write", agent_id, size))

    def debit_eviction(self, agent_id: str, victims: list, journal: list) -> None:
        if not victims:
            return
        journal[-1]["agent"] = agent_id
        self.debits.append(("evict", agent_id, len(victims)))
        # The requester now pays for the victims it forced out.
        # Without this line, the planner's ledger would under-report
        # its true cost and admit the next oversized write.


def reconcile(store: SharedStore, agent_id: str, size: int,
              ledger: LocalLedger, snap: tuple[int, int]) -> None:
    try:
        store.admit(agent_id, size, snap, ledger)
    except StaleSnapshotError:
        # Correct handling: re-snapshot and re-derive, do NOT blind-retry.
        fresh = store.snapshot()
        store.admit(agent_id, size, fresh, ledger)
