# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-tool-call-prefetching-when-a-taint-label-escalation-invalidates-the-speculative-branch-mid-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-tool-call-prefetching-when-a-taint-label-escalation-invalidates-the-speculative-branch-mid-flight.warrant.json
# Markdown SHA-256:   7183284ff04291d29c99779306c7c507bed10d8e591f8720c68e1f179bc10f3b
# Code AST SHA-256:   6c7a313d3e8cf9950519609980fc1931561502c1e3a67eb755a26dad702a9c7f
# Verified Classes:   TaintLabel, TaintedEffectLeak, SpeculativeCall, EffectLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class TaintLabel(Enum):
    INTERNAL_VERIFIED = 0
    LOW_INTEGRITY = 1
    TAINTED_EXTERNAL = 2


class TaintedEffectLeak(RuntimeError):
    """Raised when a taint escalation reaches an in-flight effectful
    speculative call that has no registered compensation token."""


@dataclass
class SpeculativeCall:
    call_id: str
    effectful: bool
    ancestor_segments: frozenset
    compensation_token: Optional[str]
    dispatched: bool = True
    committed: bool = False
    invalidated: bool = False
    compensated: bool = False


@dataclass
class EffectLedger:
    entries: dict = field(default_factory=dict)

    def record(self, call_id: str, state: str) -> None:
        self.entries[call_id] = state


def on_taint_escalation(
    escalated_segment: str,
    in_flight: list,
    ledger: EffectLedger,
) -> list:
    """Apply the decision boundary. Returns the list of call_ids that
    required compensation. Raises TaintedEffectLeak if an effectful
    call is reachable from the escalated segment with no compensation."""
    to_compensate = []
    for call in in_flight:
        reachable = escalated_segment in call.ancestor_segments
        if not reachable:
            continue
        if not call.effectful:
            call.invalidated = True
            ledger.record(call.call_id, "invalidated-no-effect")
            continue
        if call.compensation_token is None:
            ledger.record(call.call_id, "leaked")
            raise TaintedEffectLeak(
                f"speculative call {call.call_id} is effectful and reachable "
                f"from escalated segment {escalated_segment!r} but was "
                f"dispatched without a compensation token; halting trajectory "
                f"to prevent silent tainted write"
            )
        call.invalidated = True
        call.compensated = True
        ledger.record(call.call_id, "committed-then-compensated")
        to_compensate.append(call.call_id)
    return to_compensate
