# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-tool-call-branches-before-commit-and-how-does-rollback-divergence-corrupt-downstream-agent-st.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-tool-call-branches-before-commit-and-how-does-rollback-divergence-corrupt-downstream-agent-st.warrant.json
# Markdown SHA-256:   4ce938d64e93044f5e9a4839a5b99f85fefd3a2790d3326732882b25e3207889
# Code AST SHA-256:   dbf9e317050a539e1aec46938ef42c2ce6d95ac367a2f70a82a6dd1152a95d52
# Verified Classes:   SpeculationCommitError, SpeculativeCall, StagingArea
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass, field
from typing import Optional


class SpeculationCommitError(RuntimeError):
    """Raised when a speculative branch's effects escape containment or
    its rollback cannot reach every derived artifact."""


@dataclass
class SpeculativeCall:
    speculation_id: str
    tool: str
    args: dict
    effect_set: frozenset          # names of external stores / peers touched
    depends_on_content: bool       # args derived from unverified prior content
    staged: bool = False


@dataclass
class StagingArea:
    artifacts: dict = field(default_factory=dict)   # speculation_id -> artifact
    tombstones: set = field(default_factory=set)    # speculation_ids rolled back


def dispatch_speculative(
    call: SpeculativeCall,
    prior_verified: bool,
    staging: StagingArea,
    containable_stores: frozenset,
) -> str:
    # Invariant 1: effect containment.
    escaped = call.effect_set - containable_stores
    if escaped:
        raise SpeculationCommitError(
            f"speculation {call.speculation_id} for tool {call.tool!r} "
            f"touches non-containable stores {sorted(escaped)}; "
            f"abort before commit and run sequentially"
        )

    # Invariant 3: prediction validity under partial results.
    if call.depends_on_content and not prior_verified:
        raise SpeculationCommitError(
            f"speculation {call.speculation_id} depends on unverified prior "
            f"content; abort until verifier acks"
        )

    # Invariant 2: rollback reachability — every staged artifact must carry
    # the causal token so rollback can enumerate descendants.
    staging.artifacts[call.speculation_id] = {
        "tool": call.tool,
        "args": call.args,
        "token": call.speculation_id,
    }
    return call.speculation_id


def rollback(speculation_id: str, staging: StagingArea) -> None:
    if speculation_id not in staging.artifacts:
        raise SpeculationCommitError(
            f"rollback target {speculation_id} not staged; "
            f"effects may have already escaped — escalate to reconciliation"
        )
    del staging.artifacts[speculation_id]
    staging.tombstones.add(speculation_id)


def consume(speculation_id: str, staging: StagingArea) -> dict:
    if speculation_id in staging.tombstones:
        raise SpeculationCommitError(
            f"consumer read tombstoned artifact {speculation_id}; "
            f"propagating ghost state — halt downstream agent"
        )
    return staging.artifacts[speculation_id]
