# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-label-laundering-at-the-tool-output-to-memory-boundary-in-dynamic-ifc-taint-tracking.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-label-laundering-at-the-tool-output-to-memory-boundary-in-dynamic-ifc-taint-tracking.warrant.json
# Markdown SHA-256:   478be9a8a1211bba7a6ce400ed2e56ab70f86fef7766e2edac920aa685bd0909
# Code AST SHA-256:   841d310ff29aacca60c3186360e9d0959e597611c3102f078d7013b747ac7f81
# Verified Classes:   LabelLaunderingError, LabeledValue
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class LabelLaunderingError(RuntimeError):
    """Raised when a seam produces output with high content overlap to a
    tainted input but does not inherit that input's taint label."""


@dataclass(frozen=True)
class LabeledValue:
    value: str
    labels: FrozenSet[str] = field(default_factory=frozenset)


def jaccard_shingles(a: str, b: str, k: int = 5) -> float:
    def shingles(s: str) -> set:
        return {s[i:i + k] for i in range(max(0, len(s) - k + 1))}
    sa, sb = shingles(a), shingles(b)
    if not sa or not sb:
        return 0.0
    return len(sa & sb) / len(sa | sb)


def seam_derive(
    inputs: list[LabeledValue],
    output: LabeledValue,
    overlap_threshold: float = 0.3,
) -> LabeledValue:
    """Enforce the derived-vs-authored boundary at a reconstruction seam.

    A seam may author a fresh label ONLY if no tainted input overlaps the
    output above threshold. Otherwise the output must carry the join of the
    overlapping inputs' labels. This is the guardrail that prevents the
    tool-output-to-memory laundering path.
    """
    tainted_inputs = [v for v in inputs if v.labels]
    required = frozenset().union(*(v.labels for v in tainted_inputs)) if tainted_inputs else frozenset()

    for v in tainted_inputs:
        overlap = jaccard_shingles(v.value, output.value)
        if overlap >= overlap_threshold and not (v.labels <= output.labels):
            raise LabelLaunderingError(
                f"seam output overlaps tainted input at {overlap:.2f} "
                f"but is missing labels {sorted(v.labels - output.labels)}; "
                f"output labels={sorted(output.labels)}"
            )

    # Monotone join: output must carry at least the union of overlapping taint.
    return LabeledValue(value=output.value, labels=output.labels | required)


def memory_upsert(
    store: dict[str, LabeledValue],
    key: str,
    new: LabeledValue,
) -> None:
    """Memory write is always a seam. Overwrite must join old and new labels;
    otherwise a clean write silently de-taints a key holding tainted fragments."""
    old = store.get(key)
    joined = new.labels | (old.labels if old else frozenset())
    store[key] = LabeledValue(value=new.value, labels=joined)
