# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-side-effects-before-branch-commit-and-why-the-compensate-on-rollback-invariant-fails-under-concurrent-sib.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-side-effects-before-branch-commit-and-why-the-compensate-on-rollback-invariant-fails-under-concurrent-sib.warrant.json
# Markdown SHA-256:   1739cb28ad7c41b3264a20dc625fd3e6f39e641aefbfbec78849aac03cbacdf6
# Code AST SHA-256:   94bc2d4e3154c3d35d5276344815bd29623bbc0a211ca7ba899f69880ea7f47f
# Verified Classes:   SpeculativeCommitError, EffectDisposition, EffectRecord, Fork, ForkReconciler
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class SpeculativeCommitError(RuntimeError):
    """Raised when a fork's commit/rollback protocol cannot preserve cross-branch exclusivity."""
    pass


class EffectDisposition(Enum):
    COMPENSATE = "compensate"
    QUARANTINE = "quarantine"


@dataclass
class EffectRecord:
    branch_id: str
    effector_key: str
    lease_token: Optional[str]      # branch-unique token; None => identity not branch-unique
    recorded_post_state: dict       # branch's stale view at log time
    applied: bool = True


@dataclass
class Fork:
    fork_id: str
    committed_branch: Optional[str] = None
    effects: List[EffectRecord] = field(default_factory=list)


class ForkReconciler:
    """
    Enforces the invariant: no compensation for effector key K executes unless
    live state proves K is attributable to a losing branch, not the committed branch.
    """

    def __init__(self, effector):
        self.effector = effector
        self.orphan_queue: List[dict] = []

    def _live_state(self, key: str) -> dict:
        # Authoritative read against the effector, not the branch log.
        return self.effector.read(key)

    def schedule_compensation(self, fork: Fork, losing_branch_id: str) -> List[EffectDisposition]:
        if fork.committed_branch is None:
            raise SpeculativeCommitError(
                f"fork {fork.fork_id}: cannot schedule compensation before commit is durable"
            )
        if losing_branch_id == fork.committed_branch:
            raise SpeculativeCommitError(
                f"fork {fork.fork_id}: attempted to compensate the committed branch "
                f"{losing_branch_id!r}; this is the corruption path, not rollback"
            )

        dispositions: List[EffectDisposition] = []
        losing = [e for e in fork.effects if e.branch_id == losing_branch_id]
        winner_keys = {
            e.effector_key for e in fork.effects if e.branch_id == fork.committed_branch
        }

        for eff in losing:
            key = eff.effector_key
            live = self._live_state(key)

            # Rule 1: identity must be branch-unique.
            if eff.lease_token is None:
                self._quarantine(fork, eff, live, "effect identity not branch-unique")
                dispositions.append(EffectDisposition.QUARANTINE)
                continue

            # Rule 2: live state must still match what this branch left behind.
            if live != eff.recorded_post_state:
                self._quarantine(fork, eff, live, "effector state advanced past branch post-state")
                dispositions.append(EffectDisposition.QUARANTINE)
                continue

            # Rule 3: key must not be shared with the committed branch.
            if key in winner_keys:
                self._quarantine(fork, eff, live, "effector key shared with committed branch")
                dispositions.append(EffectDisposition.QUARANTINE)
                continue

            # Safe: retract exactly this branch's mutation, under per-key lock.
            with self.effector.lock(key):
                if self._live_state(key) != eff.recorded_post_state:
                    raise SpeculativeCommitError(
                        f"fork {fork.fork_id}: key {key!r} mutated between validation and "
                        f"compensation; per-key lock or total order is broken"
                    )
                self.effector.release(key, lease_token=eff.lease_token)
            dispositions.append(EffectDisposition.COMPENSATE)

        return dispositions

    def _quarantine(self, fork: Fork, eff: EffectRecord, live: dict, reason: str) -> None:
        self.orphan_queue.append({
            "fork_id": fork.fork_id,
            "branch_id": eff.branch_id,
            "effector_key": eff.effector_key,
            "lease_token": eff.lease_token,
            "recorded_post_state": eff.recorded_post_state,
            "live_state": live,
            "reason": reason,
            "ts": time.time(),
        })


def commit_fork(reconciler: ForkReconciler, fork: Fork, winner: str, losers: List[str]) -> None:
    if winner not in {e.branch_id for e in fork.effects} and fork.effects:
        raise SpeculativeCommitError(f"fork {fork.fork_id}: winner {winner!r} has no recorded effects")

    # Phase 1: durable commit marker.
    fork.committed_branch = winner

    # Phase 2: reconcile every loser against live state before releasing the fork barrier.
    for loser in losers:
        reconciler.schedule_compensation(fork, loser)
