Repository navigation
Conversation
Every coordinate in the JSON, XML, CSV and custom output was written
with out<<std::fixed<<std::setprecision(7)<<value, which goes through
glibc's general floating-point formatting. For large geometry outputs
that formatting is a large share of the CPU time.
Add Fixed7 (output_formats/fixed7.h), which writes exactly the same
characters: scale by 1e7 and round, falling back to snprintf("%.7f")
within 1e-6 of a rounding tie and for large or non-finite values. It
leaves the stream in fixed notation with precision 7, as the
manipulators did. Replace the 72 call sites.
Checked against snprintf and the stream for 92 million values: random
fixed-point coordinates, their midpoints, arbitrary doubles, exact ties
and their neighbours, signed zeros and non-finite values. No mismatches.
Nova Scotia extract, CPU time, alternating runs:
[out:json]; way[highway](44.60,-63.66,44.70,-63.52); out geom;
536 ms -> 377 ms
[out:csv(::id,::lat,::lon)]; node(44.60,-63.66,44.70,-63.52); out;
767 ms -> 468 ms
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT
|
Colin's thoughts: Caveat: I have no idea where Claude got this function from. I'm satisfied that the function likely works, given its 90 million test cases tested against the old behaviour. Followup: the project currently targets C++11, but it does also compile cleanly against C++ 17. If the project is willing to move to C++17, the custom function can be replaced with |
|
@b1tw153 notes elsewhere:
This makes a stronger argument for moving to C++17, where we can be confident that |
|
I have also mostly replaced coordinate formatting by fmt and my own rendering logic: https://codeberg.org/mmd/Overpass-API/src/branch/test7591/src/overpass_api/output_formats/output_xml.cc#L303 |
The fast path rounds value*1e7 and trusts the result when it is at least
1e-6 from a rounding tie, so the product's rounding error must stay below
that. The guard allowed it up to |value| <= 1e9, where the error can reach 1:
there, 27% of random doubles printed differently from snprintf("%.7f").
For |value| <= 360, value*1e7 is below 2^32 and its rounding error at most
2^-22, which leaves room even if the compiler fuses the multiply and the add
of 0.5. Every value lat() and lon() can return stays on the fast path, so
output is unchanged. Checked byte for byte against snprintf("%.7f") for all
2^32 inputs of lat(uint32) and all 2^32 of lon(int32): no differences.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT
|
Nice, I'll see if I can adapt some of those ideas. Skipping the intermediate double and outputting the coords from the underlying integers is attractive, but might have a big surface area on the current upstream. Templating the output seems like a cheap win that would have small ripple effect and be easy to review, so I'll explore that. |
Fixes #15.
Change
Every coordinate in the JSON, XML, CSV and custom output was written as
out<<std::fixed<<std::setprecision(7)<<value, which goes through glibc's general floating-point formatting. For large geometry outputs that was a large share of the CPU time.This adds
Fixed7(output_formats/fixed7.h) and uses it at all 72 call sites. It writes exactly the same characters:printf's digits whenever the scaled value is at least 1e-6 from a rounding tie.snprintf("%.7f"), the same conversion as before.printf's sign on negative values that round to zero (-0.0000000).std::to_charswould be simpler, but it needs C++17, and the build pins-std=c++11.Six files (one new header, four output formats,
src/Makefile.am). The second commit lowers the fast path's guard from 1e9, where it was wrong, to 360; see below. Based on fossgismaster. No change to the database format or the query API, and output is byte-identical.Impact
CPU time (user + system), median of 5 alternating runs per build, Nova Scotia test database (Geofabrik extract of 2026-11-08, imported with
--meta), warm cache, 4-core VM. Output is byte-identical for every query.master[out:json]; way[highway](44.60,-63.66,44.70,-63.52); out geom;(benchmark q10, 14.5 MB)[out:csv(::id,::lat,::lon)]; node(44.60,-63.66,44.70,-63.52); out;(17 MB)[out:json]; node(44.60,-63.66,44.70,-63.52); out body;(63 MB)[out:xml]; way[highway](44.60,-63.66,44.70,-63.52); out geom;(13 MB)[out:json]; way[building](44.640,-63.585,44.655,-63.565); out geom;(benchmark q09)[out:xml]; nwr[amenity](44.60,-63.66,44.70,-63.52); out meta;(benchmark q08)[out:json]; way[building](44.60,-63.66,44.70,-63.52); out center;(22 MB)¹ This query prints only one coordinate pair per building, so formatting is a small share of its cost. Splitting it by output mode on the all-changes branch (#12): finding the 12,420 buildings takes about 100 ms (
out ids), reading and printing their tags adds about 225 ms (out tags), and loading their node geometry for the centres plus printing adds about 195 ms. Computing the centres themselves doesn't show up in the profile.Queries with small outputs are unaffected.
Why the output is identical
Every value
Fixed7prints is either a stored coordinate or a value computed from coordinates (a centre, or the bounds of a query's bounding box). The first kind was checked exhaustively; the second is covered by a proof. Both compare againstsnprintf("%.7f"), which is what the old stream output did (see the end of this section).1. Every stored coordinate: checked exhaustively
Overpass stores coordinates as integers in steps of 1e-7 degrees and turns them into doubles in two functions (
core/index_computations.h):A test program calling these functions from the header, built with the project's flags (
-std=c++11 -O2, x86-64, GCC 13, glibc), comparedformat_fixed7withsnprintf("%.7f")byte for byte for every input of both: all 2³² values ofilat(latitudes from −91 to 338.4967295) and all 2³² values ofilon(longitudes from −214.7483648 to 214.7483647). That is every doublelat()andlon()can return, valid or not.lat(uint32)lon(int32)8,589,934,592 values, 0 mismatches, with the header at this PR's head (guard 360). It took 10 minutes on a 4-core VM.
Test program (run from
src/:g++ -std=c++11 -O2 -pthread -I. -o exhaustive exhaustive.cc && ./exhaustive)This covers node coordinates, way and relation member geometry (
out geom), and the bounds of elements (out bb), which are minima and maxima of stored coordinates. None of these values comes near a tie: scaled by 1e7, each lies within about 2e-7 of a whole number, so the fallback is never taken for them.To confirm the test can fail, a mutant that truncates instead of rounding (
floor(scaled)forfloor(scaled + 0.5)) gives 337,905 mismatches on the first 2²² latitudes and 272,994 on the 2²² longitudes around zero.2. Any other double up to 360: proof
Centres and query bounds can be arbitrary doubles. For |value| ≤ 360, with IEEE 754 binary64 arithmetic rounding to nearest:
valueis a double, and 1e7 is exactly representable, soscaled = |value| * 1e7is the exact product x rounded once. Since x ≤ 3.6e9 < 2³², doubles near it are at most 2⁻²¹ apart, so |scaled− x| ≤ 2⁻²² ≈ 2.4e-7.scaled - floor(scaled)is exact (Sterbenz's lemma), so the tie test sees the true fraction ofscaled. When it passes,scaledis at least 1e-6 from the nearest tie, and x is within 2.4e-7 ofscaled: x is strictly on the same side of that tie, at least 7.6e-7 from it. So x is not itself a tie, and rounding x and roundingscaledgive the same integer n.floor(scaled + 0.5)computes n:scaled + 0.5is at least 1e-6 from an integer, and rounding the sum moves it by at most 2⁻²², which cannot reach an integer. If the compiler fuses|value| * 1e7 + 0.5into one multiply-add, the sum is x + 0.5 rounded once: x + 0.5 is at least 7.6e-7 from an integer, and one rounding of at most 2.4e-7 still cannot reach it. So the proof holds with and without fusion.%.7frounds the exact decimal value ofvaluecorrectly, which here (not a tie) means it prints the digits of round(x) = n with seven decimals. The fast path prints n < 2³² with integer arithmetic, so its digits are exact.printfprints-exactly when the sign bit is set, including for −0.0 and for negative values that round to zero. The fast path testsstd::signbit, so the two agree.Within 1e-6 of a tie the fast path isn't used, so
printf's round-half-to-even rule needs no reproducing.The bound is what matters. The first version of this PR allowed the fast path up to 1e9, where step 1 fails: there,
scaledcan be off by up to 1, and 27% of 20 million random doubles between −1e9 and 1e9 printed differently fromsnprintf. Coordinates never come near that range, so no output was affected. The guard is now 360, which keeps every valuelat()andlon()can return on the fast path. Without fusion the proof would hold up to about 1,718. With fusion it needs |value| below about 859; 360 leaves a wide margin.The proof was also tested directly, with 0 mismatches over 100,651,123 values, in a normal build and in one with fused multiply-add forced on (
-mfma -ffp-contract=fast):valueis an odd multiple of 1/256, since 1e7 = 2⁷·5⁷ (645,120 values) —printfrounds these half to even, andFixed7hands them all to it;3. The stream and
snprintfagreelibstdc++ writes
std::fixedoutput withstd::setprecision(7)by callingvsnprintfwith"%.*f", using the C locale's formatting. Overpass never callsimbueorstd::locale::global. Its onesetlocale(LC_ALL, "C.UTF-8")call (data/regular_expression.h) leaves.as the decimal point, and%fnever groups digits.Testing
Exhaustive check and proof: see above.
CI on 39f609b (with the guard change), against
upstream/master8edf11b, this PR's base:fuzz(run): 6,000 queries, 5,986 same, 14 skipped.history(run): 2,000 queries, 1,998 same, 2 skipped.props(run): 60 seeds, no new failures.timing(run): sum of medians 0.976.13 of the skipped
fuzzqueries time out on both builds; this base predates later speed fixes. The 14th, plain query 1007 of seed 1, finished on the baseline and timed out on this PR:It prints no coordinates, so
Fixed7is never called. Locally (Nova Scotia, warm cache, 4-core VM) it takes 27.2–27.9 s on the baseline and 26.2–29.0 s on this PR over three runs each, with identical output. On the slower CI runners it sits near its 60 s limit, so which build times out is chance.Formatter against
printf(first version): 92 million values were checked against bothsnprintf("%.7f")and the stream withstd::fixed<<std::setprecision(7), with 0 mismatches. The values were:Differential fuzzer, seeds 2 and 3: 6,000 queries against
master(bench/fuzz.py, see Benchmark queries and differential fuzzer #2), mixing JSON, XML and CSV output withgeom,bb,centerandbody. 0 differences; 12 skipped, all of which time out onmaster.Update, re-fuzzed with the corrected fuzzer: this change has since been re-fuzzed as part of the all-changes branch (All changes combined (tracking PR) #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 Benchmark queries and differential fuzzer #2).Memory
No new allocations: a 64-byte stack buffer per coordinate.
Limitations
printf, which glibc and musl both have, and the fallback relies on the stream usingsnprintf, as libstdc++ does.https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT
Generated by Claude Code