# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-tombstone-before-embedding-ordering-when-a-scoped-retention-forget-call-races-the-agent-s-own-in-flight-write.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-tombstone-before-embedding-ordering-when-a-scoped-retention-forget-call-races-the-agent-s-own-in-flight-write.warrant.json
# Markdown SHA-256:   13d4ade1f74e7af97437ffeea20bc7ce75e3781990db44070ba2e2200136156d
# Code AST SHA-256:   436249fdc8e8ebb07590d809a48de064c2f78c557400235c18f2cf56021f041a
# Verified Classes:   RetentionConflict, Tombstone, VectorCommit, ScopedMemory
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class RetentionConflict(RuntimeError):
    """Raised when a vector commit would resurrect a tombstoned provenance scope."""
    pass


@dataclass
class Tombstone:
    scope_tag: str
    committed_at: float
    matched_ids: list


@dataclass
class VectorCommit:
    vec_id: str
    provenance_tag: str
    embedding_started_at: float
    derived_from: Optional[str] = None


class ScopedMemory:
    def __init__(self):
        self.tombstones: list[Tombstone] = []
        self.vectors: dict[str, VectorCommit] = {}

    def forget(self, scope_tag: str, matched_ids: list) -> Tombstone:
        ts = Tombstone(scope_tag, time.monotonic(), matched_ids)
        self.tombstones.append(ts)
        for vid in matched_ids:
            self.vectors.pop(vid, None)
        return ts

    def _matching_tombstone(self, tag: str, commit_time: float) -> Optional[Tombstone]:
        for ts in self.tombstones:
            if ts.scope_tag == tag and ts.committed_at <= commit_time:
                return ts
        return None

    def write(self, commit: VectorCommit) -> None:
        commit_time = time.monotonic()
        ts = self._matching_tombstone(commit.provenance_tag, commit_time)
        if ts is not None:
            raise RetentionConflict(
                f"write {commit.vec_id} for tag {commit.provenance_tag} "
                f"postdates tombstone committed at {ts.committed_at:.3f}; "
                f"embedding started at {commit.embedding_started_at:.3f}. "
                f"Resurrection window detected."
            )
        if commit.derived_from is not None:
            parent = self.vectors.get(commit.derived_from)
            if parent is None:
                raise RetentionConflict(
                    f"re-embed {commit.vec_id} derives from tombstoned parent "
                    f"{commit.derived_from}; provenance inheritance broken."
                )
        self.vectors[commit.vec_id] = commit


def demonstrate_window():
    mem = ScopedMemory()
    # Turn 3: embedding starts, but commit is delayed past the forget.
    commit = VectorCommit(
        vec_id="v_turn3",
        provenance_tag="session:7f2/ephemeral",
        embedding_started_at=time.monotonic(),
    )
    # Turn 4: forget fires before the write commits.
    mem.forget("session:7f2/ephemeral", matched_ids=[])
    # Turn 3's write finally commits — must be rejected, not silently stored.
    mem.write(commit)


if __name__ == "__main__":
    demonstrate_window()
