# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-tool-result-before-it-re-enters-the-reasoning-loop-rather-than-trusting-downstream-re-derivati.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-tool-result-before-it-re-enters-the-reasoning-loop-rather-than-trusting-downstream-re-derivati.warrant.json
# Markdown SHA-256:   a97e81c9557ab550d68a94fdf7fa4c5492c677b1b28caf5066b2239b887207b4
# Code AST SHA-256:   d5d16108a6bd7b6e7f47d38df9fae504a9a0f632f9731531a41a50d5652566ee
# Verified Classes:   TaintViolation, Label, TaintedValue, PureStructuralHop, SemanticHop
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class TaintViolation(RuntimeError):
    """Raised when a tainted value is promoted to trusted without an audited declassification."""
    pass


class Label(Enum):
    TRUSTED = "trusted"
    TAINTED = "tainted"


@dataclass(frozen=True)
class TaintedValue:
    payload: object
    label: Label
    provenance: FrozenSet[str] = field(default_factory=frozenset)

    def join(self, other: "TaintedValue") -> "TaintedValue":
        # Structural join: taint is the union of ancestry, never re-derived
        # from the output's surface form.
        merged_label = (
            Label.TAINTED
            if Label.TAINTED in (self.label, other.label)
            else Label.TRUSTED
        )
        return TaintedValue(
            payload=self.payload,
            label=merged_label,
            provenance=self.provenance | other.provenance,
        )


class PureStructuralHop:
    """A hop with a proven non-influence property: cannot carry injected semantics."""

    NON_INFLUENCE_PROOF = "output is a pure function of input bytes with no semantic channel"

    def apply(self, value: TaintedValue) -> TaintedValue:
        # Only permitted to re-evaluate when the proof is present AND audited.
        if not self.NON_INFLUENCE_PROOF:
            raise TaintViolation("structural hop lacks non-influence proof")
        return TaintedValue(
            payload=hash(value.payload),
            label=Label.TRUSTED,  # declassified: hash carries no semantics
            provenance=value.provenance,
        )


class SemanticHop:
    """A hop (summarize, translate, embed) that CAN launder taint. Must join."""

    def apply(self, value: TaintedValue) -> TaintedValue:
        # The output is a new value, but its label is inherited structurally.
        transformed = _summarize(value.payload)
        return TaintedValue(
            payload=transformed,
            label=value.label,  # NOT re-inspected; inherited
            provenance=value.provenance | {"semantic_hop"},
        )


def admit_to_reasoning_loop(value: TaintedValue) -> object:
    if value.label is Label.TAINTED:
        # Quarantine means EXCLUDED from context, not annotated in context.
        raise TaintViolation(
            f"tainted value from {sorted(value.provenance)} cannot enter "
            f"reasoning loop; route to quarantine, require trusted oracle "
            f"for declassification"
        )
    return value.payload


def _summarize(payload: object) -> object:
    return f"summary_of({payload!r})"


# Failure trace: content-based re-inspection drops the label at the semantic hop.
page = TaintedValue(payload="<html>...injected footnote...</html>", label=Label.TAINTED, provenance={"fetch_page"})
summary = SemanticHop().apply(page)          # label inherited: TAINTED
entities = SemanticHop().apply(summary)      # label inherited: TAINTED
try:
    admit_to_reasoning_loop(entities)        # correctly refused
except TaintViolation as exc:
    print(f"quarantined: {exc}")
