# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-data-through-a-tool-call-boundary-that-reports-success-on-a-partial-write.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-data-through-a-tool-call-boundary-that-reports-success-on-a-partial-write.warrant.json
# Markdown SHA-256:   eef627297e4589a41940b5b726c7db6edb3e189a6b5e6d89026d504f012766cd
# Code AST SHA-256:   b1daa8cef8d0ee489ebf68923ff37d088fca41d3943e64b2d2d7f7e6c14a0560
# Verified Classes:   TaintLaunderingError, Label, ToolReturn
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a tool boundary would admit a partial-success return
    without an INCOMPLETE taint marker, laundering provenance."""
    pass


@dataclass(frozen=True)
class Label:
    bits: frozenset  # e.g. {"EXTERNAL"}, {"INTERNAL_STAGED"}, {"INCOMPLETE"}

    def join(self, other: "Label") -> "Label":
        return Label(self.bits | other.bits)

    def __contains__(self, name: str) -> bool:
        return name in self.bits


@dataclass
class ToolReturn:
    value: Any
    requested: int
    completed: int
    failed_indices: List[int] = field(default_factory=list)


def enforce_boundary(
    call_id: str,
    tool: str,
    arg_label: Label,
    declared_rule: Label,
    ret: ToolReturn,
    downstream_policy_requires_total: bool,
) -> Label:
    # 1. Derive the observed completion status from the payload, not the type.
    is_partial = ret.completed < ret.requested

    # 2. Compute the nominal label from the declared rule.
    nominal = arg_label.join(declared_rule)

    # 3. If partial, the label MUST carry INCOMPLETE. If the declared rule
    #    did not include it, the tool is a laundering vector.
    if is_partial and "INCOMPLETE" not in nominal:
        raise TaintLaunderingError(
            f"call {call_id} tool={tool}: partial completion "
            f"({ret.completed}/{ret.requested}, failed={ret.failed_indices}) "
            f"but return label {nominal.bits} lacks INCOMPLETE; "
            f"refusing to admit laundered provenance"
        )

    # 4. If downstream requires total completion and we are partial, block.
    if is_partial and downstream_policy_requires_total:
        raise TaintLaunderingError(
            f"call {call_id} tool={tool}: downstream requires total completion, "
            f"observed {ret.completed}/{ret.requested}; escalate, do not commit"
        )

    # 5. Return a fresh label (never mutate the caller's object).
    return nominal
