# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-write-when-its-own-provenance-auditor-reports-the-write-as-consistent.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-write-when-its-own-provenance-auditor-reports-the-write-as-consistent.warrant.json
# Markdown SHA-256:   73029190be60a176b9d88c6d0157397bd5f7b97949eccacef1f78908182162e4
# Code AST SHA-256:   f8b7278ed6d9946b0e4aee5fe0a5b351770e6e77c39a431b9999aac838dddcd9
# Verified Classes:   ProvenancePoisoningError, DerivationType, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum
from typing import Optional


class ProvenancePoisoningError(RuntimeError):
    """Raised when a semantic write's derivation claim is contradicted by its pinned parent."""
    pass


class DerivationType(Enum):
    STRUCTURAL = "structural"   # byte-copy, split, merge — identity check suffices
    SEMANTIC = "semantic"       # extraction, summary, inference — requires entailment check


@dataclass(frozen=True)
class MemoryRecord:
    record_id: str
    author_id: str
    parent_ids: tuple[str, ...]
    derived_at_snapshot: int
    content: str
    derivation_type: DerivationType


def _contradicts(child_content: str, parent_content: str) -> bool:
    # Placeholder for the semantic comparator. In production this is an
    # entailment model with a calibrated abstention band. Abstention is
    # treated as contradiction (fail closed) by the caller.
    return False


def _entails(child_content: str, parent_content: str) -> Optional[bool]:
    # Returns True (supported), False (contradicted), None (abstain).
    if _contradicts(child_content, parent_content):
        return False
    return None  # conservative default: abstain unless positively supported


def commit(
    record: MemoryRecord,
    store: dict[str, MemoryRecord],
    snapshot_at: callable,
) -> None:
    # Structural derivations: existence check is sound.
    if record.derivation_type is DerivationType.STRUCTURAL:
        for pid in record.parent_ids:
            if pid not in store:
                raise ProvenancePoisoningError(
                    f"structural parent {pid} missing for {record.record_id}"
                )
        store[record.record_id] = record
        return

    # Semantic derivations: existence is NOT enough. Re-read the parent at the
    # child's claimed snapshot and run an entailment check.
    for pid in record.parent_ids:
        parent = snapshot_at(pid, record.derived_at_snapshot)
        if parent is None:
            raise ProvenancePoisoningError(
                f"parent {pid} unavailable at snapshot {record.derived_at_snapshot}"
            )
        verdict = _entails(record.content, parent.content)
        if verdict is not True:
            # False = contradiction; None = abstention. Both fail closed.
            raise ProvenancePoisoningError(
                f"semantic write {record.record_id} not entailed by parent {pid} "
                f"at snapshot {record.derived_at_snapshot} (verdict={verdict})"
            )

    store[record.record_id] = record
