# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-commits-from-surviving-a-rollback-that-never-replayed-their-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-commits-from-surviving-a-rollback-that-never-replayed-their-side-effects.warrant.json
# Markdown SHA-256:   d7e3cd8b067741613fe5afae1364df327dcf418ecb58bfa87257709dd3078bd8
# Code AST SHA-256:   cf3745569023db1563d4a279425cda7a9a8152d96791bb9e4d32c486360c774c
# Verified Classes:   EffectState, RollbackLeakError, ForeignStateConflictError, EffectRecord, EffectLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EffectState(Enum):
    ISSUED = "issued"
    COMMITTED = "committed"
    COMPENSATED = "compensated"
    FENCED = "fenced"
    NEVER_COMMITTED = "never_committed"


class RollbackLeakError(RuntimeError):
    """Raised when a branch is rolled back while it still holds an
    outstanding optimistic effect that no sibling can safely observe."""


class ForeignStateConflictError(RuntimeError):
    """Raised when a committed branch hits a tool conflict whose owning
    branch is an unresolved sibling, indicating contaminated world state."""


@dataclass
class EffectRecord:
    branch_id: str
    resource_id: int
    idempotency_token: str
    state: EffectState = EffectState.ISSUED
    compensable: bool = True


@dataclass
class EffectLedger:
    records: Dict[str, EffectRecord] = field(default_factory=dict)

    def register(self, rec: EffectRecord) -> None:
        # Keyed by branch+resource so rollback can drain per-branch.
        self.records[f"{rec.branch_id}:{rec.resource_id}"] = rec

    def outstanding_for(self, branch_id: str) -> list:
        return [
            r for r in self.records.values()
            if r.branch_id == branch_id
            and r.state in (EffectState.ISSUED, EffectState.COMMITTED)
        ]

    def drain(self, branch_id: str) -> None:
        """Rollback = drain, not discard. Every outstanding effect must
        reach a terminal state before the branch is considered rolled back."""
        for rec in self.outstanding_for(branch_id):
            if rec.compensable:
                # issue compensating call, then mark
                rec.state = EffectState.COMPENSATED
            else:
                # non-compensable: must be fenced so siblings see it
                rec.state = EffectState.FENCED

    def owner_of(self, resource_id: int) -> Optional[str]:
        for rec in self.records.values():
            if rec.resource_id == resource_id and rec.state in (
                EffectState.ISSUED,
                EffectState.COMMITTED,
                EffectState.FENCED,
            ):
                return rec.branch_id
        return None


def rollback_branch(ledger: EffectLedger, branch_id: str) -> None:
    outstanding = ledger.outstanding_for(branch_id)
    # Invariant: transcript rollback must not precede effect drain.
    # If drain cannot complete, we must NOT mark the branch rolled back.
    try:
        ledger.drain(branch_id)
    except Exception as exc:
        raise RollbackLeakError(
            f"branch {branch_id} rollback failed to drain "
            f"{len(outstanding)} outstanding effect(s): {exc}"
        ) from exc

    still_outstanding = ledger.outstanding_for(branch_id)
    if still_outstanding:
        raise RollbackLeakError(
            f"branch {branch_id} rolled back with "
            f"{len(still_outstanding)} live effect(s) still visible to siblings"
        )


def handle_tool_conflict(
    ledger: EffectLedger,
    committed_branch: str,
    resource_id: int,
    status_code: int,
) -> None:
    if status_code != 409:
        return
    owner = ledger.owner_of(resource_id)
    if owner is None:
        return  # genuine pre-existing resource, benign
    if owner != committed_branch:
        # Conflict owned by a sibling (possibly rolled-back) branch:
        # committed branch's world model is contaminated.
        raise ForeignStateConflictError(
            f"committed branch {committed_branch} hit 409 on resource "
            f"{resource_id} owned by sibling {owner}; "
            f"refusing to treat as benign precondition"
        )


def speculative_round(ledger: EffectLedger, winner: str, losers: list) -> None:
    for loser in losers:
        rollback_branch(ledger, loser)
    # Only after all losers drained may the winner observe shared resources.
    for rec in ledger.records.values():
        if rec.state == EffectState.FENCED and rec.branch_id in losers:
            # winner must route around fenced artifacts; surface as conflict
            handle_tool_conflict(ledger, winner, rec.resource_id, 409)
