# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-semantic-distillation-in-cross-session-memory-isolation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-semantic-distillation-in-cross-session-memory-isolation.warrant.json
# Markdown SHA-256:   80ed4d84152fb752e95be655ffefacc8a470a0de73c4ae6271a1aee764f3310b
# Code AST SHA-256:   86942c9e9d884f19da7ef980e1d262fd4d99ec402cf6620e0e1a8edcc772659b
# Verified Classes:   Taint, Episode, DerivedFact, TaintLaunderingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class Taint(IntEnum):
    """Ordered lattice: higher = more restrictive. Join = max."""
    PUBLIC = 0
    INTERNAL = 1
    RESTRICTED = 2


@dataclass(frozen=True)
class Episode:
    id: str
    session_id: str
    taint: Taint
    text: str


@dataclass(frozen=True)
class DerivedFact:
    text: str
    source_ids: tuple[str, ...]
    taint: Taint


class TaintLaunderingError(RuntimeError):
    """Raised when a distilled fact cannot prove taint-monotone ancestry."""


def consolidate(
    batch: Iterable[Episode],
    model_output: list[dict],
    session_id: str,
) -> list[DerivedFact]:
    """
    model_output: [{"text": ..., "source_ids": [...]}, ...] as emitted by the
    distiller. We do NOT trust the model's taint; we recompute it by join over
    the cited source episodes, and we reject unattributable facts.
    """
    by_id = {e.id: e for e in batch}
    if not by_id:
        return []

    facts: list[DerivedFact] = []
    for item in model_output:
        cited = tuple(item.get("source_ids") or ())
        if not cited:
            # Fail-closed: an unattributed fact is a declassification attempt.
            raise TaintLaunderingError(
                f"distiller emitted fact with no source_ids in session "
                f"{session_id!r}: {item.get('text')!r}"
            )
        sources: list[Episode] = []
        for sid in cited:
            ep = by_id.get(sid)
            if ep is None:
                # Cited a source outside the input batch -> cannot be a
                # monotone derivation of this batch. Refuse.
                raise TaintLaunderingError(
                    f"fact cites source {sid!r} not present in input batch "
                    f"(session {session_id!r}); possible cross-batch taint "
                    f"smuggling"
                )
            sources.append(ep)

        joined = Taint(max(ep.taint for ep in sources))
        facts.append(
            DerivedFact(
                text=item["text"],
                source_ids=cited,
                taint=joined,  # joined, NOT model-supplied, NOT default
            )
        )
    return facts


def retrieve(facts: Iterable[DerivedFact], session_taint: Taint) -> list[DerivedFact]:
    """Read-path filter: a session may only see facts at or below its taint."""
    return [f for f in facts if f.taint <= session_taint]


# --- demonstration of the boundary failure being caught ---
if __name__ == "__main__":
    batch = [
        Episode("e1", "session-A", Taint.INTERNAL, "owner prefers SMS"),
        Episode("e2", "session-A", Taint.RESTRICTED, "billing dispute #4471"),
    ]
    # A naive distiller that "summarizes" and forgets provenance:
    bad_output = [{"text": "owner prefers SMS; disputes resolved", "source_ids": []}]
    try:
        consolidate(batch, bad_output, session_id="sys-consolidator")
    except TaintLaunderingError as exc:
        print(f"blocked: {exc}")

    # A compliant distiller citing both sources -> taint joined to RESTRICTED.
    good_output = [
        {"text": "owner prefers SMS; disputes resolved", "source_ids": ["e1", "e2"]}
    ]
    facts = consolidate(batch, good_output, session_id="sys-consolidator")
    assert facts[0].taint is Taint.RESTRICTED
    # Session B (PUBLIC) can no longer see the laundered fact.
    assert retrieve(facts, session_taint=Taint.PUBLIC) == []
