# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-has-silently-laundered-through-a-tool-call-join-node.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-has-silently-laundered-through-a-tool-call-join-node.warrant.json
# Markdown SHA-256:   82ac4e3d9989b5b8f08baadfb062cd6f9dcdc1c148dee6dcdd481972d8ca93c9
# Code AST SHA-256:   ee91c07cb6fa806ad4b4ad6b5e4e02f165b58c4d553f3ff841439ad8fe33b7bf
# Verified Classes:   TaintLaunderingError, TaintRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TaintLaunderingError(RuntimeError):
    """Raised when an LLM-mediated join dissolves span-level taint attribution."""


@dataclass
class TaintRecord:
    labels: frozenset[str]
    bound_spans: int          # spans attributable to exactly one source
    fused_spans: int          # spans written by an LLM that fuse >=2 sources
    source_offsets: dict[str, list[tuple[int, int]]] = field(default_factory=dict)


def assert_join_preserves_attribution(
    inputs: list[TaintRecord],
    output: TaintRecord,
    sink_is_gated: bool,
) -> None:
    expected_labels = frozenset().union(*(r.labels for r in inputs))
    if output.labels != expected_labels:
        raise TaintLaunderingError(
            f"label membership drift at join: expected {expected_labels}, got {output.labels}"
        )

    if sink_is_gated and output.fused_spans > 0:
        # Fused spans mean attribution is undefined; a gated sink must fail closed.
        raise TaintLaunderingError(
            f"join produced {output.fused_spans} fused spans feeding a gated sink; "
            f"span-level attribution is UNKNOWN and gate would fall through to allow"
        )

    if output.bound_spans != len(output.labels):
        raise TaintLaunderingError(
            f"bound_spans ({output.bound_spans}) != label cardinality "
            f"({len(output.labels)}); attribution granularity lost"
        )


def gate_sink(record: TaintRecord, untrusted: str) -> bool:
    """Return True if write is permitted. Fail closed on UNKNOWN attribution."""
    if untrusted in record.labels:
        if record.fused_spans > 0 or record.bound_spans < len(record.labels):
            # Cannot attribute the tainted content to a specific span; block.
            raise TaintLaunderingError(
                f"cannot attribute {untrusted!r} to a span at sink; refusing write"
            )
        return False
    return True
