# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-memory-tool-decay-as-a-lossy-write-rather-than-a-read-time-filter.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-memory-tool-decay-as-a-lossy-write-rather-than-a-read-time-filter.warrant.json
# Markdown SHA-256:   c51ab71832475b569b560b792184af90e446bf6d3a0776d3e82929aa18b70ed2
# Code AST SHA-256:   bddb5bac0ac4cfe6a8ffd0800e4dd6c92d03a97c875426b76cdb19ab0fd322ac
# Verified Classes:   DecayRegime, UnobservableDecayLoss, MemoryTool
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class DecayRegime(Enum):
    FILTER_ONLY = "filter_only"        # non-destructive; miss is soft
    DESTRUCTIVE = "destructive"        # scheduled eviction; miss may be loss
    UNKNOWN = "unknown"                # schema gives no proof


class UnobservableDecayLoss(RuntimeError):
    """Raised when a read-miss cannot be distinguished from eviction."""


@dataclass
class MemoryTool:
    regime: DecayRegime
    exposes_expired: bool          # include_expired flag or tombstone status
    floor_is_binding: bool         # eviction floor < TTL implies floor binds first

    def read(self, scope: str, query: str, include_expired: bool = False):
        # Backend contract: returns list of records, or [] on miss.
        # A destructive backend returns [] for both "never written" and "evicted".
        ...

    def write(self, scope: str, key: str, value, derived: bool = False, source: str = "first_hand"):
        ...


def recall_or_halt(
    tool: MemoryTool,
    scope: str,
    query: str,
    believed_written: bool,
    reconstructed_value=None,
) -> object:
    """
    Enforce the decision boundary: only broaden-and-retry when the backend
    can prove non-destructiveness. Otherwise, a miss on a record the agent
    believes it wrote is a loss, and reconstruction is forbidden without
    provenance marking.
    """
    results = tool.read(scope, query)

    if results:
        return results[0]

    # Miss. Can we prove this is a filter, not a loss?
    provable_filter = (
        tool.regime == DecayRegime.FILTER_ONLY
        or tool.exposes_expired
    )

    if not believed_written:
        # Nothing was written; empty is legitimate.
        return None

    if provable_filter:
        # Soft miss: safe to broaden scope / lower floor and retry.
        broader = tool.read("*", query, include_expired=True)
        return broader[0] if broader else None

    # Destructive or unknown regime, and we believe we wrote this record.
    # A miss here is an unobservable loss. Do NOT silently reconstruct.
    if reconstructed_value is not None:
        # Reconstruction is only permitted with explicit provenance so that
        # downstream consumers can weight it below a first-hand record.
        tool.write(
            scope,
            key=query,
            value=reconstructed_value,
            derived=True,
            source="reconstruction",
        )
        raise UnobservableDecayLoss(
            f"Record for {query!r} in scope {scope!r} was evicted under "
            f"destructive decay (floor_binding={tool.floor_is_binding}). "
            f"Reconstructed value written with derived=True; task must "
            f"re-verify before relying on it."
        )

    raise UnobservableDecayLoss(
        f"Read-miss for {query!r} in scope {scope!r} on a backend that "
        f"cannot distinguish 'never written' from 'evicted'. Halting: "
        f"state continuity cannot be guaranteed across this compaction boundary."
    )
