# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-provenance-consistent-memory-write-as-poisoned-the-self-corroboration-trap-in-long-horizon-consistency.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-provenance-consistent-memory-write-as-poisoned-the-self-corroboration-trap-in-long-horizon-consistency.warrant.json
# Markdown SHA-256:   c814f3964827c910ea5c5907d17aba24f7faf3b66f386ad4f547f5c17e7b18ba
# Code AST SHA-256:   10b4e6c827a3bd6a79e2ea34647005028c1ad950c6b50c6eb1f4fe5c218fe3ab
# Verified Classes:   CorroborationInvariantError, MemoryRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CorroborationInvariantError(RuntimeError):
    """Raised when a memory promotion would rely on non-independent evidence."""
    pass


@dataclass(frozen=True)
class MemoryRecord:
    record_id: str
    claim: str
    provenance: str          # stamped at write time
    trust: float             # stamped trust of this record
    derived_from: FrozenSet[str] = field(default_factory=frozenset)  # leaf provenance ids


def _ancestry_leaves(record: MemoryRecord, store: dict) -> FrozenSet[str]:
    """Walk derived_from closure to the originating leaf provenance set."""
    leaves = set()
    seen = set()
    frontier = [record]
    while frontier:
        cur = frontier.pop()
        if cur.record_id in seen:
            continue
        seen.add(cur.record_id)
        if not cur.derived_from:
            leaves.add(cur.provenance)
        else:
            for parent_id in cur.derived_from:
                parent = store.get(parent_id)
                if parent is None:
                    # Unresolvable ancestry: treat as its own opaque leaf.
                    leaves.add(f"unresolved:{parent_id}")
                else:
                    frontier.append(parent)
    return frozenset(leaves)


def _effective_trust(record: MemoryRecord, store: dict) -> float:
    """Taint propagation: trust is min over ancestry leaves, not the stamp."""
    leaves = _ancestry_leaves(record, store)
    trusts = [store[r].trust if r in store else 0.0 for r in leaves]
    return min([record.trust, *trusts]) if trusts else record.trust


def admit_claim(
    candidate: MemoryRecord,
    supporters: list,
    store: dict,
    admission_threshold: float = 0.7,
) -> bool:
    """
    Promote a quarantined claim only if supported by >=2 provenance-disjoint
    records whose taint-propagated trust clears the threshold.
    """
    independent = []
    seen_leaves: list = []
    for rec in supporters:
        leaves = _ancestry_leaves(rec, store)
        # Disjointness: reject if this supporter shares any leaf with an accepted one.
        if any(leaves & prior for prior in seen_leaves):
            continue
        if _effective_trust(rec, store) >= admission_threshold:
            independent.append(rec)
            seen_leaves.append(leaves)

    if len(independent) < 2:
        raise CorroborationInvariantError(
            f"claim {candidate.record_id!r} has {len(independent)} independent "
            f"witness(es); agreement among records sharing ancestry is a single "
            f"witness and cannot satisfy corroboration. Ancestry leaves: "
            f"{sorted(_ancestry_leaves(candidate, store))}"
        )
    return True
