Skip to content

around: index the input set's geometry with a coarse grid - #10

Open
cldellow wants to merge 2 commits into
around-fixed-vectorsfrom
around-spatial-index
Open

cldellow wants to merge 2 commits into
around-fixed-vectorsfrom
around-spatial-index

Conversation

@cldellow

@cldellow cldellow commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner

Fixes #3.
Fixes #36.

Stacked on #7 (fixed-size vectors): this PR targets that branch, so the diff shows only the grid.

Change

around against an input set compared every candidate point and segment with every point and segment of the set. The cost grew with (set size) × (nearby candidates), so modest inputs took minutes.

This indexes the input set's points and segments in a coarse lat/lon grid (Reach_Grid, 0.01° cells):

  • Filing: each entry goes in every cell covered by its reach box, its bounding box widened by its own length plus the radius.
  • Lookup: a candidate is tested only against entries in the cells its own reach box touches.
  • The exact spherical tests are unchanged. The grid only decides which entries to test, never whether something matches.

Why no match can be lost. Each exact test can only pass when the two objects' reach boxes overlap (the reasoning is in a comment in around.cc):

  • Point near segment: the test requires distance to the segment's first point ≤ √(len² + r²) ≤ len + r.
  • Segment near point: the same test with the roles swapped.
  • Segments intersecting: the crossing point lies within each segment's length of that segment's first point.

The widening uses a 2% + 1 m margin, and the latitude nearest the pole for the longitude scale. These cases are never pruned:

  • entries near a pole (|lat| > 80°)
  • entries crossing the antimeridian
  • entries spanning more than 64 cells

Such entries are checked by every lookup, and such candidates are checked against everything.

Two files (around.cc, around.h), about 200 lines. No change to the database format or the query API.

Impact

Wall time (single-threaded, so close to CPU time) on the Nova Scotia test database (see #2). Outputs are identical in every case.

Query master #7 only #7 + this PR
A: around 282 ways (defined below) 24.1 s 9.9 s 1.2 s
B: around nodes and ways within 1 km 33.8 s 11.6 s 0.2 s
C: around every way in a downtown Halifax bbox > 10 min > 2 min 4.7 s
around against small sets (benchmark q06: node[amenity=cafe](bbox); node(around:300)[shop], and spot checks) unchanged unchanged unchanged
Full text of the timed queries

A (282 ways around a point in Dartmouth, then everything within 100 m of them):

[out:csv(::count)]; way(around:250,44.679085,-63.511161)->.s0; way(around.s0:100); out count;

B (nodes and ways within 1 km, then ways within 100 m of them):

[out:csv(::count)]; nw(around:1000,44.790135,-65.396762)->.s0; way(around.s0:100)["width"!="1"]; out count;

C (every way in a downtown Halifax bbox, then ways within 100 m of them):

[out:csv(::count)]; way(44.648535,-63.573386,44.662526,-63.528647)->.s0; way(around.s0:100)["created_by"!~"^JO"]; out count;

Update (2026-11-21): grid revision

A second commit fixes three inefficiencies in the grid (#36), found by the degenerate-query hunt:

  • Each entry is now tested once per lookup. An input segment filed under several cells used to be tested once for every cell the lookup box shared with it. A stamp per entry now prevents repeats.
  • Large lookup boxes now scan each entry once. When a candidate segment's box is too large to look up cell by cell, the lookup used to walk every cell's list, testing entries up to 64 times. It now scans a list of the filed entries once.
  • Segment reach boxes are tighter. A segment's box was widened by its own length plus the radius. It is now widened by the radius plus twice the most a great-circle arc of that length can bulge out of its endpoints' box (L² tan(latitude) / 8R, a few metres for segments of some km), plus 1 m. The old bound is kept beyond 50 km or 80° latitude. The comment in around.cc gives the argument that each exact test still only passes when the two boxes overlap.

The exact tests are unchanged.

Impact: CPU time on this branch (#7 + this PR) with the revision. The A, B and C figures were timed separately from those above, so the comparison is rough.

Query Before (above) With the revision
A 1.2 s 1.05 s
B 0.2 s 0.18 s
C 4.7 s 4.35 s
[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; (history database, current data; .s0 includes province-long road routes and rural boundaries) over 120 s on master 11.9 s

On top of the all-changes branch (#12), the revision takes that last query from 17.9 s to 11.2 s. A dense urban query (all ways within 20 m of the highways in 44.60,-63.70,44.75,-63.45) goes from 11.2 s to 10.5 s. Most of the remaining cost of the routes query comes from how candidates are chosen for relation inputs; #38 fixes that.

Testing of the revision: done on the all-changes branch with this revision and #38, against all-changes.

  • Differential fuzzer:

    • plain database: 3,000 queries
    • areas: 1,500 queries
    • history database, users,complete: 1,500 queries

    0 differences in all three.

  • Targeted check: 600 around queries with a single relation or way as input, at radii from 0 to 1,000 m. 0 differences.

  • Mutation test: a build whose lookups never advance the stamp, so an entry seen once is skipped in every later lookup, was first confirmed to give wrong counts on known queries. It then differed on 158 of the 600 targeted queries, and on 3 of 1,000 fuzz queries. A mutant that only shrinks the reach boxes did not change any result. Lookups cover whole 0.01° cells (about 1 km), so reach errors of tens of metres rarely matter. This is also why the tighter bound is safe, but it means that part is checked by the argument in the comment rather than by tests.

  • Long-limit re-runs: the 27 queries from the degenerate-query hunt that time out or are slow on master give identical output to all-changes.

Memory of the revision: peak RSS for query A is 31.0 MB on this branch with the revision, and 31.1 MB on all-changes without it.

Testing

  • Differential fuzzer, seeds 2 and 3: 6,000 queries against master, about 860 of them using around against a set. 0 differences. 11 of the 12 queries that time out on master now finish (0.2–25 s).
  • The formerly timed-out queries, re-run with long limits and compared on full output:
    • 6 are identical to master (largest output 2.7 MB).
    • 3 more, which master cannot finish in 10 minutes, are identical to an exhaustive build (around: use fixed-size arrays for 3-D vectors #7 alone: the same all-pairs comparison as master, only faster), including a 5.5 MB output.
    • 2 (seed 3 queries 2448 and 2618) cannot be compared, because no build without the grid finishes them within 30 minutes. The grid build finishes them in 25 s and 23 s.
  • Grid-specific tests: the mutation test in Benchmark queries and differential fuzzer #2 shows the fuzzer catches lost results in around paths.
Full text of the two queries that could not be compared

Seed 3, query 2448 (differential fuzzer seed 3, query 2448):

[timeout:60][maxsize:536870912][out:json];
nwr(44.686790,-63.561455,44.714157,-63.518726)->.s0;
way(around.s0:100)["capacity"!="48"]->.s1;
wr(bn.s1)->.s2;
.s0 out count;
.s1 out body 42;

Seed 3, query 2618 (differential fuzzer seed 3, query 2618):

[timeout:60][maxsize:536870912];
nwr(44.647364,-63.561179,44.690833,-63.496374)->.s0;
node(around.s0:20)["maxspeed"!~"^6"]->.s1;
.s1 out meta center;

These were generated by bench/fuzz.py (bench-tools branch) with a vocabulary built by bench/fuzz_vocab.py from the Geofabrik Nova Scotia extract of 2026-11-08. The text above is authoritative; regenerating it requires the same vocabulary.

- **Update, re-fuzzed with the corrected fuzzer:** this change has since been re-fuzzed as part of the all-changes branch (#12), with the corrected fuzzer and a bigger vocabulary (areas, history, users and `complete`). That covered 10,000 queries across the plain, area and history databases (6,000 / 2,000 / 2,000), with **0 differences**. The per-PR fuzz run above predates a fuzzer fix: about 8% of its queries were invalid on both builds, so it rests on roughly 5,500 queries that ran (see #2).

Memory

Bound: each input-set point or segment is filed in at most 64 cells, at 4 bytes per cell entry plus hash-map overhead per occupied cell. The revision adds 8 bytes per filed entry: one in the list of filed entries and one for its stamp. Larger entries go to a single always-checked list. This roughly offsets the about 120 bytes per segment that #7 saves. Overpass counts only result sets toward [maxsize:]. Auxiliary structures, such as around's segment lists, are not counted, and these new structures follow that convention. Counting them would change which queries fail with "Oversized", which is an observable behaviour change.

Peak memory (RSS), master against all changes combined (#12):

Query master Combined
A: [out:csv(::count)]; way(around:250,44.679085,-63.511161)->.s0; way(around.s0:100); out count; 29.8 MB 30.1 MB
around with a 3 km radius: [out:csv(::count)]; way(around:250,44.679085,-63.511161)->.s0; node(around.s0:3000)["amenity"]; out count; 16.2 MB 17.0 MB

Limitations

  • Candidate selection is unchanged in this PR (around: take candidate ranges for relation inputs from their members #38 now addresses it for relation inputs). around with a relation in the input set still reads every candidate in the relation's extent (e.g. rel(45.566265,-62.428420,45.586924,-62.388716)->.s0; node(around.s0:0)["footway"];, where .s0 holds long trails and boundaries; see around with a selective tag filter reads every candidate in the input set's extent first #9). The grid makes each candidate cheap, but the candidate count stays large.
  • Cell size is fixed at 0.01°. It isn't tuned, and very large or very dense inputs may benefit from an adaptive size.
  • Polar and antimeridian data take the always-checked path. That path is correct but unaccelerated, and is not covered by the Nova Scotia tests.
  • Narrow test setup: one extract, warm cache, one 4-core VM.

Generated by Claude Code

around compared every candidate point and segment against every point
and segment of the input set, so the cost grew with (input set size) x
(number of nearby candidates). An input set of 282 ways took 24 s.

Index the input set's points and segments in a lat/lon grid. Each entry
is filed under the cells of its reach box: its bounding box widened by
its own length plus the radius. Every exact test (point near segment,
segment near point, segments intersecting) can only pass when the two
reach boxes overlap, so a candidate is tested only against entries in
the cells its reach box touches. The exact tests are unchanged.

Boxes near a pole, crossing the antimeridian or spanning more than 64
cells are never pruned: such entries are checked by every lookup, and
such candidates are checked against every entry.

Nova Scotia extract, after the fixed-size vector change:
  way(around.s0:100), 282 ways in .s0       9.9 s -> 1.2 s
  way(around.s0:100), ways in a city bbox  >120 s -> 4.7 s
  way(around.s0:100), nw within 1 km       11.6 s -> 0.2 s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT
@cldellow cldellow added the query-perf Query performance change; collected on all-changes label Nov 20, 2026 — with Claude
@cldellow

cldellow commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner Author

Colin's thoughts:

In theory: low risk, high confidence, high benefit.

This is a "slap an index on it" optimization - make it cheap to rule out certain cases to avoid doing expensive comparisons when not needed. Preventing degenerate cases helps keep the overall system healthy.

However, this is high complexity to review. At least higher than most of the other PRs proposed in this work. On a few minutes of reading it, I don't understand how it works. I trust the change due to the fuzzer, but wouldn't be comfortable offering this upstream without better understanding or a lot of caveats.

@cldellow cldellow added human-reviewed Colin has reviewed this. maybe-not-simple labels Nov 21, 2026
Three changes to the reach grid that narrows down which input points and segments
around's exact tests look at:

- An entry filed under several cells was passed to the exact test once per cell
  the lookup box shared with it. Each lookup now passes it once, using a stamp per
  entry.
- When a lookup box was too large to look up cell by cell (a long candidate
  segment), every cell's list was scanned, so entries were tested once per cell
  they were filed in, up to 64 times. Such lookups now scan a list of the filed
  entries once.
- A segment's reach box was widened by its own length plus the radius. It is now
  widened by the radius plus twice the most a great-circle arc of that length can
  bulge out of its endpoints' bounding box (L^2 tan(latitude) / 8R, a few metres
  for segments of some km), plus one metre. Beyond 50 km or 80 degrees of latitude
  the old bound is kept. The comment in around.cc gives the argument that each
  exact test still only passes when the two reach boxes overlap.

The exact tests are unchanged, so results are the same.

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

Clearing the human review label as there has been a new commit added

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maybe-not-simple query-perf Query performance change; collected on all-changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants