# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tool-pre-execution-has-crossed-the-commit-horizon-the-pre-execution-commit-divergence-boundary-in-probabi.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tool-pre-execution-has-crossed-the-commit-horizon-the-pre-execution-commit-divergence-boundary-in-probabi.warrant.json
# Markdown SHA-256:   7f41b7a96b4c9db08d7a7f3e3523b79925d17be45577292773cfb38cf895c00e
# Code AST SHA-256:   ccdc0496c02af56334931a00bd706f21d0bae025c6be91bd8cfb421e9c949038
# Verified Classes:   CommitHorizonViolation, EffectClass, SpeculativeEffect, SpeculationBatch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List


class CommitHorizonViolation(RuntimeError):
    """Raised when a batch abort is attempted after an effect externalized."""
    pass


class EffectClass(Enum):
    STAGED = "staged"            # locally buffered, no external witness
    EXTERNALIZED = "externalized"  # acknowledged by an external system


@dataclass
class SpeculativeEffect:
    name: str
    effect_class: EffectClass = EffectClass.STAGED
    external_witness_at: float | None = None
    compensated: bool = False


@dataclass
class SpeculationBatch:
    effects: Dict[str, SpeculativeEffect] = field(default_factory=dict)
    commit_horizon_crossed: bool = False

    def observe_response(self, name: str, response_class: EffectClass) -> None:
        eff = self.effects[name]
        eff.effect_class = response_class
        if response_class is EffectClass.EXTERNALIZED:
            eff.external_witness_at = time.monotonic()
            self.commit_horizon_crossed = True

    def abort(self) -> None:
        # The invariant: batch abort is only atomic while nothing externalized.
        if self.commit_horizon_crossed:
            externalized = [
                e.name for e in self.effects.values()
                if e.effect_class is EffectClass.EXTERNALIZED and not e.compensated
            ]
            raise CommitHorizonViolation(
                "batch abort attempted after commit horizon crossed; "
                f"uncompensated externalized effects: {externalized}. "
                "Route through compensation plan, not rollback."
            )
        for eff in self.effects.values():
            eff.effect_class = EffectClass.STAGED  # discard staged work


def safe_abort(batch: SpeculationBatch, compensation_plan: Dict[str, bool]) -> List[str]:
    """Abort if below horizon; otherwise compensate externalized effects only."""
    if not batch.commit_horizon_crossed:
        batch.abort()
        return []

    uncompensated = []
    for name, eff in batch.effects.items():
        if eff.effect_class is EffectClass.EXTERNALIZED:
            if compensation_plan.get(name):
                eff.compensated = True
            else:
                uncompensated.append(name)
    if uncompensated:
        # Surface divergence rather than pretending the abort succeeded.
        raise CommitHorizonViolation(
            f"divergence: externalized effects without compensation: {uncompensated}"
        )
    return [n for n, e in batch.effects.items() if e.compensated]
