# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tool-result-derived-context-segment-when-taint-labels-are-lost-at-the-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tool-result-derived-context-segment-when-taint-labels-are-lost-at-the-tool-boundary.warrant.json
# Markdown SHA-256:   0edbf7c85da8414f0a2661c7ede425a29cb032455f2907d15f5e39ce14438010
# Code AST SHA-256:   7185a406739fe5daeed9ba20e7f9257340ee79754988824ba7e79997fd0b0eac
# Verified Classes:   ProvenanceGapError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ProvenanceGapError(RuntimeError):
    """Raised when a context segment's taint cannot be proven from labeled sources."""
    pass


def taint_join(source_labels):
    # Taint is a join: untrusted dominates, unknown is treated as untrusted.
    if not source_labels:
        return "unknown"
    if "untrusted" in source_labels or "unknown" in source_labels:
        return "untrusted"
    return "trusted"


def derive_segment(source_labels, transform_is_labeled):
    if not transform_is_labeled:
        # Derivation dropped the label; provenance is now unprovable.
        raise ProvenanceGapError(
            f"unlabeled transform over sources {source_labels!r}: provenance closure unknown"
        )
    return taint_join(source_labels)


def guard_action(action_name, input_segment_labels, derivation_labeled):
    try:
        closure = derive_segment(input_segment_labels, derivation_labeled)
    except ProvenanceGapError as e:
        # Fail closed: unknown provenance is at least as restrictive as untrusted.
        raise ProvenanceGapError(
            f"blocked action {action_name!r}: {e}"
        ) from e

    if closure != "trusted":
        raise ProvenanceGapError(
            f"blocked action {action_name!r}: provenance closure is {closure!r}"
        )
    return "admitted"


# Failure trace: tool result tainted, paraphrased by an unlabeled model turn.
try:
    guard_action("transfer_funds", ["untrusted"], derivation_labeled=False)
except ProvenanceGapError as err:
    print("quarantined:", err)
