# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-rollback-divergence-under-shared-workspace-speculation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-rollback-divergence-under-shared-workspace-speculation.warrant.json
# Markdown SHA-256:   b5e674f0358dcac3ae8ae7fda341c1a89a6fcc90d9437ca4661ef575bf451ea9
# Code AST SHA-256:   a917cebf69cf9108481db6fa08bfe0f2fbcc49043e02e1dda4512b42c6e2a85c
# Verified Classes:   SpeculativeContaminationError, ForkPoint, EffectLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class SpeculativeContaminationError(RuntimeError):
    """Raised when a speculative branch's read set intersects an abandoned
    branch's effect set, or when a branch attempts an unledgered observable
    effect. Signals that rollback cannot restore a sound commit decision."""


@dataclass(frozen=True)
class ForkPoint:
    snapshot_id: str


@dataclass
class EffectLedger:
    # writes: branch_id -> set of observable effect ids it produced
    writes: dict[str, set[str]] = field(default_factory=dict)
    # reads: branch_id -> set of (effect_id, snapshot_id) it consumed
    reads: dict[str, set[tuple[str, str]]] = field(default_factory=dict)
    abandoned: set[str] = field(default_factory=set)

    def record_write(self, branch_id: str, effect_id: str) -> None:
        self.writes.setdefault(branch_id, set()).add(effect_id)

    def record_read(self, branch_id: str, effect_id: str, snapshot_id: str) -> None:
        self.reads.setdefault(branch_id, set()).add((effect_id, snapshot_id))

    def abandon(self, branch_id: str) -> None:
        self.abandoned.add(branch_id)


def assert_branch_isolated(
    branch_id: str,
    fork: ForkPoint,
    ledger: EffectLedger,
    pending_effect_id: str | None = None,
) -> None:
    """Guard called before any observable effect and before commit.

    Aborts the branch if it is about to leak an unledgered effect, or if any
    of its reads were served from a snapshot other than its own fork point
    (i.e., a sibling already contaminated the read path).
    """
    if pending_effect_id is not None and pending_effect_id not in ledger.writes.get(
        branch_id, set()
    ):
        raise SpeculativeContaminationError(
            f"branch {branch_id} attempted observable effect {pending_effect_id!r} "
            f"without ledger registration; rollback would be partial"
        )

    for effect_id, snapshot_id in ledger.reads.get(branch_id, set()):
        if snapshot_id != fork.snapshot_id:
            raise SpeculativeContaminationError(
                f"branch {branch_id} read effect {effect_id!r} from snapshot "
                f"{snapshot_id!r}, expected fork point {fork.snapshot_id!r}; "
                f"input set is contaminated by a sibling timeline"
            )


def assert_commit_sound(
    selected: str,
    fork: ForkPoint,
    ledger: EffectLedger,
) -> None:
    """Guard called at commit. Rejects commit if the selected branch's read
    set intersects any abandoned branch's effect set."""
    abandoned_effects: set[str] = set()
    for b in ledger.abandoned:
        abandoned_effects |= ledger.writes.get(b, set())

    for effect_id, _snapshot in ledger.reads.get(selected, set()):
        if effect_id in abandoned_effects:
            raise SpeculativeContaminationError(
                f"commit of branch {selected!r} rejected: its input {effect_id!r} "
                f"was produced by an abandoned branch; selection heuristic is "
                f"operating on corrupted evidence"
            )

    assert_branch_isolated(selected, fork, ledger)
