# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-in-persistent-agent-memory-when-a-poisoned-episodic-record-is-re-distilled-into-semantic-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-in-persistent-agent-memory-when-a-poisoned-episodic-record-is-re-distilled-into-semantic-memory.warrant.json
# Markdown SHA-256:   ee3ae18bd6ef06d7ac59da4816ffaf9f808bd304c1bee7290ae6626809cc2a76
# Code AST SHA-256:   45129e69b598bb8d9538fd19c5f580cf631d246c228e3d772b8f17b744f4c0fe
# Verified Classes:   ProvenanceLaunderingError, EpisodicRecord, SemanticFact
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Hashable


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a semantic write would collapse or truncate derivation provenance."""


@dataclass(frozen=True)
class EpisodicRecord:
    rid: Hashable
    untrusted: bool


@dataclass
class SemanticFact:
    fid: Hashable
    text: str
    derivation: frozenset  # leaf episodic rids, transitively closed
    tainted: bool = field(init=False)

    def __post_init__(self) -> None:
        if not self.derivation:
            raise ProvenanceLaunderingError(
                f"fact {self.fid!r} has empty derivation set; provenance lost"
            )


def distill(
    fid: Hashable,
    text: str,
    inputs: list,          # EpisodicRecord | SemanticFact
    episodic: dict,
    semantic: dict,
    max_leaves: int = 4096,
) -> SemanticFact:
    leaves = set()
    for item in inputs:
        if isinstance(item, EpisodicRecord):
            leaves.add(item.rid)
        elif isinstance(item, SemanticFact):
            # transitive closure: expand prior semantic facts to their episodic leaves
            leaves |= set(item.derivation)
        else:
            raise ProvenanceLaunderingError(f"unknown input type {type(item)!r}")

    if len(leaves) > max_leaves:
        # capping is the failure mode; refuse rather than truncate silently
        raise ProvenanceLaunderingError(
            f"fact {fid!r} derivation would exceed {max_leaves} leaves; "
            "partition the batch by trust class instead of truncating"
        )

    # taint is a monotone OR-join over leaves, never a vote
    tainted = any(episodic[r].untrusted for r in leaves if r in episodic)
    fact = SemanticFact(fid=fid, text=text, derivation=frozenset(leaves))
    fact.tainted = tainted
    semantic[fid] = fact
    return fact


def retrieve(semantic: dict, fid: Hashable) -> SemanticFact:
    fact = semantic[fid]
    if fact.tainted:
        raise ProvenanceLaunderingError(
            f"refusing to surface tainted fact {fid!r}; "
            f"reachable untrusted leaf in derivation {sorted(fact.derivation)}"
        )
    return fact
