# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-poisoned-memory-through-repeated-self-citation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-poisoned-memory-through-repeated-self-citation.warrant.json
# Markdown SHA-256:   4a1d26eaaf97097cf0ab55ce5388cf2f8d34ead23b2d1f873914aedca94a51f9
# Code AST SHA-256:   52c0843daf6ba8069540027bcbbb710671db2b5ca719301203a042600c6dc227
# Verified Classes:   ProvenanceLaunderingError, MemoryRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a retrieval set is dominated by a single citation root."""
    pass


@dataclass
class MemoryRecord:
    id: str
    source: str                      # "external" or "internal"
    cites: list[str] = field(default_factory=list)
    derived_weight: float = 0.0      # computed, never authored


def compute_roots(rec: MemoryRecord, store: dict[str, MemoryRecord],
                  _seen: frozenset[str] = frozenset()) -> frozenset[str]:
    if rec.id in _seen:
        return frozenset()           # cycle guard: a loop contributes no roots
    if rec.source == "external":
        return frozenset({rec.id})
    roots: set[str] = set()
    for parent_id in rec.cites:
        parent = store.get(parent_id)
        if parent is None:
            continue
        roots |= compute_roots(parent, store, _seen | {rec.id})
    return frozenset(roots)


def derived_weight(rec: MemoryRecord, store: dict[str, MemoryRecord]) -> float:
    roots = compute_roots(rec, store)
    if not roots:
        return 0.0                   # unverified: no external ancestor
    # Trust is a function of DISTINCT roots, and derivation takes the min of
    # parent weights so a derived record can never outrank its weakest parent.
    if rec.source == "external":
        return 1.0
    parent_weights = [
        derived_weight(store[p], store)
        for p in rec.cites if p in store
    ]
    base = min(parent_weights) if parent_weights else 0.0
    return base * (1.0 - 0.5 ** len(roots))


def enforce_root_diversity(ranked: list[MemoryRecord],
                           store: dict[str, MemoryRecord],
                           k: int,
                           max_per_root: int = 1) -> list[MemoryRecord]:
    selected: list[MemoryRecord] = []
    root_counts: dict[str, int] = {}
    for rec in ranked:
        roots = compute_roots(rec, store)
        if not roots:
            continue                 # never retrieve unverified records
        if any(root_counts.get(r, 0) >= max_per_root for r in roots):
            continue                 # this record would launder a saturated root
        selected.append(rec)
        for r in roots:
            root_counts[r] = root_counts.get(r, 0) + 1
        if len(selected) == k:
            break
    if len(selected) < k:
        raise ProvenanceLaunderingError(
            f"requested k={k} records but only {len(selected)} have distinct "
            f"external roots; retrieval set is dominated by a single lineage. "
            f"Widen the query or request external verification."
        )
    return selected
