# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-rollback-against-a-committed-sibling-before-releasing-its-lease.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-rollback-against-a-committed-sibling-before-releasing-its-lease.warrant.json
# Markdown SHA-256:   b094f390d88c89f07f16a0086b96f58576e0c1ee665a649a17d9aeec3a518872
# Code AST SHA-256:   aacdbeac596fab6d1f99eb13c2ec49ff31d091c19eb405a00b5435705a195070
# Verified Classes:   UnreconciledRollbackError, Commit, SpeculativeBranch, RollbackReconciler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class UnreconciledRollbackError(RuntimeError):
    """Raised when a speculative branch attempts to release its lease
    before classifying sibling commits newer than its snapshot token."""


@dataclass
class Commit:
    branch_id: str
    resource: str
    timestamp: float
    read_dependencies: List[str] = field(default_factory=list)


@dataclass
class SpeculativeBranch:
    branch_id: str
    resource: str
    snapshot_ts: float
    lease_held: bool = True
    reconciled_commits: List[str] = field(default_factory=list)


class RollbackReconciler:
    def __init__(self) -> None:
        self._commit_log: Dict[str, List[Commit]] = {}

    def record_commit(self, commit: Commit) -> None:
        self._commit_log.setdefault(commit.resource, []).append(commit)

    def _newer_sibling_commits(self, branch: SpeculativeBranch) -> List[Commit]:
        return [
            c
            for c in self._commit_log.get(branch.resource, [])
            if c.branch_id != branch.branch_id and c.timestamp > branch.snapshot_ts
        ]

    def reconcile_or_rollback(self, branch: SpeculativeBranch) -> str:
        if not branch.lease_held:
            raise UnreconciledRollbackError(
                f"branch {branch.branch_id} has no lease; cannot reconcile"
            )

        newer = self._newer_sibling_commits(branch)

        if not newer:
            # Safe: no sibling commit is newer than our snapshot; compensate.
            branch.lease_held = False
            return "compensated"

        # Reconciliation required. Every newer sibling must be classified
        # as independent-of-region or explicitly reconciled before release.
        for commit in newer:
            if commit.read_dependencies and branch.resource in commit.read_dependencies:
                if commit.branch_id not in branch.reconciled_commits:
                    raise UnreconciledRollbackError(
                        f"branch {branch.branch_id} cannot release lease: "
                        f"sibling commit {commit.branch_id}@{commit.timestamp:.3f} "
                        f"depends on region {branch.resource} read inside "
                        f"speculative window (snapshot {branch.snapshot_ts:.3f}); "
                        f"re-validate or escalate to arbiter"
                    )

        branch.lease_held = False
        return "reconciled"


if __name__ == "__main__":
    rec = RollbackReconciler()
    t0 = time.time()

    branch_a = SpeculativeBranch("A", "plan.region", snapshot_ts=t0)
    # Sibling B commits a read-dependent verdict after A's snapshot.
    rec.record_commit(
        Commit(
            branch_id="B",
            resource="plan.region",
            timestamp=t0 + 0.040,
            read_dependencies=["plan.region"],
        )
    )

    # A loses arbitration and attempts rollback -> must fail loudly.
    rec.reconcile_or_rollback(branch_a)  # raises UnreconciledRollbackError
