# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-speculative-side-effects-before-committing-a-pruned-branch-in-optimistic-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-speculative-side-effects-before-committing-a-pruned-branch-in-optimistic-multi-agent-execution.warrant.json
# Markdown SHA-256:   4bc412331ebfbafb516cfc5e65ee2fb092f4caabdf15f054aed84be6eaf18c0f
# Code AST SHA-256:   5b76223064c6efe1adb5a1227cde69f97a5566290a749b3ba51ad8bc209af8d2
# Verified Classes:   OrphanedEffectCommitError, Effect, SpeculativePlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Set, Dict


class OrphanedEffectCommitError(RuntimeError):
    """Raised when a committing branch would inherit a non-idempotent
    side effect whose provenance includes a pruned branch."""
    pass


@dataclass
class Effect:
    invocation_id: str
    idempotent: bool
    provenance: Set[str]  # branch ids that legitimately depend on this effect


@dataclass
class SpeculativePlan:
    branches: Set[str]
    pruned: Set[str] = field(default_factory=set)
    effects: Dict[str, Effect] = field(default_factory=dict)

    def record_effect(self, eff: Effect) -> None:
        # Deduplication must union provenance, never collapse it.
        if eff.invocation_id in self.effects:
            self.effects[eff.invocation_id].provenance |= eff.provenance
        else:
            self.effects[eff.invocation_id] = eff

    def audit_before_commit(self, winner: str) -> None:
        if winner in self.pruned:
            raise OrphanedEffectCommitError(
                f"winner {winner!r} is itself pruned; cannot commit"
            )
        for eff in self.effects.values():
            if eff.idempotent:
                continue
            orphaned = eff.provenance & self.pruned
            if orphaned:
                raise OrphanedEffectCommitError(
                    f"effect {eff.invocation_id!r} has provenance "
                    f"intersecting pruned branches {sorted(orphaned)}; "
                    f"committing {winner!r} would inherit an orphaned write. "
                    f"Re-execute from pre-invocation checkpoint or compensate."
                )


def commit_branch(plan: SpeculativePlan, winner: str) -> None:
    plan.audit_before_commit(winner)
    # safe to persist winner's state
    return None


if __name__ == "__main__":
    plan = SpeculativePlan(branches={"A", "B", "C"})
    # shared fetch that mutates upstream state on read-miss
    plan.record_effect(Effect("fetch_and_normalize", idempotent=False,
                              provenance={"A", "B"}))
    plan.record_effect(Effect("post_adjustment_C", idempotent=False,
                              provenance={"C"}))
    plan.pruned = {"A", "B"}
    commit_branch(plan, "C")  # raises OrphanedEffectCommitError
