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

pull sipa wants to merge 5 commits into bitcoin:master from sipa:202611_skiplist changing 4 files +496 −121
  1. sipa commented at 5:05 AM on November 30, 2026: 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 (review)). 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://github.com/user-attachments/assets/24fb6622-86ec-439c-bc86-d70de2e78501" />

    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
  2. test: check GetAncestor with missing skip pointers
    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.
    2e6152146a
  3. DrahtBot commented at 5:05 AM on November 30, 2026: contributor

    <!--e57a25ab6845829454e8d69fc972939a-->

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

    <!--006a51241073e994b41acfe9ec718e94-->

    External sites

    <!--021abf342d371248e50ceaed478a90ca-->

    Reviews

    See the guideline and AI policy 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 <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 <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-->

  4. sipa force-pushed on Nov 30, 2026
  5. sipa force-pushed on Nov 30, 2026
  6. in src/chain.cpp:175 in 3427788c10 outdated
     181 | -}
     182 | +/** The number of heights in a subtree of the given level. */
     183 | +constexpr uint32_t TreeSize(int level) { return (uint32_t{1} << level) - 1; }
     184 | +
     185 | +/** A height, as a node in the arrangement of heights into trees described above. */
     186 | +class TreeNode
    


    ajtowns commented at 6:57 AM on November 30, 2026:

    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
    

    sipa commented at 12:39 PM on November 30, 2026:

    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 commented at 3:30 AM on December 1, 2026:

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

  7. flack commented at 10:09 AM on November 30, 2026: contributor

    #4220 in the description should probably be #4420

  8. chain: replace the skip pointer scheme of CBlockIndex
    The heights that CBlockIndex::pskip points to were chosen in c9a0918330f
    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 <aj@erisian.com.au>
    3a05dfa2ba
  9. chain: add GetAncestorWithSteps, and test the number of steps
    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.
    e562a46073
  10. refactor: compute skip heights with a TreeNode class
    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.
    447b2e07c8
  11. chain: keep track of the tree node in GetAncestor
    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.
    7ee87e2992
  12. sipa force-pushed on Nov 30, 2026
  13. optout21 commented at 2:23 PM on December 4, 2026: contributor

    Nice to see a systematic solution for the under-documented skip-heights (that I happened to stumble upon in #33661).

    Had a glance at the code. Reproduced the benchmark results (with own vibe-coded test code).

    I'm still undecided on the value of this change, however, based on the pros-cons:

    Pro:

    • Faster, fewer pointer steps on average at every distance; about 2× fewer for long distances (d=330000: avg 26.8 vs 60.3, max 37 vs 110).
    • Well documented and tested, more modern code
    • Theoretically sound, with clear worst-case bound (O(log n) worst case; ≤ 2·⌊log₂(H+1)⌋−1 steps)

    Con:

    • The gain is likely not measurable in real node use (IBD, reindex, normal operation).
    • More code (~36 → ~280 lines in chain.cpp, about 90 of them code) in a consensus-affecting function.
    • Worse tail for short distances: d=20 max 10 → 20, d=40 max 14 → 23, even though the average and median improve.
    • No "wall-time" benchmark results, time may be affected by the extra cost of building skip pointers.

github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-12-05 04:51 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me