# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-agent-rollback-from-corrupting-externally-committed-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-agent-rollback-from-corrupting-externally-committed-side-effects.warrant.json
# Markdown SHA-256:   ea5177d0eaaf8141f51648d30e177ffb35f292a4c7c7f75afa69d3355e2fc9ab
# Code AST SHA-256:   ec5c8e3bde7d097ce2b6bd0487f92bd85b442497e8ba9e610935ef600e699830
# Verified Classes:   SpeculativeCommitViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculativeCommitViolation(RuntimeError):
    """Raised when a speculative branch attempts an effect that cannot be rolled back."""
    pass


UNBUFFERABLE = {"charge_card", "send_email", "delete_resource"}
BUFFERABLE = {"create_draft_branch", "post_review_comment", "enqueue_job"}


def assert_speculation_safe(reachable_tools: set[str], branch_state: str) -> None:
    if branch_state != "SPECULATIVE":
        return
    offenders = reachable_tools & UNBUFFERABLE
    if offenders:
        raise SpeculativeCommitViolation(
            f"speculative branch reaches unbufferable tools {sorted(offenders)}; "
            f"insert a promotion gate before these calls or disable speculation"
        )
    unknown = reachable_tools - BUFFERABLE - UNBUFFERABLE
    if unknown:
        raise SpeculativeCommitViolation(
            f"unclassified tools {sorted(unknown)} on speculative path; "
            f"classify as buffered-safe, namespace-safe, or unbufferable before forking"
        )


def promote_branch(branch, resume_pointer, promotion_token: str) -> None:
    if branch.state != "SPECULATIVE":
        raise SpeculativeCommitViolation(f"cannot promote branch in state {branch.state}")
    if branch.promotion_token == promotion_token:
        return  # idempotent promotion
    for effect in branch.outbox:
        effect.flush(idempotency_key=promotion_token)
    branch.promotion_token = promotion_token
    branch.state = "COMMITTED"
    resume_pointer.advance_to(branch.post_commit_snapshot)
