# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-result-as-tainted-when-the-injection-payload-arrives-after-the-call-that-reads-it-i-e-the-label-la.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-result-as-tainted-when-the-injection-payload-arrives-after-the-call-that-reads-it-i-e-the-label-la.warrant.json
# Markdown SHA-256:   d4b3231d727a728ceb1a7427125e5e2fbe5a5a3fea69b0af10a79dbed262091a
# Code AST SHA-256:   13f1a97f88467cdd3ba1b1f04db7edd8ad8bdb184283c87a97aa152786cd23eb
# Verified Classes:   TaintLaunderingError, Handle, HandleRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a handle is re-dereferenced after returning untrusted bytes
    without an explicit declassification, i.e. the reachability-taint invariant
    is violated."""


@dataclass(frozen=True)
class Handle:
    key: str
    reachable_sources: FrozenSet[str] = frozenset()
    deref_count: int = 0
    returned_untrusted: bool = False

    def dereference(self, endpoint_trust: str) -> "Handle":
        # A handle carries the taint of every region it can reach, plus the
        # intrinsic trust of the endpoint it resolves to.
        new_sources = self.reachable_sources | ({endpoint_trust} if endpoint_trust == "untrusted" else set())
        returned_untrusted = "untrusted" in new_sources
        return Handle(
            key=self.key,
            reachable_sources=frozenset(new_sources),
            deref_count=self.deref_count + 1,
            returned_untrusted=returned_untrusted,
        )


class HandleRegistry:
    def __init__(self) -> None:
        self._handles: dict[str, Handle] = {}

    def register(self, handle: Handle) -> None:
        self._handles[handle.key] = handle

    def dereference(self, key: str, endpoint_trust: str) -> Handle:
        if key not in self._handles:
            raise TaintLaunderingError(f"unknown handle {key!r}; cannot prove provenance")
        h = self._handles[key]
        # The invariant: a second dereference of a handle that previously
        # returned untrusted bytes is a re-open event. It must not be silently
        # reclassified as trusted just because the argument was model-authored.
        if h.deref_count >= 1 and h.returned_untrusted and endpoint_trust != "untrusted":
            raise TaintLaunderingError(
                f"handle {key!r} re-dereferenced after returning untrusted bytes; "
                f"reachable_sources={sorted(h.reachable_sources)}; "
                f"explicit declassify() required before reuse"
            )
        updated = h.dereference(endpoint_trust)
        self._handles[key] = updated
        return updated


def fetch_and_label(registry: HandleRegistry, key: str, endpoint_trust: str) -> Handle:
    return registry.dereference(key, endpoint_trust)


if __name__ == "__main__":
    reg = HandleRegistry()
    reg.register(Handle(key="https://docs.example.org/memo?id=8812"))

    # First dereference: returns untrusted bytes, handle now marked.
    h1 = fetch_and_label(reg, "https://docs.example.org/memo?id=8812", "untrusted")
    assert h1.returned_untrusted

    # Second dereference: the laundering attempt. Must raise, not silently clear.
    try:
        fetch_and_label(reg, "https://docs.example.org/memo?id=8812", "trusted")
    except TaintLaunderingError as e:
        print(f"blocked: {e}")
