# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-speculative-tool-invocation-whose-side-effect-committed-before-the-rollback-barrier-closed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-speculative-tool-invocation-whose-side-effect-committed-before-the-rollback-barrier-closed.warrant.json
# Markdown SHA-256:   c4e832e06c8c3266cdc2bf1a6ecc2c18cfdc875397b622aa3b99a66db3b276ec
# Code AST SHA-256:   66f7109f361272f448248c88ae21ef8bb43b74a1d391bacd191f83ce00d290ea
# Verified Classes:   RollbackInvariantError, EffectStatus, ToolEffect, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class RollbackInvariantError(RuntimeError):
    """Raised when a branch is marked cleanly rolled back despite unproven effects."""
    pass


class EffectStatus(Enum):
    NEVER_DISPATCHED = "never_dispatched"
    COMPENSATED = "compensated"
    REJECTED = "rejected"
    COMMITTED = "committed"
    COMMITTED_UNKNOWN = "committed_unknown"


@dataclass
class ToolEffect:
    branch_id: str
    tool: str
    args: dict
    external_id: Optional[str]
    status: EffectStatus
    dispatched_at: float
    settled_at: Optional[float] = None


@dataclass
class Branch:
    branch_id: str
    effects: list = field(default_factory=list)


CLEAN_STATUSES = {
    EffectStatus.NEVER_DISPATCHED,
    EffectStatus.COMPENSATED,
    EffectStatus.REJECTED,
}


def close_rollback_barrier(branch: Branch, settle_timeout_s: float = 5.0) -> None:
    """
    Drain in-flight tool calls, then verify the branch has no live effects.
    Any effect still COMMITTED or COMMITTED_UNKNOWN at barrier close is an
    open obligation and must not be silently discarded.
    """
    deadline = time.monotonic() + settle_timeout_s

    for eff in branch.effects:
        while eff.settled_at is None and time.monotonic() < deadline:
            time.sleep(0.05)
        if eff.settled_at is None and eff.status == EffectStatus.COMMITTED:
            # Drain timed out: we cannot prove the effect is absent.
            eff.status = EffectStatus.COMMITTED_UNKNOWN

    live = [e for e in branch.effects if e.status not in CLEAN_STATUSES]
    if live:
        raise RollbackInvariantError(
            f"branch {branch.branch_id} cannot be cleanly rolled back: "
            f"{len(live)} effect(s) unproven "
            f"({[ (e.tool, e.external_id, e.status.value) for e in live ]}); "
            f"route to reconciliation obligation queue instead"
        )


def reconcile_winner(winner: Branch, losers: list) -> dict:
    """
    Elect winner, then diff orphaned effects from losers against the winner.
    Silent orphaning is forbidden; every orphan is either compensated or
    attached to the winner's provenance.
    """
    winner_external_ids = {e.external_id for e in winner.effects if e.external_id}
    obligations = []

    for loser in losers:
        for eff in loser.effects:
            if eff.status in CLEAN_STATUSES:
                continue
            if eff.external_id in winner_external_ids:
                # Duplicate logical effect already represented by winner.
                obligations.append(("dedupe", loser.branch_id, eff))
            else:
                obligations.append(("orphan", loser.branch_id, eff))

    return {
        "winner": winner.branch_id,
        "obligations": obligations,
        "requires_human_review": any(kind == "orphan" for kind, _, _ in obligations),
    }
