# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-speculative-rollback-of-an-irreversible-tool-effect-during-branch-and-rollback-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-speculative-rollback-of-an-irreversible-tool-effect-during-branch-and-rollback-multi-agent-execution.warrant.json
# Markdown SHA-256:   d07f94bafee873a0e0e33a0d2425a0565a37713cfd710bb166ac3ac43753c847
# Code AST SHA-256:   73b56ae11301398b0ae627013361aa0b5e575bacff2a2fd0bcc1af1b47428154
# Verified Classes:   IrreversibleSpeculativeEffect, EffectClass, CompensationFidelity
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class IrreversibleSpeculativeEffect(RuntimeError):
    """Raised when a losing branch emitted a non-compensable effect and rollback cannot restore pre-effect state."""
    pass


class EffectClass:
    STAGED = "staged"            # effect held in orchestrator-controlled outbox; discard is local
    IMMEDIATE = "immediate"      # effect emitted to external system on call


class CompensationFidelity:
    EXTERNAL_VERIFIED = "external_verified"  # compensation postcondition readable from external system
    LOCAL_ONLY = "local_only"                # compensation mutates local state only; no external proof


def classify_tool(tool) -> tuple[str, str]:
    return tool.effect_class, tool.compensation_fidelity


def may_speculate(tool) -> bool:
    effect, fidelity = classify_tool(tool)
    if effect == EffectClass.STAGED:
        return True
    if effect == EffectClass.IMMEDIATE and fidelity == CompensationFidelity.EXTERNAL_VERIFIED:
        return True
    return False  # IMMEDIATE + LOCAL_ONLY: must serialize or lease


def rollback_branch(branch, tool_registry, external_reader):
    """Attempt to compensate a losing branch. Refuses when the effect is irreversible."""
    for effect in reversed(branch.committed_effects):
        tool = tool_registry[effect.tool_name]
        effect_class, fidelity = classify_tool(tool)

        if effect_class == EffectClass.STAGED:
            tool.discard_staged(effect.staging_id)
            branch.mark_rolled_back(effect)
            continue

        if fidelity == CompensationFidelity.LOCAL_ONLY:
            # Compensation would report success without restoring the world.
            raise IrreversibleSpeculativeEffect(
                f"branch {branch.id} emitted {effect.tool_name} with local-only compensation; "
                f"effect is non-compensable and must be reconciled, not rolled back"
            )

        # EXTERNAL_VERIFIED: compensate, then read back the external state.
        tool.compensate(effect)
        post = external_reader.read(effect.external_ref)
        if not post.equals(effect.pre_effect_snapshot):
            raise IrreversibleSpeculativeEffect(
                f"compensation for {effect.tool_name} returned success but external readback "
                f"diverges from pre-effect state; ledger/world split detected"
            )
        branch.mark_rolled_back(effect)
