# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-data-through-a-side-channel-sink-that-the-sandbox-s-label-model-does-not-recognize.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-data-through-a-side-channel-sink-that-the-sandbox-s-label-model-does-not-recognize.warrant.json
# Markdown SHA-256:   6f8e036c2703bc1c52598704f81b1d926607474df295852d41b0ca507dc04369
# Code AST SHA-256:   653d3e5075f9f521d7b75118c5ed4403f2a8f512ac1d557aff7998daefd6b623
# Verified Classes:   ImplicitFlowViolation, ActionTaintGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ImplicitFlowViolation(RuntimeError):
    """Raised when an egress action's shape depends on tainted state without a warrant."""
    pass


class ActionTaintGuard:
    def __init__(self, egress_tools: set[str]):
        self.egress_tools = egress_tools
        self.task_tainted = False
        self.warrant: set[str] = set()
        self._egress_shapes: dict[str, list[tuple]] = {}

    def observe_source(self, label: str) -> None:
        if label.startswith("secret://"):
            self.task_tainted = True

    def grant_warrant(self, endpoint: str) -> None:
        # Human-granted, out-of-band. Never derivable from model output.
        self.warrant.add(endpoint)

    def check_call(self, tool: str, endpoint: str, args: tuple) -> None:
        if tool not in self.egress_tools:
            return
        if not self.task_tainted:
            return
        if endpoint in self.warrant:
            return
        shape = (tool, endpoint, args)
        prior = self._egress_shapes.setdefault(endpoint, [])
        if prior and shape not in prior:
            raise ImplicitFlowViolation(
                f"egress shape changed mid-task on {endpoint!r} under taint: "
                f"prior={prior!r} now={shape!r}; implicit flow not warranted"
            )
        if not prior:
            prior.append(shape)
        # Even a constant shape is only safe if count is bounded and constant.
        if len(prior) > 1 and prior.count(shape) > 1:
            raise ImplicitFlowViolation(
                f"repeated egress on {endpoint!r} under taint without warrant; "
                f"call count is an implicit channel"
            )
