# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-subagent-s-context-budget-without-inheriting-its-invalidation-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-subagent-s-context-budget-without-inheriting-its-invalidation-epoch.warrant.json
# Markdown SHA-256:   5b8cda08e99c798368ea062f5f70a326502f048408a1f302b50628d26936c17d
# Code AST SHA-256:   f65bb514019e770c62f78878d976681463ad218a0b9a2436cb9d9a24a4d74a5b
# Verified Classes:   ContextInvalidationBudgetConflict, Entry, SharedScratchpad, ChildContext
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict


class ContextInvalidationBudgetConflict(RuntimeError):
    """Raised when a child cannot afford to re-fetch an invalidated entry
    and would otherwise proceed on stale snapshot data."""
    pass


@dataclass
class Entry:
    entry_id: str
    text: str
    epoch: int
    writer_id: str


class SharedScratchpad:
    def __init__(self) -> None:
        self._entries: Dict[str, Entry] = {}
        self._epoch: int = 0

    def write(self, entry_id: str, text: str, writer_id: str) -> int:
        self._epoch += 1
        self._entries[entry_id] = Entry(entry_id, text, self._epoch, writer_id)
        return self._epoch

    def current_epoch(self, entry_id: str) -> int:
        return self._entries[entry_id].epoch

    def read(self, entry_id: str) -> Entry:
        return self._entries[entry_id]


class ChildContext:
    def __init__(self, pad: SharedScratchpad, snapshot: Dict[str, Entry],
                 snapshot_epoch: int, budget_tokens: int,
                 refetch_cost: int = 200) -> None:
        self.pad = pad
        self.snapshot = snapshot
        self.snapshot_epoch = snapshot_epoch
        self.budget_tokens = budget_tokens
        self.refetch_cost = refetch_cost

    def resolve(self, entry_id: str) -> Entry:
        snap = self.snapshot[entry_id]
        live_epoch = self.pad.current_epoch(entry_id)
        if live_epoch <= self.snapshot_epoch:
            return snap
        # Entry was mutated after our fork: must re-fetch live.
        if self.budget_tokens < self.refetch_cost:
            raise ContextInvalidationBudgetConflict(
                f"entry {entry_id!r} invalidated at epoch {live_epoch} "
                f"(snapshot {self.snapshot_epoch}); refetch needs "
                f"{self.refetch_cost} tokens, only {self.budget_tokens} remain"
            )
        self.budget_tokens -= self.refetch_cost
        return self.pad.read(entry_id)


def run_child(pad: SharedScratchpad, child: ChildContext) -> str:
    # Child believes finding_summary is settled from its snapshot.
    entry = child.resolve("finding_summary")
    return f"recommendation based on: {entry.text!r} (epoch {entry.epoch})"


if __name__ == "__main__":
    pad = SharedScratchpad()
    pad.write("finding_summary", "clause unenforceable", writer_id="parent")
    fork_epoch = pad.current_epoch("finding_summary")
    snapshot = {"finding_summary": pad.read("finding_summary")}

    # Parent revises after the child's snapshot was taken.
    pad.write("finding_summary", "clause enforceable under amendment 4",
              writer_id="parent")

    # Child has almost no budget left: cannot afford the re-fetch.
    starved = ChildContext(pad, snapshot, fork_epoch, budget_tokens=50)
    try:
        run_child(pad, starved)
    except ContextInvalidationBudgetConflict as exc:
        print(f"ABORT (correct): {exc}")

    # Child with validation overhead reserved proceeds honestly.
    funded = ChildContext(pad, snapshot, fork_epoch, budget_tokens=1000)
    print(run_child(pad, funded))
