# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-tool-output-as-tainted-across-a-resumed-session-and-why-per-call-data-flow-labels-break-at-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-tool-output-as-tainted-across-a-resumed-session-and-why-per-call-data-flow-labels-break-at-checkpoint.warrant.json
# Markdown SHA-256:   2d25d0cbf169863af6775d23d49e1680d030f3bdc983a033bf138388ed960c37
# Code AST SHA-256:   ba692e4c33acdb5c611f7cdd38a303dde3f45427870af25fbea2f179e0edd699
# Verified Classes:   TaintSeveranceError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TaintSeveranceError(RuntimeError):
    """Raised when a checkpoint/resume round-trip loses a taint label
    that the enforcement point depends on."""


def resume_with_taint_check(
    checkpoint: dict,
    rehydrated_context: list[dict],
    label_map_at_checkpoint: dict[str, str],
) -> list[dict]:
    """
    Rehydrate a session and verify that every tainted value that was
    labeled at checkpoint time is still resolvable by the sandbox after
    the real serialization round-trip. Fail closed on any severance.
    """
    # Count tainted values that existed at checkpoint.
    expected_tainted = {
        call_id: label
        for call_id, label in label_map_at_checkpoint.items()
        if label != "TRUSTED"
    }

    # Resolve which labels survived into the context the sandbox will read.
    reachable: dict[str, str] = {}
    for msg in rehydrated_context:
        call_id = msg.get("call_id")
        # A label is only reachable if it is embedded in the value
        # representation the sandbox parses, not a sidecar field.
        inline = msg.get("content_envelope", {}).get("taint")
        if call_id and inline:
            reachable[call_id] = inline

    severed = [
        cid for cid in expected_tainted
        if reachable.get(cid) != expected_tainted[cid]
    ]

    if severed:
        # Do NOT default severed values to TRUSTED. Reclassify as
        # UNTRUSTED and force re-derivation by the agent.
        for cid in severed:
            for msg in rehydrated_context:
                if msg.get("call_id") == cid:
                    msg.setdefault("content_envelope", {})["taint"] = "UNTRUSTED"
                    msg["requires_revalidation"] = True
        raise TaintSeveranceError(
            f"taint labels severed across checkpoint for call_ids={severed}; "
            f"values reclassified UNTRUSTED and marked for re-fetch. "
            f"Sinks must fail closed until provenance is re-established."
        )

    return rehydrated_context
