# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-rollback-when-branch-reconciliation-outpaces-its-own-checkpoint-lineage.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-rollback-when-branch-reconciliation-outpaces-its-own-checkpoint-lineage.warrant.json
# Markdown SHA-256:   b86a8aa268c86d4833142b8334f37db1f741f1376640e15051e2a27eff9380b0
# Code AST SHA-256:   6e39f1407c45aeb533da5d056a3a1bda57f429ead06130f7830e95e7074dff1d
# Verified Classes:   PhantomAncestorError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class PhantomAncestorError(RuntimeError):
    """Raised when a rollback ancestor no longer resolves to a replayable payload."""
    pass


def commit_rollback(reconciler, branch_id, ancestor_id):
    """
    Commit a rollback for branch_id to ancestor_id.
    Sound only if the ancestor payload is pinned and the lineage epoch is unchanged
    across the read-then-commit window.
    """
    read = reconciler.lineage.read(ancestor_id)
    epoch_at_read = reconciler.lineage.epoch()

    # Condition 1: payload must be a full checkpoint, not a distillation redirect.
    if read.kind == "redirect":
        raise PhantomAncestorError(
            f"ancestor {ancestor_id} redirected to {read.target}; "
            f"rollback would resume from a lossy summary, not a replayable checkpoint"
        )
    if read.kind == "retired":
        raise PhantomAncestorError(
            f"ancestor {ancestor_id} retired by branch-local compaction; "
            f"no payload to replay"
        )

    # Condition 2: lineage must not have moved between read and commit.
    if not reconciler.lineage.cas_epoch(epoch_at_read):
        raise PhantomAncestorError(
            f"lineage epoch advanced during rollback window for {ancestor_id}; "
            f"a sibling retired or redirected the ancestor mid-commit"
        )

    # Condition 3: idempotency keys must derive from the checkpoint payload itself.
    if read.idempotency_source != "payload":
        raise PhantomAncestorError(
            f"ancestor {ancestor_id} derives idempotency keys from context projection; "
            f"resume would regenerate keys and duplicate side effects"
        )

    return reconciler.lineage.write_resume_pointer(branch_id, ancestor_id, epoch_at_read)
