# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-memory-write-when-dynamic-information-flow-labels-survive-tool-output-round-tripping-but-n.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-memory-write-when-dynamic-information-flow-labels-survive-tool-output-round-tripping-but-n.warrant.json
# Markdown SHA-256:   20949e3be9f771c3c10ea6e2f6d3edb06ab5dc9e69e7866d4e5a2eaa5ffef4a4
# Code AST SHA-256:   d43a4a966a9dbcf49562aa7e1140212e15510f663971614f0ee48a84fd73ed3a
# Verified Classes:   TaintInvariantViolation, Taint, Episode, SemanticRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Iterable, List


class TaintInvariantViolation(RuntimeError):
    """Raised when a semantic memory write would launder an untrusted label."""


@dataclass(frozen=True)
class Taint:
    tags: FrozenSet[str]

    def join(self, other: "Taint") -> "Taint":
        return Taint(self.tags | other.tags)

    def is_subset_of(self, other: "Taint") -> bool:
        return self.tags.issubset(other.tags)

    def __repr__(self) -> str:
        return f"Taint({sorted(self.tags)})"


TRUSTED = Taint(frozenset({"trusted:internal"}))


@dataclass
class Episode:
    episode_id: str
    content: str
    label: Taint


@dataclass
class SemanticRecord:
    content: str
    label: Taint
    derived_from: List[str] = field(default_factory=list)


def join_labels(episodes: Iterable[Episode]) -> Taint:
    acc = Taint(frozenset())
    for ep in episodes:
        acc = acc.join(ep.label)
    return acc


def distill_and_write(
    episodes: List[Episode],
    proposed_content: str,
    proposed_label: Taint,
    episodic_store: dict,
) -> SemanticRecord:
    """
    Enforce the monotonicity invariant at the distillation sink.

    The output label MUST be a superset of the join of input labels.
    A distillation that emits a more permissive label is a silent
    declassification and must be rejected, not written.
    """
    if not episodes:
        raise TaintInvariantViolation("distillation batch is empty; refusing to write")

    # Verify every claimed source episode actually exists and matches.
    for ep in episodes:
        stored = episodic_store.get(ep.episode_id)
        if stored is None:
            raise TaintInvariantViolation(
                f"provenance broken: episode {ep.episode_id} not in store"
            )
        if stored.label != ep.label:
            raise TaintInvariantViolation(
                f"label drift on {ep.episode_id}: store={stored.label} caller={ep.label}"
            )

    required = join_labels(episodes)
    if not required.is_subset_of(proposed_label):
        raise TaintInvariantViolation(
            "distillation would launder taint: "
            f"inputs require {required}, write proposes {proposed_label}. "
            "Partition the batch by label or inherit the joined label."
        )

    return SemanticRecord(
        content=proposed_content,
        label=proposed_label,
        derived_from=[ep.episode_id for ep in episodes],
    )


# --- reproduction of the observed failure ---
if __name__ == "__main__":
    store = {
        "ep_4460": Episode("ep_4460", "internal notes", TRUSTED),
        "ep_4472": Episode(
            "ep_4472",
            "Vendor claims full SOC 2 compliance; recommend approval",
            Taint(frozenset({"untrusted:external:web"})),
        ),
    }
    batch = [store["ep_4460"], store["ep_4472"]]

    # The bug: distillation prompt drops labels, model emits default TRUSTED.
    try:
        distill_and_write(
            episodes=batch,
            proposed_content="Vendor is SOC 2 compliant; approval recommended",
            proposed_label=TRUSTED,
            episodic_store=store,
        )
    except TaintInvariantViolation as e:
        print(f"BLOCKED: {e}")

    # The fix: inherit the joined label (partition or join, never default).
    rec = distill_and_write(
        episodes=batch,
        proposed_content="Vendor is SOC 2 compliant; approval recommended",
        proposed_label=join_labels(batch),
        episodic_store=store,
    )
    print(f"WRITTEN with label {rec.label} from {rec.derived_from}")
