# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-branch-before-rollback-reconciliation-and-how-does-the-prune-before-commit-invariant-prevent-gh.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-branch-before-rollback-reconciliation-and-how-does-the-prune-before-commit-invariant-prevent-gh.warrant.json
# Markdown SHA-256:   2e5a4e72142b4546bc7ac9288b37d56df751ba3ea4baf7d97f1fef875a4cbd02
# Code AST SHA-256:   ae58425ea44874313d1b7d4e885abe2cf1012f0743df8c88c82cacf29d4a2b5a
# Verified Classes:   ReconciliationIncomplete, StaleGenerationWrite, Branch, Resource
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ReconciliationIncomplete(RuntimeError):
    """Raised when commit is attempted while sibling rollbacks are unresolved."""
    pass


class StaleGenerationWrite(RuntimeError):
    """Raised when a write/delete carries a generation older than the resource's."""
    pass


@dataclass
class Branch:
    name: str
    generation: int
    touched: List[str] = field(default_factory=list)


@dataclass
class Resource:
    # key -> (generation, value)
    store: Dict[str, tuple] = field(default_factory=dict)

    def put(self, key: str, value, generation: int) -> None:
        cur = self.store.get(key)
        if cur is not None and generation < cur[0]:
            raise StaleGenerationWrite(
                f"put({key}) gen={generation} < resource gen={cur[0]}"
            )
        self.store[key] = (generation, value)

    def delete(self, key: str, generation: int) -> None:
        cur = self.store.get(key)
        if cur is None:
            return
        if generation < cur[0]:
            raise StaleGenerationWrite(
                f"delete({key}) gen={generation} < resource gen={cur[0]}"
            )
        del self.store[key]


def reconcile_and_commit(
    resource: Resource,
    winner: Branch,
    losers: List[Branch],
    rollback_status: Dict[str, str],  # branch -> "done" | "inflight" | "failed"
    budget_exhausted: bool,
) -> None:
    # Hard fence: no commit until every loser is quiescent.
    unresolved = [b.name for b in losers if rollback_status.get(b.name) != "done"]
    if unresolved:
        if budget_exhausted:
            raise ReconciliationIncomplete(
                f"aborting rollout: unresolved rollbacks {unresolved} "
                f"and budget exhausted; refusing to commit into open compensation window"
            )
        raise ReconciliationIncomplete(
            f"commit blocked: siblings {unresolved} not pruned to quiescence"
        )

    # Losers' deletes already applied under their generations; winner commits
    # under a strictly later generation so fencing is well-ordered.
    commit_gen = winner.generation + 1000
    for key in winner.touched:
        resource.put(key, f"{winner.name}_value", commit_gen)
