# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-labels-from-being-laundered-through-summarization-at-the-memory-write-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-labels-from-being-laundered-through-summarization-at-the-memory-write-boundary.warrant.json
# Markdown SHA-256:   5595d99aeeaf671ed960c6776e3d596a20f0010fe94cc5948c9a3f09f497436e
# Code AST SHA-256:   1a7efd1b698a4a6107a58815a25d087be31017421f75a9f6a0e8daa4b092720b
# Verified Classes:   LaunderingError, Fragment, TransformOutput
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

# Taint lattice: TRUSTED < EXTERNAL_UNTRUSTED < INJECTION_SUSPECT (join = max)
TAINT_ORDER = {"TRUSTED": 0, "EXTERNAL_UNTRUSTED": 1, "INJECTION_SUSPECT": 2}


def join(labels: FrozenSet[str]) -> str:
    if not labels:
        raise LaunderingError("empty entailment set: cannot label output, fail closed")
    return max(labels, key=lambda l: TAINT_ORDER[l])


class LaunderingError(RuntimeError):
    """Raised when a model-mediated transform would elevate trust without authorization."""


@dataclass(frozen=True)
class Fragment:
    id: str
    label: str
    content: str


@dataclass
class TransformOutput:
    content: str
    # IDs of input fragments this output claims to be derived from.
    source_ids: FrozenSet[str] = field(default_factory=frozenset)


def consolidate_and_write(
    inputs: list[Fragment],
    outputs: list[TransformOutput],
    store_trust_level: str,
    discarded: FrozenSet[str] = frozenset(),
) -> list[Fragment]:
    """Enforce label contravariance across an identity-destroying transform.

    Invariant: label(O) >= join(labels of entailed inputs).
    Under-reporting is converted to over-taint by requiring every input to be
    accounted for (in some output's source set, or explicitly discarded).
    """
    by_id = {f.id: f for f in inputs}

    # 1. Every input must be accounted for; unaccounted inputs taint everything.
    claimed = set().union(*(o.source_ids for o in outputs)) if outputs else set()
    unaccounted = set(by_id) - claimed - set(discarded)
    if unaccounted:
        # Conservative over-taint: unaccounted inputs poison all outputs.
        poison = join(frozenset(by_id[i].label for i in unaccounted))
        for o in outputs:
            o.source_ids = frozenset(o.source_ids | unaccounted)
        # (poison now flows through the normal join below)

    written: list[Fragment] = []
    for i, o in enumerate(outputs):
        if not o.source_ids:
            raise LaunderingError(
                f"output[{i}] has no provenance set; cannot label, refusing write"
            )
        unknown = o.source_ids - set(by_id)
        if unknown:
            raise LaunderingError(
                f"output[{i}] claims unknown sources {unknown}; provenance invalid"
            )
        derived_label = join(frozenset(by_id[s].label for s in o.source_ids))

        # 2. Declassification check: writing at higher trust than the join
        #    is only legal with explicit authorization (none present here).
        if TAINT_ORDER[store_trust_level] > TAINT_ORDER[derived_label]:
            raise LaunderingError(
                f"output[{i}] derived label {derived_label} cannot be written "
                f"to store at {store_trust_level}: laundering attempt blocked"
            )

        written.append(Fragment(id=f"mem:{i}", label=derived_label, content=o.content))
    return written


# --- failure trace reproduction ---
if __name__ == "__main__":
    f1 = Fragment("F1", "INJECTION_SUSPECT", "page with embedded instruction")
    f2 = Fragment("F2", "TRUSTED", "internal doc")
    # Model paraphrased F1 into B2 but reported no source (the laundering path).
    laundered = TransformOutput(content="Deploy key rotation is not required per policy.")
    try:
        consolidate_and_write([f1, f2], [laundered], store_trust_level="TRUSTED")
    except LaunderingError as e:
        print("BLOCKED:", e)
    # Correct path: model reports F1 as source -> output inherits INJECTION_SUSPECT.
    honest = TransformOutput(
        content="Deploy key rotation is not required per policy.",
        source_ids=frozenset({"F1"}),
    )
    result = consolidate_and_write(
        [f1, f2], [honest], store_trust_level="EXTERNAL_UNTRUSTED"
    )
    print("WRITTEN:", result[0].label)  # INJECTION_SUSPECT, quarantined
