# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-idempotent-tool-output-caches.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-idempotent-tool-output-caches.warrant.json
# Markdown SHA-256:   71311bbd0041e12d43faef72d5f51a155ce33673dd54d0a29768d0db7f219250
# Code AST SHA-256:   e92786a494fa3421cfc7ee57d161fe6690c6c5fb405974a4e0cd6a68ab21bbd4
# Verified Classes:   TaintLaunderingError, Provenance, ToolOutputCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Hashable


class TaintLaunderingError(RuntimeError):
    """Raised when a cache hit would re-label a value more trusted than its addressable callers."""


@dataclass(frozen=True)
class Provenance:
    label: str  # e.g. "trusted:user", "untrusted:tool_output"
    rank: int   # lower = more trusted; join = max rank

    def join(self, other: "Provenance") -> "Provenance":
        return self if self.rank >= other.rank else other


TRUSTED = Provenance("trusted:user", 0)
UNTRUSTED = Provenance("untrusted:tool_output", 2)


class ToolOutputCache:
    def __init__(self) -> None:
        # key -> (payload, stored_provenance, addressable_caller_ranks)
        self._store: dict[Hashable, tuple[bytes, Provenance, set[int]]] = {}

    def put(self, key: Hashable, payload: bytes, stored: Provenance, caller: Provenance) -> None:
        ranks = self._store.get(key, (b"", stored, set()))[2]
        ranks.add(caller.rank)
        self._store[key] = (payload, stored, ranks)

    def get(self, key: Hashable, caller: Provenance) -> tuple[bytes, Provenance]:
        if key not in self._store:
            raise KeyError(key)
        payload, stored, caller_ranks = self._store[key]
        # The entry is addressable by any caller that shares the key; its
        # effective label must be the join over all addressable callers.
        effective = stored
        for r in caller_ranks:
            effective = effective.join(Provenance("", r))
        effective = effective.join(caller)
        if effective.rank < stored.rank:
            raise TaintLaunderingError(
                f"cache hit for {key!r} would upgrade {stored.label} "
                f"to {effective.label} for caller {caller.label}"
            )
        return payload, effective


def admit_to_sink(value_label: Provenance, sink_admits: Provenance) -> None:
    if value_label.rank > sink_admits.rank:
        raise TaintLaunderingError(
            f"sink admits up to {sink_admits.label}, got {value_label.label}"
        )
