# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-prunes-speculative-branches-on-a-heuristic-that-is-stale-relative-to-a-sibling-s-committed-state.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-prunes-speculative-branches-on-a-heuristic-that-is-stale-relative-to-a-sibling-s-committed-state.warrant.json
# Markdown SHA-256:   71a2d52a68ae733b66756da0dad80dbd11a77dad812a353dc32ea50896ffe3fc
# Code AST SHA-256:   b645109bd690a8061ab569a0a76dd8cd6393ba5869ea29b4448a4cd1b63d1bb9
# Verified Classes:   StalePruneError, Branch, PrunedSet
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StalePruneError(RuntimeError):
    """Raised when a pruned branch's read-set intersects a committed write
    from a dispatched sibling, meaning the prune decision is no longer valid."""
    pass


@dataclass
class Branch:
    name: str
    score: float
    read_set: frozenset
    write_set: frozenset
    scored_at_version: int


@dataclass
class PrunedSet:
    branches: dict = field(default_factory=dict)  # name -> Branch
    state_version: int = 0

    def prune(self, branch: Branch, threshold: float) -> None:
        if branch.score < threshold:
            self.branches[branch.name] = branch

    def on_commit(self, writer: Branch, written_fields: frozenset) -> None:
        self.state_version += 1
        for name, pruned in list(self.branches.items()):
            if pruned.read_set & written_fields:
                # The pruned branch's score was computed against a state
                # that this commit has just invalidated.
                raise StalePruneError(
                    f"branch {name!r} pruned at version "
                    f"{pruned.scored_at_version} reads fields "
                    f"{sorted(pruned.read_set & written_fields)} which "
                    f"{writer.name!r} committed at version "
                    f"{self.state_version}; prune is stale and branch "
                    f"must be re-expanded or the commit rolled back"
                )


def dispatch_with_prune_guard(
    dispatched: list,
    pruned: PrunedSet,
    threshold: float,
) -> None:
    for b in dispatched:
        pruned.prune(b, threshold)
    for writer in dispatched:
        # Simulate a commit from the worker; in production this is the
        # postcondition diff against the worker's declared write_set.
        committed = writer.write_set
        pruned.on_commit(writer, committed)
