# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-when-dynamic-information-flow-taint-labels-silently-decay-across-tool-output-and-memory-write-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-when-dynamic-information-flow-taint-labels-silently-decay-across-tool-output-and-memory-write-boundaries.warrant.json
# Markdown SHA-256:   5f1c06dcc2a4a494ba96a36d0cf01235ddea5b33a2c1f9ff186897ecf525dce1
# Code AST SHA-256:   339b34ad175aa2254fec03a9641c2e8a18ccfb6ed0d622ff7a3489551b0dc5c7
# Verified Classes:   TaintDecayError, Labeled
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class TaintDecayError(RuntimeError):
    """Raised when a sink receives data whose taint set is a strict subset of
    its transitive upstream taint with no recorded declassification rule."""
    pass


@dataclass(frozen=True)
class Labeled:
    value: object
    taint: FrozenSet[str] = field(default_factory=frozenset)
    declassified_by: Optional[str] = None  # rule id, if a rule fired


def merge(left: Labeled, right: Labeled) -> Labeled:
    # Label-join must be set-union, never left/first.
    return Labeled(
        value=(left.value, right.value),
        taint=left.taint | right.taint,
        declassified_by=None,
    )


def declassify(x: Labeled, rule_id: str, allowed_sources: FrozenSet[str]) -> Labeled:
    if not x.taint.issubset(allowed_sources):
        raise TaintDecayError(
            f"declassification rule {rule_id!r} does not cover taint {sorted(x.taint)}"
        )
    return Labeled(value=x.value, taint=frozenset(), declassified_by=rule_id)


def assert_sink_invariant(upstream: Labeled, at_sink: Labeled, sink_name: str) -> None:
    """Enforce taint(v) >= taint(u) unless a declassification rule fired."""
    if at_sink.declassified_by is not None:
        return  # reduction is authorized and logged
    missing = upstream.taint - at_sink.taint
    if missing:
        raise TaintDecayError(
            f"taint decay at sink {sink_name!r}: upstream taint {sorted(upstream.taint)} "
            f"lost {sorted(missing)} with no declassification record"
        )


def checked_tool_output(raw: dict) -> Labeled:
    """Parser that refuses to emit a bare scalar from a labeled envelope."""
    if "taint" not in raw:
        raise TaintDecayError("tool output missing taint envelope; cannot propagate")
    return Labeled(value=raw["result"], taint=frozenset(raw["taint"]))


def checked_memory_write(consolidated_from: Labeled, note: Labeled) -> None:
    """Memory consolidation must inherit source provenance, not the agent's trust."""
    if note.taint != consolidated_from.taint and note.declassified_by is None:
        raise TaintDecayError(
            f"memory write laundered taint: source {sorted(consolidated_from.taint)} "
            f"-> note {sorted(note.taint)}"
        )
