# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-speculative-tool-call-as-non-idempotent-and-refuse-rollback-only-reconciliation-across-a-multi-agent-branch.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-speculative-tool-call-as-non-idempotent-and-refuse-rollback-only-reconciliation-across-a-multi-agent-branch.warrant.json
# Markdown SHA-256:   8ebf315544601017671236b563c238558fd9cb336794d74dcbc6e6770dbbac34
# Code AST SHA-256:   72486c271f2c99b2869adcf0e14a2ea46d0116386f0389bbfd80df5c117b7545
# Verified Classes:   SpeculativeRollbackViolation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a branch is abandoned after dispatching a non-retractable effect."""
    pass


SIDE_EFFECT_CLASSES = {"pure", "idempotent", "compensable", "external_nonidempotent"}


def assert_rollback_safe(branch, tool_manifest):
    """
    Call before abandoning a speculative branch. Refuses rollback-only
    reconciliation if any dispatched call escaped orchestrator state
    without a dedup key or a registered compensator.
    """
    for call in branch.dispatched_calls:
        manifest = tool_manifest[call.tool_name]
        effect_class = manifest.get("side_effect_class", "external_nonidempotent")

        if effect_class == "pure":
            continue
        if effect_class == "idempotent" and call.dedup_key is not None:
            continue
        if effect_class == "compensable" and call.compensator is not None:
            continue

        raise SpeculativeRollbackViolation(
            f"branch {branch.id} cannot be rolled back: tool "
            f"{call.tool_name!r} (class={effect_class}) dispatched without "
            f"dedup_key or compensator; external effect is already live and "
            f"would orphan on reconciliation. Require commit-gate staging or "
            f"register a compensator before abandoning."
        )
    return True
