Skip to content

All changes combined (tracking PR) - #12

Open
cldellow wants to merge 80 commits into
masterfrom
all-changes
Open

cldellow wants to merge 80 commits into
masterfrom
all-changes

Conversation

@cldellow

@cldellow cldellow commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner

Fixes #6, fixes #4, fixes #3, fixes #5, fixes #9, fixes #15, fixes #16, fixes #19, fixes #23, fixes #27, fixes #30, fixes #36, fixes #37, fixes #32, fixes #40, fixes #62, fixes #70, fixes #78, fixes #79, fixes #85, fixes #63, fixes #72, fixes #77, fixes #76, fixes #94, fixes #96, fixes #93, fixes #103, fixes #120, fixes #119, fixes #125, fixes #129, fixes #127, fixes #135, fixes #137, fixes #139, fixes #149, fixes #156, fixes #161, fixes #166, fixes #212, fixes #217, fixes #219, fixes #221, fixes #223, fixes #215, fixes #232, fixes #234, fixes #236, fixes #238, fixes #240, fixes #173, fixes #177, fixes #176, fixes #175, fixes #181, fixes #183, fixes #190, fixes #192, fixes #169, fixes #197, fixes #209, fixes #242, fixes #246, fixes #248, fixes #250, fixes #252, fixes #254.

all-changes combines every performance and memory change explored in this fork, cherry-picked onto master (fossgis, a9d8f15). Each change also has its own PR for review. This PR tracks their combined effect. None of the changes alters the database format or the query API.

All measurements below are from one snapshot, 2026-11-27: master a9d8f15 against all-changes 02ea396 (80 commits), on every query this description defines. Output is identical on every query that both builds finish (master doesn't finish four prompting queries, see ¹). Commits 14, 20 and 39 were merged upstream and are part of master a9d8f15, so these numbers don't count them. Per-commit effects are in each commit's PR.

Summary

Set CPU master → all-changes Peak memory
Benchmark queries, q01–q12 2,912 ms → 1,527 ms (−48%) up to 67% lower; about 3 MB higher on the smallest queries ²
Area queries, a1–a4 3,012 ms → 1,087 ms (−64%) 17–43% lower on three of four; a1 up 5 MB ²
Client-tool queries, t01–t11 2,902 ms → 1,074 ms (−63%) up to 76% lower (t03, t06); up for t04 (block cache) and 2–6 MB on the small ones ²
Point-of-interest queries, p01–p10 4,517 ms → 1,685 ms (−63%) up on unions that re-read blocks (block cache, up to 140 MB)
History queries, h1–h6 13,645 ms → 7,873 ms (−42%) h3 528 → 93 MB; others up to 44% lower
Large result sets, R1–R21, P1, P2 289 s → 93 s (−68%) 1.1–1.5 GB → 0.1–0.4 GB on the largest
Prompting queries 2× to 250× faster; four that master can't finish within its own CPU limit take 0.5–9 s up to 24× lower

Commits

In branch order. The prompting queries are defined under Prompting queries; q, a, t, p and h are the benchmark sets.

# Commit Change PR Prompting query
1 Reject non-matching ids with a bit filter before binary search Hashed bit filter in front of Id_Predicate's binary search #1 q01, q02
2 around: use fixed-size arrays for 3-D vectors std::array instead of heap-allocated vectors in around's geometry #7 A
3 around: index the input set's geometry with a coarse grid Spatial grid so around only tests nearby geometry #10 A, B, C
4 around: check the query's time limit while filtering candidates Periodic health_check inside around's candidate loops #8 D
5 around: let the tag index drive queries whose around area is large Area-aware strategy, so a selective tag filter can drive the query #13 E
6 Format output coordinates without general float formatting Exact fixed-point formatter for all coordinate outputs #17 q10, F
7 Collect relation node members and way nodes in one pass > and >> read each node block once instead of twice #18 q07
8 bbox filter: keep ways in inner tiles without loading their geometry No geometry check for ways whose index tile lies inside the box. Its helper was replaced by commit 72, which covers compound indexes too #21 q04, G
9 Write tag strings without an escaped copy when nothing needs escaping Replaced by commit 79 (#206); no longer on this branch. Escape keys, values, users and roles only when needed #26 (closed) H
10 area queries: decode area blocks once per tile, skip blocks out of range Area boundary blocks decoded once per tile; blocks whose longitude range misses the point skipped #29 a2, a3
11 Meta_Collector: keep a tile's metadata in a sorted vector, not a std::set Metadata lookups (out meta, newer, user filters) use a sorted vector #31 h3, h5
12 around grid: test each entry once per lookup, tighter reach for segments Revision of the grid: no repeated tests, a single scan for oversized lookups, tighter segment boxes #10 (second commit) I
13 around: take candidate ranges for relation inputs from their members Candidate ranges for relation inputs from their members' indexes, not the relation's extent #38 I, J
14 user: filter relations by touched ids whenever the set has relations Merged upstream; no longer on this branch. Correctness fix: uid_touched and user_touched returned relations the users never touched when the set had relations but no nodes #41 (merged upstream)
15 user: compute the ids of touched objects once per query The touched ids are computed once per query instead of in every lookup and loop iteration #42 h6, L
16 query: run metadata-only filters before geometry filters newer and the user filters run before bbox, around and area checks #43 K
17 around: skip index entries without objects when computing candidate ranges Empty index entries left by date filtering no longer widen around's ranges #66 N
18 area and poly queries: decode each block once per tile for the segment tests Segment tests take blocks decoded once per tile #71 t08, a2
19 Geometry stores: keep member node positions in 16 bytes, not 40 Memory: geometry stores keep 16-byte positions instead of 40-byte nodes #67 R1–R4, R9, R10
20 Don't copy the input set when passing it or an empty set by reference Merged upstream; no longer on this branch. Memory: out count and around no longer copy their input set #68 (merged upstream) R5, R6
21 filter_attic_elements: per-index timestamps in a sorted vector, not a std::map Memory: per-candidate timestamps at a past date in a sorted vector #73 R7, R8
22 poly queries: test nodes against blocks decoded once per tile poly: node tests use decoded blocks with an early longitude exit #80 P, t08
23 area and poly queries: skip the segment test when bounding boxes don't overlap Segment tests skipped for block pairs with disjoint boxes #81 t08, a2
24 collect_items_range: keep the result size up to date instead of recounting it The memory-limit check in range scans keeps a running total #86 h3
25 Segment pre-check: allow the 1-unit latitude slack intersects_inner uses Correctness fix to commit 23: the box test allows the slack the exact test uses #81 (second commit)
26 Collect_Items: cap chunk size, and chunk queries at a past date Memory: chunks also end at 64 MiB accounted, and queries at a past date chunk too #87 R1, h3, R11
27 keep_matching_skeletons: valid-until timestamps in a sorted vector, not a std::map Memory: picking the version valid at a past date uses a sorted vector #88 R9, R12, R13
28 user: keep touched ids for the whole query, whatever their number Commit 15 without its 2M-id bound, so the most prolific users benefit too #42 (second commit) h6, L
29 Collect relation node members and way nodes in one pass at past dates Commit 7's single pass for [date:] and [diff:] #95 Q
30 filter_attic_elements: build and use the timestamps one index at a time Memory: per-candidate timestamps built, used and dropped per index #97 R7, R8
31 changed: collect only the ids other constraints allow Memory: changed: keeps only the ids the other constraints allow #98 R14–R16
32 bbox query: collect and filter nodes in chunks at a past date Memory: a standalone node(bbox) at a past date works chunk by chunk #104 R7, R17
33 around: weight the time-limit check by the work done, and check inside long ways Commit 4's check counts comparisons and runs inside the per-way test. Here the per-test estimate is capped at 1,024, because the grid narrows tests #8 (second commit)
34 around: take candidate ranges for relations at a past date from their members Commit 13 for relations at a past date #38 (second commit) S
35 around: look up the input relations' members once per input The member ranges are kept per input instead of looked up about 6 times per execution #38 (third commit) J, S
36 Collect_Items: count elements, not only indexes, in way and relation history collection Memory: way and relation collection at a past date reaches the size check, so commit 26's cap applies #87 (second commit) R12
37 bbox query: count the accumulated result in the chunk loop's size checks Commit 32's size checks count the result built so far, so a standalone node(bbox) at a past date whose result exceeds [maxsize:] fails as soon as it does, not after building the whole result #104 (second commit) R7, R17 with [maxsize:]
38 print: reserve the id-sorted element references exactly Memory: out (except qt) reserves its id-sorted references instead of growing them to up to 2.2× their size #121 R18, P1
39 collect_items: pass end iterators to reconstruct_items by reference Merged upstream; no longer on this branch. Collecting objects at a past date no longer copies two block buffers per index #117 (merged upstream) R13
40 collect_items_by_timestamp: keep the result size up to date instead of recounting it Commit 24's running size for collection at a past date, instead of recounting the whole result every 128K objects #122 (stacked on #86) R12
41 tag_store: remove placeholder tags only from the entries just collected Tag collection at a past date no longer re-scans every object collected so far for each coarse index #126 R9
42 Filter bbox and past-date results in place, without vector slack Memory: filter_by_bbox and filter_attic_elements compact each vector in place and shrink it, instead of rebuilding it by push_back #130 R7, P2
43 Tag_Store: generate the id list once, and keep only a chunk's attic tags Memory: chunked out with tags builds the id lists once, not per chunk, and drops earlier chunks' attic tags #128 P2, R21
44 area and poly queries: build each way's geometry once in collect_ways Area and poly: queries build each candidate way's geometry once instead of twice #136 a3
45 tag_store: find tag entries' ids with a forward cursor instead of a binary search Tag output finds each tag entry's object in the tile's id list from a forward cursor instead of a binary search #138 q12, t05
46 Tag_Store: keep only a chunk's ids when printing in chunks Memory: chunked out with tags builds each chunk's id lists from that chunk's elements, not the whole set #140 (stacked on #128) P2, R21
47 print: reference id-sorted elements in 8 bytes Memory: out (except qt) sorts 8-byte references (vector entry, position) instead of 16-byte, or 24-byte with attic elements #150 (stacked on #121) R18, P1
48 print: look up current and attic references the same way Commit 47 finds both kinds of element through one table, without a branch in the sort #150 (second commit) R18, P1
49 query: narrow ranges to the candidates' cells inside them, not all candidates When tag filters pick the candidates, the scan is narrowed to the candidates' coarse cells inside the search area; a faulty test skipped this for nearly every tag in a large area #157 p04
50 query: merge overlapping ranges before filtering the candidates' cells Correctness fix to commit 49, found by the CI fuzz run: the cell filter's binary search needs non-overlapping ranges #157 (second commit)
51 around: build a polyline's candidate range directly Correctness fix to commit 17, found by a CI fuzz trial: around with a polyline returned nothing, because commit 17 skips the empty map entry the polyline's range was built from #66 (second commit), #161
52 template_db: keep decompressed blocks that a query reads repeatedly Replaced by commit 67; no longer on this branch. Adds a cache of decompressed blocks, owned by the read-only file index: only a block's used bytes, at most 32 MiB per process, no eviction. As first committed, a block read for the third time is kept; commits 53 and 54 change when. Memory: up to 32 MiB more per query #167 p04
53 union: cache blocks from their first read when statements will re-read them Replaced by commit 67; no longer on this branch. A union of two or more query statements with the same type and the same filters apart from tag filters (e.g. node statements around the same point with different tags) reads the same blocks once per statement. While such a union runs, blocks are kept from their first read #167 (second commit) p01, p04, p05, p09
54 template_db: keep blocks only while a statement expects re-reads Replaced by commit 67; no longer on this branch. Drops commit 52's third-read rule: blocks are kept only while a union detected by commit 53 runs. Every other query runs as before the cache #167 (third commit) p10
55 block iterators: compare index entries in place instead of decoding them The range and discrete assessors compare raw index entries with less(void*)/leq(void*) instead of building an Index, which allocated two strings per tag entry examined. Its collect_tags_framed lookup change is already here (cursor commit), so only the assessor part is cherry-picked #213 20 US northeast production-shaped queries
56 block iterators: decode index entries and objects without a heap allocation Idx_Handle decodes into storage inside the handle instead of new/delete per entry; also adds the missing return *this to its operator= #214 20 US northeast production-shaped queries
57 diff: move tags and geometry into the *_With_Context records Each diffed element's tags and geometry are copied once instead of twice. No measurable gain (−0.25% instructions at most) #218 diff queries in #218
58 diff: pass the input set's derived elements to compute_deriveds by reference Removes one copy per diff of a usually empty map. No measurable gain #220 diff queries in #220
59 collect_items: remember the last result slot while collecting One map lookup per index instead of per object in the collection loops. Here the NOW loop of collect_items_range already did this (commit 40's running size), so it covers the other 5 #222 s_m1 (−3.4% instructions)
60 local tags: read an entry's cell from the raw index instead of decoding it Local tag loops read a tag entry's cell from its raw bytes and decode key and value only for entries they use #224 p05 (−7.3% instructions)
61 area queries: skip the way-area pass when the input holds no way-areas ways_contained_in no longer builds every candidate way's geometry when the input set has no ways to take as areas, or once the last way-area tile has passed #216 a2, a3
62 Collect_Items: end a chunk at 16 MiB accounted, not 64 MiB Memory: commit 26's chunk cap drops to 16 MiB accounted (2M nodes or 128k ways). Peak −56% to −61% for queries whose candidates exceeded it, CPU unchanged #233 (stacked on #87) m1, p04, h8, d1 in #233
63 query: build the late tag check's ids one cell at a time Memory: the late tag check fills each cell's candidate ids just before filtering it, instead of copying all ids up front #235 m1 in #235
64 tag filters at a past date: don't add every candidate to the timestamp map find() instead of operator[] in the past-date value listener, which inserted a map entry per rejected candidate. CPU only #237 d1, d4 in #237
65 query: run (if:) filters that need geometry after the other filters Commit 16's ordering gains a last pass for (if:) filters whose expression needs geometry, so spatial filters narrow the candidates first. 12–90× on such queries #239 (stacked on #43) fuzz seed 3 drolbr#285, drolbr#695 in #239
66 changed: reuse the ids found within the known ids in filter() filter() reuses the ids commit 31's get_*_ids_within found instead of reading the changelog again #241 (stacked on #98) fuzz seed 3 history #1238 in #241
67 union: keep decompressed blocks while statements will re-read them Replaces commits 52–54 with #167's reviewed design: the cache belongs to the transaction (cleared with its snapshot) and holds at most a quarter of [maxsize:] (128 MiB by default); it is used only while a union whose query statements share all non-tag filters runs. Memory: up to [maxsize:]/4 more for such unions, nothing for other queries #167 p04
68 tags: run tag index regexes once per key and value, not per element Tag index regex filters run once per distinct key and value instead of once per element #174 p12, p20 in #174
69 query: read only the checked keys' tag entries in late tag checks Late tag checks read only the entries of the keys they check #178 in #178
70 regex: match plain word alternations without the regex library Patterns that are only ASCII words separated by | (anchored or not) are matched by substring search or comparison; other patterns and non-ASCII values use the library #179 p12, p20 in #179
71 tags: remove redundant sorts of the candidate ids for late tag checks The late tag check's candidate ids are sorted once #180 in #180
72 bbox: don't load the geometry of ways whose index lies inside the bbox Commit 8 for every index, compound ones too; replaces commit 8's helper #182 in #182
73 around: don't load the geometry of ways whose index lies within the radius Commit 72's idea for around #184 in #184
74 around: skip points too far apart in latitude before the distance test A latitude difference check before the great-circle distance #191 in #191
75 recurse: handle wr(bn) in the query constraint Correctness fix: wr(bn.s) with a tag filter returned nothing at the current date and unrelated relations at past dates; it also no longer scans globally ("Filters too weak") #193 in #193
76 tags: bound the ids collected from attic tags, as for current data Memory: past-date tag filters bound their candidate ids as current-data ones do #194 in #194
77 changed: scan only the changelogs of element types in the set changed: skips the changelog of a type the set has no elements of #198 in #198
78 recurse: skip the scan for parent relations of no relations rel(br) returns at once when the input has no relations #204 in #204
79 Write escaped strings in one pass, copying runs that need no escaping Replaces commit 9: table-driven escaping that copies unescaped runs #206 H
80 tag_store: build each element's tag list once, at its final size Chunked tag collection builds each element's list once #210 in #210
81 output: hand tags to output handlers by reference, without copying them Memory: output handlers get tags by reference #211 (stacked on #210) in #211
82 query: drop tag-index candidates outside the query's ranges during the lookup With a bbox of 1 square degree or more, candidates from the global tag index are dropped after each key if their cell lies outside the query's ranges, keys are looked up smallest first (counted in index blocks), and the remaining tags are checked late when that reads fewer blocks. The maxheight query over an empty 1° box: 0.24 → 0.00 s #243 maxheight query (#242)
83 query: collect few tag-index candidates by their exact indices Candidates are collected by their exact indices from the id map instead of their whole coarse cells, when the map blocks read are fewer than half the skeleton blocks saved #247 (stacked on #243) dense_1 in #247
84 tags: reject entries of later keys with a bit filter before the binary search Commit 1's Id_Bit_Filter in front of the binary search in filter_id_list #249 (stacked on #1) p20, p12 in #249
85 tag_store: reject other elements' tag entries with a bit filter The same filter in front of commit 45's cursor in collect_tags_framed; here applied to the cursor version rather than #251's binary search #251 (stacked on #1) p07, p18 in #251
86 block cache: don't keep global tag index blocks Memory: commit 67's cache no longer keeps *_tags_global blocks, which a union's statements don't re-read #253 (stacked on #167) empty_1, p20 in #253
87 query: collect only the elements the local tag index says match Memory: with the range strategy (bbox under 1 square degree, around under 2 km), the ids carrying every positive tag filter are read from the local tag index first, so collection skips the rest without decoding them. The maxheight query at 0.99999°: 3.61 → 0.76 s, 213 → 142 MB #255 dense_099, p04 in #255

Added on 2026-11-27: commits 82–87, from profiling the maxheight query (#242, one of the worst offenders on the public servers) in dense, sparse and empty boxes at 1° and 0.99999°. Against the previous tip (a71b7e3), on the 41 queries of #255 (the maxheight variants, the 20 production-shaped queries and 15 diff, meta and past-date queries), total CPU fell 19.0%, and output is identical to upstream/master on all 41. Largest changes: dense_099 3.61 → 0.76 s, p04 3.65 → 0.82 s, p20 0.26 → 0.02 s, p12 0.32 → 0.08 s, p05 0.35 → 0.11 s, p19 2.80 → 1.11 s, empty_1 0.26 → 0.00 s; peak memory p12 79 → 16 MB, p20 68 → 13 MB, empty_1 73 → 9 MB. Commits 84 and 85 were resolved against this branch's versions of the code they change (commit 45's cursor, #174's matcher); the others applied as in their PRs.

Rebuilt on 2026-11-26 to add commits 67–81 (every open performance and memory PR that wasn't here yet) and to replace two superseded changes: commit 9 (#26, closed) by commit 79 (#206), and commits 52–54 (the first block-cache design) by commit 67 (#167 as reviewed). Replaced and upstreamed rows stay in the table, struck out, so the numbering doesn't change. Three commits needed conflicts resolved when cherry-picked: commit 72 replaces commit 8's ways-in-inner-tiles helper, which it subsumes; commit 73 keeps commit 33's health check in around's filter calls; commits 80 and 81 use commit 45's forward cursor and commit 46's per-chunk ids in collect_tags_framed, and commit 47's compact references in print.

Method

CPU is user + system time of osm3s_query, warm page cache, on a 4-core VM (bench/compare.py --no-cache --rss: runs alternate between the builds, and each table shows the median). Runs per build: 7 for q and a, 5 for t, p, w and h, 3 for the prompting queries, 1 for the large result sets. Peak memory is RSS from one extra run under GNU time. Run-to-run noise is about ±10% per query, so differences under that are within noise; single runs (large result sets) are noisier.

² Small queries peak about 3 MB higher than in the previous measurement (e.g. q01 8.8 → 11.5 MB on all-changes, with master unchanged at 8.6 MB). Not yet traced to a commit.

¹ master doesn't finish C, D, I or J: the process's hard CPU limit (2 × [timeout:] + 60 s, so 420 s at the default 180 s, or 80 s for D's [timeout:10]) kills it with no output. All-changes was run 3 times on these, master once.

  • Plain and Areas: the current data (osmium time-filter) of the Nova Scotia full-history extract below, as of 2026-11-15 (12.7M nodes, 883k ways, 21.4k relations), imported with --meta by master's update_database, with the standard area rules run. Queries that don't use areas ("plain" below) ran on this database too.
  • History: a Geofabrik full-history extract of Nova Scotia (2006 to 2026-11-15), imported with the better-imports build of update_database.
  • Both databases use --compression-method=lz4 --map-compression-method=lz4 (an uncompressed id map didn't fit on this VM's disk during the import).

Benchmark queries

Query CPU master CPU all-changes Change Peak master Peak all-changes
q01 global tag 141 ms 90 ms −37% 8.6 MB 11.5 MB
q02 rare global tag 153 ms 56 ms −64% 8.5 MB 11.5 MB
q03 bbox, all nodes 38 ms 28 ms −26% 18.5 MB 17.7 MB
q04 bbox + tag 117 ms 45 ms −61% 28.9 MB 15.1 MB
q05 recurse down 129 ms 104 ms −19% 10.6 MB 11.0 MB
q06 around a node set 94 ms 30 ms −68% 20.2 MB 11.6 MB
q07 province boundary (._;>>;) 613 ms 359 ms −41% 34.2 MB 35.0 MB
q08 out meta 347 ms 118 ms −66% 37.7 MB 12.6 MB
q09 out geom, small box 56 ms 30 ms −47% 10.6 MB 10.1 MB
q10 out geom, large box 440 ms 198 ms −55% 31.5 MB 17.9 MB
q11 recurse up 53 ms 36 ms −32% 9.2 MB 11.6 MB
q12 JOSM-style download 731 ms 434 ms −41% 27.2 MB 22.9 MB
Total 2,912 ms 1,527 ms −48%
Queries q01–q12
Query Text
q01 [out:csv(::count)]; nwr[amenity=restaurant]; out count;
q02 [out:csv(::count)]; node[natural=peak]; out count;
q03 [out:csv(::count)]; node(44.60,-63.66,44.70,-63.52); out count;
q04 [out:csv(::count)]; way[highway](44.60,-63.66,44.70,-63.52); out count;
q05 [out:csv(::count)]; way[highway=motorway]; (._;>;); out count;
q06 [out:csv(::count)]; node[amenity=cafe](44.60,-63.66,44.70,-63.52); node(around:300)[shop]; out count;
q07 [out:csv(::count)]; rel[boundary=administrative][admin_level=4][name="Nova Scotia"]; (._;>>;); out count;
q08 [out:xml]; nwr[amenity](44.60,-63.66,44.70,-63.52); out meta;
q09 [out:json]; way[building](44.640,-63.585,44.655,-63.565); out geom;
q10 [out:json]; way[highway](44.60,-63.66,44.70,-63.52); out geom;
q11 [out:csv(::count)]; node[highway=traffic_signals](44.60,-63.66,44.70,-63.52); way(bn); rel(bw); out count;
q12 [out:xml]; nwr(44.640,-63.590,44.655,-63.570); (._;>;); out meta;

Area queries

Query CPU master CPU all-changes Change Peak master Peak all-changes
a1 cafés in Halifax 57 ms 34 ms −39% 10.1 MB 14.9 MB
a2 highways in Halifax 981 ms 207 ms −79% 51.0 MB 28.9 MB
a3 buildings in the regional municipality 1,806 ms 721 ms −60% 134 MB 106 MB
a4 is_in for cafés 168 ms 124 ms −26% 22.5 MB 18.7 MB
w1 highways in parks (ways as areas) 309 ms 200 ms −35% 30.2 MB 18.1 MB
w2 buildings in residential areas (ways as areas) 174 ms 115 ms −34% 23.7 MB 17.6 MB
Total 3,495 ms 1,402 ms −60%
Queries a1–a4
Query Text
a1 [out:csv(::count)]; area[name="Halifax"][admin_level=8]->.a; node[amenity=cafe](area.a); out count;
a2 [out:csv(::count)]; area[name="Halifax"][admin_level=8]->.a; way[highway](area.a); out count;
a3 [out:csv(::count)]; area[name="Halifax Regional Municipality"]->.a; way[building](area.a); out count;
a4 [out:csv(::count)]; node[amenity=cafe](44.60,-63.66,44.70,-63.52); is_in; out count;

w1 is [out:csv(::count)]; way[leisure=park](44.60,-63.66,44.70,-63.52)->.p; way[highway](area.p); out count; and w2 is [out:csv(::count)]; way[landuse=residential](44.60,-63.66,44.70,-63.52)->.r; way[building](area.r); out count;.

Client-tool queries

Built from the templates of overpass turbo, JOSM, QGIS QuickOSM, osmnx, osmdata and MapComplete, filled in for Halifax, on the area database.

Query CPU master CPU all-changes Change Peak master Peak all-changes
t01 overpass turbo, default example 22 ms 13 ms −40% 8.6 MB 11.7 MB
t02 overpass turbo wizard, in an area 125 ms 53 ms −57% 10.0 MB 14.5 MB
t03 overpass turbo wizard, in a box 234 ms 51 ms −78% 41.8 MB 9.9 MB
t04 overpass turbo, cycle network example 182 ms 84 ms −54% 10.0 MB 32.4 MB
t05 JOSM, full download 563 ms 309 ms −45% 20.6 MB 18.2 MB
t06 JOSM query wizard 271 ms 74 ms −73% 41.9 MB 11.7 MB
t07 QuickOSM, in an area 136 ms 63 ms −54% 10.3 MB 14.5 MB
t08 osmnx road network for a place 1,012 ms 268 ms −73% 36.0 MB 18.0 MB
t09 osmnx features for a place 149 ms 81 ms −45% 10.1 MB 12.8 MB
t10 osmdata 113 ms 43 ms −62% 9.4 MB 12.0 MB
t11 MapComplete 97 ms 35 ms −64% 11.0 MB 16.2 MB
Total 2,902 ms 1,074 ms −63%
Queries t01–t11
Query Text
t01 node[amenity=drinking_water](viewport); out;
t02 [out:json][timeout:25]; area(id:3609092218)->.searchArea; nwr["amenity"="restaurant"](area.searchArea); out geom;
t03 [out:json][timeout:25]; nwr["shop"](city bbox); out geom;
t04 [out:json]; (relation[route=bicycle](city bbox); way[highway=cycleway](city bbox); way[highway=path][bicycle=designated](city bbox);); out body; >; out skel qt;
t05 [out:xml]; (node(viewport); <;); (._;>;); out meta;
t06 [out:xml][timeout:90][bbox:city bbox]; (nwr["shop"];); (._;>;); out meta;
t07 [out:xml] [timeout:25]; area(3609092218) -> .area_0; (node["amenity"="restaurant"](area.area_0); way["amenity"="restaurant"](area.area_0); relation["amenity"="restaurant"](area.area_0);); (._;>;); out body;
t08 [out:json][timeout:180];(way["highway"]["area"!~"yes"]["access"!~"private"]["highway"!~"<highway list>"]["motor_vehicle"!~"no"]["motorcar"!~"no"]["service"!~"<service list>"](poly:'<Halifax boundary>');>;);out;
t09 [out:json][timeout:180];((node['amenity'='restaurant'](poly:'<Halifax boundary>');(._;>;););(way['amenity'='restaurant'](poly:'<Halifax boundary>');(._;>;););(relation['amenity'='restaurant'](poly:'<Halifax boundary>');(._;>;););out;
t10 [out:xml][timeout:25]; (node ["amenity"="restaurant"] (city bbox); way ["amenity"="restaurant"] (city bbox); relation ["amenity"="restaurant"] (city bbox);); (._;>;); out body;
t11 [out:json][timeout:30][bbox:44.6400,-63.5875,44.6560,-63.5575];(nwr["amenity"="bench"];nwr["leisure"="playground"];nwr["amenity"="waste_basket"];);out body;out meta;>;out skel qt;
  • viewport is 44.6440,-63.5800,44.6520,-63.5650; city bbox is 44.5812,-63.7227,44.7112,-63.5427, the bounding box of Halifax (relation 9092218, area id 3609092218).
  • <Halifax boundary> is the outer ring of relation 9092218 from the public extract: 1,041 points as lat lon pairs.
  • <highway list> is abandoned|bridleway|bus_guideway|construction|corridor|cycleway|elevator|escalator|footway|no|path|pedestrian|planned|platform|proposed|raceway|razed|rest_area|service|services|steps|track; <service list> is alley|driveway|emergency_access|parking|parking_aisle|private.

Point-of-interest queries

bench/queries-poi/: shaped like the heaviest query templates on the public servers (#159), on the area database.

Query CPU master CPU all-changes Change Peak master Peak all-changes
p01 union of 14 statements around a point (0.5–5 km) 185 ms 68 ms −63% 11.4 MB 24.8 MB
p02 brand and name regexes, ,i, in a box 940 ms 135 ms −86% 63.9 MB 59.6 MB
p03 global tag, out center tags 315 ms 113 ms −64% 9.6 MB 11.7 MB
p04 union around a point, 25 km, regex values 572 ms 173 ms −70% 19.0 MB 63.9 MB
p05 union around a point, anchored alternations 255 ms 104 ms −59% 16.2 MB 32.8 MB
p06 union of tag filters in a province box 925 ms 450 ms −51% 18.7 MB 140 MB
p07 admin boundaries in an area, out geom 616 ms 431 ms −30% 14.2 MB 14.1 MB
p08 union around a point, name regexes, ,i 169 ms 51 ms −70% 12.7 MB 18.4 MB
p09 many tag filters in a global bbox, out geom 198 ms 50 ms −75% 11.7 MB 18.4 MB
p10 fuel stations in a province box, out center 342 ms 113 ms −67% 10.7 MB 12.1 MB
Total 4,517 ms 1,685 ms −63%

Peak memory rises on the unions of statements that read the same blocks (p01, p04–p06, p08, p09, and t04 and t11 above): commit 67 keeps their decompressed blocks while the union runs, up to a quarter of [maxsize:] (128 MiB by default). Other queries keep nothing.

Queries p01–p10
Query Text
p01 `[out:json][timeout:30]; (node"amenity"="school"; way"amenity"="school"; node"amenity"="kindergarten"; node"amenity"="hospital"; way"amenity"="hospital"; node"amenity"="pharmacy"; node["shop"~"supermarket
p02 `[out:json][timeout:25]; (node["amenity"~"fuel
p03 [out:json][timeout:300]; (node["amenity"="fuel"]; way["amenity"="fuel"]; ); out center tags;
p04 `[out:json][timeout:45]; (node"tourism"; way"tourism"; node["amenity"~"restaurant
p05 `[out:json][timeout:15]; (node["amenity"~"^(restaurant
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
p09 `[out:json][timeout:25][bbox:44.6440,-63.5800,44.6520,-63.5650]; (node[amenity]; way[amenity]; relation[amenity]; node[building~"^(commercial
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;

History queries

Query CPU master CPU all-changes Change Peak master Peak all-changes
h1 box + tag at a past date 998 ms 581 ms −42% 85.1 MB 70.4 MB
h2 [diff:] on a box 4,684 ms 3,507 ms −25% 306 MB 267 MB
h3 newer on a province-sized box 4,418 ms 2,132 ms −52% 528 MB 93.1 MB
h4 recursion at a past date 256 ms 169 ms −34% 12.4 MB 12.7 MB
h5 one user's objects in a box, out meta 1,572 ms 795 ms −49% 89.5 MB 49.8 MB
h6 objects a user ever touched in a box 1,717 ms 688 ms −60% 75.6 MB 62.2 MB
Total 13,645 ms 7,873 ms −42%
Queries h1–h6
Query Text
h1 [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; nwr[amenity](44.60,-63.66,44.70,-63.52); out count;
h2 [diff:"2026-11-12T00:00:00Z","2026-11-19T00:00:00Z"]; nwr(44.60,-63.66,44.70,-63.52); out meta;
h3 [out:csv(::count)]; nwr(newer:"2026-11-08T00:00:00Z")(43.3,-66.5,47.1,-59.6); out count;
h4 [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; way[highway=primary](44.60,-63.66,44.70,-63.52); (._;>;); out count;
h5 nwr(uid:{{UID}})(44.60,-63.66,44.70,-63.52); out meta;
h6 [out:csv(::count)]; nwr(uid_touched:{{UID}})(44.60,-63.66,44.70,-63.52); out count;

{{UID}} is the user id with the most current objects in the box. It comes from licensed data, so it isn't given.

Prompting queries

The queries that prompted individual changes.

Query Database CPU master CPU all-changes Peak master Peak all-changes
A: around 282 ways plain 20.6 s 0.74 s 30.1 MB 18.2 MB
B: around nodes and ways within 1 km plain 27.7 s 0.11 s 21.9 MB 17.4 MB
C: around every way in a downtown box plain killed at the 420 s CPU limit, no output ¹ 3.26 s 180 MB 105 MB
D: around a set reaching a national boundary, [timeout:10] plain killed at the 80 s CPU limit, no output ¹ 9.25 s (finishes within its 10 s limit) 1,105 MB 236 MB
D without a time limit plain killed at the 420 s CPU limit, no output ¹ 8.75 s 1,105 MB 237 MB
E: footway nodes on relations touching a small box plain 1.97 s 0.10 s 395 MB 17.0 MB
F: CSV coordinates of every node in a box (17 MB) plain 0.65 s 0.31 s 90.9 MB 47.9 MB
G: count every way in a box plain 0.23 s 0.06 s 58.2 MB 23.5 MB
H: JSON tags of every building in a box (13 MB) plain 0.45 s 0.20 s 53.3 MB 26.2 MB
I: ways near objects edited since 2016, around province-long routes history killed at the 420 s CPU limit, no output ¹ 2.36 s 1,112 MB 170 MB
J: all nodes on relations touching a small box plain killed at the 420 s CPU limit, no output ¹ 0.48 s 298 MB 77.3 MB
K: ways edited since a date, province box history 5.63 s 0.63 s 1,094 MB 91.4 MB
L: a user's touched objects near each of 76 cafés, in a loop history 108.4 s 5.42 s 67.6 MB 72.0 MB
N: around at a past date, after a date filter left empty index entries history 14.3 s 0.12 s 534 MB 33.9 MB
P: amenity nodes in the 1,041-point Halifax poly: areas 2.47 s 0.04 s 31.6 MB 10.2 MB
Q: hiking routes with > at a past date history 1.25 s 0.65 s 64.5 MB 64.5 MB
S: E at a past date history 10.9 s 1.01 s 1,270 MB 53.8 MB
Queries A–S
Query Text
A [out:csv(::count)]; way(around:250,44.679085,-63.511161)->.s0; way(around.s0:100); out count;
B [out:csv(::count)]; nw(around:1000,44.790135,-65.396762)->.s0; way(around.s0:100)["width"!="1"]; out count;
C [out:csv(::count)]; way(44.648535,-63.573386,44.662526,-63.528647)->.s0; way(around.s0:100)["created_by"!~"^JO"]; out count;
D [timeout:10][out:csv(::count)]; rel(id:5429184,7081003,8322255,9270031,10270951,13448043)->.s0; .s0 <<->.s2; way(around.s2:0)[!"height"]; out count; (without a time limit: the same without [timeout:10])
E [out:csv(::count)]; rel(45.566265,-62.428420,45.586924,-62.388716)->.s0; node(around.s0:0)["footway"]; out count;
F [out:csv(::id,::lat,::lon)]; node(44.60,-63.66,44.70,-63.52); out;
G [out:csv(::count)]; way(44.60,-63.66,44.70,-63.52); out count;
H [out:json]; way[building](44.60,-63.66,44.70,-63.52); out tags;
I [out:csv(::count)]; wr(newer:"2016-12-19T18:03:25Z")(45.574002,-62.284014,45.619842,-62.234392)->.s0; way(around.s0:20)["material"!~"^conc"]; out count;
J [out:csv(::count)]; rel(45.566265,-62.428420,45.586924,-62.388716)->.s0; node(around.s0:0); out count;
K [out:csv(::count)]; way(43.3,-66.5,47.1,-59.6)(newer:"2026-11-08T00:00:00Z"); out count;
L [out:csv(::count)]; node[amenity=cafe](44.64,-63.60,44.66,-63.56)->.c; foreach.c->.it { nwr(around.it:100)(uid_touched:{{UID}}); out count; }
N [out:csv(::count)][date:"2013-08-30T00:17:55Z"]; wr(around:50,44.943655,-65.061855)->.s0; way(around.s0:0)["noexit"!~"^y"]; out count;
P [out:csv(::count)];node["amenity"](poly:'<Halifax boundary>');out count;
Q [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; rel[route=hiking]; (._;>;); out count;
S [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; rel(45.566265,-62.428420,45.586924,-62.388716)->.s0; node(around.s0:0)["footway"]; out count;

{{UID}} and <Halifax boundary> are as defined above.

Large result sets

One run per build.

Query Database CPU master CPU all-changes Peak master Peak all-changes
R1 plain 5.30 s 1.11 s 1,094 MB 397 MB
R2 plain 5.70 s 3.20 s 288 MB 149 MB
R3 plain 2.30 s 1.55 s 330 MB 194 MB
R4 plain 4.56 s 3.97 s 266 MB 160 MB
R5 plain 1.24 s 0.72 s 298 MB 290 MB
R6 plain 1.75 s 1.08 s 331 MB 252 MB
P1 plain 3.91 s 3.41 s 684 MB 390 MB
P2 plain 27.9 s 11.1 s 825 MB 401 MB
R7 history 8.05 s 4.05 s 1,238 MB 219 MB
R8 history 4.10 s 2.08 s 331 MB 217 MB
R9 history 11.3 s 5.33 s 236 MB 144 MB
R10 history 17.1 s 7.99 s 265 MB 157 MB
R11 history 33.3 s 11.6 s 1,502 MB 99.8 MB
R12 history 14.8 s 4.50 s 690 MB 336 MB
R13 history 9.73 s 5.83 s 324 MB 196 MB
R14 history 1.92 s 0.25 s 264 MB 11.3 MB
R15 history 2.11 s 0.40 s 264 MB 11.9 MB
R16 history 0.71 s 0.02 s 23.9 MB 9.1 MB
R17 history 9.46 s 5.08 s 1,316 MB 164 MB
R18 history 10.0 s 6.31 s 1,173 MB 331 MB
R21 history 113.4 s 13.1 s 1,242 MB 318 MB
Total 288.6 s 92.8 s
Queries R1–R21, P1, P2
Query Text
R1 [out:csv(::count)]; way(42,-67.6,47.5,-58); out count;
R2 [out:json]; way[highway]; out geom;
R3 [out:xml]; rel(42,-67.6,47.5,-58); out body;
R4 [out:json]; nwr[name]; out center;
R5 [out:csv(::count)]; node(42,-67.6,47.5,-58); out count;
R6 [out:csv(::count)]; node(44.4,-64.0,45.0,-63.0); node(around:5)[amenity]; out count;
R7 [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; node(42,-67.6,47.5,-58); out count;
R8 [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; node(44.4,-64.0,45.0,-63.0); node(around:5)[amenity]; out count;
R9 [date:"2018-01-01T00:00:00Z"][out:json]; way[highway]; out geom;
R10 [date:"2018-01-01T00:00:00Z"][out:json]; nwr[name]; out center;
R11 [date:"2020-01-01T00:00:00Z"][out:csv(::count)]; nwr(newer:"2019-06-01T00:00:00Z")(43.3,-66.5,47.1,-59.6); out count;
R12 [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; way(42,-67.6,47.5,-58); out count;
R13 [date:"2018-01-01T00:00:00Z"][out:xml]; rel(42,-67.6,47.5,-58); out body;
R14 [out:csv(::count)]; node(id:834791230,904610765)(changed:"2010-10-25T12:15:57Z"); out count;
R15 [out:csv(::count)]; node["amenity"="cafe"](changed:"2010-10-25T12:15:57Z"); out count;
R16 [out:csv(::count)]; way(id:24000000,25000000,26000000)(changed:"2010-10-25T12:15:57Z"); out count;
R17 [date:"2012-01-01T00:00:00Z"][out:csv(::id;false)]; node(42,-67.6,47.5,-58); out ids;
R18 [date:"2021-03-01T00:00:00Z"][out:csv(::id;false)]; node(42,-67.6,47.5,-58); out ids;
R21 [date:"2018-01-01T00:00:00Z"][out:xml]; node(42,-67.6,47.5,-58); out;
P1 [out:csv(::id;false)]; node(42,-67.6,47.5,-58); out ids;
P2 [out:xml]; node(42,-67.6,47.5,-58); out;

New structures are bounded. The id filter is at most 16 MiB per predicate, the around grid at most 64 cells per entry, and the block cache a quarter of [maxsize:]. The kept touched-id lists hold one id per touched object; master already holds two such lists at once. Like the existing auxiliary structures, they don't count toward [maxsize:]; counting them would change which queries fail.

Not on this branch: mimalloc

Preloading mimalloc instead of glibc's malloc is a deployment choice, not a code change, so it's kept off this branch. On an earlier state of all-changes, it saved about 6% more CPU on the plain and area sets and about 11% on the history set (#35). It wasn't re-measured for this update.

Testing

Limitations

https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT

https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm


Generated by Claude Code

@cldellow cldellow added the query-perf Query performance change; collected on all-changes label Nov 20, 2026 — with Claude
This was referenced Nov 20, 2026
@cldellow cldellow added bug Fixes wrong results (in addition to the kind label) query-memory labels Nov 21, 2026 — with Claude
claude and others added 21 commits November 26, 2026 20:58
ways_contained_in tests the candidate ways against the input's ways and
relations taken as areas. It walked every candidate way tile by tile,
building each way's geometry in Tilewise_Way_Iterator, even when there
were no such areas (the usual case, area[...]->.a; way(area.a)) or after
the last one had been passed, and then discarded it all.

Return before building the way iterator if the area iterator is empty,
and leave the loop once it is exhausted. Both ways_contained_in overloads
(current and attic).

Geofabrik Nova Scotia extract with areas, warm cache, 25 alternating pairs:

  [out:csv(::count)]; area[name="Halifax Regional Municipality"]->.a; way[building](area.a); out count;
      1607 ms -> 1163 ms (-28%)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT
Query_Statement collects candidates in chunks and filters each chunk
before collecting the next; MAX_CHUNK_ACCOUNTED_SIZE ends a chunk once
eval_map counts that much. eval_map counts a node as 8 bytes, so 64 MiB
let a chunk hold 8 million nodes, about 100 MB in memory. Queries whose
candidates fit under that, such as a tag filter over a city-sized box,
held all of them at once.

The cap is now 16 MiB accounted (2 million nodes or 128k ways). Chunks end
at index boundaries, so filtering a chunk repeats no work of the previous
one.

On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM,
peak RSS, CPU as the median of 7 alternating runs:

  node["amenity"](42.2,-71.3,42.5,-70.9); out meta;
      174 MB -> 77 MB, CPU x0.94
  [date:"2018-06-01T00:00:00Z"]; (node["amenity"](42.2,-71.3,42.5,-70.9); way["amenity"](42.2,-71.3,42.5,-70.9);); out meta;
      543 MB -> 171 MB, CPU x0.98

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35
(cherry picked from commit 4b95ce3)
Query_Statement::filter_by_tags checks tags late for candidates collected
by area: generate_ids_by_coarse copied the id of every candidate into a
map of per-cell id lists, and filter_ids_by_tags then narrowed each list
to the matching ids. All candidate ids were held at once, alongside the
candidates themselves, although only one cell's are needed at a time.

filter_by_tags now creates the map's entries (one per cell, still needed
for the range query and filter_by_ids) without ids, and fill_cell_ids
fills a cell's ids from the items, and attic items at a past date, just
before that cell is filtered. Each list then shrinks to its matches, so
the map ends up holding only those.

On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM,
median of 3 alternating runs:

  node["amenity"](42.2,-71.3,42.5,-70.9); out meta;
      peak RSS 174 MB -> 137 MB, CPU 1.46 s -> 1.29 s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35
(cherry picked from commit d4cc14a)
…p map

Tag_Entry_Listener_Value_Regex::filter_ids keeps the candidates whose
tag matched at the requested date. It looked each candidate up with
timestamps[*it], and operator[] inserts a map entry for every candidate
without a matching tag entry, only to reject it. For a cell of a common
key that is a node allocation per candidate.

It now uses find(); a candidate absent from the map is rejected as before.

On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM,
median CPU of 3 alternating runs:

  [adiff:"2025-01-01T00:00:00Z","2026-11-01T00:00:00Z"]; (node["amenity"](42.2,-71.3,42.5,-70.9); way["building"](42.3,-71.15,42.4,-71.0); ); out geom;
      16.68 s -> 15.36 s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35
(cherry picked from commit 563e4b5)
Query_Statement::apply_all_filters runs metadata-only filters first and
the others in query order. An (if:) filter builds what its expression
needs for every element it evaluates (Set_With_Context::prefetch); for
geometry that is a way or relation geometry store over all candidates.
Written before a spatial filter, as in wr(if:length()>10)(around:10,...),
it computed the geometry of every relation in the coarse candidate ranges,
which the exact around test then nearly all dropped.

Query_Constraint gains filter_needs_geometry(). Filter_Constraint answers
it from its criterion's request_context() (Set_Usage::GEOMETRY), and
apply_all_filters runs such filters in a last pass. (if:) filters on tags,
ids or metadata keep their place, so they still drop candidates before an
expensive spatial test. The filters only remove elements, so the order
doesn't change the result.

On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM,
median of 5 alternating runs:

  [out:json]; wr(if:length()>10)(around:10,40.580976,-75.522374)->.s0; way(r.s0:"house")->.s1; rel.s0(39.638451,-80.311484,39.819817,-80.194662)->.s2; .s2 <<->.s3; .s2 out meta center qt 20;
      CPU 5.44 s -> 0.14 s, peak RSS 187 MB -> 23 MB

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35
(cherry picked from commit 9acbe90)
Changed_Constraint::get_*_ids_within reads the changelog for the given
period and keeps the changed ids among those the other constraints allow.
filter() then read the whole changelog for the period again, to keep the
collected elements that changed. That second read is redundant: an element
outside the known ids fails another constraint anyway, so the ids from the
first read decide the same.

The constraint keeps the ids get_*_ids_within found, per element type, and
filter() uses them instead of reading the changelog again. get_*_ids (the
path without known ids) clears them, so a statement executed again, as in a
loop, can't reuse a previous execution's ids.

On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM,
median of 3 alternating runs:

  node["electrified"="no"](around:250,42.437849,-70.979304)["tiger:zip_left_1"~"^17"](changed:"2008-03-26T21:18:32Z")->.s0; foreach.s0->.it{ .it out ids; (.it; .it >;)->.x; .x out count; } .s0 out meta bb asc;
      CPU 16.21 s -> 9.18 s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35
(cherry picked from commit 4c30af0)
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>
filter_id_list tests every global tag index entry against the key and
value regexes. There is one entry per element, sorted by key and value,
so a filter like ["highway"~"primary|secondary"] runs the same regex on
the same strings once for every element in the database with the key.

Remember the result for the last key and value, and run the regexes only
when either changes. key=value lookups have no regex and keep the plain
test.

This path runs for key-regex filters when the tags are not checked late:
around with a radius of 2 km or more, a bbox of 1 square degree or more,
large polygons and areas, and no spatial filter. For example, on a US
northeast extract this query takes 40% less CPU:

[out:json]; (node["office"="hr"](around:25000,42.3601,-71.0589);
way["office"="hr"](around:25000,42.3601,-71.0589);
node["office"="consulting"]["name"~"hr|human resource|talent|workforce|people",i](around:25000,42.3601,-71.0589);
way["office"="consulting"]["name"~"hr|human resource|talent|workforce|people",i](around:25000,42.3601,-71.0589);
); out body center qt;
When a statement checks tags late, filter_by_tags read every local tag
entry of every coarse index that holds a candidate: all keys of all
elements there, though it only looks at the keys the statement filters
on. A union of statements over the same small area reads all of them
again for each statement.

Restrict the ranges to the entries of the filtered keys, and for negated
filters to the negated keys. Statements with a key regex
([~"k"~"v"]) still read every key. Tag entries are sorted by coarse
index, key and value, so the narrower ranges skip whole blocks.

On a US northeast extract this query takes about half the CPU:

[out:json]; nwr["building"]["building"!="yes"](42.34,-71.08,42.38,-71.04); out count;
Most tag regexes in today's queries are lists of plain words: unanchored
("cafe|bar|pub", a value containing one of them) or anchored as a whole
("^(cafe|bar|pub)$", a value equal to one of them), often
case-insensitive. Each regexec call in the C.UTF-8 locale is slow, more so
with REG_ICASE, which converts the value to wide characters.

Recognise these two forms when the words are ASCII letters, digits and a
few punctuation characters, and match ASCII values by substring search or
comparison, folding ASCII case for case-insensitive patterns. That gives
the same result as the library. Values with other bytes, and all other
patterns, still go to regexec.

On a US northeast extract this query takes about 40% less CPU:

[out:json]; (node["amenity"="clinic"]["name"~"cosmetic|aesthetic|beauty|skin|plastic",i](around:25000,42.3601,-71.0589);
way["amenity"="clinic"]["name"~"cosmetic|aesthetic|beauty|skin|plastic",i](around:25000,42.3601,-71.0589);
node["healthcare"~"aesthetics|cosmetics",i](around:25000,42.3601,-71.0589);
way["healthcare"~"aesthetics|cosmetics",i](around:25000,42.3601,-71.0589);
); out body center qt;
Remove two redundant sorts, and add a guard to avoid a redundant sort in
some cases:

- generate_ids_by_coarse (both overloads) sorted each coarse index's ids
  a second time, after already sorting them and removing duplicates.
- filter_ids_by_tags sorts the ids before checking each required key.
  The first key's ids are always already sorted, so it now sorts only if
  std::is_sorted says they aren't.

Geofabrik Nova Scotia extract, warm cache, 25 alternating pairs:

  [out:json]; (node["shop"](44.45,-63.80,44.85,-63.40); node["amenity"](44.45,-63.80,44.85,-63.40); node["tourism"](44.45,-63.80,44.85,-63.40); ); out count;
      638 ms -> 561 ms (-13%)

Co-Authored-By: Colin Dellow <cldellow@gmail.com>
To test ways against a bbox, Bbox_Filter loads the nodes of every
candidate way and checks its segments. A way's index covers all its
nodes, so when the area of the index lies inside the bbox, every node of
the way does, and the way matches. In a large bbox that is nearly every
way, yet the filter loaded all their nodes, for each way statement.

Move those ways aside before building the geometry store, and keep them.
The bbox must not cross the antimeridian and must span less than 180
degrees of longitude, as segments are then tested without wrapping.

The one difference: a way that references a node missing from the
database has no geometry, and was dropped before. With its index inside
the bbox it is now kept. Consistent databases have no such ways.

On a US northeast extract this query takes 19% less CPU, and a count of
the ways in a 2 x 3.5 degree box needs 2.3 GB instead of 5.1 GB:

[out:json][timeout:120]; (way["maxheight"](41.24,-73.51,42.89,-69.93);
way["maxweight"](41.24,-73.51,42.89,-69.93);
way["maxlength"](41.24,-73.51,42.89,-69.93);
way["maxwidth"](41.24,-73.51,42.89,-69.93);
way["hazmat"](41.24,-73.51,42.89,-69.93);
way["hgv"](41.24,-73.51,42.89,-69.93);
node["maxheight"](41.24,-73.51,42.89,-69.93);
node["maxweight"](41.24,-73.51,42.89,-69.93); ); out geom;
…adius

To test ways against around, Around_Constraint loads the nodes of every
candidate way and measures their distance. A way's index covers all its
nodes, so when the whole area of the index lies within the radius of a
point, every node of the way does, and the way matches. With a large
radius that is most of the ways, yet the filter loaded all their nodes.

For around with points (lat/lon, or input nodes, up to 64), move those
ways aside before building the geometry store, and keep them. Over a
lat/lon box narrower than 180 degrees the distance to a point is greatest
at a corner, so the four corners are tested, with a margin of 1 m. The
area must also lie in the bbox that add_coord registers the point for,
since is_inside only looks there.

The one difference: a way that references a node missing from the
database has no geometry, and was dropped before. With its index within
the radius it is now kept. Consistent databases have no such ways.

On a US northeast extract this query takes about half the CPU and a
third less memory:

[out:json]; way[highway](around:25000,42.3601,-71.0589); out count;
Around_Statement::is_inside(lat, lon) computes the great-circle distance
to every point registered for the candidate's tile until one is within
the radius. When the input set is dense, a tile holds thousands of
points, and the cosines and arccosine dominate the query.

A great-circle distance is at least the difference in latitude, which
great_circle_dist counts as 10,000 km per 90 degrees. Skip points whose
latitude differs by more than the radius plus 1 m; the metre covers
rounding in great_circle_dist, so no match is lost.

On a US northeast extract this query takes a fifth of the CPU:

[out:json]; node(42.35,-71.07,42.37,-71.05)->.s;
node(around.s:20)["highway"]; out count;
A query statement such as wr(bn.s)["highway"] uses Recurse_Constraint
with the type RECURSE_NODE_WR, which none of the constraint's methods
handled, unlike the standalone wr(bn.s):

- get_way_ranges and get_relation_ranges returned global ranges, and
  get_data didn't collect anything, so the statement fell back to the
  tag filters alone over the whole database: it failed with "Filters too
  weak" after scanning, or read every element with the tag.
- filter dropped all ways, and of the relations only the current ones,
  keeping every relation version from attic data unfiltered.

So wr(bn.s) with a tag filter returned nothing, or an error, at the
current date, and unrelated relations at past dates. Treat
RECURSE_NODE_WR as RECURSE_NODE_WAY for ways and as
RECURSE_NODE_RELATION for relations, as the standalone statement does.
The results now match (way(bn.s)[...]; rel(bn.s)[...];).
At a past date, collect_ids built a map of every element that ever had a
filter's tag, in the whole database, for each tag filter of a statement.
At the current date, filter_id_list gives up on the first filter after
1,048,576 ids when tags can also be checked late, and later filters keep
only ids already collected. Do the same at a past date:

- collect_attic_kv, collect_attic_k and collect_attic_kregv take a limit
  and stop once their map holds that many ids. collect_ids passes 1024*1024
  under the same conditions as at the current date (the first filter, and
  prefer_ranges or ids_useful), and gives up as it does there when the
  limit is reached.
- For later filters, collect_ids passes the ids collected so far as
  relevant_ids, so the map holds only those. collect_attic_k gains the
  relevant_ids parameter the other two already have.

Peak RSS, Geofabrik Nova Scotia full-history extract, warm cache, 4-core
VM, for

  [out:xml][date:"2025-12-06T00:00:00Z"]; way(1)->.x; way.x[foot=yes][building=yes]; out meta;

21 MB -> 10 MB (the input set is empty, so 10 MB is the baseline). On a
planet database, a common tag such as highway=service takes several GB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT
When changed: filters a statement's candidates, Changed_Constraint::filter
scans the node, way and relation changelogs over the whole time range,
each time testing every change against the set, even for types the set
doesn't hold. A way statement still scans every node change in the
range, which on a large database is most of the work.

Skip a type's changelog when the set has no elements of that type,
current or attic: the scan can only keep elements already there.
rel(br.s) and its role form find the relations that have a relation of
.s as a member by scanning every relation, as relations have no index by
member. At a past date that means reconstructing every old version of
every relation, several seconds on a regional database, even when .s
holds no relations and nothing can match.

Return an empty result when the input has no relations, current or
attic.
escape_xml and escape_cstr built an escaped copy of every key, value,
user and role written, even though most need no escaping. Printing now
writes the string straight to the stream in one pass: runs of bytes that
need no escaping are written as they are, and each byte that does is
replaced from a 256-entry table, as in Go's encoding/xml (escapeText) and
libxml2's attribute serializer. escape_xml and escape_cstr use the same
table and loop, so the escaping rules are defined once.

Output is unchanged: for every byte value and 200,000 random strings,
both functions and the stream writers give the same result as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm
Chunked tag output (prefetch_chunk -> collect_tags_framed) appended every
matching tag entry to its element's vector in a std::map keyed by id: one
map lookup per tag, and each element's vector grown, and its strings moved,
as tags arrived.

Per coarse index, record the matches as (id, key/value slot) pairs, keeping
each distinct key/value once; sort them by id, keeping tag order; then fill
each element's vector once, reserved to its final size. Also look up the
coarse index's id list once per coarse index instead of once per tag entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT
Chunked tag output copied every tag's key and value into its element's
list, once per element: building=yes is copied once for every building.

Output handlers now take tags as a Tag_List (core/tag_list.h), a vector
of Tag_Ref, which refers to a key and value stored elsewhere and has the
same first/second members, so the output formats read it unchanged.
Tag_Store keeps one copy of each key and value per coarse index and
gives the printing code reference lists (get_refs); get() still returns
copies, for evaluators. Callers that hold tags as pairs (diff output,
derived elements, timestamps) go through adaptors on Output_Handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT
@cldellow

Copy link
Copy Markdown
Owner Author

Fuzz failures are from integrating the #193 fix, which fixes a correctness bug on master. Will see about patching the fuzzer/property tests in the meantime.

…e lookup

With a bbox of 1 square degree or more, a query statement with tag filters
looks up ids in the global tag index (collect_ids) and filters by the bbox
afterwards. It looked keys up in the order written, and each further key
read its whole index range, binary-searching every entry against the
candidates so far. For way["maxheight"]["highway"] over open ocean that
meant collecting every maxheight way in the database and then reading the
whole highway index, though none of them could be in the box.

Query_Statement::execute now computes the constraints' node, way and
relation ranges before the tag lookup (they don't depend on it) and passes
them to progress_1 and collect_ids. At the current date:

- keep_ids_inside drops candidates whose cell lies outside those ranges
  after each lookup; when none are left, the lookup stops.
- The key and key-value lookups run smallest first, counted in blocks of
  the global tag index (Block_Backend::count_blocks, from the block index
  alone).
- When checking the remaining tags late would read fewer local tag blocks
  than the remaining lookups would read global ones, the lookup stops and
  the query checks all tags late (check_keys_late = prefer_ranges).

The global tag index stores coarse indices, so a candidate is kept if its
cell overlaps the ranges, as intersect_ranges does.

On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM,
median CPU of 5 runs:

  [out:json][timeout:90]; (way["maxheight"]["highway"](39.0,-70.0,40.0,-69.0); way["bridge"]["maxheight"](39.0,-70.0,40.0,-69.0); way["tunnel"]["maxheight"](39.0,-70.0,40.0,-69.0); node["maxheight"]["highway"](39.0,-70.0,40.0,-69.0); ); out center;
      0.24 s -> 0.00 s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35
(cherry picked from commit 77135ca)
The global tag index stores each element's coarse index (a multiple of
0x100), so Query_Statement::execute intersected the constraints' ranges
with whole coarse cells (intersect_ranges) and read every element of each
candidate's cell. In dense areas that is thousands of elements per
candidate: for maxheight ways in a 1 x 1 degree box around Worcester, 2,185
distinct way blocks for 1,025 results.

Each element type's id map (the skeleton file's Random_File) gives exact
indices. exact_indices_pay_off compares the map blocks the candidate ids
fall in (the map holds a fixed number of ids per block and decompresses one
block at a time) with the skeleton blocks the coarse ranges touch
(Block_Backend::count_blocks); when the map blocks are fewer than half,
the ranges are further intersected with the candidates' exact indices
(get_indexes_, exact_ranges). At a past date nothing changes.

On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM,
median CPU of 3 alternating runs:

  [out:json][timeout:90]; (way["maxheight"]["highway"](42.0,-72.0,43.0,-71.0); way["bridge"]["maxheight"](42.0,-72.0,43.0,-71.0); way["tunnel"]["maxheight"](42.0,-72.0,43.0,-71.0); node["maxheight"]["highway"](42.0,-72.0,43.0,-71.0); ); out center;
      1.24 s -> 0.88 s, way blocks read 3,389 -> 391

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35
(cherry picked from commit e0bbfaa)
…y search

filter_id_list, which intersects the ids of a tag lookup with the
candidates of the earlier ones, binary-searched every index entry of the
later key in the candidate list. For a common key such as highway that is
millions of searches, nearly all of which fail.

It now builds an Id_Bit_Filter of the candidates and skips entries whose
id the filter rejects; the binary search confirms the rest.

On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM,
median CPU of 3 alternating runs:

  [out:json][timeout:90]; (way["maxheight"]["highway"](39.0,-70.0,40.0,-69.0); way["bridge"]["maxheight"](39.0,-70.0,40.0,-69.0); way["tunnel"]["maxheight"](39.0,-70.0,40.0,-69.0); node["maxheight"]["highway"](39.0,-70.0,40.0,-69.0); ); out center;
      0.33 s -> 0.21 s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35
(cherry picked from commit 284a109)
collect_tags_framed reads every local tag entry of a cell and keeps those
of the elements being printed, binary-searching each entry's id among
them. Most entries of a cell belong to other elements.

It now builds an Id_Bit_Filter of the cell's ids and skips entries whose
id the filter rejects before the bound checks and the binary search.

On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM,
median CPU of 3 alternating runs:

  (rel['seamark:type']; >; way['seamark:type']; >; node['seamark:type']; ); out meta;
      4.66 s -> 3.66 s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35
(cherry picked from commit edf6f1e)
While a union whose statements will re-read the same blocks runs, the
transaction's Block_Cache keeps the decompressed blocks of every data file
it reads. Such statements share every filter apart from their tag filters,
so they read the same skeleton and local tag blocks, but look up different
tags in the global tag index: its blocks are not read again. They only
filled the cache, up to its limit, and cost a copy each.

Nonsynced_Transaction::data_index no longer attaches the block cache to
the *_tags_global files.

On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM,
peak RSS, CPU as the median of 3 alternating runs:

  [out:json][timeout:90]; (way["maxheight"]["highway"](39.0,-70.0,40.0,-69.0); way["bridge"]["maxheight"](39.0,-70.0,40.0,-69.0); way["tunnel"]["maxheight"](39.0,-70.0,40.0,-69.0); node["maxheight"]["highway"](39.0,-70.0,40.0,-69.0); ); out center;
      74 MB -> 13 MB, CPU 0.36 s -> 0.33 s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35
(cherry picked from commit 6fde65a)
When a query statement checks tags late (a bbox under 1 square degree,
around under 2 km, and other range strategies), it collected every element
in its ranges, decoded each skeleton with its member list, checked the tags
of all of them, and kept the matches. In a dense 0.99999 x 0.99999 degree
box around Worcester, way["maxheight"]["highway"] decoded about two million
ways to keep about a thousand.

Before collecting, Query_Statement::execute now asks ids_from_local_tags for
the ids that carry every positive tag filter (keys, key-values,
key-regexes): it reads only those keys' entries in the local tag index for
the ranges' coarse cells, and intersects the per-filter id lists. Collection
then gets these ids, so it skips the other elements on their raw id without
decoding them. The late tag check still runs on what is collected, so
negated filters and regex keys behave as before.

It applies at the current date, without an id constraint already in place,
and when the ranges span at most 65,536 coarse cells. Uint31_Index orders by
the low 31 bits first, so for ways and relations the cells are taken from
those bits.

On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM,
median CPU and peak RSS of 3 alternating runs:

  [out:json][timeout:90]; (way["maxheight"]["highway"](42.0,-72.0,42.99999,-71.00001); way["bridge"]["maxheight"](42.0,-72.0,42.99999,-71.00001); way["tunnel"]["maxheight"](42.0,-72.0,42.99999,-71.00001); node["maxheight"]["highway"](42.0,-72.0,42.99999,-71.00001); ); out center;
      6.49 s -> 1.59 s, 608 MB -> 14 MB

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35
(cherry picked from commit d053c62)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment