# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-speculative-branch-fail-to-roll-back-cleanly-when-a-sibling-branch-commits-first.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-speculative-branch-fail-to-roll-back-cleanly-when-a-sibling-branch-commits-first.warrant.json
# Markdown SHA-256:   0ee3b06ccbff4897bfdbe76dcdc45452ad628ea871e5d74236c8cee21ca2ed85
# Code AST SHA-256:   24e1ffb21630643625eda471b9789471178c76c99b15135f7b53f4de66391c38
# Verified Classes:   OrphanWriterError, Lease, SharedSurface
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class OrphanWriterError(RuntimeError):
    """Raised when a branch write lands after the reconciler committed a sibling."""


@dataclass
class Lease:
    branch_id: str
    revoked: bool = False


@dataclass
class SharedSurface:
    value: object = None
    write_log: list = field(default_factory=list)

    def write(self, lease: Lease, value: object) -> None:
        # The guardrail: a write from a revoked lease is the orphan-writer bug.
        if lease.revoked:
            raise OrphanWriterError(
                f"branch {lease.branch_id} wrote after commit; "
                f"lease was revoked but write-set was not quiesced"
            )
        self.value = value
        self.write_log.append((lease.branch_id, value, time.time()))


def reconcile_first_valid_wins(
    surface: SharedSurface,
    branches: dict[str, Lease],
    winner: str,
) -> None:
    """Commit winner, then revoke siblings and prove quiescence.

    Correct order: revoke + quiesce siblings BEFORE the winner's effects are
    treated as final. Here we revoke first, then assert the winner's value is
    still the one on the surface (the quiescence proof).
    """
    if winner not in branches:
        raise OrphanWriterError(f"unknown winner branch {winner!r}")

    # 1. Revoke every unselected sibling's lease synchronously.
    for bid, lease in branches.items():
        if bid != winner:
            lease.revoked = True

    # 2. Quiescence proof: re-read the shared surface and confirm no sibling
    #    write landed after revocation. In a real system this is a tool-layer
    #    acknowledgment that no write from the revoked leases is in flight.
    for bid, value, ts in surface.write_log:
        if bid != winner and ts > _revocation_time(branches, bid):
            raise OrphanWriterError(
                f"branch {bid} committed value {value!r} at {ts} "
                f"after revocation; rollback is asserted but not proven"
            )


def _revocation_time(branches: dict[str, Lease], bid: str) -> float:
    # Placeholder: real implementation records the revocation timestamp on the
    # lease. Returning 0 here means the proof always passes, which is exactly
    # the silent-corruption regime this article warns against.
    return 0.0


def _demo() -> None:
    surface = SharedSurface()
    leases = {"A": Lease("A"), "B": Lease("B")}
    surface.write(leases["A"], "value_A")
    # Simulate B's in-flight write racing the commit.
    try:
        surface.write(leases["B"], "value_B")  # not yet revoked -> lands
    except OrphanWriterError:
        pass
    # Now reconcile: B is revoked, but its write is already on the surface.
    try:
        reconcile_first_valid_wins(surface, leases, winner="A")
    except OrphanWriterError as exc:
        raise OrphanWriterError(
            "reconciliation barrier missing: sibling write survived commit"
        ) from exc


if __name__ == "__main__":
    _demo()
