# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-tool-call-prefetch-has-escaped-its-safety-envelope-before-the-abort-barrier-completes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-tool-call-prefetch-has-escaped-its-safety-envelope-before-the-abort-barrier-completes.warrant.json
# Markdown SHA-256:   51d3e32da8046106110696c1dbb3378f2d75809d0cee10d13d2740fe807c9995
# Code AST SHA-256:   9c305aa1ee1d17a84f729027f2fbb6f6cd3a88dcc1bf91119b0d3a460a951e40
# Verified Classes:   EnvelopeBreachError, SpeculativeEffect
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class EnvelopeBreachError(RuntimeError):
    """Raised when a speculative effect may be durable despite a clean abort."""
    pass


class SpeculativeEffect:
    def __init__(self, effect_id, tool, commit_horizon_s, reversible, compensation):
        self.effect_id = effect_id
        self.tool = tool
        self.commit_horizon_s = commit_horizon_s
        self.reversible = reversible
        self.compensation = compensation


def enforce_abort_envelope(effects, abort_returned, tool_state, elapsed_s):
    """
    Validate that aborting speculation did not leave durable effects
    outside the ledger. `tool_state` maps effect_id -> 'applied' | 'absent' | 'unknown'.
    """
    if not abort_returned:
        raise EnvelopeBreachError(
            "abort barrier did not complete; envelope cannot be asserted"
        )

    breaches = []
    for eff in effects:
        state = tool_state.get(eff.effect_id, "unknown")

        if state == "applied":
            breaches.append((eff.effect_id, "applied_despite_abort"))

        elif state == "unknown":
            # Ambiguity is itself a breach if we are past the commit horizon.
            if elapsed_s >= eff.commit_horizon_s:
                breaches.append((eff.effect_id, "unresolved_past_commit_horizon"))

        elif state == "absent":
            continue

    if breaches:
        raise EnvelopeBreachError(
            f"speculative envelope breached at data plane: {breaches}; "
            f"abort was a control-plane-only success"
        )

    # Envelope clean only if every effect is confirmed absent or compensated.
    return True


def speculate(effects, abort_returned, tool_state, elapsed_s):
    try:
        return enforce_abort_envelope(effects, abort_returned, tool_state, elapsed_s)
    except EnvelopeBreachError:
        # Escalate: schedule compensations for every applied/unresolved effect.
        for eff in effects:
            if tool_state.get(eff.effect_id) in ("applied", "unknown"):
                if eff.reversible and eff.compensation is not None:
                    eff.compensation(eff.effect_id)
                else:
                    raise EnvelopeBreachError(
                        f"irreversible effect {eff.effect_id} escaped envelope; "
                        f"no compensation available"
                    )
        raise
