# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-the-orphaned-speculative-branch-when-rollback-safe-tool-invocation-and-branch-reconciliation-disagree-on-commit-order.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-the-orphaned-speculative-branch-when-rollback-safe-tool-invocation-and-branch-reconciliation-disagree-on-commit-order.warrant.json
# Markdown SHA-256:   348c6adcc25f703f30fae8c8fe1c7d5a06ce890fae8f5aa420820dc92488d5a9
# Code AST SHA-256:   609b42559a3ee8620c228aef5fbd7525cc4943324e172927a7697f023b8270f8
# Verified Classes:   OrphanedSpeculativeBranchError, BranchRecord, ReconciliationLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, List


class OrphanedSpeculativeBranchError(RuntimeError):
    """Raised when reconciliation commits before sibling compensation acknowledges."""
    pass


@dataclass
class BranchRecord:
    branch_id: str
    last_tool_call_ts: float = 0.0
    compensation_ack_ts: float = 0.0
    ledger_state: str = "SPECULATING"  # SPECULATING | COMMITTED | COMPENSATING | ROLLED_BACK


@dataclass
class ReconciliationLedger:
    branches: Dict[str, BranchRecord] = field(default_factory=dict)
    commit_ts: float = 0.0

    def record_commit(self, branch_id: str, ts: float) -> None:
        self.branches[branch_id].ledger_state = "COMMITTED"
        self.branches[branch_id].last_tool_call_ts = ts
        self.commit_ts = ts

    def record_compensation_ack(self, branch_id: str, ts: float) -> None:
        self.branches[branch_id].compensation_ack_ts = ts
        self.branches[branch_id].ledger_state = "ROLLED_BACK"


def reconcile_join_point(ledger: ReconciliationLedger, selected: str) -> None:
    """Release the join point only if no sibling is orphaned.

    Orphan condition: a sibling's last tool call or compensation ack
    occurs after the reconciliation commit timestamp.
    """
    orphans: List[str] = []
    for bid, rec in ledger.branches.items():
        if bid == selected:
            continue
        if rec.ledger_state == "COMPENSATING":
            orphans.append(bid)
            continue
        if rec.compensation_ack_ts > ledger.commit_ts:
            orphans.append(bid)
            continue
        if rec.last_tool_call_ts > ledger.commit_ts:
            orphans.append(bid)

    if orphans:
        raise OrphanedSpeculativeBranchError(
            f"Join point released with orphaned branches {orphans}; "
            f"commit_ts={ledger.commit_ts:.6f}, "
            f"acks={[ledger.branches[b].compensation_ack_ts for b in orphans]}. "
            f"Re-run from pre-dispatch snapshot; do not re-issue compensation."
        )


def run_join(ledger: ReconciliationLedger, selected: str) -> str:
    reconcile_join_point(ledger, selected)
    return f"released:{selected}"


# --- demonstration of the orphan ---
ledger = ReconciliationLedger()
ledger.branches["A"] = BranchRecord("A")
ledger.branches["B"] = BranchRecord("B")

now = time.time()
ledger.record_commit("A", now)
# B's compensation was dispatched but acknowledged AFTER the commit:
ledger.branches["B"].ledger_state = "COMPENSATING"
ledger.record_compensation_ack("B", now + 0.050)

try:
    run_join(ledger, selected="A")
except OrphanedSpeculativeBranchError as e:
    print(f"detected: {e}")
