# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-tool-call-whose-taint-is-cleared-by-a-downstream-sanitizer.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-tool-call-whose-taint-is-cleared-by-a-downstream-sanitizer.warrant.json
# Markdown SHA-256:   ad491e3abddaa1b1ee16420f5aa504b9405569678682490192458b226d2e6c4b
# Code AST SHA-256:   cc9b850f6b5cb99d89322c8254cfcaa30d908e6ea08a30892acaac917a8fff36
# Verified Classes:   TaintClearingUnsoundError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintClearingUnsoundError(RuntimeError):
    """Raised when a cleared taint label is admitted to an egress sink
    while the capability that produced the original label is still live."""
    pass


def admit_tool_call(
    arg_taint: frozenset,
    sanitizer_destroying: bool,
    live_capabilities: frozenset,
    label_producers: frozenset,
    sink_is_egress: bool,
) -> bool:
    """Return True if the call may proceed, else raise.

    Boundary: empty taint is NOT sufficient for egress admission.
    The producing capability must be dead (destroying sanitizer) or
    provably disjoint from the live capability set.
    """
    if not sink_is_egress:
        return True

    if arg_taint:
        # Non-empty taint to an egress sink is a hard refusal.
        raise TaintClearingUnsoundError(
            f"egress sink invoked with live taint {sorted(arg_taint)}"
        )

    # Taint is empty. Check whether the clearing was sound.
    producer_still_live = bool(label_producers & live_capabilities)
    if producer_still_live and not sanitizer_destroying:
        raise TaintClearingUnsoundError(
            "empty taint on egress sink, but producing capability "
            f"{sorted(label_producers & live_capabilities)} is still live "
            "and sanitizer is transforming (not destroying); "
            "refusing to admit"
        )

    return True
