# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-speculative-branch-and-verify-rollback-has-failed-to-quiesce-in-multi-agent-tool-calling-systems.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-speculative-branch-and-verify-rollback-has-failed-to-quiesce-in-multi-agent-tool-calling-systems.warrant.json
# Markdown SHA-256:   e07e6e5376adc2661c4a8e72936a05370fc4e5dddff41e6b8011d460d78543c6
# Code AST SHA-256:   587c8b2348a72406b5a55d5f063ae04c828d9f5d386dc93e5d22d1d405117b50
# Verified Classes:   ZombieBranchError, EffectState, EffectEntry, EffectLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Tuple


class ZombieBranchError(RuntimeError):
    """Raised when a branch is declared terminal while speculative effects remain unacknowledged."""


class EffectState(Enum):
    DISPATCHED = "dispatched"
    APPLIED = "applied"
    COMPENSATED = "compensated"
    FENCED = "fenced"


@dataclass
class EffectEntry:
    branch_id: str
    call_id: str
    seq: int
    state: EffectState = EffectState.DISPATCHED
    applied_seq: int = -1
    compensated_seq: int = -1


@dataclass
class EffectLedger:
    entries: Dict[Tuple[str, str], EffectEntry] = field(default_factory=dict)

    def record_dispatch(self, branch_id: str, call_id: str, seq: int) -> None:
        self.entries[(branch_id, call_id)] = EffectEntry(branch_id, call_id, seq)

    def record_applied(self, branch_id: str, call_id: str, seq: int) -> None:
        e = self.entries[(branch_id, call_id)]
        e.state = EffectState.APPLIED
        e.applied_seq = seq

    def record_compensated(self, branch_id: str, call_id: str, seq: int) -> None:
        e = self.entries[(branch_id, call_id)]
        # A compensation that precedes the effect it undoes is not a compensation.
        if e.state is EffectState.DISPATCHED or seq <= e.applied_seq:
            e.state = EffectState.FENCED  # treat as fenced; the tool must reject the late effect
            return
        e.state = EffectState.COMPENSATED
        e.compensated_seq = seq

    def assert_quiescent(self, branch_id: str) -> None:
        orphans = [
            e for e in self.entries.values()
            if e.branch_id == branch_id
            and e.state not in (EffectState.COMPENSATED, EffectState.FENCED)
        ]
        if orphans:
            raise ZombieBranchError(
                f"branch {branch_id} declared terminal with "
                f"{len(orphans)} unacknowledged speculative effects: "
                f"{[o.call_id for o in orphans]}"
            )


def finalize_branch(ledger: EffectLedger, branch_id: str, verdict: str) -> None:
    if verdict in ("DIVERGED", "ROLLED_BACK"):
        ledger.assert_quiescent(branch_id)
    # commit path omitted; only the rollback quiescence invariant is enforced here
