# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-taint-survive-the-tool-call-graph-boundary-and-where-it-must-not.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-taint-survive-the-tool-call-graph-boundary-and-where-it-must-not.warrant.json
# Markdown SHA-256:   df5818643827b879748b2087e9ea7d4c804979ea4ebf35aa8874eb81625a250c
# Code AST SHA-256:   33e51e428b675db2b08e4b1b7d360709323876f01e3027f75488b5c33f90dbaa
# Verified Classes:   TaintLaunderingError, TaintSaturationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when tainted content would cross a hop whose schema cannot carry the label."""
    pass


class TaintSaturationError(RuntimeError):
    """Raised when a label set exceeds the decision-useful bound and must be reset."""
    pass


TRUSTED_RESET_AUTHORITIES = frozenset({"human_confirm", "signed_policy_check", "first_party_refetch"})
EXTERNAL_EFFECT_SINKS = frozenset({"email_send", "payment_charge", "code_exec"})
MAX_HOPS_WITHOUT_SINK = 6


def carry_taint(value: str, tainted: bool, hop_schema_has_sink: bool, hop_name: str) -> dict:
    if tainted and not hop_schema_has_sink:
        # Schema-gap laundering: refuse rather than drop the label silently.
        raise TaintLaunderingError(
            f"hop {hop_name!r} schema cannot carry provenance; tainted value would be laundered"
        )
    return {"value": value, "tainted": tainted, "hop": hop_name}


def reset_taint(label: dict, authority: str) -> dict:
    if authority not in TRUSTED_RESET_AUTHORITIES:
        # An unauthenticated clear is indistinguishable from laundering.
        raise TaintLaunderingError(
            f"reset by unauthenticated authority {authority!r} rejected"
        )
    return {**label, "tainted": False, "reset_by": authority}


def admit_to_sink(label: dict, sink: str, hops_since_sink: int) -> dict:
    if hops_since_sink > MAX_HOPS_WITHOUT_SINK and label["tainted"]:
        # Expired label -> unknown, not clean; external sinks must fail closed.
        if sink in EXTERNAL_EFFECT_SINKS:
            raise TaintSaturationError(
                f"label expired after {hops_since_sink} hops; treating as unknown at sink {sink!r}"
            )
        return {**label, "tainted": "unknown"}
    if label["tainted"] is True and sink in EXTERNAL_EFFECT_SINKS:
        raise TaintLaunderingError(f"tainted value reached external sink {sink!r}")
    return label
