# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-dynamic-taint-label-before-the-next-tool-call-rather-than-propagate-it-as-a-soft-annotation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-dynamic-taint-label-before-the-next-tool-call-rather-than-propagate-it-as-a-soft-annotation.warrant.json
# Markdown SHA-256:   ed9cc8bbdc092ad5fb1d2d5e98cb398470be80e5385ff15d2ef9cee010fae1e3
# Code AST SHA-256:   a97c9f0e92486743119261c1e48b48ee52d43d0fa52e0396d0db495220a81e6d
# Verified Classes:   TaintLaunderingError, Segment, ToolSchema
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TaintLaunderingError(RuntimeError):
    """Raised when a derivation edge would decrease taint below the join of inputs."""


@dataclass(frozen=True)
class Segment:
    id: str
    taint: FrozenSet[str] = field(default_factory=frozenset)
    origin: str = "unknown"


@dataclass(frozen=True)
class ToolSchema:
    name: str
    # None means "no transfer function declared" -> treated as TOP (quarantine).
    transfer: Optional[callable] = None
    opaque: bool = False


def join_taint(inputs: list[Segment]) -> FrozenSet[str]:
    out: FrozenSet[str] = frozenset()
    for s in inputs:
        out = out | s.taint
    return out


def derive_output(
    tool: ToolSchema,
    inputs: list[Segment],
    produced: Segment,
) -> Segment:
    """Compute the enforced label for a tool output and reject laundering."""
    expected = join_taint(inputs)

    if tool.opaque:
        enforced = expected
    elif tool.transfer is not None:
        enforced = frozenset(tool.transfer(expected))
    else:
        # No declared transfer function: the produced label is untrustworthy.
        # Treat as TOP-of-lattice for this segment's class and quarantine.
        raise TaintLaunderingError(
            f"tool {tool.name!r} produced {produced.id!r} with no declared "
            f"taint-transfer function; input taint {sorted(expected)} cannot "
            f"be verified against output taint {sorted(produced.taint)}. "
            f"Quarantine {produced.id!r} before any side-effecting dispatch."
        )

    if not expected.issubset(enforced):
        raise TaintLaunderingError(
            f"monotonicity violated on edge {tool.name}->{produced.id}: "
            f"input taint {sorted(expected)} not contained in enforced "
            f"output taint {sorted(enforced)}."
        )

    return Segment(id=produced.id, taint=enforced, origin=produced.origin)


def pre_dispatch_check(arg: Segment, allowed_taint: FrozenSet[str]) -> None:
    if not arg.taint.issubset(allowed_taint):
        raise TaintLaunderingError(
            f"dispatch denied: argument {arg.id!r} carries taint "
            f"{sorted(arg.taint)} outside policy {sorted(allowed_taint)}."
        )
