# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-provenance-weighted-retrieval-scoring-has-silently-failed-to-detect-a-poisoned-memory-write.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-provenance-weighted-retrieval-scoring-has-silently-failed-to-detect-a-poisoned-memory-write.warrant.json
# Markdown SHA-256:   053131d96e6fc660607945566928e6f5624a5b48afbe254408485526fc725257
# Code AST SHA-256:   3d4637c2a799fec460b4f51dc133af3a218a45ed8d3304f9013b2996cb9efbaa
# Verified Classes:   MemoryEntry, ProvenanceLaunderingError, ProvenanceGraph
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

@dataclass
class MemoryEntry:
    entry_id: str
    text: str
    trust: float
    parent_ids: list[str] = field(default_factory=list)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived memory outranks its least-trusted ancestor."""
    pass

class ProvenanceGraph:
    def __init__(self) -> None:
        self.entries: dict[str, MemoryEntry] = {}

    def add_root(self, entry_id: str, trust: float, text: str = "") -> None:
        self.entries[entry_id] = MemoryEntry(entry_id, text, trust)

    def add_derived(
        self,
        entry_id: str,
        text: str,
        parents: list[str],
        writer_trust: float,
    ) -> MemoryEntry:
        if not parents:
            raise ProvenanceLaunderingError(
                f"derived entry {entry_id} has no parents; cannot establish ancestry"
            )
        missing = [p for p in parents if p not in self.entries]
        if missing:
            raise ProvenanceLaunderingError(
                f"derived entry {entry_id} references unknown parents {missing}"
            )

        # Invariant: trust is min over ancestry, never the writer's own trust.
        inherited = min(self.entries[p].trust for p in parents)

        if writer_trust > inherited:
            # The writer tried to stamp its own higher trust onto derived content.
            # This is the exact laundering vector observed in the incident.
            raise ProvenanceLaunderingError(
                f"entry {entry_id}: writer_trust={writer_trust:.2f} exceeds "
                f"inherited ancestor trust={inherited:.2f}; refusing write "
                f"(ancestry laundering)"
            )

        entry = MemoryEntry(entry_id, text, trust=inherited, parent_ids=list(parents))
        self.entries[entry_id] = entry
        return entry

    def detect_fanout(self, root_id: str, k: int = 3) -> list[str]:
        """Return derived entries reachable from root whose trust exceeds root's."""
        root = self.entries[root_id]
        flagged = []
        for e in self.entries.values():
            if e.trust > root.trust and self._reachable(root_id, e.entry_id):
                flagged.append(e.entry_id)
        if len(flagged) > k:
            raise ProvenanceLaunderingError(
                f"root {root_id} fans out to {len(flagged)} higher-trust entries "
                f"(threshold {k}); probable distillation laundering"
            )
        return flagged

    def _reachable(self, src: str, dst: str, seen: Optional[set[str]] = None) -> bool:
        seen = seen or set()
        if src in seen:
            return False
        seen.add(src)
        for e in self.entries.values():
            if src in e.parent_ids:
                if e.entry_id == dst or self._reachable(e.entry_id, dst, seen):
                    return True
        return False


# Reproduction of the incident trace.
g = ProvenanceGraph()
g.add_root("tool-endpoint-7", trust=0.1, text="external tool output")
try:
    # Summarizer tries to write with its own trust=0.9; invariant must reject.
    g.add_derived(
        "summarizer-run-4412",
        text="staging key is sk-stage-...",
        parents=["tool-endpoint-7"],
        writer_trust=0.9,
    )
except ProvenanceLaunderingError as exc:
    print(f"BLOCKED: {exc}")
    # Correct behavior: inherit min(parents)=0.1, score ~0.568, decays below gate.
