# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tool-s-return-channel-as-tainted-by-construction-rather-than-tainted-by-content.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tool-s-return-channel-as-tainted-by-construction-rather-than-tainted-by-content.warrant.json
# Markdown SHA-256:   9d624adb5f79e5c1c52c6c479a790a109db665646972ceac43852a3e752a9ccb
# Code AST SHA-256:   3f36aa027222d821b1b0cb9c9a1f1be0cb65c77c9262e13de33140abcdaeb3d1
# Verified Classes:   TaintSelectionLeak
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintSelectionLeak(RuntimeError):
    """Raised when a call's observable projection is conditioned on a live taint label."""
    pass


# Observable projection an adversary could see for a single call.
def observable_projection(call: dict) -> tuple:
    return (
        call["host"],
        call["path"],
        call["query"],
        len(call.get("body", "")) // 16,   # length bucket
        call.get("timing_bucket", 0),
    )


def enforce_noninterference(
    live_taint_labels: set,
    proposed_call: dict,
    call_was_selected_by_tainted_context: bool,
    distinguishable_call_set_size: int,
) -> None:
    """
    Fail closed if the call's selection or projection can carry a bit
    derived from tainted state. Taint-by-content is insufficient here.
    """
    if not live_taint_labels:
        return  # untainted context: no channel to protect

    if call_was_selected_by_tainted_context and distinguishable_call_set_size > 1:
        raise TaintSelectionLeak(
            f"tainted context selected among {distinguishable_call_set_size} "
            f"distinguishable calls; selection encodes "
            f"{distinguishable_call_set_size.bit_length() - 1} bits per call "
            f"over labels {sorted(live_taint_labels)}"
        )

    proj = observable_projection(proposed_call)
    if proposed_call.get("projection_depends_on_taint", False):
        raise TaintSelectionLeak(
            f"observable projection {proj} is a function of live taint; "
            f"payload may be clean while channel is open"
        )


def guarded_dispatch(call: dict, ctx: dict) -> dict:
    enforce_noninterference(
        live_taint_labels=ctx["taint_labels"],
        proposed_call=call,
        call_was_selected_by_tainted_context=ctx["selector_tainted"],
        distinguishable_call_set_size=ctx["call_set_size"],
    )
    return ctx["transport"].send(call)
