# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-semantic-store-write-that-passed-episodic-consistency-audit-yet-diverges-under-replay-time-re-derivation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-semantic-store-write-that-passed-episodic-consistency-audit-yet-diverges-under-replay-time-re-derivation.warrant.json
# Markdown SHA-256:   66017aa2d1bdd193a743192300de11191a559964130ba93aeee01ede256ee20f
# Code AST SHA-256:   0e5871a835230ed922142a324430947fa0b5cbc146c9123238576f9d270b5d20
# Verified Classes:   LineageViolation, SemanticEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, Sequence

class LineageViolation(RuntimeError):
    """Raised when a semantic entry is not re-derivable from its cited episodic slice."""
    pass

@dataclass(frozen=True)
class SemanticEntry:
    key: str
    value: str
    cited_episode_ids: tuple[str, ...]
    reducer_version: str

def audit_semantic_write(
    entry: SemanticEntry,
    episodic_store: dict[str, str],
    reducer: Callable[[Sequence[str], str], str],
    pinned_reducer_version: str,
    citation_closed: bool,
) -> None:
    # Gate 1: citation closure — evidence must be fully enumerated.
    if not citation_closed:
        raise LineageViolation(
            f"citation set for {entry.key!r} is not closed; "
            f"evidence outside {entry.cited_episode_ids} may have influenced value"
        )

    # Gate 2: reducer version must be pinned to the derivation-time version.
    if entry.reducer_version != pinned_reducer_version:
        raise LineageViolation(
            f"reducer version mismatch for {entry.key!r}: "
            f"entry={entry.reducer_version!r} pinned={pinned_reducer_version!r}; "
            f"replay is vacuous"
        )

    # Gate 3: replay-re-derivation over citation closure — the real invariant.
    slice_ = [episodic_store[eid] for eid in entry.cited_episode_ids]
    rederived = reducer(slice_, pinned_reducer_version)

    if rederived != entry.value:
        # Consistency may still pass here; that is precisely the poisoning signature.
        raise LineageViolation(
            f"semantic entry {entry.key!r} is not a fixed point of its citation set: "
            f"stored={entry.value!r} rederived={rederived!r} "
            f"over episodes={entry.cited_episode_ids} — quarantine, do not overwrite"
        )
