# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-plan-tree-silently-resurrect-pruned-branches-under-cost-bounded-parallel-pruning.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-plan-tree-silently-resurrect-pruned-branches-under-cost-bounded-parallel-pruning.warrant.json
# Markdown SHA-256:   4004d35b9842cb63810cc39eeeed0d39645ae835cd8439ba269c82b67015266c
# Code AST SHA-256:   363cc175320f41021f07a2be4c3a098ae2e976ca021b7b245ba0845322b23adc
# Verified Classes:   PrunedBranchWriteError, GenerationTaggedAccumulator, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Any


class PrunedBranchWriteError(RuntimeError):
    """Raised when a branch writes to shared state after its node was pruned."""
    pass


@dataclass
class GenerationTaggedAccumulator:
    """Shared partial-result store that rejects writes from pruned epochs."""
    _pruned_epochs: set = field(default_factory=set)
    _data: dict = field(default_factory=dict)

    def mark_pruned(self, epoch: int) -> None:
        self._pruned_epochs.add(epoch)

    def write(self, epoch: int, key: str, value: Any) -> None:
        if epoch in self._pruned_epochs:
            # The zombie branch tried to contribute after being pruned.
            raise PrunedBranchWriteError(
                f"epoch {epoch} is pruned; write to {key!r} rejected"
            )
        self._data[key] = value


@dataclass
class Branch:
    epoch: int
    acc: GenerationTaggedAccumulator
    _halted: bool = False

    def cancel(self) -> None:
        self._halted = True

    def run_step(self, key: str, value: Any) -> None:
        # Simulate a blocking tool call that returns before the halt check.
        time.sleep(0.05)
        # Write happens at the tool-completion boundary, before the next
        # top-of-loop halt check — this is the prune-to-cancel window.
        self.acc.write(self.epoch, key, value)
        if self._halted:
            return


def prune_and_join(branch: Branch, acc: GenerationTaggedAccumulator) -> None:
    """Barrier prune: mark pruned, cancel, and require quiescence.

    The generation tag is the backstop; the join is the primary guarantee.
    """
    acc.mark_pruned(branch.epoch)
    branch.cancel()
    # A correct implementation would join the worker here. If the worker
    # is still in flight and writes, the tag converts the race into a
    # detectable error rather than a silent chimera.
    try:
        branch.run_step("evidence", ["zombie-write"])  # simulates late write
    except PrunedBranchWriteError as exc:
        raise PrunedBranchWriteError(
            "prune was not a barrier: branch wrote after pruning"
        ) from exc


if __name__ == "__main__":
    acc = GenerationTaggedAccumulator()
    b2 = Branch(epoch=2, acc=acc)
    prune_and_join(b2, acc)
