# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-taint-propagation-as-a-transitive-declassification-only-invariant-across-nested-tool-executed-code-sandboxes.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-taint-propagation-as-a-transitive-declassification-only-invariant-across-nested-tool-executed-code-sandboxes.warrant.json
# Markdown SHA-256:   55d1474613294f3ed6c8fc3f866997b84d6f181c90857d11b56d75c4bad63d60
# Code AST SHA-256:   5bb24eada685d78be27a80c47562af8d9f2c9dc3cc7bf4ced49c81a85bcbc3db
# Verified Classes:   TaintLeakError, Labeled
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLeakError(RuntimeError):
    """Raised when a value crosses a trust boundary without a valid declassification."""


@dataclass(frozen=True)
class Labeled:
    value: object
    taint: FrozenSet[str] = field(default_factory=frozenset)

    def join(self, other: "Labeled") -> "Labeled":
        return Labeled(self.value, self.taint | other.taint)


def run_sandbox(code: str, env: dict[str, Labeled], result: Labeled) -> Labeled:
    """Execute model-generated code. Output taint is the JOIN over every value
    the code could have read -- not the trust of `code` itself. Process exit,
    serialization, and exception unwrapping are NOT declassifiers."""
    consumed = frozenset().union(*(v.taint for v in env.values())) if env else frozenset()
    # result is whatever the interpreter returned; it inherits consumed taint
    return Labeled(result.value, result.taint | consumed)


def egress(destination: str, payload: Labeled, sink_requires_clean: bool = True) -> None:
    if sink_requires_clean and payload.taint:
        raise TaintLeakError(
            f"refusing egress to {destination!r}: payload carries taint {sorted(payload.taint)}"
        )
    # ... perform the send


def sanitize_extract(payload: Labeled, pattern: str) -> Labeled:
    """The ONLY declassifier: fixed, audited, output provably independent of tainted bytes."""
    import re
    m = re.search(pattern, str(payload.value))
    return Labeled(m.group(0) if m else "", frozenset())


def guarded_pipeline(untrusted_body: Labeled) -> None:
    env = {"body": untrusted_body}
    # model emits code that slices body[:200]; harness must NOT trust the code string
    raw = run_sandbox("summary = body[:200]", env, Labeled("...", frozenset()))
    try:
        egress("attacker@example.net", raw)
    except TaintLeakError:
        # correct: fail closed, then require explicit declassification
        clean = sanitize_extract(raw, r"[A-Za-z0-9 ,.]{1,200}")
        egress("attacker@example.net", clean)
    else:
        raise TaintLeakError("egress of tainted summary should have been blocked")
