# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-has-already-polluted-shared-tool-state-a-rollback-invariant-analysis.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-has-already-polluted-shared-tool-state-a-rollback-invariant-analysis.warrant.json
# Markdown SHA-256:   b1f1cd71b9a39b3f71cc88dff228c5a7347a1a75af108e64c82d5d81211559ba
# Code AST SHA-256:   700036fac6a3dab61407a02f984c1b5620ad784299538abf95226fcf94e1aadd
# Verified Classes:   SpeculativeRollbackViolation, BranchEffects
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a speculative branch's effect set cannot be soundly reconciled."""
    pass


@dataclass
class BranchEffects:
    dispatched_intents: Set[str] = field(default_factory=set)   # keys written BEFORE dispatch
    returned_effects: Set[str] = field(default_factory=set)     # keys observed on return
    reconciled: Set[str] = field(default_factory=set)           # keys rolled back or confirmed
    in_flight: Set[str] = field(default_factory=set)            # dispatched, not yet settled


def reconcile_branch(branch_id: str, fx: BranchEffects, can_probe: bool) -> Set[str]:
    """
    Return the set of effect keys that must be rolled back.
    Raises if the intent log cannot soundly determine the effect set.
    """
    # In-flight effects at reconciliation time mean cancellation raced dispatch.
    if fx.in_flight:
        raise SpeculativeRollbackViolation(
            f"branch {branch_id}: {len(fx.in_flight)} in-flight effect(s) at reconciliation; "
            f"cancellation must drain before rollback — keys={sorted(fx.in_flight)}"
        )

    # Effects derived from intents, NOT from returns. A timed-out call with a
    # durable intent is still a candidate effect.
    candidates = fx.dispatched_intents - fx.reconciled

    # Any intent with no observed return is ambiguous: it may have succeeded
    # server-side. Without a probe we cannot declare it absent.
    unreturned = candidates - fx.returned_effects
    if unreturned and not can_probe:
        raise SpeculativeRollbackViolation(
            f"branch {branch_id}: {len(unreturned)} intent(s) have no return and no probe "
            f"capability; cannot soundly declare effect-free — keys={sorted(unreturned)}"
        )

    return candidates


def assert_no_leak(branch_id: str, fx: BranchEffects) -> None:
    residual = fx.dispatched_intents - fx.reconciled
    if residual:
        raise SpeculativeRollbackViolation(
            f"branch {branch_id}: intent-log residual {sorted(residual)} at post-reconcile; "
            f"rollback ran against an incomplete journal"
        )
