# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-fork-a-speculative-branch-the-read-after-write-shadow-divergence-at-rollback-checkpoints.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-fork-a-speculative-branch-the-read-after-write-shadow-divergence-at-rollback-checkpoints.warrant.json
# Markdown SHA-256:   4b089c16127736d2fa16bfde2227d90d7e1afb42740fb7b061cb59bf8f3caac9
# Code AST SHA-256:   021dad8ae6f9300d682ec62816a41e8358f356dc57587f73bad8ac706687437c
# Verified Classes:   ShadowDivergenceError, UnsafeSpeculativeWriteError, Effect, Branch, CheckpointOrchestrator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Callable, Dict, List, Optional


class ShadowDivergenceError(RuntimeError):
    """Raised when a surviving branch reads an effect it cannot attribute to its own ancestry."""
    pass


class UnsafeSpeculativeWriteError(RuntimeError):
    """Raised when a branch attempts a non-idempotent, non-namespaced write before selection is final."""
    pass


@dataclass
class Effect:
    effect_id: str
    branch_id: str
    namespace: str
    idempotent: bool
    compensation: Optional[Callable[[], None]] = None


@dataclass
class Branch:
    branch_id: str
    ancestry: List[str]
    selection_final: bool = False
    effects: List[Effect] = field(default_factory=list)


class CheckpointOrchestrator:
    def __init__(self) -> None:
        self.effect_log: Dict[str, Effect] = {}
        self.committed_pre_checkpoint: set = set()

    def speculative_write(self, branch: Branch, namespace: str,
                          idempotent: bool, compensation: Optional[Callable[[], None]]) -> Effect:
        # Guard: refuse non-idempotent, non-namespaced writes before selection is final.
        if not idempotent and not branch.selection_final:
            raise UnsafeSpeculativeWriteError(
                f"branch {branch.branch_id} attempted non-idempotent write to '{namespace}' "
                f"before selection was final; defer via intent instead"
            )
        eid = f"{branch.branch_id}:{namespace}:{time.time_ns()}"
        eff = Effect(eid, branch.branch_id, namespace, idempotent, compensation)
        branch.effects.append(eff)
        self.effect_log[eid] = eff
        return eff

    def prune(self, branch: Branch) -> None:
        # Compensate every effect the pruned branch committed, before survivors resume.
        for eff in branch.effects:
            if eff.compensation is not None:
                eff.compensation()
            self.effect_log.pop(eff.effect_id, None)

    def guarded_read(self, survivor: Branch, returned_objects: List[dict]) -> None:
        # Every returned object must be attributable to survivor ancestry or pre-checkpoint log.
        allowed = set(survivor.ancestry) | self.committed_pre_checkpoint
        for obj in returned_objects:
            owner = obj.get("branch_id")
            if owner is not None and owner not in allowed:
                raise ShadowDivergenceError(
                    f"survivor {survivor.branch_id} read object {obj.get('id')} "
                    f"authored by pruned branch {owner}; context is not a superset of visible effects"
                )


def run_speculative_step(orch: CheckpointOrchestrator, branch: Branch,
                         planned_write: bool, returned_objects: List[dict]) -> None:
    if planned_write:
        orch.speculative_write(branch, namespace="purchase_orders", idempotent=False, compensation=None)
    orch.guarded_read(branch, returned_objects)
