# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-labels-after-a-tool-boundary-and-why-static-propagation-silently-fails.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-labels-after-a-tool-boundary-and-why-static-propagation-silently-fails.warrant.json
# Markdown SHA-256:   f90bc73a7664e9bccba2d26389c64f1276d55fedbc6e8bb690f8f98799c43f59
# Code AST SHA-256:   e37c949466f18c5301b3b35e5d83a2d9d25a4e6ab4030c521fa44653adb55c55
# Verified Classes:   TaintBoundaryError, ToolSpec, LabeledValue
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintBoundaryError(RuntimeError):
    """Raised when a tool boundary would drop a taint label it cannot prove is preserved."""


@dataclass(frozen=True)
class ToolSpec:
    name: str
    echo_safe: bool                 # output is a byte-projection of input
    propagates_taint_to_output: bool  # output inherits taint of tainted args


@dataclass
class LabeledValue:
    value: Any
    taint: frozenset[str] = field(default_factory=frozenset)  # source ids

    def is_tainted(self) -> bool:
        return bool(self.taint)


REGISTRY: dict[str, ToolSpec] = {
    "read_email": ToolSpec("read_email", echo_safe=True, propagates_taint_to_output=True),
    "fetch": ToolSpec("fetch", echo_safe=False, propagates_taint_to_output=True),
    "search": ToolSpec("search", echo_safe=False, propagates_taint_to_output=True),
    "pay": ToolSpec("pay", echo_safe=True, propagates_taint_to_output=False),
}


def invoke_tool(spec: ToolSpec, args: list[LabeledValue], raw_output: Any) -> LabeledValue:
    """Propagate taint across a tool boundary, refusing unsafe boundaries."""
    arg_taint: frozenset[str] = frozenset().union(*(a.taint for a in args)) if args else frozenset()

    if not arg_taint:
        return LabeledValue(raw_output, frozenset())

    if spec.echo_safe:
        # Echo tools: output is a projection; taint carries only if output overlaps input.
        # We conservatively keep taint only when the tool declares output propagation.
        if spec.propagates_taint_to_output:
            return LabeledValue(raw_output, arg_taint)
        return LabeledValue(raw_output, frozenset())

    # Non-echo tool with tainted args: the ONLY sound behavior is to propagate taint
    # to the entire output. Dropping it here is the silent-failure bug.
    if not spec.propagates_taint_to_output:
        raise TaintBoundaryError(
            f"tool '{spec.name}' is not echo-safe but does not propagate taint to output; "
            f"calling it with tainted args {sorted(arg_taint)} would silently declassify data"
        )
    return LabeledValue(raw_output, arg_taint)


def privileged_sink(spec: ToolSpec, args: list[LabeledValue]) -> None:
    """A sink rejects any tainted argument; declassification must happen upstream."""
    for a in args:
        if a.is_tainted():
            raise TaintBoundaryError(
                f"sink '{spec.name}' received tainted argument from sources {sorted(a.taint)}; "
                f"route through an explicit declassifier"
            )
    return None


# --- Reproduce the invoice trace and show the guardrail firing ---

def run_invoice_flow() -> None:
    email = LabeledValue("invoice at http://x; payee is ACME CORP (acct 9981)", frozenset({"email:msg_8841"}))
    url = LabeledValue("http://x/invoice.pdf", email.taint)  # literal substring -> carries taint

    fetch = REGISTRY["fetch"]
    page = invoke_tool(fetch, [url], raw_output={"payee": "ACME CORP", "amount": 1240.0})
    # page.taint == {"email:msg_8841"} despite reformatting; no silent drop.

    pay = REGISTRY["pay"]
    try:
        privileged_sink(pay, [LabeledValue(page.value["payee"], page.taint),
                              LabeledValue(page.value["amount"], page.taint)])
    except TaintBoundaryError as e:
        print(f"BLOCKED: {e}")
        return
    raise TaintBoundaryError("payment executed despite tainted provenance — invariant violated")


if __name__ == "__main__":
    run_invoice_flow()
