# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-execute-downstream-agents-before-its-own-verification-gate-commits-and-how-does-rollback-leak-unverified-side-effec.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-execute-downstream-agents-before-its-own-verification-gate-commits-and-how-does-rollback-leak-unverified-side-effec.warrant.json
# Markdown SHA-256:   fb0b87913d94837bcdab43d6830cf41356cba6bb487c031306a0c553cd3d9a45
# Code AST SHA-256:   8fbd48579acfaeae5631fbcb9be958fb652830287c42cc7a276785fb30da8399
# Verified Classes:   SpeculativeEffectLeak, EffectClass
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeEffectLeak(RuntimeError):
    """Raised when a speculative branch performs an irreversible effect
    before its governing verification gate has committed the input."""
    pass


class EffectClass:
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"


def dispatch_speculative(branch, governing_gate, effect_log, tool_registry):
    """Dispatch a downstream agent speculatively against an uncommitted input.

    Invariant: irreversible tools may only be invoked as recorded intents
    until governing_gate commits. Any direct irreversible call is a leak.
    """
    if not governing_gate.is_committed(branch.input_ref):
        # Speculative window: swap irreversible tools for intent recorders.
        for tool_name in branch.declared_tools:
            cls = tool_registry.classify(tool_name)
            if cls == EffectClass.IRREVERSIBLE:
                branch.bind(tool_name, effect_log.recorder(tool_name))

    result = branch.run()

    # Detect any irreversible effect that escaped the staging authority.
    leaked = [
        e for e in effect_log.committed_effects(branch.id)
        if tool_registry.classify(e.tool_name) == EffectClass.IRREVERSIBLE
        and not governing_gate.is_committed(branch.input_ref)
    ]
    if leaked:
        raise SpeculativeEffectLeak(
            f"branch {branch.id} executed irreversible effects "
            f"{[e.tool_name for e in leaked]} before gate "
            f"{governing_gate.id} committed input {branch.input_ref}; "
            f"these cannot be rolled back, only compensated"
        )

    if governing_gate.verdict(branch.input_ref) == "reject":
        effect_log.discard_intents(branch.id)  # reference drop, not compensation
        return None
    effect_log.flush_intents(branch.id)        # now safe to mutate the world
    return result
