# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-speculative-multi-agent-execution-diverge-from-its-rollback-checkpoint-when-branch-reconciliation-occurs-under-concurrent-toke.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-speculative-multi-agent-execution-diverge-from-its-rollback-checkpoint-when-branch-reconciliation-occurs-under-concurrent-toke.warrant.json
# Markdown SHA-256:   d8b4ae541c2465f5955bbf6fca6824fc5a0d8bd64df82e65f25dd2ea9bf5b726
# Code AST SHA-256:   1f8fea0ef11c12f68e0aea5253f11fd5f04ab8d2dfc2328dfacf2ba8c29f9d57
# Verified Classes:   FuzzyCheckpointDivergence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class FuzzyCheckpointDivergence(RuntimeError):
    """Raised when a rollback checkpoint is taken while branch emissions are in flight."""


def checkpoint_or_abort(branches, target_seq: int, in_flight: dict) -> dict:
    """
    Take a rollback checkpoint at target_seq, but only if no branch has an
    in-flight fragment whose sequence is <= target_seq. Otherwise the snapshot
    would be fuzzy and reconciliation would admit zombie effects.
    """
    dangling = {
        agent_id: frag_seq
        for agent_id, frag_seq in in_flight.items()
        if frag_seq <= target_seq
    }
    if dangling:
        raise FuzzyCheckpointDivergence(
            f"refusing checkpoint at seq={target_seq}: branches {sorted(dangling)} "
            f"have in-flight fragments at or below the checkpoint "
            f"({dangling}); a fuzzy snapshot would orphan these effects on rollback"
        )
    return {"seq": target_seq, "branches": [b.id for b in branches], "fuzzy": False}


def reconcile(canonical_log, surviving_branches, target_seq: int, in_flight: dict):
    snapshot = checkpoint_or_abort(surviving_branches, target_seq, in_flight)
    merged = canonical_log.copy()
    for branch in surviving_branches:
        for effect in branch.effects_after(snapshot["seq"]):
            if effect.seq <= snapshot["seq"]:
                raise FuzzyCheckpointDivergence(
                    f"effect {effect.id} from branch {branch.id} has seq={effect.seq} "
                    f"<= checkpoint {snapshot['seq']} but arrived after snapshot; "
                    f"this is a zombie effect and must not be merged"
                )
            merged.append(effect)
    return merged
