Use O(log n) skiplist construction in CBlockIndex #37015

Open
sipa wants to merge 5 commits from 202611_skiplist into master AGit
sipa commented 2026-11-30 05:05:03 +00:00 (Migrated from github.com)

CBlockIndex contains, in addition to the pprev pointer to it parent block, a pskip pointer that points further back added in #4420. This allows GetAncestor(), and since #33515 also LastCommonAncestor() to locate ancestors and fork points in faster than linear time.

Contrary to what I believed when #4420 was written, the scheme is not \mathcal{O}(\log n) but \mathcal{O}(\log^2 n) (see https://github.com/bitcoin/bitcoin/pull/33661#discussion_r2783298594). However, true \mathcal{O}(\log n) schemes exist: Fable 5.2 found the paper "An applicative random-access stack" by Eugene W. Myers (1983)... and then improved it by a factor 1.5. That is what is implemented here.

The idea is to lay out all the heights in a binary tree (not the block tree, this is just to arrange what heights point to which other ones):

skiplist_tree

For inner nodes, pskip points to the left child (blue) and pprev to the right child (orange). For leaf nodes, pprev points to one below (light blue), and pskip points to the leftmost leaf descendant of it (light orange). Going from one height to another is simply following pskip when it doesn't overshoot the target, and pprev otherwise.

The scheme guarantees that any jump from a height H takes at most 2 \\, \lfloor\log_2(H+1)\rfloor - 1 steps. The proof is explained in the comments, and (a tighter version of) the formula tested in the unit tests.

The number of pointers followed to go d blocks back, over all heights from 500000 to 1499999 (before / after):

d avg p50 p95 p99 max
10 4.44 / 4.37 5 / 4 6 / 7 6 / 9 6 / 10
144 13.52 / 10.37 14 / 10 20 / 14 22 / 17 23 / 26
2016 26.20 / 16.19 26 / 16 38 / 20 41 / 23 43 / 29
50000 45.91 / 23.03 46 / 23 63 / 27 70 / 29 82 / 34
210000 56.78 / 25.99 57 / 26 77 / 30 84 / 32 101 / 36
`CBlockIndex` contains, in addition to the `pprev` pointer to it parent block, a `pskip` pointer that points further back added in #4420. This allows `GetAncestor()`, and since #33515 also `LastCommonAncestor()` to locate ancestors and fork points in faster than linear time. Contrary to what I believed when #4420 was written, the scheme is not $\mathcal{O}(\log n)$ but $\mathcal{O}(\log^2 n)$ (see https://github.com/bitcoin/bitcoin/pull/33661#discussion_r2783298594). However, true $\mathcal{O}(\log n)$ schemes exist: Fable 5.2 found the paper "An applicative random-access stack" by Eugene W. Myers (1983)... and then improved it by a factor 1.5. That is what is implemented here. The idea is to lay out all the heights in a binary tree (not the block tree, this is just to arrange what heights point to which other ones): <img width="950" height="510" alt="skiplist_tree" src="https://git.fish.foo/attachments/f3c16735-3453-414b-ad4f-7536e5f1a7f1" /> For inner nodes, `pskip` points to the left child (blue) and `pprev` to the right child (orange). For leaf nodes, `pprev` points to one below (light blue), and `pskip` points to the leftmost leaf descendant of it (light orange). Going from one height to another is simply following `pskip` when it doesn't overshoot the target, and `pprev` otherwise. The scheme guarantees that any jump from a height $H$ takes at most $2 \\, \lfloor\log_2(H+1)\rfloor - 1$ steps. The proof is explained in the comments, and (a tighter version of) the formula tested in the unit tests. The number of pointers followed to go $d$ blocks back, over all heights from 500000 to 1499999 (before / after): | $d$ | avg | p50 | p95 | p99 | max | |---:|:---:|:---:|:---:|:---:|:---:| | 10 | 4.44 / 4.37 | 5 / 4 | 6 / 7 | 6 / 9 | 6 / 10 | | 144 | 13.52 / 10.37 | 14 / 10 | 20 / 14 | 22 / 17 | 23 / 26 | | 2016 | 26.20 / 16.19 | 26 / 16 | 38 / 20 | 41 / 23 | 43 / 29 | | 50000 | 45.91 / 23.03 | 46 / 23 | 63 / 27 | 70 / 29 | 82 / 34 | | 210000 | 56.78 / 25.99 | 57 / 26 | 77 / 30 | 84 / 32 | 101 / 36 |
DrahtBot commented 2026-11-30 05:05:14 +00:00 (Migrated from github.com)

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.
A summary of reviews will appear here.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36844 (iwyu: Fix warnings in more modules in src/ and treat them as errors by hebasto)
  • #35229 (refactor: Use CBlockIndex parameters as reference by optout21)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/37015 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/37015.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/37015#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. A summary of reviews will appear here. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36844](https://github.com/bitcoin/bitcoin/pull/36844) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36844.svg"></sub> (iwyu: Fix warnings in more modules in `src/` and treat them as errors by hebasto) * [#35229](https://github.com/bitcoin/bitcoin/pull/35229) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35229.svg"></sub> (refactor: Use CBlockIndex parameters as reference by optout21) If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. <!--5faf32d7da4f0f540f40219e4f7537a3-->
First-time contributor

Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments.

🔵 Suggestion · Immediate-parent lookups pay for unnecessary TreeNode setup

LocatorEntries and time-based sequence-lock checks pay for TreeNode setup even when the answer is pprev; a direct return removes that work without changing results or step counts, though its wall-clock benefit is unmeasured.

Location: src/chain.cpp:321 (head).

🔵 Suggestion · Pointer counts leave the tracked-walk trade-off unmeasured

The supplied pointer counts do not measure TreeNode setup versus avoided cache misses, so they cannot establish whether the final walk improves on the simpler traversal for hot short and cold long lookups.

Location: src/chain.cpp:218 (head).

🔵 Suggestion · Step-count instrumentation arrives after the scheme replacement

Although the final tree tests the bounds, the series adds step counting only after replacing the old walk, separating the bounds from their assertions and preventing a same-counter comparison across the scheme change.

Location: src/chain.cpp:166 (commit).

Review coverage was incomplete.


Reviewed: 7ee87e299243 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:312ddb2095238aa2ca395a9cc39b05ab5a38a7177afbdb0d69098df9c3e0bef9:9a7f127b15c6116c267953d38288a9f17ec7c7bcd3a975fb71a2db8bfd974dbf --> <!-- ralph-base:1ea904d983f8841c28cb8240c576e46ac2efe529 --> <!-- ralph-head:7ee87e299243ad2c1d8986d0189a55023dcefe93 --> <!-- ralph-case:5189ba58138c5f93bc63e041705adcddaf0f4e3225546c637abbae53a66f80be --> Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments. **🔵 Suggestion · Immediate-parent lookups pay for unnecessary `TreeNode` setup** `LocatorEntries` and time-based sequence-lock checks pay for `TreeNode` setup even when the answer is `pprev`; a direct return removes that work without changing results or step counts, though its wall-clock benefit is unmeasured. Location: [`src/chain.cpp:321`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/7ee87e299243ad2c1d8986d0189a55023dcefe93/src/chain.cpp#L321>) (head). **🔵 Suggestion · Pointer counts leave the tracked-walk trade-off unmeasured** The supplied pointer counts do not measure `TreeNode` setup versus avoided cache misses, so they cannot establish whether the final walk improves on the simpler traversal for hot short and cold long lookups. Location: [`src/chain.cpp:218`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/7ee87e299243ad2c1d8986d0189a55023dcefe93/src/chain.cpp#L218>) (head). **🔵 Suggestion · Step-count instrumentation arrives after the scheme replacement** Although the final tree tests the bounds, the series adds step counting only after replacing the old walk, separating the bounds from their assertions and preventing a same-counter comparison across the scheme change. Location: src/chain.cpp:166 (commit). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`7ee87e299243`](<https://git.fish.foo/bitcoin/bitcoin/commit/7ee87e299243ad2c1d8986d0189a55023dcefe93>) · [Review report](<https://review.fish.foo/report/37015-7ee87e299243ad2c1d8986d0189a55023dcefe93-3358-4.html>) · [Previous reports](<https://review.fish.foo/traces/37015/>) [permalink](<https://review.fish.foo/report/37015-7ee87e299243ad2c1d8986d0189a55023dcefe93-3358-4.html>)
ajtowns (Migrated from github.com) reviewed 2026-11-30 06:57:35 +00:00
ajtowns (Migrated from github.com) commented 2026-11-30 06:57:34 +00:00

Can this just be a function?

def base_skip(height):
    size = (1 << (height + 1).bit_length()) - 1   # perfect tree holding 0..height
    start = 0       # first entry of the current subtree
    skip = 0        # start of the last subtree we entered from the right
    while height != start + size - 1: # until height is subtree's root
        size //= 2
        if height >= start + size: # height is in the right half
            if size > 1:
                skip = start
            start += size
    if size == 1: # leaf
        return skip
    else: # inner node: its left child
        return height - (size + 1) // 2
Can this just be a function? ```python def base_skip(height): size = (1 << (height + 1).bit_length()) - 1 # perfect tree holding 0..height start = 0 # first entry of the current subtree skip = 0 # start of the last subtree we entered from the right while height != start + size - 1: # until height is subtree's root size //= 2 if height >= start + size: # height is in the right half if size > 1: skip = start start += size if size == 1: # leaf return skip else: # inner node: its left child return height - (size + 1) // 2 ```
flack commented 2026-11-30 10:09:38 +00:00 (Migrated from github.com)

#4220 in the description should probably be #4420

#4220 in the description should probably be #4420
sipa (Migrated from github.com) reviewed 2026-11-30 12:39:07 +00:00
sipa (Migrated from github.com) commented 2026-11-30 12:39:07 +00:00

The reason for having it as a class is the last commit, which allows computing the pskip values everywhere along GetAncestor's walk path before dereferencing pskip.

But your description of the algorithm is much shorter than what I had. I'll use that in the 2nd commit, and turn it into a class later.

The reason for having it as a class is the last commit, which allows computing the pskip values everywhere along `GetAncestor`'s walk path before dereferencing `pskip`. But your description of the algorithm is much shorter than what I had. I'll use that in the 2nd commit, and turn it into a class later.
sipa (Migrated from github.com) reviewed 2026-12-01 03:30:26 +00:00
sipa (Migrated from github.com) commented 2026-12-01 03:30:26 +00:00

I have updated the initial commit to use this approach, plus added Python reference code to generate a SHA256 of the first 2M skip heights, which is verified in the unit tests.

The last two commits deviate from it somewhat, by using it just in the construction of the TreeNode class, which can do more than just compute the skip height, but also "walk" the tree (updating its state to match following pprev or pskip but without dereferencing). It's a nontrivial change, and it's really only beneficial when the filter is not in CPU cache, as its goal is avoiding RAM lookup by trading them for a bit more CPU. I could be talked into dropping the last commit (and the preparation commit before it).

I have updated the initial commit to use this approach, plus added Python reference code to generate a SHA256 of the first 2M skip heights, which is verified in the unit tests. The last two commits deviate from it somewhat, by using it just in the construction of the `TreeNode` class, which can do more than just compute the skip height, but also "walk" the tree (updating its state to match following `pprev` or `pskip` but without dereferencing). It's a nontrivial change, and it's really only beneficial when the filter is not in CPU cache, as its goal is avoiding RAM lookup by trading them for a bit more CPU. I could be talked into dropping the last commit (and the preparation commit before it).
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!37015
No description provided.