# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-before-side-effecting-tool-calls-reconcile-on-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-before-side-effecting-tool-calls-reconcile-on-rollback.warrant.json
# Markdown SHA-256:   45dbbd5224d10a46950e616e1e525cea13355b5e2d4f4d15c9cb444a763cccb5
# Code AST SHA-256:   94934005173bd249a9ad308f272fe302933ade1d500c73f5270d50b2226a08cf
# Verified Classes:   SpeculativeEffectViolation, EffectClass
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeEffectViolation(RuntimeError):
    """Raised when a speculative branch would commit a non-reconcilable effect."""
    pass


class EffectClass:
    def __init__(self, idempotent: bool, reversible: bool, task_scoped_key: bool):
        self.idempotent = idempotent
        self.reversible = reversible
        self.task_scoped_key = task_scoped_key

    def safe_to_speculate(self) -> bool:
        # Idempotent under a task-scoped key collapses duplicates at the store.
        # Reversible effects may be compensated only if branch identity survives.
        return self.idempotent and self.task_scoped_key


def dispatch_speculative(branch, tool_name, effect: EffectClass, has_commit_lease: bool):
    if not effect.safe_to_speculate() and not has_commit_lease:
        raise SpeculativeEffectViolation(
            f"branch {branch.id} attempted speculative dispatch of non-idempotent "
            f"tool {tool_name!r} without a commit lease; this effect cannot be "
            f"reconciled on rollback and would orphan in the effect store"
        )
    return branch.invoke(tool_name)


def rollback_branch(branch, committed_effects):
    if committed_effects:
        # Do NOT discard: retain identity so a reconciler can authorize reversal.
        branch.state = "QUARANTINED"
        raise SpeculativeEffectViolation(
            f"branch {branch.id} holds {len(committed_effects)} durable non-idempotent "
            f"effect(s); discard forbidden, promoted to QUARANTINED pending reconciliation"
        )
    branch.state = "DISCARDED"
    return branch.state
