# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-a-speculative-branch-it-cannot-roll-back-when-a-sibling-agent-s-tool-side-effect-lands-after-the-merge-barrier.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-a-speculative-branch-it-cannot-roll-back-when-a-sibling-agent-s-tool-side-effect-lands-after-the-merge-barrier.warrant.json
# Markdown SHA-256:   acdefd653f19db2156053220ec20691d6ed3024ca4f8b988dce6f0a792ecd2b2
# Code AST SHA-256:   bf4c2f4ae0486f47c7cb4e86efe4f02901b0cd5f4a5028c21070e605397b101b
# Verified Classes:   SpeculativeCommitError, EffectStatus, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class SpeculativeCommitError(RuntimeError):
    """Raised when optimistic commit would merge a branch whose side-effect
    durability is unconfirmed or whose rollback lacks a compensation."""
    pass


class EffectStatus(Enum):
    NOT_DISPATCHED = "not_dispatched"
    DISPATCHED_UNKNOWN = "dispatched_unknown"   # timeout: landed? unknown
    CONFIRMED_DURABLE = "confirmed_durable"
    COMPENSATED = "compensated"


@dataclass
class Branch:
    branch_id: str
    non_idempotent_handle: Optional[str] = None
    effect_status: EffectStatus = EffectStatus.NOT_DISPATCHED
    reads_sibling_effects: set = field(default_factory=set)


def probe_durability(handle: str, deadline_s: float = 2.0) -> EffectStatus:
    """Idempotency-keyed probe. In production this calls the resource API;
    here we simulate an unresolved timeout."""
    start = time.monotonic()
    while time.monotonic() - start < deadline_s:
        # real impl: if resource_api.exists(handle): return CONFIRMED_DURABLE
        time.sleep(0.1)
    return EffectStatus.DISPATCHED_UNKNOWN


def commit_merge_set(branches: list[Branch]) -> list[str]:
    """Optimistic commit with the durability invariant enforced.

    Invariant: a branch may be committed only if every effect it depends on
    (its own or a sibling's it read) is CONFIRMED_DURABLE, and any rollback
    carries a compensation, not a ledger-only edit.
    """
    by_handle = {b.non_idempotent_handle: b for b in branches if b.non_idempotent_handle}

    # Resolve every DISPATCHED_UNKNOWN to CONFIRMED_DURABLE or fail closed.
    for b in branches:
        if b.effect_status is EffectStatus.DISPATCHED_UNKNOWN:
            resolved = probe_durability(b.non_idempotent_handle)
            if resolved is not EffectStatus.CONFIRMED_DURABLE:
                raise SpeculativeCommitError(
                    f"branch {b.branch_id} effect {b.non_idempotent_handle} "
                    f"is UNKNOWN, not FAILED; refusing optimistic commit of siblings"
                )
            b.effect_status = resolved

    # Reject undeclared cross-branch dependency on an unconfirmed effect.
    for b in branches:
        for dep_handle in b.reads_sibling_effects:
            dep = by_handle.get(dep_handle)
            if dep is None or dep.effect_status is not EffectStatus.CONFIRMED_DURABLE:
                raise SpeculativeCommitError(
                    f"branch {b.branch_id} reads sibling effect {dep_handle} "
                    f"with status {dep.effect_status if dep else 'missing'}; "
                    f"must serialize after durability confirmation"
                )

    return [b.branch_id for b in branches]


def rollback_branch(branch: Branch, compensation: Optional[callable]) -> None:
    """Rollback must compensate the world, not just rewrite the ledger."""
    if branch.effect_status is EffectStatus.CONFIRMED_DURABLE and compensation is None:
        raise SpeculativeCommitError(
            f"branch {branch.branch_id} has durable effect "
            f"{branch.non_idempotent_handle} but no registered compensation; "
            f"ledger-only rollback would create a phantom dependency"
        )
    if compensation is not None:
        compensation()
    branch.effect_status = EffectStatus.COMPENSATED
