# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-merge-a-speculative-branch-whose-rollback-journal-is-incomplete.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-merge-a-speculative-branch-whose-rollback-journal-is-incomplete.warrant.json
# Markdown SHA-256:   f863f8ca588e075e8a176b614b6e053c24cc8c57560bc301aad6a50f3fdbe5b7
# Code AST SHA-256:   d9d3c1993be6a662003b7c8a631e2a03d74fed6dce9bec38aa75f458e2bdda46
# Verified Classes:   IncompleteRollbackJournal, BranchJournal
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class IncompleteRollbackJournal(RuntimeError):
    """Raised when a speculative branch cannot be safely merged or rolled back."""
    pass


class BranchJournal:
    def __init__(self, branch_id, seal_generation):
        self.branch_id = branch_id
        self.seal_generation = seal_generation
        self.entries = []          # (seq, path, observed_post_state, compensator)
        self.paths_touched = set()

    def record(self, seq, path, observed_post_state, compensator):
        # Write-ahead: entry must exist before the mutation is applied.
        self.entries.append((seq, path, observed_post_state, compensator))
        self.paths_touched.add(path)


def disposition(branch, winner, path_generations):
    """
    Decide merge / rollback / quarantine for one speculative branch.
    path_generations: {path: latest_generation} at merge time.
    """
    if not branch.entries:
        # Empty journal is ambiguous: either no effects or unjournaled effects.
        raise IncompleteRollbackJournal(
            f"branch {branch.branch_id}: empty journal cannot be distinguished "
            f"from unjournaled mutations; quarantine required"
        )

    # Integrity check 1: monotonic sequence, no gaps.
    seqs = [e[0] for e in branch.entries]
    if seqs != sorted(seqs) or seqs != list(range(seqs[0], seqs[0] + len(seqs))):
        raise IncompleteRollbackJournal(
            f"branch {branch.branch_id}: non-monotonic or gapped journal {seqs}"
        )

    # Integrity check 2: rollback isolation — no concurrent write post-seal.
    for path in branch.paths_touched:
        gen = path_generations.get(path, 0)
        if gen > branch.seal_generation:
            raise IncompleteRollbackJournal(
                f"branch {branch.branch_id}: path {path} written at generation "
                f"{gen} after seal {branch.seal_generation}; rollback would clobber"
            )

    # Integrity check 3: compensator determinism — every entry must carry
    # an observed post-state, not a tool self-report.
    for seq, path, observed, comp in branch.entries:
        if observed is None or comp is None:
            raise IncompleteRollbackJournal(
                f"branch {branch.branch_id}: entry {seq} on {path} lacks "
                f"observed state or compensator; journal is lossy"
            )

    if winner:
        return "merge"
    return "rollback"


def reconcile(branches, winner_id, path_generations):
    results = {}
    for b in branches:
        try:
            results[b.branch_id] = disposition(
                b, b.branch_id == winner_id, path_generations
            )
        except IncompleteRollbackJournal:
            results[b.branch_id] = "quarantine"
    return results
