# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-taint-label-joins-at-mcp-tool-boundaries-as-lossy-and-refuse-an-a2a-delegation-whose-envelope-taint-is-a-stri.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-taint-label-joins-at-mcp-tool-boundaries-as-lossy-and-refuse-an-a2a-delegation-whose-envelope-taint-is-a-stri.warrant.json
# Markdown SHA-256:   5e8dede3cd8c085a74110db99caa4d12b2895450fdb861856aa137deb997eabf
# Code AST SHA-256:   f41c71ed6cbe8d0d217dcc02d57fec93aa5a2d3c64beace5d391930abdabadde
# Verified Classes:   TaintJoinCollapse, Taint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import Iterable

# Taint levels as a total order; join = max. Namespaces alias to a shared key.
LEVELS = {"trusted": 0, "derived": 1, "internal": 2, "untrusted": 3}
ALIAS = {"web": "net", "user": "net", "net": "net", "tool": "sys", "transform": "sys"}


class TaintJoinCollapse(RuntimeError):
    """Raised when a boundary round-trip loses taint (reconstructed is a strict subset)."""


@dataclass(frozen=True)
class Taint:
    # namespace -> max level seen; this is the *true* join, key-injective.
    levels: dict[str, str] = field(default_factory=dict)

    def join(self, other: "Taint") -> "Taint":
        out = dict(self.levels)
        for ns, lvl in other.levels.items():
            if ns not in out or LEVELS[lvl] > LEVELS[out[ns]]:
                out[ns] = lvl
        return Taint(out)

    def __ge__(self, other: "Taint") -> bool:
        return all(
            ns in self.levels and LEVELS[self.levels[ns]] >= LEVELS[lvl]
            for ns, lvl in other.levels.items()
        )


def encode_flat(t: Taint) -> str:
    # Lossy: emits every element, aliasing namespaces, preserving insertion order.
    return ",".join(f"{ns}:{lvl}" for ns, lvl in t.levels.items())


def decode_dict(header: str) -> Taint:
    # Lossy: dict keyed by ALIASed namespace, last-writer-wins.
    out: dict[str, str] = {}
    for tok in header.split(","):
        if not tok:
            continue
        ns, lvl = tok.split(":")
        key = ALIAS.get(ns, ns)
        out[key] = lvl  # last writer wins -> can DOWNGRADE
    return Taint(out)


def decode_multimap(header: str) -> Taint:
    # Safe: join on read, max per aliased key.
    out: dict[str, str] = {}
    for tok in header.split(","):
        if not tok:
            continue
        ns, lvl = tok.split(":")
        key = ALIAS.get(ns, ns)
        if key not in out or LEVELS[lvl] > LEVELS[out[key]]:
            out[key] = lvl
    return Taint(out)


def delegate(taint: Taint, decoder) -> Taint:
    header = encode_flat(taint)
    reconstructed = decoder(header)
    if not (reconstructed >= taint):
        raise TaintJoinCollapse(
            f"boundary under-taint: sender={taint.levels} "
            f"reconstructed={reconstructed.levels} header={header!r}"
        )
    return reconstructed


if __name__ == "__main__":
    # web:untrusted then web:trusted -> true join is untrusted (max).
    t = Taint({"web": "untrusted"}).join(Taint({"web": "trusted"}))
    assert t.levels == {"web": "untrusted"}
    # Safe decoder holds the invariant; lossy decoder collapses it.
    delegate(t, decode_multimap)          # ok
    delegate(t, decode_dict)              # raises TaintJoinCollapse
