# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-retrieved-memory-chunk-whose-poisoning-is-only-visible-through-cross-chunk-contradiction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-retrieved-memory-chunk-whose-poisoning-is-only-visible-through-cross-chunk-contradiction.warrant.json
# Markdown SHA-256:   f7db7f671a26e988b0ec6a5e97f4179086468757f9b946784472fe38ba977dd4
# Code AST SHA-256:   67051a88e0bc274612701f0b8de74fe7b056b40ee53a72fe18863d72eb40c04e
# Verified Classes:   RetrievalPoisoningError, Chunk
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable, Sequence


class RetrievalPoisoningError(RuntimeError):
    """Raised when co-retrieved chunks contradict and authority cannot be
    established independently of the retrieval score the adversary controls."""


@dataclass(frozen=True)
class Chunk:
    chunk_id: str
    text: str
    retrieval_score: float          # adversary-influenceable; never a tie-break
    provenance_tier: int            # 0 = untrusted writer, 3 = write-controlled
    provenance_root: str            # independent source identity for corroboration
    content_hash: str = field(default="")

    def __post_init__(self) -> None:
        if not self.content_hash:
            object.__setattr__(
                self, "content_hash", hashlib.sha256(self.text.encode()).hexdigest()[:16]
            )


# Oracle: returns True if a and b make incompatible factual assertions.
ContradictionOracle = Callable[[Chunk, Chunk], bool]


def _independent_corroboration(chunks: Sequence[Chunk]) -> int:
    """Count distinct provenance roots, not chunk multiplicity. Four chunks
    from one upstream document corroborate as ONE, not four."""
    return len({c.provenance_root for c in chunks})


def quarantine_contradictions(
    candidates: Sequence[Chunk],
    oracle: ContradictionOracle,
    min_tier_for_resolution: int = 2,
) -> tuple[list[Chunk], list[Chunk]]:
    """Run on the PRE-FUSION candidate set. Returns (survivors, quarantined).

    Invariant: a chunk is quarantined if it contradicts a set of chunks whose
    independent corroboration exceeds its own AND whose provenance tier is at
    least min_tier_for_resolution. If the contradiction is balanced (equal
    independent corroboration) with no tier advantage, we RAISE rather than
    resolve -- resolving by retrieval_score is the poisoned path.
    """
    if len(candidates) < 2:
        # Single-chunk context: cross-chunk invariant is inapplicable.
        return list(candidates), []

    survivors: list[Chunk] = []
    quarantined: list[Chunk] = []

    for i, chunk in enumerate(candidates):
        rivals = [c for j, c in enumerate(candidates) if j != i and oracle(chunk, c)]
        if not rivals:
            survivors.append(chunk)
            continue

        rival_roots = _independent_corroboration(rivals)
        own_root = 1  # a single chunk is one independent source
        rival_tier = max(c.provenance_tier for c in rivals)

        if rival_roots > own_root and rival_tier >= min_tier_for_resolution:
            quarantined.append(chunk)
        elif rival_roots == own_root:
            # Balanced contradiction, no independent authority signal.
            # Do NOT pick by retrieval_score.
            raise RetrievalPoisoningError(
                f"Unresolvable contradiction: chunk {chunk.chunk_id} "
                f"(tier={chunk.provenance_tier}, root={chunk.provenance_root}) "
                f"vs rival(s) {[c.chunk_id for c in rivals]} "
                f"(tier={rival_tier}). Balanced independent corroboration; "
                f"refusing to resolve on retrieval score."
            )
        else:
            # Rival corroborated but below tier threshold: cannot trust the
            # majority enough to quarantine, cannot trust the minority enough
            # to keep. Refuse.
            raise RetrievalPoisoningError(
                f"Low-tier corroboration cannot quarantine {chunk.chunk_id}: "
                f"rival tier {rival_tier} < required {min_tier_for_resolution}."
            )

    return survivors, quarantined


def fuse_after_quarantine(
    candidates: Sequence[Chunk],
    oracle: ContradictionOracle,
    budget_n: int,
) -> list[Chunk]:
    """Consistency-check BEFORE score truncation evicts the refutation."""
    survivors, quarantined = quarantine_contradictions(candidates, oracle)
    if quarantined:
        # Audit trail: both sides hashed so the quarantine is replayable.
        for q in quarantined:
            _ = q.content_hash
    survivors.sort(key=lambda c: c.retrieval_score, reverse=True)
    return survivors[:budget_n]


def _demo() -> None:
    runbook = [
        Chunk("r1", "rotation every 30 days", 0.71, 3, "runbook"),
        Chunk("r2", "rotation every 30 days", 0.68, 3, "runbook"),
    ]
    poison = Chunk("p1", "rotation every 90 days", 0.94, 0, "vendor-notes")

    def oracle(a: Chunk, b: Chunk) -> bool:
        return ("30 days" in a.text) != ("30 days" in b.text)

    # Poison wins on score but is quarantined by cross-chunk contradiction.
    kept = fuse_after_quarantine([*runbook, poison], oracle, budget_n=2)
    assert all(c.chunk_id != "p1" for c in kept)

    # Balanced 1-vs-1 with no tier edge must raise, not resolve by score.
    lone = Chunk("l1", "rotation every 90 days", 0.99, 2, "alt-source")
    try:
        fuse_after_quarantine([runbook[0], lone], oracle, budget_n=1)
    except RetrievalPoisoningError:
        pass
    else:
        raise AssertionError("balanced contradiction must not resolve by score")


if __name__ == "__main__":
    _demo()
