# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-session-scoped-taint-label-across-a-memory-store-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-session-scoped-taint-label-across-a-memory-store-compaction-boundary.warrant.json
# Markdown SHA-256:   8ee6f02bacf5c044434f53b9dbd27960ec699035a49d3f7250a5b750a4907d62
# Code AST SHA-256:   d8026d8144b2c17c3102dca2c98189b94687886c347789f55af708cd93f0f0ee
# Verified Classes:   TaintProvenanceDivergence, Record, CompactionGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintProvenanceDivergence(RuntimeError):
    """Raised when a compaction output's label no longer covers its content provenance."""
    pass


@dataclass(frozen=True)
class Record:
    record_id: str
    session_id: str
    text: str


@dataclass
class CompactionGate:
    # Refuse any merge/distill whose inputs span >1 taint label.
    # Widening the label is permitted only if the read path can redact
    # per-session; this gate assumes it cannot, so it blocks instead.
    allow_label_join: bool = False

    def merge(self, inputs: Iterable[Record]) -> Record:
        inputs = list(inputs)
        if not inputs:
            raise TaintProvenanceDivergence("empty merge set")

        labels = {r.session_id for r in inputs}
        if len(labels) > 1 and not self.allow_label_join:
            raise TaintProvenanceDivergence(
                f"cross-session merge blocked: inputs span labels {sorted(labels)}; "
                f"merging would narrow label to one session and leak the others"
            )

        merged_text = "\n".join(r.text for r in inputs)
        merged_label = inputs[0].session_id  # only safe when len(labels) == 1
        return Record(
            record_id=f"merged:{inputs[0].record_id}",
            session_id=merged_label,
            text=merged_text,
        )

    def distill(self, cluster: Iterable[Record], summary: str) -> Record:
        cluster = list(cluster)
        labels = {r.session_id for r in cluster}
        if len(labels) > 1 and not self.allow_label_join:
            raise TaintProvenanceDivergence(
                f"cross-session distillation blocked: cluster spans {sorted(labels)}; "
                f"summary would inherit medoid label and fuse foreign content"
            )
        return Record(
            record_id=f"distilled:{cluster[0].record_id}",
            session_id=cluster[0].session_id,
            text=summary,
        )


def verify_label_continuity(record: Record, source_records: Iterable[Record]) -> None:
    """Post-hoc audit: every source whose text contributed to `record` must share its label."""
    for src in source_records:
        if src.text and src.text in record.text and src.session_id != record.session_id:
            raise TaintProvenanceDivergence(
                f"record {record.record_id} labeled {record.session_id} "
                f"contains text from session {src.session_id}"
            )
