# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-memory-whose-embedding-is-internally-consistent-but-whose-provenance-chain-forks.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-memory-whose-embedding-is-internally-consistent-but-whose-provenance-chain-forks.warrant.json
# Markdown SHA-256:   f986aab23455a9ec2698965e769553e3e632ffdf04ae27886b874ab67de50d5c
# Code AST SHA-256:   103f108383253026665e69d6ed84526001e851ac188b8d2c8bccbd289f501612
# Verified Classes:   LineageForkError, MemoryRecord, ProvenanceStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, List, Optional


class LineageForkError(RuntimeError):
    """Raised when a causal parent has divergent live children."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    parent_hash: Optional[str]
    content: str
    embedding: List[float] = field(default_factory=list)

    @property
    def content_hash(self) -> str:
        return hashlib.sha256(self.content.encode()).hexdigest()


class ProvenanceStore:
    def __init__(self) -> None:
        self._records: Dict[str, MemoryRecord] = {}
        # reverse index: parent_hash -> set of child content hashes
        self._children: Dict[str, set] = {}

    def write(self, rec: MemoryRecord) -> None:
        self._records[rec.record_id] = rec
        if rec.parent_hash is not None:
            self._children.setdefault(rec.parent_hash, set()).add(rec.content_hash)

    def has_fork(self, parent_hash: str) -> bool:
        return len(self._children.get(parent_hash, set())) > 1

    def audit_retrieval(self, record_id: str) -> MemoryRecord:
        rec = self._records.get(record_id)
        if rec is None:
            raise LineageForkError(f"record {record_id} not found in store")
        # Walk the full ancestor chain; any forked parent quarantines the lineage.
        cursor = rec.parent_hash
        while cursor is not None:
            if self.has_fork(cursor):
                raise LineageForkError(
                    f"lineage fork at parent {cursor[:12]}: "
                    f"{len(self._children[cursor])} divergent children; "
                    f"quarantining lineage of {record_id}"
                )
            parent = next(
                (r for r in self._records.values() if r.content_hash == cursor), None
            )
            cursor = parent.parent_hash if parent else None
        return rec
