Skip to content

Keep decompressed blocks while a union re-reads them - #167

Open
cldellow wants to merge 1 commit into
masterfrom
block-cache
Open

cldellow wants to merge 1 commit into
masterfrom
block-cache

Conversation

@cldellow

@cldellow cldellow commented Nov 23, 2026 •

Copy link
Copy Markdown
Owner

Fixes #166.

Change

A query that unions several statements over the same area decompresses each data block once per statement. Point-of-interest lookups, the main load on the public servers, have this shape. The prompting query p04 decompresses nodes.bin blocks 1,709 times for 263 distinct blocks, and LZ4 decompression takes 49% of its CPU time.

While a union that will re-read blocks runs, each block it decompresses is kept, and later reads copy it instead of decompressing it again. Three commits:

  1. Block_Cache (template_db/file_blocks_index.h, used by File_Blocks::read_block_ in template_db/file_blocks.h). The read-only file index owns a cache of decompressed blocks by block position:
    • What's kept: only the bytes a block uses (a block starts with that count, header included).
    • Bound: all caches of a process together hold at most 32 MiB, and nothing is evicted. Once the limit is reached, blocks are decompressed on every read as before. Each index gives its bytes back when destroyed, so long-lived processes such as the area-rules loop keep their budget. Like other auxiliary structures, the cache doesn't count toward [maxsize:].
    • What bypasses it: uncompressed files (nothing to save), write transactions (data changes), and continuation blocks of large objects (read with check_idx == false; they don't start with a size).
  2. Which unions: Union_Statement::execute checks whether two or more of its query statements have the same Query_Statement::block_signature(), their type plus their filters other than tag filters rendered as QL (e.g. node(around:25000,44.6488,-63.5752)). Such statements read the same blocks. While that union runs, Block_Cache::rereads_expected() is raised. Statements of different types read different files, so a union of a node, a way and a relation statement over one bbox doesn't count.
  3. Only then: blocks are kept only while rereads_expected() is raised, from their first read. Blocks kept during the union still serve later reads, e.g. by out center. Every other query runs as before.

About 100 lines in five files. No change to the query API or the on-disk format.

How the policy was chosen

The first commit alone kept a block on its third read in every query. That gave p04 −20% against master, but made p06 and t04 4–8% slower on all-changes, p10 about 4% slower against master, and used up to 32 MiB on queries that gain nothing. Caching on the second read everywhere made q06, p08 and t01 9–13% slower. Inside detected unions, caching from the first read beats caching from the second (p04 −14% vs −5% against the first commit). Leaving the type out of the signature flagged unions such as t10 (a node, a way and a relation statement over one bbox) that never re-read, filling the cache for nothing. The 2nd and 3rd commits are those findings.

Impact

Geofabrik Nova Scotia extract imported with --meta, LZ4 compression, page cache warm, 4-core cloud VM. bench/compare.py --paired --reps 25 --rss: CPU time (user+system) per query, 25 alternating pairs. Baseline: upstream/master (8edf11b); candidate: this PR (cf4564c). Output is identical for every query.

Point-of-interest set (bench/queries-poi, prompting query p04)

Query master this PR paired B/A (95% CI) B faster sign test p peak RSS (MB)
p01 230 ms 164 ms 0.709 (0.689–0.730) 25/25 <0.0001 11.5 → 35.7
p02 1124 ms 1044 ms 0.920 (0.898–0.942) 24/25 <0.0001 63.8 → 95.6
p03 401 ms 388 ms 0.974 (0.950–0.998) 18/25 0.043 9.3 → 9.4
p04 712 ms 515 ms 0.719 (0.707–0.732) 25/25 <0.0001 18.8 → 51.1
p05 301 ms 220 ms 0.747 (0.726–0.769) 25/25 <0.0001 15.9 → 35.5
p06 1125 ms 1091 ms 0.978 (0.962–0.994) 20/25 0.004 18.1 → 50.6
p07 737 ms 731 ms 1.005 (0.990–1.020) 12/25 1. 14.8 → 14.2
p08 208 ms 206 ms 0.987 (0.955–1.021) 12/25 1. 12.8 → 45.0
p09 260 ms 201 ms 0.766 (0.747–0.786) 25/25 <0.0001 11.7 → 25.1
p10 436 ms 426 ms 0.976 (0.962–0.991) 18/25 0.043 10.3 → 10.7

The POI queries, run on the plain database except p07, which needs areas:

  • p01: [out:json][timeout:30]; (node["amenity"="school"](around:3000,44.6488,-63.5752); way["amenity"="school"](around:3000,44.6488,-63.5752); node["amenity"="kindergarten"](around:3000,44.6488,-63.5752); node["amenity"="hospital"](around:5000,44.6488,-63.5752); way["amenity"="hospital"](around:5000,44.6488,-63.5752); node["amenity"="pharmacy"](around:3000,44.6488,-63.5752); node["shop"~"supermarket|convenience|mall"](around:2000,44.6488,-63.5752); way["shop"~"supermarket|convenience|mall"](around:2000,44.6488,-63.5752); node["highway"="bus_stop"](around:1500,44.6488,-63.5752); way["leisure"="park"](around:2000,44.6488,-63.5752); way["highway"~"primary|secondary|tertiary"](around:2000,44.6488,-63.5752); way["highway"~"residential|unclassified|service"](around:500,44.6488,-63.5752); way["landuse"="industrial"](around:3000,44.6488,-63.5752); node["amenity"="fuel"](around:3000,44.6488,-63.5752); ); out center body;
  • p02: [out:json][timeout:25]; (node["amenity"~"fuel|cafe"]["brand"~"tim hortons|irving|esso|shell|petro-canada|ultramar|circle k|needs|starbucks",i](44.45,-63.85,44.85,-63.35); node["amenity"~"fuel|cafe"]["name"~"tim hortons|irving|esso|shell|petro-canada|ultramar|circle k|needs|starbucks",i](44.45,-63.85,44.85,-63.35); way["amenity"~"fuel|cafe"]["brand"~"tim hortons|irving|esso|shell|petro-canada|ultramar|circle k|needs|starbucks",i](44.45,-63.85,44.85,-63.35); node["shop"~"supermarket|convenience"]["brand"~"sobeys|superstore|atlantic superstore|walmart|lawtons|shoppers drug mart|foodland",i](44.45,-63.85,44.85,-63.35); way["shop"~"supermarket|convenience"]["brand"~"sobeys|superstore|atlantic superstore|walmart|lawtons|shoppers drug mart|foodland",i](44.45,-63.85,44.85,-63.35); ); out center tags;
  • p03: [out:json][timeout:300]; (node["amenity"="fuel"]; way["amenity"="fuel"]; ); out center tags;
  • p04: [out:json][timeout:45]; (node["tourism"](around:25000,44.6488,-63.5752); way["tourism"](around:25000,44.6488,-63.5752); node["amenity"~"restaurant|cafe|bar|pub|fast_food|ice_cream"](around:25000,44.6488,-63.5752); way["amenity"~"restaurant|cafe|bar|pub"](around:25000,44.6488,-63.5752); node["leisure"~"park|garden|stadium|sports_centre|marina|golf_course"](around:25000,44.6488,-63.5752); way["leisure"~"park|garden|stadium|nature_reserve"](around:25000,44.6488,-63.5752); node["historic"](around:25000,44.6488,-63.5752); way["historic"](around:25000,44.6488,-63.5752); node["natural"~"peak|beach|waterfall"](around:25000,44.6488,-63.5752); ); out body center 500;
  • p05: [out:json][timeout:15]; (node["amenity"~"^(restaurant|fast_food|cafe|pharmacy|school)$"](around:4828,44.6488,-63.5752); way["amenity"~"^(restaurant|fast_food|cafe|pharmacy|school)$"](around:4828,44.6488,-63.5752); node["shop"~"^(supermarket|convenience|bakery)$"](around:4828,44.6488,-63.5752); way["shop"~"^(supermarket|convenience|bakery)$"](around:4828,44.6488,-63.5752); node["leisure"~"^(park|playground|fitness_centre)$"](around:4828,44.6488,-63.5752); way["leisure"~"^(park|playground|fitness_centre)$"](around:4828,44.6488,-63.5752); relation["leisure"~"^(park|recreation_ground)$"](around:4828,44.6488,-63.5752); ); out center tags;
  • p06: [out:json][timeout:90]; (way["maxspeed"]["highway"="primary"](43.3,-66.5,47.1,-59.6); way["bridge"]["maxspeed"](43.3,-66.5,47.1,-59.6); way["tunnel"](43.3,-66.5,47.1,-59.6); node["maxheight"](43.3,-66.5,47.1,-59.6); ); out center;
  • p07: [out:json][timeout:30]; area["name"="Nova Scotia"]["admin_level"="4"]->.p; (way["boundary"="administrative"]["admin_level"="6"](area.p); relation["boundary"="administrative"]["admin_level"="6"](area.p); ); out geom;
  • p08: [out:json][timeout:30]; (node["amenity"="clinic"]["name"~"dental|medical|health|family|physio",i](around:25000,44.6488,-63.5752); way["amenity"="clinic"]["name"~"dental|medical|health|family|physio",i](around:25000,44.6488,-63.5752); node["healthcare"~"dentist|physiotherapist|optometrist",i](around:25000,44.6488,-63.5752); way["healthcare"~"dentist|physiotherapist|optometrist",i](around:25000,44.6488,-63.5752); ); out body center qt;
  • p09: [out:json][timeout:25][bbox:44.6440,-63.5800,44.6520,-63.5650]; (node[amenity]; way[amenity]; relation[amenity]; node[building~"^(commercial|retail|office|public|civic|school|university|hospital|church|hotel|supermarket)$"]; way[building~"^(commercial|retail|office|public|civic|school|university|hospital|church|hotel|supermarket)$"]; node[entrance]; node[highway~"^(bus_stop|crossing|elevator)$"]; way[highway~"^(cycleway|footway|living_street|path|pedestrian|primary|residential|secondary|service|steps|tertiary|trunk|unclassified)$"]; node[leisure]; way[leisure~"^(pitch|park|garden|playground)$"]; node[shop]; way[shop]; node[tourism]; way[tourism]; ); out geom;
  • p10: [out:json][timeout:420]; (node["amenity"="fuel"](43.3,-66.5,47.1,-59.6); way["amenity"="fuel"](43.3,-66.5,47.1,-59.6); ); out center;

Other sets

No query is significantly slower; a few unions and some single statements are 2–5% faster:

Set master (sum of medians) this PR Significant per-query changes
Benchmark queries q01–q12 3,328 ms 3,290 ms q06 0.970 (0.952–0.989), q11 0.947 (0.914–0.981); peak RSS within 0.4 MB
Client-tool queries t01, t03–t06, t08–t11 3,164 ms 3,105 ms t04 0.837 (0.812–0.862), RSS 9.9 → 36.5 MB; t11 0.875 (0.868–0.882), RSS 9.7 → 22.1 MB; t03 0.985; others' RSS within 0.5 MB
Area queries a1–a4, t02, t07 (areas database) 3,905 ms 3,884 ms a1 0.963, t02 0.964; RSS within 0.5 MB

Peak RSS rises only for unions the heuristic detects: p01, p02, p04, p05, p06, p08, p09, t04 and t11, by up to the 32 MiB limit.

On all-changes (d6f343b without these commits against e0954f4 with them, same method), the gains are larger: p04 0.675 (0.664–0.687), p05 0.685 (0.664–0.706), p01 0.707 (0.691–0.723), p09 0.767 (0.755–0.779), t04 0.846 (0.823–0.870), t11 0.890 (0.856–0.925), p02 0.923 (0.907–0.939). Only p10 looks slower, p10 1.018 (1.003–1.032), sign test p=0.11. p10 is not a detected union, and its peak RSS is unchanged (10.3 → 10.6 MB).

Testing

  • Output is identical to the baseline for all 37 queries above.

  • This PR's CI (cf4564c):

    • fuzz run 45280378363: 5,986 same, 14 skipped, 0 differences.
    • history run 45280378230: 1,998 same, 2 skipped, 0 differences.
    • props run 45280377959: 60 seeds, no new failures.

    The skips time out on both builds, except plain query 1007, which takes about 30–31 s on both builds, right at fuzz.py's 30 s limit (see the earlier comment).

  • On all-changes (e0954f4):

    • fuzz run 45281762847: 5,986 same, 14 skipped.
    • history run 45281767630: 1,999 same, 1 skipped.
    • props run 45281771102: 60 seeds, no new failures.
  • Mutation testing: a mutant that keeps each cached block without its last 8 bytes is caught by six props checks (mutate run 45216773318, on the first commit). Mutants of the 2nd and 3rd commits can only change which blocks are cached, never what a read returns, so they are equivalent and recorded as such.

Limitations and open questions

  • Memory: up to 32 MiB more per query, for detected unions. p06 and p08 are detected unions that fill the cache without gaining much: their statements read each block about twice. The limit is a constant and could be lowered.
  • Heuristic: the signature compares QL text, so equivalent filters written differently (e.g. coordinates with more digits) don't match. Unions that re-read for other reasons are not detected. Before the third commit, the third-read rule caught some of them; p07 gained 7% that way.
  • Production configuration: only LZ4 was measured. Zlib-compressed databases decompress more slowly, so they should gain more.
  • A merged scan of the union's statements would save the remaining per-statement work as well (see the discussion below). It is a much larger change.

https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT


Generated by Claude Code

@cldellow cldellow added the query-perf Query performance change; collected on all-changes label Nov 23, 2026 — with Claude

Copy link
Copy Markdown
Owner Author

CI results (PR runs against upstream/master)

  • fuzz run 45215858951: 5,986 same, 14 skipped, 0 differences.
  • history run 45215858930: 1,998 same, 2 skipped, 0 differences.
  • props run 45215858908: 60 seeds, no new failures.

13 of the 14 fuzz skips timed out on both builds. The other, plain query 1007 (seed 1), finished on master and timed out on this branch, both in the first run and in a rerun. The baseline's outcome came from the cache in both runs. Locally, on the same extract, it takes 30.8 and 31.8 s on master and 30.4 and 30.7 s on this branch, with identical output. So it sits right at fuzz.py's 30 s limit, and the cached master outcome was from a run that just made it. This is not a slowdown. The query:

[timeout:60][maxsize:536870912];
rel(44.874138,-63.922351,44.888190,-63.869536)->.s0;
way(around.s0:20)["highway"~"^motorw",i]->.s1;
rel(br.s0)->.s2;
.s1 out skel 27;

(On all-changes it takes 0.29 s.)

On all-changes (3b4e810, this change as commit 52), dispatched from master:

  • fuzz run 45216684089: 5,987 same, 13 skipped.
  • history run 45216688471: 1,999 same, 1 skipped.
  • props run 45216692274: 60 seeds, no new failures.

Mutation test: the mutant for commit 52 keeps each cached block without its last 8 bytes (#168). It is caught by six props checks (mutate run 45216773318).


Generated by Claude Code

@cldellow

Copy link
Copy Markdown
Owner Author

Colin thoughts: I like this because it's simple and generally usable in many places. I dislike it because it still leaves a lot of performance on the table. I wonder if there's a heuristic we could use to know earlier that a query will be re-reading its inputs?

More exotic: could we have something akin to a peephole optimizer that rewrites the queries into a format that is less likely to do multiple reads? Assumption: part of the waste is inherent in how the input sets are written, i.e. as a union of multiple statements instead of as a single statement with a suitable filter expression.

cldellow commented Nov 23, 2026 •

Copy link
Copy Markdown
Owner Author

Testing the assumption that the waste comes from writing the input as a union of statements instead of one statement with a suitable filter.

I rewrote p04 (the prompting query, defined in the description) in four equivalent ways and ran each on three builds: upstream/master; this PR (upstream/master plus the block cache); and all-changes at 3b4e810, which already includes this PR as commit 52 along with the other 51 commits. Setup: Nova Scotia extract with --meta, LZ4, warm page cache. CPU is user+system, single runs. All 15 outputs are identical.

p04 form master all-changes (includes this PR) this PR (master + cache)
v0: the original union of 9 statements 0.50 s 0.34 s 0.47 s
v1: around once per type into a set, then the tag filters on that set 2.96 s 2.83 s 2.88 s
v2: key-only statements merged with a key regex 0.48 s 0.31 s 0.38 s
v3: one statement per type with an (if: is_tag(...) || ...) filter 2.62 s 2.61 s 2.90 s
v4: the tag filters first, over the whole database, then around once 1.23 s 0.86 s 1.10 s

What this shows:

  • The union isn't the waste. Each statement in the union scans only the cells holding its own tag's candidates inside the circle, narrowed by the tag index. The forms that read the area once (v1, v3) lose that narrowing and scan every node and way within 25 km: 6× slower, and 140–220 MB. v4 keeps the tag index but drops the spatial narrowing.
  • The only single-statement form that helps is v2, which merges statements with the same key-only shape. It gains 9% on all-changes and 19% on master with the cache, but it applies only to such statements.
  • The waste is reading the same blocks for different filters. The fix would be a merged scan inside the engine rather than a rewrite of the QL: for a union of query statements with the same spatial constraint, take the union of their candidate ranges, read each block once, and test each element against every statement's filter. It's a peephole rewrite of the execution plan, not of the text.
  • Size of the prize: its decompression savings are bounded by what this PR gets with an unbounded cache. An earlier prototype that cached on the second read with a 64 MiB budget took 26% off p04, against this PR's 18–20%. A merged scan would also save the per-statement range and around geometry work. After this PR, master spends 24% of p04 in the tag binary search (already replaced on all-changes by tag_store: find tag entries' ids with a forward cursor instead of a binary search #138) and 26% decompressing distinct blocks, which nothing can avoid.

Knowing early that a query will re-read: yes, from the parsed query, before execution. A union with two or more query statements sharing an identical around, bbox or area constraint will re-read. That signal could switch the cache on from the first read for those queries, and leave every other query at zero cost. It is simpler than a merged scan, and it would remove the regressions seen against all-changes (p06, t04), which come from caching blocks that are read only three times.

The rewritten queries
  • v1: [out:json][timeout:45]; node(around:25000,44.6488,-63.5752)->.n; way(around:25000,44.6488,-63.5752)->.w; (node.n["tourism"]; way.w["tourism"]; node.n["amenity"~"restaurant|cafe|bar|pub|fast_food|ice_cream"]; way.w["amenity"~"restaurant|cafe|bar|pub"]; node.n["leisure"~"park|garden|stadium|sports_centre|marina|golf_course"]; way.w["leisure"~"park|garden|stadium|nature_reserve"]; node.n["historic"]; way.w["historic"]; node.n["natural"~"peak|beach|waterfall"]; ); out body center 500;
  • v2: [out:json][timeout:45]; (node[~"^(tourism|historic)$"~"."](around:25000,44.6488,-63.5752); way[~"^(tourism|historic)$"~"."](around:25000,44.6488,-63.5752); node["amenity"~"restaurant|cafe|bar|pub|fast_food|ice_cream"](around:25000,44.6488,-63.5752); way["amenity"~"restaurant|cafe|bar|pub"](around:25000,44.6488,-63.5752); node["leisure"~"park|garden|stadium|sports_centre|marina|golf_course"](around:25000,44.6488,-63.5752); way["leisure"~"park|garden|stadium|nature_reserve"](around:25000,44.6488,-63.5752); node["natural"~"peak|beach|waterfall"](around:25000,44.6488,-63.5752); ); out body center 500;
  • v3: [out:json][timeout:45]; (node(around:25000,44.6488,-63.5752)(if: is_tag("tourism") || is_tag("historic") || is_tag("amenity") || is_tag("leisure") || is_tag("natural"))->.n; way(around:25000,44.6488,-63.5752)(if: is_tag("tourism") || is_tag("historic") || is_tag("amenity") || is_tag("leisure"))->.w;); (node.n["tourism"]; way.w["tourism"]; node.n["amenity"~"restaurant|cafe|bar|pub|fast_food|ice_cream"]; way.w["amenity"~"restaurant|cafe|bar|pub"]; node.n["leisure"~"park|garden|stadium|sports_centre|marina|golf_course"]; way.w["leisure"~"park|garden|stadium|nature_reserve"]; node.n["historic"]; way.w["historic"]; node.n["natural"~"peak|beach|waterfall"]; ); out body center 500;
  • v4: [out:json][timeout:45]; (node["tourism"]; node["historic"]; node["amenity"~"restaurant|cafe|bar|pub|fast_food|ice_cream"]; node["leisure"~"park|garden|stadium|sports_centre|marina|golf_course"]; node["natural"~"peak|beach|waterfall"];)->.n; (way["tourism"]; way["historic"]; way["amenity"~"restaurant|cafe|bar|pub"]; way["leisure"~"park|garden|stadium|nature_reserve"];)->.w; (node.n(around:25000,44.6488,-63.5752); way.w(around:25000,44.6488,-63.5752);); out body center 500;

Generated by Claude Code

@cldellow cldellow changed the title template_db: keep decompressed blocks that a query reads repeatedly Keep decompressed blocks while a union re-reads them Nov 23, 2026
A union of query statements of one type with the same filters apart
from tag filters, such as node statements around the same point with
different tags, reads and decompresses the same blocks once per
statement. While such a union runs, each block read from a compressed
read-only file is kept decompressed, and later reads copy it instead of
decompressing it again. Other queries keep nothing.

The cache belongs to the transaction, which gives it to the indexes of
its read-only files, so it lives no longer than the snapshot it was read
from, and flush() empties it. It keeps only a block's used bytes, holds
at most a quarter of the query's [maxsize:] (128 MiB by default) per
transaction, and evicts nothing. Like other auxiliary structures it
isn't counted toward [maxsize:]; it stays within the headroom of the
process memory limit, 2 x maxsize + 1 GiB. Whether a union qualifies
only decides what is kept; results never depend on it.

Geofabrik Nova Scotia extract (2026-11-08) with the area rules run,
warm cache, 4-core VM, 15 alternating pairs: CPU time 28% lower, peak
memory 19 -> 51 MB:

  [out:json][timeout:45]; (node["tourism"](around:25000,44.6488,-63.5752);
    way["tourism"](around:25000,44.6488,-63.5752);
    node["amenity"~"restaurant|cafe|bar|pub|fast_food|ice_cream"](around:25000,44.6488,-63.5752);
    way["amenity"~"restaurant|cafe|bar|pub"](around:25000,44.6488,-63.5752);
    node["leisure"~"park|garden|stadium|sports_centre|marina|golf_course"](around:25000,44.6488,-63.5752);
    way["leisure"~"park|garden|stadium|nature_reserve"](around:25000,44.6488,-63.5752);
    node["historic"](around:25000,44.6488,-63.5752);
    way["historic"](around:25000,44.6488,-63.5752);
    node["natural"~"peak|beach|waterfall"](around:25000,44.6488,-63.5752);
  ); out body center 500;

Co-Authored-By: Colin Dellow <cldellow@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

query-perf Query performance change; collected on all-changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unions of statements over the same area decompress each data block once per statement

2 participants