# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamic-information-flow-label-as-sticky-across-a-tool-boundary-rather-than-re-deriving-it-at-the-calle.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamic-information-flow-label-as-sticky-across-a-tool-boundary-rather-than-re-deriving-it-at-the-calle.warrant.json
# Markdown SHA-256:   575e6c4cd1f07051a7930c6d20440257c0a63bd383534948fdc96fb5b41aa78d
# Code AST SHA-256:   2c6024bb2801a6a8348d1f7c3c0d30866103fc41e3afdc0ae81b24b2c03716a7
# Verified Classes:   TaintLaunderingError, Labeled
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Trust = Literal["untrusted:retrieved", "untrusted:tool_output", "untrusted:caller", "trusted:caller", "trusted:system"]

# Total order on the trust lattice; higher index = more privileged.
_TRUST_RANK: dict[Trust, int] = {
    "untrusted:retrieved": 0,
    "untrusted:tool_output": 1,
    "untrusted:caller": 2,
    "trusted:caller": 3,
    "trusted:system": 4,
}


class TaintLaunderingError(RuntimeError):
    """Raised when a tool boundary would re-derive an opaque payload's label
    to a trust class higher than its incoming label (upward laundering)."""


@dataclass
class Labeled:
    payload: str
    label: Trust
    lineage: list[str] = field(default_factory=list)


def join(a: Trust, b: Trust) -> Trust:
    """Least upper bound; never returns lower than either input."""
    return a if _TRUST_RANK[a] >= _TRUST_RANK[b] else b


def cross_boundary(
    incoming: Labeled,
    callee_default: Trust,
    schema_has_provenance_field: bool,
    callee_has_privileged_sink: bool,
    serialized_label_present: bool,
) -> Labeled:
    """Enforce the stickiness invariant at a tool/MCP boundary.

    Re-derivation is permitted only when the schema carries provenance
    structurally, OR no privileged sink is reachable, OR the callee default
    is no more permissive than the incoming label.
    """
    opaque = not schema_has_provenance_field
    upward_gradient = _TRUST_RANK[callee_default] > _TRUST_RANK[incoming.label]

    if opaque and callee_has_privileged_sink and upward_gradient:
        # Re-derivation here would launder taint. Require a bound label.
        if not serialized_label_present:
            raise TaintLaunderingError(
                f"opaque payload labeled {incoming.label!r} reached a privileged "
                f"sink whose default is {callee_default!r} with no serialized "
                f"label bound to the payload; refusing to re-derive"
            )
        # Serialized label present: inherit, do NOT adopt callee default.
        effective = join(incoming.label, incoming.label)
        return Labeled(
            payload=incoming.payload,
            label=effective,
            lineage=incoming.lineage + [f"boundary:inherit({callee_default})"],
        )

    # Safe re-derivation: clamp to the join of incoming and default.
    effective = join(incoming.label, callee_default)
    return Labeled(
        payload=incoming.payload,
        label=effective,
        lineage=incoming.lineage + [f"boundary:join({callee_default})"],
    )


def dispatch_extract_entities(chunk: Labeled) -> Labeled:
    # Tool server with an opaque {"text": "string"} schema and a privileged
    # downstream sink (the entity extractor can schedule actions).
    return cross_boundary(
        incoming=chunk,
        callee_default="trusted:caller",   # local assumption: caller is a peer
        schema_has_provenance_field=False,  # bare string on the wire
        callee_has_privileged_sink=True,
        serialized_label_present=False,     # label was stripped in JSON-RPC
    )
