# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-tool-call-hedge-before-rollback-and-how-does-branch-provenance-divergence-force-it.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-tool-call-hedge-before-rollback-and-how-does-branch-provenance-divergence-force-it.warrant.json
# Markdown SHA-256:   ed9401715c98380f3e117ad85793ddb2afb9e49f089be418c4a546a73a679669
# Code AST SHA-256:   c49ba13d5709f72f090ed05e87f004b67cc20fe9be209fda7def764297580fba
# Verified Classes:   ProvenanceDivergenceError, SideEffect, SpeculativeFork
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable


class ProvenanceDivergenceError(RuntimeError):
    """Raised when rollback cannot be safely issued because a losing branch's
    side effects share a key with the winning branch, or a compensator's
    precondition is no longer true at abort time."""


@dataclass
class SideEffect:
    branch_id: str
    key: str
    compensator: Callable[[], bool]  # returns True iff precondition still holds


@dataclass
class SpeculativeFork:
    winner: str
    branches: dict[str, list[SideEffect]] = field(default_factory=dict)

    def _keys_by_branch(self) -> dict[str, set[str]]:
        return {b: {e.key for e in effects} for b, effects in self.branches.items()}

    def check_provenance(self) -> None:
        keys = self._keys_by_branch()
        winner_keys = keys.get(self.winner, set())
        for branch_id, branch_keys in keys.items():
            if branch_id == self.winner:
                continue
            collision = branch_keys & winner_keys
            if collision:
                raise ProvenanceDivergenceError(
                    f"branch {branch_id} shares keys {sorted(collision)} with "
                    f"winner {self.winner}; rollback would clobber winner state"
                )

    def rollback(self) -> None:
        # Provenance must be re-checked at abort time, not spawn time.
        self.check_provenance()
        for branch_id, effects in self.branches.items():
            if branch_id == self.winner:
                continue
            for effect in effects:
                if not effect.compensator():
                    raise ProvenanceDivergenceError(
                        f"compensator precondition false for branch {branch_id} "
                        f"key {effect.key}; refusing rollback, quarantine required"
                    )


def abort_and_reconcile(fork: SpeculativeFork) -> str:
    try:
        fork.rollback()
        return f"committed winner {fork.winner}"
    except ProvenanceDivergenceError as exc:
        # Do NOT fall back to partial rollback. Quarantine the whole fork.
        return f"quarantined fork: {exc}"
