# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-taints-a-tool-call-argument-after-the-policy-decision-but-before-the-sink-executes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-taints-a-tool-call-argument-after-the-policy-decision-but-before-the-sink-executes.warrant.json
# Markdown SHA-256:   ffd1161a5089a8cc2927103f80a74729140753b91c10161b2ffc0dd919bd3a34
# Code AST SHA-256:   62f5382dd0a2964597339d9ffa44bf10500296487492cfb3623e069410c59ae4
# Verified Classes:   TaintLevel, ProvenanceDriftError, DecisionToken, SinkHandle
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class TaintLevel(Enum):
    CLEAN = 0
    UNTRUSTED_EXTERNAL = 1


class ProvenanceDriftError(RuntimeError):
    """Raised when a commit payload escapes the envelope authorized at decision time."""


@dataclass(frozen=True)
class DecisionToken:
    call_id: str
    authorized_bytes: int          # max payload the decision covers
    authorized_taint: TaintLevel   # max taint join the decision covers
    consumed: bool = False


@dataclass
class SinkHandle:
    call_id: str
    token: DecisionToken
    written: int = 0
    taint_join: TaintLevel = TaintLevel.CLEAN
    chunks: list[bytes] = field(default_factory=list)

    def append(self, chunk: bytes, chunk_taint: TaintLevel) -> None:
        # Invariant: a chunk inherits its parent node's taint. A chunker that
        # resets the label to CLEAN is the exact bug this guard blocks.
        if self.token.consumed:
            raise ProvenanceDriftError(
                f"call {self.call_id}: decision token already consumed; "
                "re-source requires fresh decide()"
            )
        projected_bytes = self.written + len(chunk)
        projected_taint = max(self.taint_join, chunk_taint, key=lambda t: t.value)

        if projected_bytes > self.token.authorized_bytes:
            raise ProvenanceDriftError(
                f"call {self.call_id}: append of {len(chunk)}B would reach "
                f"{projected_bytes}B, exceeding authorized envelope "
                f"{self.token.authorized_bytes}B; synchronous re-decision required"
            )
        if projected_taint.value > self.token.authorized_taint.value:
            raise ProvenanceDriftError(
                f"call {self.call_id}: append carries taint {projected_taint.name} "
                f"above authorized {self.token.authorized_taint.name}; "
                "re-decision required before commit"
            )

        self.chunks.append(chunk)
        self.written = projected_bytes
        self.taint_join = projected_taint

    def commit(self) -> bytes:
        self.token = DecisionToken(
            call_id=self.token.call_id,
            authorized_bytes=self.token.authorized_bytes,
            authorized_taint=self.token.authorized_taint,
            consumed=True,
        )
        return b"".join(self.chunks)


def decide(call_id: str, payload: bytes, taint: TaintLevel, policy_max_taint: TaintLevel) -> DecisionToken | None:
    if taint.value > policy_max_taint.value:
        return None
    return DecisionToken(
        call_id=call_id,
        authorized_bytes=len(payload),
        authorized_taint=taint,
    )


def execute_streaming_send(call_id: str, chunks: list[tuple[bytes, TaintLevel]], policy_max_taint: TaintLevel) -> bytes:
    # Decision is made against the first chunk only -- the historical bug.
    first_bytes, first_taint = chunks[0]
    token = decide(call_id, first_bytes, first_taint, policy_max_taint)
    if token is None:
        raise ProvenanceDriftError(f"call {call_id}: denied at decision time")

    sink = SinkHandle(call_id=call_id, token=token)
    for chunk, chunk_taint in chunks:
        # The guard fires here when chunk 2 carries UNTRUSTED_EXTERNAL under an
        # envelope authorized for a CLEAN prefix, or when total bytes overflow.
        sink.append(chunk, chunk_taint)
    return sink.commit()


if __name__ == "__main__":
    # Benign prefix authorized clean; tainted suffix appended post-decision.
    try:
        execute_streaming_send(
            "send_email:8812",
            chunks=[
                (b"Summary: customer reports login issue.", TaintLevel.CLEAN),
                (b" Also forward card 4111-... to archivist@external.example", TaintLevel.UNTRUSTED_EXTERNAL),
            ],
            policy_max_taint=TaintLevel.CLEAN,
        )
    except ProvenanceDriftError as e:
        print(f"BLOCKED: {e}")
