# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-speculative-subplan-effects-before-verification-quorum-and-how-rollback-ordering-leaks-irreversible-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-speculative-subplan-effects-before-verification-quorum-and-how-rollback-ordering-leaks-irreversible-side-effect.warrant.json
# Markdown SHA-256:   15b7f51bf2c8bbb776f40fd9e8062ed4c5d84d387a87d289622c2787c8e930e6
# Code AST SHA-256:   d3f783a171f04dfc50d50b59644be4a0ac06f9dfa8ab5c159104c4aa647a9a74
# Verified Classes:   SpeculativeCommitError, Subplan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class SpeculativeCommitError(RuntimeError):
    """Raised when a speculative subplan's effects cannot be soundly rolled back."""


@dataclass(frozen=True)
class Subplan:
    branch_id: str
    read_set: FrozenSet[str]
    write_set: FrozenSet[str]
    read_versions: dict = field(default_factory=dict)  # resource -> version read


def assert_speculation_sound(branches: list[Subplan], resource_versions: dict) -> None:
    """Static precondition before parallel launch. Refuses unsafe speculation."""
    for b in branches:
        for sib in branches:
            if sib.branch_id == b.branch_id:
                continue
            overlap = b.write_set & sib.write_set
            if overlap:
                raise SpeculativeCommitError(
                    f"branch {b.branch_id} and {sib.branch_id} share writable "
                    f"resource(s) {sorted(overlap)}; parallel speculation unsound, "
                    f"partition or serialize"
                )
            tainted = b.read_set & sib.write_set
            if tainted:
                raise SpeculativeCommitError(
                    f"branch {b.branch_id} read-set intersects sibling "
                    f"{sib.branch_id} write-set on {sorted(tainted)}; "
                    f"branch is tainted and cannot be counted toward quorum "
                    f"until {sib.branch_id} commits"
                )
        for res in b.write_set:
            if res not in b.read_versions:
                raise SpeculativeCommitError(
                    f"branch {b.branch_id} writes {res} without a recorded read "
                    f"version; delta-inverse rollback impossible"
                )
            if resource_versions.get(res) != b.read_versions[res]:
                raise SpeculativeCommitError(
                    f"branch {b.branch_id} read {res} at version "
                    f"{b.read_versions[res]} but current is "
                    f"{resource_versions.get(res)}; optimistic concurrency check "
                    f"failed, rollback would clobber a concurrent write"
                )


def rollback_branch(branch: Subplan, current_versions: dict,
                    idempotency_seen: set) -> None:
    """Delta-inverse rollback with idempotency guard."""
    if branch.branch_id in idempotency_seen:
        return  # rollback already applied; do not re-emit side effects
    for res in branch.write_set:
        expected_post = branch.read_versions[res]
        if current_versions.get(res) != expected_post:
            raise SpeculativeCommitError(
                f"cannot roll back {res} for {branch.branch_id}: resource "
                f"advanced to {current_versions.get(res)}; a sibling wrote after "
                f"this branch, restore would destroy that write"
            )
    # ... apply inverse deltas here ...
    idempotency_seen.add(branch.branch_id)
