# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-runs-speculative-tool-branches-past-an-unlabeled-injection-signal-taint-propagation-gaps-in-speculative-execution-gating.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-runs-speculative-tool-branches-past-an-unlabeled-injection-signal-taint-propagation-gaps-in-speculative-execution-gating.warrant.json
# Markdown SHA-256:   dc0763a8732f1071d40f651eddcfd57d7c579d9f1b130d0e1ee1d5a349265e49
# Code AST SHA-256:   b056088d02de5bb1ddad57a9feacf12bce1d6663d9f8f335328f5eebf6248e77
# Verified Classes:   TaintGateError, Disposition, RiskEvent, SpeculativeBranch, SpeculativeExecutor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class TaintGateError(RuntimeError):
    """Raised when a speculative branch set cannot soundly resolve a risk event."""
    pass


class Disposition(Enum):
    HALT_BRANCH = "halt_branch"
    HALT_ALL = "halt_all"
    CLEARED = "cleared"


@dataclass
class RiskEvent:
    score: float
    branch_id: Optional[int]
    scope: Optional[str]          # "global" or None
    timestamp_ms: int
    resolver: Optional[str] = None


@dataclass
class SpeculativeBranch:
    branch_id: int
    committed: bool = False
    committed_at_ms: Optional[int] = None


@dataclass
class SpeculativeExecutor:
    active: dict = field(default_factory=dict)
    threshold: float = 0.7
    window_end_ms: int = 1000

    def resolve_event(self, e: RiskEvent) -> Disposition:
        if e.score <= self.threshold:
            return Disposition.CLEARED
        if e.branch_id is not None and e.branch_id in self.active:
            return Disposition.HALT_BRANCH
        if e.scope == "global":
            return Disposition.HALT_ALL
        if e.resolver is not None:
            return Disposition.CLEARED
        # Unlabeled, unscoped, unresolved: blocking ambiguity.
        raise TaintGateError(
            f"unlabeled risk event score={e.score} at t={e.timestamp_ms}ms "
            f"has no branch binding, no global scope, and no resolver; "
            f"fail-closed required"
        )

    def gate(self, events: list) -> None:
        for e in events:
            try:
                disp = self.resolve_event(e)
            except TaintGateError:
                # Fail closed: halt every in-flight branch.
                for b in self.active.values():
                    if b.committed and b.committed_at_ms is not None \
                            and b.committed_at_ms <= self.window_end_ms:
                        raise TaintGateError(
                            f"late-taint: branch {b.branch_id} committed at "
                            f"{b.committed_at_ms}ms before unlabeled event "
                            f"at {e.timestamp_ms}ms; quarantine required"
                        )
                self.active.clear()
                raise
            if disp is Disposition.HALT_BRANCH:
                self.active.pop(e.branch_id, None)
            elif disp is Disposition.HALT_ALL:
                self.active.clear()


def run_fanout(executor: SpeculativeExecutor, events: list) -> None:
    if not executor.active:
        raise TaintGateError("no active branches to gate")
    executor.gate(events)


if __name__ == "__main__":
    ex = SpeculativeExecutor(active={
        1: SpeculativeBranch(1),
        2: SpeculativeBranch(2),
        3: SpeculativeBranch(3),
    })
    # Injected doc classifier output: score high, no lineage.
    run_fanout(ex, [RiskEvent(score=0.91, branch_id=None, scope=None,
                              timestamp_ms=340)])
