# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-subtree-rollback-as-non-atomic-when-child-agents-have-already-emitted-irreversible-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-subtree-rollback-as-non-atomic-when-child-agents-have-already-emitted-irreversible-side-effects.warrant.json
# Markdown SHA-256:   43d4be3b90203b8fa049c29125194703f001d0f997e3001dba7ea6a7ab2c9154
# Code AST SHA-256:   5fba9c2cd7a10b5206b72e65f23164ef8d25d2fe7c8f047422a3dd12ad08bc80
# Verified Classes:   SpeculativeRollbackViolation, ToolEffectClass
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a speculative subtree is rolled back after committing an
    effect that the orchestrator cannot reconcile. Indicates the atomic-rollback
    assumption was violated at the tool transport layer."""
    pass


class ToolEffectClass:
    EFFECT_FREE = "effect_free"
    PROVISIONAL = "provisional"      # staged behind a commit/abort token
    RECONCILABLE = "reconcilable"    # irreversible but compensable via intent record
    IRREVERSIBLE = "irreversible"    # no handle, no compensation


def classify_subtree(tool_graph, entry_tool):
    """Transitive classification over the reachable tool graph.

    A subtree is only speculatable if EVERY reachable tool is effect-free or
    provisional. If any reachable tool is reconcilable, speculation requires
    intent records. If any is irreversible, the subtree must not be forked.
    """
    reachable = tool_graph.reachable_from(entry_tool)
    classes = {t: tool_graph.effect_class(t) for t in reachable}

    if any(c == ToolEffectClass.IRREVERSIBLE for c in classes.values()):
        return "serial_only"
    if any(c == ToolEffectClass.RECONCILABLE for c in classes.values()):
        return "speculate_with_intent"
    return "speculate_freely"


def fork_branch(orchestrator, branch_id, entry_tool):
    mode = classify_subtree(orchestrator.tool_graph, entry_tool)
    if mode == "serial_only":
        # Do not fork: effects cannot be undone if the verifier rejects.
        raise SpeculativeRollbackViolation(
            f"branch {branch_id}: entry tool {entry_tool} transitively reaches an "
            f"irreversible effect; subtree is not speculatable and must run "
            f"serially after verification."
        )
    if mode == "speculate_with_intent":
        orchestrator.register_intent_required(branch_id)
    return orchestrator.spawn(branch_id)


def emit_effect(orchestrator, branch_id, tool, args):
    """Every effect-emitting call from a speculative branch must be preceded by
    a durable intent record that survives branch rollback."""
    if not orchestrator.is_speculative(branch_id):
        return orchestrator.call_tool(tool, args)

    if not orchestrator.has_durable_intent(branch_id, tool, args):
        raise SpeculativeRollbackViolation(
            f"branch {branch_id}: effect-emitting call to {tool} dispatched "
            f"without a durable intent record; rollback would orphan the effect."
        )
    return orchestrator.call_tool(tool, args)


def rollback_branch(orchestrator, branch_id):
    """Rollback is a compensation pass, not a discard."""
    intents = orchestrator.intents_for(branch_id)
    uncompensated = [i for i in intents if not i.compensable]
    if uncompensated:
        raise SpeculativeRollbackViolation(
            f"branch {branch_id}: cannot roll back; {len(uncompensated)} effect(s) "
            f"have no compensation path: {[i.handle for i in uncompensated]}"
        )
    for intent in intents:
        orchestrator.compensate(intent)
    orchestrator.discard_state(branch_id)
