# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-parallel-branch-has-silently-committed-a-non-idempotent-side-effect-before-conflict-resolution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-parallel-branch-has-silently-committed-a-non-idempotent-side-effect-before-conflict-resolution.warrant.json
# Markdown SHA-256:   01053c1989ca3473c152f3a3149d76ae9da447bf580ffd1aa959875628352913
# Code AST SHA-256:   9d96027c539bb9b55f2a7c8c51b797ca8ddd9c1ec464918276e55a0172b61f20
# Verified Classes:   SpeculativeCommitViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeCommitViolation(RuntimeError):
    """Raised when a discarded branch is found to have committed an external side effect."""
    pass


COMMIT_REQUIRED = {"send_email", "charge_card", "post_message", "write_row"}
SPECULATABLE = {"read_record", "search", "draft_text"}


def classify_branch_tools(granted_tools: set[str]) -> dict[str, str]:
    classification = {}
    for tool in granted_tools:
        if tool in SPECULATABLE:
            classification[tool] = "speculatable"
        elif tool in COMMIT_REQUIRED:
            classification[tool] = "commit-required"
        else:
            # Unknown tools are never speculatable. This is the gate.
            classification[tool] = "commit-required"
    return classification


def assert_speculation_safe(branch_id: str, granted_tools: set[str]) -> None:
    cls = classify_branch_tools(granted_tools)
    unsafe = [t for t, c in cls.items() if c == "commit-required"]
    if unsafe:
        raise SpeculativeCommitViolation(
            f"branch {branch_id} granted commit-required tools {unsafe}; "
            f"must run pessimistic, not speculative"
        )


def reconcile_resolution(resolution: dict, external_log: list[dict]) -> None:
    """Called after conflict resolution. Detects orphaned side effects."""
    committed_ids = {
        call["message_id"]
        for branch in resolution["branches"]
        if branch["status"] == "committed"
        for call in branch.get("tool_calls", [])
        if call["tool"] in COMMIT_REQUIRED
    }
    for entry in external_log:
        if entry["tool"] not in COMMIT_REQUIRED:
            continue
        if entry["message_id"] not in committed_ids:
            raise SpeculativeCommitViolation(
                f"orphaned side effect: {entry['tool']} -> {entry['message_id']} "
                f"from branch {entry['branch_id']} marked discarded; "
                f"external state diverged from resolver ledger"
            )
