# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tainted-tool-call-as-unquarantinable-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tainted-tool-call-as-unquarantinable-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   1d23373f7c60b37fb57ff5d9781ca3b270e48968b1318a292955678a63ba0016
# Code AST SHA-256:   1802c0ed481266c696cb431fd67a97314c5fbf284da166d946f5dc5e72662926
# Verified Classes:   TaintLaunderingError, Taint, DeclassificationEntry, ToolResult, TaintTracker
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a tool return annotation attempts an unregistered declassification."""
    pass


@dataclass(frozen=True)
class Taint:
    labels: frozenset[str]

    def join(self, other: "Taint") -> "Taint":
        return Taint(self.labels | other.labels)

    @property
    def clean(self) -> bool:
        return not self.labels


CLEAN = Taint(frozenset())


@dataclass(frozen=True)
class DeclassificationEntry:
    tool_id: str
    content_hash: str
    authority: str
    # field name -> sound predicate that rejects any unsafe value
    field_predicates: dict[str, Any]


@dataclass
class ToolResult:
    value: dict[str, Any]
    taint: Taint


class TaintTracker:
    def __init__(self, registry: dict[tuple[str, str], DeclassificationEntry]):
        self._registry = registry

    def resolve_return_taint(
        self,
        tool_id: str,
        content_hash: str,
        input_taint: Taint,
        declared_trusted_fields: set[str],
        result: dict[str, Any],
    ) -> ToolResult:
        key = (tool_id, content_hash)
        entry = self._registry.get(key)

        if declared_trusted_fields and entry is None:
            # Annotation claims declassification but tool is unregistered.
            # Refuse the drop; propagate input taint to every field.
            raise TaintLaunderingError(
                f"tool {tool_id}@{content_hash} declared trusted fields "
                f"{sorted(declared_trusted_fields)} but has no declassification "
                f"registry entry; refusing to drop taint from {sorted(result)}"
            )

        if entry is None:
            # Taint-preserving tool: output taint = input taint.
            return ToolResult(value=result, taint=input_taint)

        out_taint = CLEAN
        for fname, fval in result.items():
            if fname in declared_trusted_fields:
                pred = entry.field_predicates.get(fname)
                if pred is None:
                    raise TaintLaunderingError(
                        f"field {fname!r} declared trusted but no predicate "
                        f"registered for tool {tool_id}@{content_hash}"
                    )
                if not pred(fval):
                    # Predicate rejected the value: it cannot be declassified.
                    out_taint = out_taint.join(input_taint)
                    continue
                # Sound predicate passed: declassify this field only.
                # (Log entry.authority + input_taint here in production.)
            else:
                out_taint = out_taint.join(input_taint)
        return ToolResult(value=result, taint=out_taint)


def gate_tool_call(
    tracker: TaintTracker,
    tool_id: str,
    content_hash: str,
    input_taint: Taint,
    declared_trusted_fields: set[str],
    result: dict[str, Any],
) -> ToolResult:
    return tracker.resolve_return_taint(
        tool_id, content_hash, input_taint, declared_trusted_fields, result
    )


# --- incident replay ---

def _is_numeric(v: Any) -> bool:
    return isinstance(v, int) and not isinstance(v, bool)


registry = {
    ("parse_amount", "sha256:abc"): DeclassificationEntry(
        tool_id="parse_amount",
        content_hash="sha256:abc",
        authority="sandbox:typed-parser",
        field_predicates={"amount": _is_numeric},
    ),
}

tracker = TaintTracker(registry)
doc_taint = Taint(frozenset({"untrusted:document"}))

# extract_entities is NOT in the registry, but its schema declares TrustedEntities.
try:
    gate_tool_call(
        tracker,
        tool_id="extract_entities",
        content_hash="sha256:def",
        input_taint=doc_taint,
        declared_trusted_fields={"assignee", "title"},
        result={"assignee": "svc-admin@corp", "title": "rotate keys"},
    )
except TaintLaunderingError as e:
    # Correct behavior: annotation refused, downstream create_ticket
    # must be quarantined because assignee remains tainted.
    print(f"quarantined: {e}")

# A registered, sound declassification is honored per-field.
res = gate_tool_call(
    tracker,
    tool_id="parse_amount",
    content_hash="sha256:abc",
    input_taint=doc_taint,
    declared_trusted_fields={"amount"},
    result={"amount": 42, "memo": "svc-admin@corp"},
)
assert "untrusted:document" not in res.taint.labels or True
# amount declassified; memo still tainted -> downstream gate sees memo taint.
assert res.taint.labels == frozenset({"untrusted:document"})
