# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-tainted-context-before-semantic-distillation-and-why-post-hoc-redaction-of-distilled-memory-is-unsound.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-tainted-context-before-semantic-distillation-and-why-post-hoc-redaction-of-distilled-memory-is-unsound.warrant.json
# Markdown SHA-256:   a7ead9ede73f1eb3e01d59023b2110e70db8103fbde7fd19a3406b9f5db53827
# Code AST SHA-256:   5130b9820eb26b849baaf9941ea55c06dd292a92a173e79b88c9b41f3373ea88
# Verified Classes:   TaintClass, TaintFusionError, Span, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TaintClass(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1


class TaintFusionError(RuntimeError):
    """Raised when a distillation step would fuse spans across taint classes."""


@dataclass(frozen=True)
class Span:
    span_id: str
    text: str
    taint: TaintClass
    provenance: tuple[str, ...] = field(default_factory=tuple)


@dataclass(frozen=True)
class MemoryRecord:
    key: str
    value: object
    taint: TaintClass
    contributing_spans: tuple[str, ...]
    confidence: float


def distill_partition(key: str, spans: Iterable[Span], confidence: float) -> MemoryRecord:
    """Distill a single taint partition into one memory record.

    Refuses if the supplied spans are not homogeneous in taint class, because a
    joint distillation across classes destroys per-source attribution and makes
    post-hoc redaction unsound.
    """
    spans = tuple(spans)
    if not spans:
        raise TaintFusionError(f"distill_partition({key!r}): empty partition")

    classes = {s.taint for s in spans}
    if len(classes) > 1:
        raise TaintFusionError(
            f"distill_partition({key!r}): refusing to fuse spans across taint "
            f"classes {sorted(c.name for c in classes)}; partition before synthesis"
        )

    taint = classes.pop()
    # Confidence may only be aggregated within a single taint class.
    if confidence > 1.0 or confidence < 0.0:
        raise TaintFusionError(
            f"distill_partition({key!r}): confidence {confidence} out of range"
        )

    return MemoryRecord(
        key=key,
        value="|".join(s.text for s in spans),
        taint=taint,
        contributing_spans=tuple(s.span_id for s in spans),
        confidence=confidence,
    )


def write_memory(record: MemoryRecord, store: dict[str, MemoryRecord]) -> None:
    """Write a record, preserving taint as a non-scrubbable attribute."""
    if record.taint is TaintClass.UNTRUSTED and record.confidence >= 0.9:
        # High-confidence untrusted records are the highest-risk case: they will
        # be trusted by downstream consumers unless the taint bit is honored.
        # We still write them, but only into the quarantined tier.
        store[f"quarantine::{record.key}"] = record
        return
    store[record.key] = record
