# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-across-nested-tool-dispatch-and-silently-re-escalate-injected-instructions.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-across-nested-tool-dispatch-and-silently-re-escalate-injected-instructions.warrant.json
# Markdown SHA-256:   0801b5a3f30f2cdcac419823477a2c08042ca18db0aefd4f18449e10d30d3915
# Code AST SHA-256:   d1286a3c4768622477a299686a9a8824a1259c3ca3691fa18dc89d529cb90169
# Verified Classes:   TaintFloorViolation, ProvenanceGap, ExecContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Any

T0, T1 = 0, 1  # lower = more trusted; meet = min


class TaintFloorViolation(RuntimeError):
    """Raised when a dispatch exceeds the execution context's taint floor."""


class ProvenanceGap(TaintFloorViolation):
    """Raised when taint provenance cannot be established for consumed data."""


@dataclass(frozen=True)
class ExecContext:
    # Out-of-band: never serialized into any model-visible schema.
    taint_floor: int
    trace: tuple[str, ...] = field(default_factory=tuple)

    def ingest(self, source: str, label: int | None) -> "ExecContext":
        if label is None:
            # Fail closed: unknown provenance is untrusted.
            raise ProvenanceGap(f"no taint label for source {source!r}")
        return ExecContext(min(self.taint_floor, label), self.trace + (source,))

    def dispatch(self, tool: str, required_taint: int, fn: Callable[..., Any], **kw: Any) -> Any:
        if required_taint < self.taint_floor:
            raise TaintFloorViolation(
                f"tool {tool!r} requires taint<={required_taint} "
                f"but context floor is {self.taint_floor} via {self.trace}"
            )
        return fn(context=self, **kw)


def spawn_sub_orchestrator(parent: ExecContext, consumed: list[tuple[str, int | None]]) -> ExecContext:
    ctx = parent
    for source, label in consumed:
        ctx = ctx.ingest(source, label)  # meet over all ingested data
    return ctx
