Skip to content

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

Open
sipa wants to merge 5 commits into
bitcoin:masterfrom
sipa:202611_skiplist
Open

sipa wants to merge 5 commits into
bitcoin:masterfrom
sipa:202611_skiplist

Conversation

@sipa

@sipa sipa commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

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 #33661 (comment)). 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::GetAncestor follows pprev from entries whose pskip is not
set. Several unit tests rely on that, by building chains without calling
BuildSkip, but nothing tests it directly. Add a test for it, including
for chains in which only some entries have a skip pointer.
@DrahtBot

DrahtBot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

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.

@sipa
sipa force-pushed the 202611_skiplist branch 2 times, most recently from 066e34e to 85325bf Compare November 30, 2026 05:35
Comment thread src/chain.cpp
constexpr uint32_t TreeSize(int level) { return (uint32_t{1} << level) - 1; }

/** A height, as a node in the arrangement of heights into trees described above. */
class TreeNode

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@flack

flack commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

#4220 in the description should probably be #4420

sipa and others added 4 commits November 30, 2026 18:15
The heights that CBlockIndex::pskip points to were chosen in c9a0918
for doing well in simulations. With them, GetAncestor follows
O(log^2(n)) pointers from height n, on average as well as in the worst
case.

Replace them with a scheme in which that is O(log(n)): getting from
height n to any ancestor means following at most 2*floor(log2(n+1))-1
pointers. The heights are arranged into a binary tree like in Myers' "An
applicative random-access stack" (1983), but with other skip pointers: a
node with children points to its left child (pprev points to the right
one), and a pair of leaves points to the lowest height of the subtree
below the pair. See the comment in chain.cpp for the scheme and for why
the bound holds.

GetAncestor now follows pskip whenever that does not lead below the
requested height, which it tells from the height of the entry that pskip
points to, rather than by computing that height.

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

The height that pskip points to still depends on the height only, so
LastCommonAncestor is unaffected. Skip pointers are not stored on disk.

GetSkipHeight, which finds that height by descending the tree from its
root, is now declared in chain.h. The unit test for the skip heights
encoded the old scheme. Replace it with one that compares the skip
heights with reference hashes, computed by the Python code in the test.

Co-authored-by: Anthony Towns <[email protected]>
GetAncestorWithSteps is like GetAncestor, but also returns the number of
pointers followed. Both call an always-inlined FindAncestor, so that
GetAncestor does not pay for the counting.

Use it to test that lookups find the right entry within the two bounds
on the number of steps that chain.cpp gives. This is done for all pairs
of heights below 256 and a fixed pattern of lookups in a longer chain,
whose step counts must also match a reference hash, and for random
lookups. Going from height 2^k - 3 to height 1 must take 2*k - 3 steps,
which is exactly the bound.
Turn GetSkipHeight into a wrapper around a new TreeNode class, which
holds a height together with the size of its subtree, and has a member
function for every height that the skip height is built from (the left
child, the root of the subtree below, and so on). This prepares for
keeping track of such a node during a walk, in the next commit.

The descent from the root moves into the constructor, where it finds the
size of the subtree of a height. It no longer remembers where the pskip
of a leaf leads. That is now found through the nodes of the heights
below the leaf.

The skip heights do not change, as the reference hashes in the unit test
show.
To decide whether to follow pskip, GetAncestor reads the height of the
entry that it points to. If pskip is then not followed, that touched an
entry that is not on the path, and that is likely not in the CPU cache.
Going 144 blocks back reads 15.0 entries on average, of which 10.4 are
on the path.

Instead, keep track of where the walk is in the tree of heights (the
size of the subtree of the current height, and the sizes of the subtrees
below it), which tells where pskip and pprev lead with a constant amount
of work per step. TreeNode gets a field for those sizes, and its member
functions now return nodes rather than heights (Skip replaces
SkipHeight, and so on). Only finding the node of the starting height
takes a loop.

This is faster when entries are not in the CPU cache, and slower for
short lookups between recently used entries, where finding the node of
the starting height takes longer than the walk itself.

Add a test that GetAncestor only uses the height of the entry it starts
from, by giving all other entries a wrong height.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants