# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-and-survive-a-gc-race-against-its-own-working-memory-during-scoped-persistence-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-and-survive-a-gc-race-against-its-own-working-memory-during-scoped-persistence-compaction.warrant.json
# Markdown SHA-256:   0868b3a0ba03f914678a532a5ae583c2965c32d3973f1a14591c3534a4f05715
# Code AST SHA-256:   e3da65793e65f40974ad16c9fef734cba2db14b2cbd02edebfc0ef113b6838ae
# Verified Classes:   MemoryVerdict, ScopedRead, MemoryForkError, ScopedMemoryClient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class MemoryVerdict(Enum):
    LIVE = "live"
    EVICTED = "evicted"
    NOT_FOUND = "not_found"


@dataclass(frozen=True)
class ScopedRead:
    verdict: MemoryVerdict
    value: Optional[bytes]
    generation: int
    written_at: Optional[float]
    evicted_at: Optional[float] = None
    policy_id: Optional[str] = None


class MemoryForkError(RuntimeError):
    """Raised when an agent's recovery path would fork scoped state.

    Fires when a read returns EVICTED and the caller attempts to
    re-initialize the key from in-context state instead of rehydrating
    from a durable source. This is the exact condition that produced
    the silent ledger fork: EVICTED was collapsed into NOT_FOUND and
    the agent re-wrote a biased subset.
    """


class ScopedMemoryClient:
    def __init__(self, substrate, durable_replica):
        self._substrate = substrate
        self._durable = durable_replica
        self._last_seen_generation: dict[str, int] = {}

    def read(self, key: str) -> ScopedRead:
        raw = self._substrate.read(key)
        if raw is None:
            return ScopedRead(MemoryVerdict.NOT_FOUND, None, generation=0, written_at=None)
        if raw.get("tombstone"):
            return ScopedRead(
                MemoryVerdict.EVICTED,
                None,
                generation=raw["generation"],
                written_at=raw.get("written_at"),
                evicted_at=raw.get("evicted_at"),
                policy_id=raw.get("policy_id"),
            )
        result = ScopedRead(
            MemoryVerdict.LIVE,
            raw["value"],
            generation=raw["generation"],
            written_at=raw["written_at"],
        )
        self._last_seen_generation[key] = result.generation
        return result

    def recover(self, key: str, in_context_copy: bytes) -> bytes:
        """Recovery path. Must NOT re-initialize from context on EVICTED."""
        observed = self.read(key)

        if observed.verdict is MemoryVerdict.LIVE:
            prior_gen = self._last_seen_generation.get(key)
            if prior_gen is not None and observed.generation != prior_gen:
                # Generation advanced under us: another writer or a
                # compaction rewrote the key. Re-read, do not append.
                raise MemoryForkError(
                    f"generation drift on {key!r}: saw {prior_gen}, "
                    f"now {observed.generation}; refusing to append stale context"
                )
            return observed.value or b""

        if observed.verdict is MemoryVerdict.EVICTED:
            # Correct behavior: rehydrate from durable, never from context.
            durable = self._durable.fetch_latest(key)
            if durable is None:
                raise MemoryForkError(
                    f"{key!r} evicted by policy {observed.policy_id!r} at "
                    f"{observed.evicted_at} and durable replica is empty; "
                    f"cannot re-initialize from in-context copy without forking state"
                )
            return durable

        # NOT_FOUND with generation 0 is the only legitimate initialize path.
        if observed.generation != 0:
            raise MemoryForkError(
                f"{key!r} NOT_FOUND but generation={observed.generation}; "
                f"substrate lost a tombstone — refusing optimistic init"
            )
        self._substrate.write(key, in_context_copy)
        return in_context_copy
