# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-invalidation-when-an-optimistic-result-has-already-tainted-downstream-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-invalidation-when-an-optimistic-result-has-already-tainted-downstream-state.warrant.json
# Markdown SHA-256:   5ca4e589cf4f0f84126ea62813ff10003725c000af95f0cc599db5fa0259aeda
# Code AST SHA-256:   bc5c262dc38df79262b507a834fc5e2c99592294094a04a001c4b323ac6239e4
# Verified Classes:   TaintLeakError, Speculation, SpeculativeExecutor
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Any, Callable


class TaintLeakError(RuntimeError):
    """Raised when a speculative value's taint closure cannot be fully
    invalidated, or when a retry is attempted before retraction completes."""
    pass


@dataclass
class Speculation:
    speculation_id: str
    assumed_result: Any
    tainted_nodes: list = field(default_factory=list)
    resolved: bool = False


class SpeculativeExecutor:
    def __init__(self):
        self._specs: dict[str, Speculation] = {}
        self._staged: dict[str, Any] = {}       # surface -> staged value
        self._committed: dict[str, Any] = {}     # surface -> live value
        self._ledger: dict[str, set] = {}        # speculation_id -> surfaces

    def speculate(self, spec_id: str, assumed_result: Any,
                  derived_writes: dict[str, Any]) -> None:
        # derived_writes maps surface-name -> value computed under assumption.
        # All are STAGED, never committed, until confirmation.
        spec = Speculation(spec_id, assumed_result)
        self._specs[spec_id] = spec
        self._ledger[spec_id] = set()
        for surface, value in derived_writes.items():
            self._staged[f"{spec_id}::{surface}"] = value
            self._ledger[spec_id].add(surface)

    def confirm(self, spec_id: str, real_result: Any) -> None:
        spec = self._specs[spec_id]
        if spec.assumed_result != real_result:
            raise TaintLeakError(
                f"confirm() called on divergent result for {spec_id}; "
                f"use invalidate()"
            )
        for key in list(self._staged):
            if key.startswith(f"{spec_id}::"):
                surface = key.split("::", 1)[1]
                self._committed[surface] = self._staged.pop(key)
        spec.resolved = True

    def invalidate(self, spec_id: str) -> None:
        # Walk full taint closure; retract every staged write.
        if spec_id not in self._ledger:
            raise TaintLeakError(f"unknown speculation {spec_id}")
        for key in list(self._staged):
            if key.startswith(f"{spec_id}::"):
                self._staged.pop(key)
        # A committed surface reachable from this spec is an unretractable leak.
        leaked = self._ledger[spec_id] & set(self._committed)
        if leaked:
            raise TaintLeakError(
                f"taint leak: surfaces {leaked} committed before confirmation "
                f"of {spec_id}; cannot retract"
            )
        self._ledger[spec_id].clear()
        self._specs[spec_id].resolved = True

    def retry(self, spec_id: str, fn: Callable[[], Any]) -> Any:
        # Retry must be blocked until retraction completes.
        if spec_id in self._specs and not self._specs[spec_id].resolved:
            raise TaintLeakError(
                f"retry attempted for {spec_id} before taint retraction"
            )
        return fn()

    def sweep(self) -> int:
        # Invariant check: zero live nodes bearing an orphaned taint.
        orphans = sum(len(v) for v in self._ledger.values())
        if orphans:
            raise TaintLeakError(f"{orphans} orphaned taint nodes remain")
        return 0
