# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-speculative-multi-agent-execution-fail-at-branch-reconciliation-when-rollback-depth-exceeds-the-shared-checkpoint-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-speculative-multi-agent-execution-fail-at-branch-reconciliation-when-rollback-depth-exceeds-the-shared-checkpoint-horizon.warrant.json
# Markdown SHA-256:   71cf136e989a6e8eb1580b12ea013292f27659422f4cde57ecf0f1773fa9fe7e
# Code AST SHA-256:   16292d72e6c12b020533ee327518bc6efa6ce5c0f6b23d09ed2e4a2fc57c53e9
# Verified Classes:   CheckpointHorizonExceeded, BranchAbortedBeforeHorizon
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CheckpointHorizonExceeded(RuntimeError):
    """Raised when a speculative branch's rollback target has been pruned
    from the shared checkpoint log before reconciliation could anchor to it.
    Fail closed: never fall back to 'nearest available checkpoint'."""
    pass


class BranchAbortedBeforeHorizon(RuntimeError):
    """Raised when a branch exceeded the depth bound and was force-aborted
    before its ancestor could be pruned. Tombstone must be committed."""
    pass


def reconcile_branch(branch, checkpoint_log, max_depth, watermark):
    # Enforce depth bound BEFORE the watermark can prune the ancestor.
    if branch.depth > max_depth:
        # Commit an explicit tombstone so reconciliation sees the abort,
        # not a missing ancestor.
        checkpoint_log.commit_tombstone(branch.id, branch.branch_point)
        raise BranchAbortedBeforeHorizon(
            f"branch {branch.id} depth {branch.depth} > bound {max_depth}; "
            f"aborted at {branch.branch_point} before watermark {watermark}"
        )

    # Fail closed if the branch point is no longer recoverable.
    if not checkpoint_log.contains(branch.branch_point):
        raise CheckpointHorizonExceeded(
            f"branch {branch.id} branch_point {branch.branch_point} "
            f"pruned; watermark={watermark}; cannot reconcile. "
            f"Do NOT fall back to nearest checkpoint."
        )

    ancestor = checkpoint_log.get(branch.branch_point)
    return compute_three_way_merge(ancestor, branch.tip, checkpoint_log.head())
