# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-outlived-its-reconciliation-window-in-multi-agent-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-outlived-its-reconciliation-window-in-multi-agent-rollback.warrant.json
# Markdown SHA-256:   d4d06ed901bb6e234ddc854dcb412761502c6c30a524fd1b367a55bbf498edc4
# Code AST SHA-256:   778d29653718eb189fe0c5c27a949622c5c37cf3ded5e9dac676f0d5ebc6e85b
# Verified Classes:   ZombieCommitError, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ZombieCommitError(RuntimeError):
    """Raised when a branch's optimistic effects are live but unreconciled."""


@dataclass
class Branch:
    name: str
    step_counter: int = 0
    last_tool_seq: int = 0
    applied_effect_ids: set = field(default_factory=set)
    discarded_effect_ids: set = field(default_factory=set)
    flush_deadline: Optional[float] = None
    lease_held: bool = True


def check_reversibility(branch: Branch, now: float, reconciliation_p99: float) -> str:
    """Return 'preempt', 'demote', or 'safe'. Raise on unrecoverable zombie."""
    stalled = branch.step_counter > 0 and branch.last_tool_seq == 0
    behind_flush = branch.flush_deadline is not None and now >= branch.flush_deadline

    if branch.applied_effect_ids and branch.discarded_effect_ids == branch.applied_effect_ids:
        return "safe"  # fully reverted, effect-ID-complete

    if behind_flush and branch.applied_effect_ids - branch.discarded_effect_ids:
        # Effects are live, deadline passed, discard incomplete: zombie.
        missing = branch.applied_effect_ids - branch.discarded_effect_ids
        raise ZombieCommitError(
            f"branch {branch.name!r} crossed flush deadline with live effects {sorted(missing)}; "
            f"reconciler must replay ledger in ID order, not trust discard"
        )

    if stalled:
        remaining = (branch.flush_deadline or now) - now
        if remaining > reconciliation_p99:
            return "preempt"
        return "demote"

    return "safe"


def reconcile(branches, winner: str, now: float, p99: float) -> None:
    for b in branches:
        if b.name == winner:
            continue
        verdict = check_reversibility(b, now, p99)
        if verdict == "demote":
            b.lease_held = False
        elif verdict == "preempt":
            # force branch to declare effect set before proceeding
            b.last_tool_seq = max(b.last_tool_seq, 1)
