# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-branch-commits-as-non-idempotent-under-rollback-and-merge-task-graphs.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-branch-commits-as-non-idempotent-under-rollback-and-merge-task-graphs.warrant.json
# Markdown SHA-256:   38c7916dca9c546144a7ec55817692584a853145e10b026f0d51b2fc0a52dfb4
# Code AST SHA-256:   5d3fc5dc58d73f4fb25eb6fa5e884eb97958dbd648e3cd3ad334c987f47adf5d
# Verified Classes:   SpeculativeRollbackViolation, Tool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a branch's side effects cannot be reverted before merge."""
    pass


class Tool:
    def __init__(self, name, speculation_safe, has_compensator, namespaced):
        self.name = name
        self.speculation_safe = speculation_safe
        self.has_compensator = has_compensator
        self.namespaced = namespaced


def assert_branch_speculable(branch_id, planned_tools):
    """Reject a branch at fork time if any planned tool cannot be rolled back."""
    for tool in planned_tools:
        if tool.speculation_safe:
            continue
        if tool.has_compensator or tool.namespaced:
            continue
        raise SpeculativeRollbackViolation(
            f"branch {branch_id} plans non-compensable, un-namespaced tool "
            f"'{tool.name}'; cannot speculate without contaminating shared state. "
            f"Degrade to serial execution after merge decision."
        )


def verify_rollback(branch_id, environment_diff, journal_drained):
    """Rollback is a claim, not a flag: verify the environment is clean."""
    if environment_diff:
        raise SpeculativeRollbackViolation(
            f"branch {branch_id} reported ROLLED_BACK but environment diff is "
            f"non-empty: {environment_diff}. Losers' effects persist."
        )
    if not journal_drained:
        raise SpeculativeRollbackViolation(
            f"branch {branch_id} compensation journal not drained; "
            f"inverse replay incomplete."
        )
    return True
