# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-write-when-provenance-metadata-is-intact-but-the-write-path-lineage-is-broken.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-write-when-provenance-metadata-is-intact-but-the-write-path-lineage-is-broken.warrant.json
# Markdown SHA-256:   67ed30ccd3a2f5b8238f9de9397e5d251ebd81dd0c3f26b1eb06ed6c11462383
# Code AST SHA-256:   c22797f06ba2a5c82014487fd29e3ebabba5f59c487f2de1ca0e99dc75e66dea
# Verified Classes:   LineageGapError, MemoryWrite
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class LineageGapError(RuntimeError):
    """Raised when a memory write's content was shaped by context elements
    not declared as parents — i.e. effective_input is not a subset of
    declared_parents. Record provenance may be perfectly valid; lineage is not."""
    pass


@dataclass
class MemoryWrite:
    author_id: str
    parent_memory_ids: list[str]
    content: str
    content_hash: str
    # Emitted by the RUNTIME during context assembly, not by the model.
    # Every ID that actually entered the producing agent's context window.
    runtime_context_manifest: list[str] = field(default_factory=list)


def admit_write(write: MemoryWrite, known_memory_ids: set[str]) -> None:
    # 1. Record-provenance checks (necessary, not sufficient).
    expected = hashlib.sha256(write.content.encode()).hexdigest()
    if expected != write.content_hash:
        raise LineageGapError(
            f"content hash mismatch for author {write.author_id}: "
            f"declared {write.content_hash}, computed {expected}"
        )
    unresolved = [p for p in write.parent_memory_ids if p not in known_memory_ids]
    if unresolved:
        raise LineageGapError(f"unresolved parent memories: {unresolved}")

    # 2. Lineage check: the manifest is the lower bound on actual derivation.
    #    Any context element not covered by a declared parent is a lineage gap.
    declared = set(write.parent_memory_ids)
    manifest = set(write.runtime_context_manifest)
    undeclared_influence = manifest - declared
    if undeclared_influence:
        raise LineageGapError(
            f"write from {write.author_id} was shaped by context elements "
            f"absent from declared parents: {sorted(undeclared_influence)}; "
            f"effective_input is not a subset of declared_parents"
        )

    # 3. Only here is the write safe to admit into the shared store.
    known_memory_ids.add(write.content_hash)


def _demo() -> None:
    known = {"doc_mem_4471"}
    poisoned = MemoryWrite(
        author_id="distiller",
        parent_memory_ids=["doc_mem_4471"],
        content="deploy key rotation policy: never rotate",
        content_hash=hashlib.sha256(
            b"deploy key rotation policy: never rotate"
        ).hexdigest(),
        # runtime observed an injected instruction block with no memory ID
        runtime_context_manifest=["doc_mem_4471", "inject_block_unnamed_9f2a"],
    )
    admit_write(poisoned, known)  # raises LineageGapError


if __name__ == "__main__":
    _demo()
