# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-tombstoned-episodes-when-a-provenance-tag-is-re-issued-after-targeted-deletion.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-tombstoned-episodes-when-a-provenance-tag-is-re-issued-after-targeted-deletion.warrant.json
# Markdown SHA-256:   f008e2369d9be0849325c00ca711b54a26a367687d4e53ea8b89571d3abdf45c
# Code AST SHA-256:   b72899d6b3c0e3b1ee8e2140c5f569f5c2ac0dfea218085e3f6f445309648f5a
# Verified Classes:   TombstoneViolation, TagStatus, Tombstone, EpisodicStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class TombstoneViolation(RuntimeError):
    """Raised when a write targets a provenance tag that is tombstoned but not revived."""
    pass


class TagStatus(Enum):
    LIVE = "live"
    TOMBSTONED = "tombstoned"
    REVIVED = "revived"


@dataclass
class Tombstone:
    tag: str
    epoch: int
    reason: str
    gc_eligible: bool = False


@dataclass
class EpisodicStore:
    # Append-only tombstone ledger. Never silently GC'd; gc requires a warrant.
    tombstones: dict[str, Tombstone] = field(default_factory=dict)
    records: dict[str, list[dict]] = field(default_factory=dict)
    epoch: int = 0

    def tag_status(self, tag: str) -> TagStatus:
        ts = self.tombstones.get(tag)
        if ts is None:
            return TagStatus.LIVE
        return TagStatus.REVIVED if ts.gc_eligible else TagStatus.TOMBSTONED

    def forget(self, tag: str, reason: str) -> int:
        n = len(self.records.pop(tag, []))
        self.epoch += 1
        self.tombstones[tag] = Tombstone(tag=tag, epoch=self.epoch, reason=reason)
        return n

    def write(self, tag: str, record: dict, revive_warrant: Optional[str] = None) -> None:
        status = self.tag_status(tag)
        if status is TagStatus.TOMBSTONED:
            if revive_warrant is None:
                raise TombstoneViolation(
                    f"write to tombstoned tag {tag!r} (epoch {self.tombstones[tag].epoch}); "
                    f"allocate a fresh tag or pass an audited revive_warrant"
                )
            # Audited revival: record it, keep the original tombstone for the audit trail.
            self.epoch += 1
            self.tombstones[tag].gc_eligible = True
        self.records.setdefault(tag, []).append(record)

    def read(self, tag: str) -> list[dict]:
        if self.tag_status(tag) is TagStatus.TOMBSTONED:
            # Fail closed: a tombstoned tag is not readable even if records linger.
            raise TombstoneViolation(f"read against tombstoned tag {tag!r}")
        return list(self.records.get(tag, []))


def replay_turn(store: EpisodicStore, tag: str, output: dict) -> None:
    """Simulates a retry harness that re-derives provenance deterministically."""
    # The retry regenerates the same tag string; the store must refuse it.
    store.write(tag=tag, record=output)


if __name__ == "__main__":
    s = EpisodicStore()
    s.write("sess-7f3a:turn:41:tool:search", {"doc": "poisoned"})
    s.forget("sess-7f3a:turn:41:tool:search", reason="prompt_injection_containment")
    try:
        replay_turn(s, "sess-7f3a:turn:41:tool:search", {"doc": "clean_retry"})
    except TombstoneViolation as e:
        print(f"contained: {e}")
        # Correct path: allocate a fresh tag with a supersedes pointer.
        s.write("sess-7f3a:turn:41:tool:search:retry1",
                {"doc": "clean_retry", "supersedes": "sess-7f3a:turn:41:tool:search"})
