# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-that-auto-compaction-preserved-the-preconditions-it-silently-discarded.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-that-auto-compaction-preserved-the-preconditions-it-silently-discarded.warrant.json
# Markdown SHA-256:   d1f12a5aa9db9f01904a7d497de318129104a04fd441c271590c08070ba2e81b
# Code AST SHA-256:   1ebc851ac94140def8b2724d29331901a714131fbf3bfae67c3fc7876673563c
# Verified Classes:   PreconditionEvictedError, LedgerEntry, PreconditionLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

"""
Precondition-ledger guard for auto-compacting agents.

Enforces: no action may consume a precondition that was evicted by
compaction unless it is re-acquired (and re-validated) first.
"""

from dataclasses import dataclass, field
from typing import Any


class PreconditionEvictedError(RuntimeError):
    """Raised when an action depends on state lost to compaction."""
    pass


@dataclass
class LedgerEntry:
    name: str
    value: Any
    verbatim: bool          # True only if copied byte-exact, never summarized
    reacquirable: bool      # True only if a side-effect-free re-read exists
    reacquire_fn: Any = None


class PreconditionLedger:
    """Lives OUTSIDE the compaction boundary. Compaction must never touch it."""

    def __init__(self) -> None:
        self._entries: dict[str, LedgerEntry] = {}

    def record(self, entry: LedgerEntry) -> None:
        self._entries[entry.name] = entry

    def get(self, name: str) -> LedgerEntry | None:
        return self._entries.get(name)


def guarded_action(ledger: PreconditionLedger,
                   action: str,
                   requires: list[str],
                   perform) -> Any:
    """
    Execute `perform()` only if every required precondition is either
    (a) present verbatim in the ledger, or (b) successfully re-acquired
    and re-validated right now. Otherwise refuse -- do NOT let the model
    pattern-complete a substitute value from a summary.
    """
    resolved: dict[str, Any] = {}

    for name in requires:
        entry = ledger.get(name)

        if entry is not None and entry.verbatim:
            resolved[name] = entry.value
            continue

        # Missing or non-verbatim (i.e. summary-derived) -> must re-acquire.
        if entry is None or not entry.reacquirable or entry.reacquire_fn is None:
            raise PreconditionEvictedError(
                f"action={action!r} requires precondition {name!r}, which was "
                f"evicted by compaction and is not safely re-acquirable; "
                f"refusing to act on a reconstructed value."
            )

        fresh = entry.reacquire_fn()
        if fresh is None:
            raise PreconditionEvictedError(
                f"re-acquisition of {name!r} for action={action!r} returned "
                f"nothing; precondition may have rotated or expired."
            )
        # Promote the fresh, verbatim value back into the ledger.
        ledger.record(LedgerEntry(name=name, value=fresh,
                                  verbatim=True, reacquirable=True,
                                  reacquire_fn=entry.reacquire_fn))
        resolved[name] = fresh

    return perform(**resolved)


# --- illustrative use -------------------------------------------------------
if __name__ == "__main__":
    ledger = PreconditionLedger()

    # Turn 4: entity resolved. Cheap, idempotent re-read exists -> reacquirable.
    ledger.record(LedgerEntry(
        name="join_key",
        value="ent_7f3a",
        verbatim=True,
        reacquirable=True,
        reacquire_fn=lambda: "ent_7f3a",   # re-call resolve_entity()
    ))

    # Turn 22: compaction ran and dropped the literal. Simulate eviction by
    # recording a summary-derived (non-verbatim) entry instead.
    ledger.record(LedgerEntry(
        name="join_key",
        value="the target entity",         # paraphrase, NOT the id
        verbatim=False,
        reacquirable=True,
        reacquire_fn=lambda: "ent_7f3a",
    ))

    # Turn 31: action consumes the precondition. Guard re-acquires verbatim.
    result = guarded_action(
        ledger, action="reconcile_line_items", requires=["join_key"],
        perform=lambda join_key: f"joined on {join_key}",
    )
    print(result)  # joined on ent_7f3a

    # A precondition with no safe re-read must hard-fail, not fabricate.
    ledger.record(LedgerEntry(
        name="warrant_nonce", value=None, verbatim=False,
        reacquirable=False, reacquire_fn=None,
    ))
    guarded_action(
        ledger, action="commit_merge", requires=["warrant_nonce"],
        perform=lambda warrant_nonce: "committed",
    )  # -> raises PreconditionEvictedError
