Skip to content

Format output coordinates without general float formatting - #17

Open
cldellow wants to merge 2 commits into
masterfrom
fast-coordinate-output
Open

cldellow wants to merge 2 commits into
masterfrom
fast-coordinate-output

Conversation

@cldellow

@cldellow cldellow commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

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:

  • Fast path: for |value| ≤ 360, scale by 1e7 and round. The proof below shows this gives printf's digits whenever the scaled value is at least 1e-6 from a rounding tie.
  • Fallback: within 1e-6 of a rounding tie, and for |value| > 360, infinities and NaN, it calls snprintf("%.7f"), the same conversion as before.
  • Negative zero: keeps printf's sign on negative values that round to zero (-0.0000000).
  • Stream state: leaves the stream in fixed notation with precision 7, as the manipulators did, so later output that relies on that state is unaffected.

std::to_chars would 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 fossgis master. 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.

Query master This PR Change
[out:json]; way[highway](44.60,-63.66,44.70,-63.52); out geom; (benchmark q10, 14.5 MB) 536 ms 377 ms −30%
[out:csv(::id,::lat,::lon)]; node(44.60,-63.66,44.70,-63.52); out; (17 MB) 767 ms 468 ms −39%
[out:json]; node(44.60,-63.66,44.70,-63.52); out body; (63 MB) 1,087 ms 771 ms −29%
[out:xml]; way[highway](44.60,-63.66,44.70,-63.52); out geom; (13 MB) 526 ms 418 ms −21%
[out:json]; way[building](44.640,-63.585,44.655,-63.565); out geom; (benchmark q09) 81 ms 63 ms −22%
[out:xml]; nwr[amenity](44.60,-63.66,44.70,-63.52); out meta; (benchmark q08) 371 ms 351 ms −5%
[out:json]; way[building](44.60,-63.66,44.70,-63.52); out center; (22 MB) 671 ms 695 ms noise ¹

¹ 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 Fixed7 prints 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 against snprintf("%.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):

inline double lat(uint32 ilat) { return ((double)ilat)/10000000 - 91.0; }
inline double lon(int32 ilon)  { return ((double)ilon)/10000000; }

A test program calling these functions from the header, built with the project's flags (-std=c++11 -O2, x86-64, GCC 13, glibc), compared format_fixed7 with snprintf("%.7f") byte for byte for every input of both: all 2³² values of ilat (latitudes from −91 to 338.4967295) and all 2³² values of ilon (longitudes from −214.7483648 to 214.7483647). That is every double lat() and lon() can return, valid or not.

function inputs values from to mismatches
lat(uint32) 4,294,967,296 −91.0000000 338.4967295 0
lon(int32) 4,294,967,296 −214.7483648 214.7483647 0

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)
// Compares format_fixed7 with snprintf("%.7f") for every double lat(uint32) and lon(int32) can return.
#include "overpass_api/core/index_computations.h"
#include "overpass_api/output_formats/fixed7.h"
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <thread>
#include <vector>

struct Result { uint64_t checked = 0, mismatches = 0, fallbacks = 0; int64_t first_bad = -1; };

template< typename F >
void run(F decode, int64_t from, int64_t to, Result& r)
{
  char a[64], b[64];
  for (int64_t i = from; i < to; ++i)
  {
    double v = decode(i);
    double scaled = std::abs(v) * 1e7;
    if (std::abs((scaled - std::floor(scaled)) - 0.5) < 1e-6)
      ++r.fallbacks;
    int la = format_fixed7(a, v);
    int lb = std::snprintf(b, 64, "%.7f", v);
    ++r.checked;
    if (la != lb || std::memcmp(a, b, la))
    {
      if (r.mismatches++ == 0)
        r.first_bad = i;
    }
  }
}

template< typename F >
Result run_all(const char* name, F decode, int64_t from, int64_t to)
{
  unsigned n = std::thread::hardware_concurrency();
  std::vector< Result > rs(n);
  std::vector< std::thread > ts;
  int64_t step = (to - from + n - 1) / n;
  for (unsigned t = 0; t < n; ++t)
  {
    int64_t lo = from + t*step, hi = std::min(to, lo + step);
    ts.emplace_back([=, &rs]() { run(decode, lo, hi, rs[t]); });
  }
  Result total;
  for (unsigned t = 0; t < n; ++t)
  {
    ts[t].join();
    total.checked += rs[t].checked;
    total.mismatches += rs[t].mismatches;
    total.fallbacks += rs[t].fallbacks;
    if (total.first_bad < 0)
      total.first_bad = rs[t].first_bad;
  }
  std::printf("%s: %llu values from %.7f to %.7f, %llu mismatches, %llu near ties (fallback)",
      name, (unsigned long long)total.checked, decode(from), decode(to - 1),
      (unsigned long long)total.mismatches, (unsigned long long)total.fallbacks);
  if (total.first_bad >= 0)
    std::printf(", first at input %lld", (long long)total.first_bad);
  std::printf("\n");
  std::fflush(stdout);
  return total;
}

int main()
{
  Result lat_r = run_all("lat(uint32)", [](int64_t i) { return lat((uint32)i); }, 0, INT64_C(1) << 32);
  Result lon_r = run_all("lon(int32)", [](int64_t i) { return lon((int32)i); }, INT32_MIN, INT64_C(1) + INT32_MAX);
  return (lat_r.mismatches || lon_r.mismatches) ? 1 : 0;
}

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) for floor(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:

  1. value is a double, and 1e7 is exactly representable, so scaled = |value| * 1e7 is 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.
  2. scaled - floor(scaled) is exact (Sterbenz's lemma), so the tie test sees the true fraction of scaled. When it passes, scaled is at least 1e-6 from the nearest tie, and x is within 2.4e-7 of scaled: 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 rounding scaled give the same integer n.
  3. floor(scaled + 0.5) computes n: scaled + 0.5 is 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.5 into 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.
  4. glibc's %.7f rounds the exact decimal value of value correctly, 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.
  5. Sign: printf prints - exactly when the sign bit is set, including for −0.0 and for negative values that round to zero. The fast path tests std::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, scaled can be off by up to 1, and 27% of 20 million random doubles between −1e9 and 1e9 printed differently from snprintf. Coordinates never come near that range, so no output was affected. The guard is now 360, which keeps every value lat() and lon() 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):

  • every exact tie up to 360, with three neighbouring doubles on each side: x is a tie exactly when value is an odd multiple of 1/256, since 1e7 = 2⁷·5⁷ (645,120 values) — printf rounds these half to even, and Fixed7 hands them all to it;
  • 1,000 neighbouring doubles on each side of −360, 0 and 360 (6,003 values);
  • 100 million random doubles in [−360, 360].

3. The stream and snprintf agree

libstdc++ writes std::fixed output with std::setprecision(7) by calling vsnprintf with "%.*f", using the C locale's formatting. Overpass never calls imbue or std::locale::global. Its one setlocale(LC_ALL, "C.UTF-8") call (data/regular_expression.h) leaves . as the decimal point, and %f never groups digits.

Testing

  • Exhaustive check and proof: see above.

  • CI on 39f609b (with the guard change), against upstream/master 8edf11b, 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 fuzz queries 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:

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

    It prints no coordinates, so Fixed7 is 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 both snprintf("%.7f") and the stream with std::fixed<<std::setprecision(7), with 0 mismatches. The values were:

    • random fixed-point coordinates as Overpass stores them, and their midpoints (as used for centres)
    • random doubles in [−180, 180]
    • 4 million exact rounding ties, each with its two neighbouring doubles
    • signed zeros, tiny negatives, large values, infinities and NaN
  • 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 with geom, bb, center and body. 0 differences; 12 skipped, all of which time out on master.

  • 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

  • The proof assumes IEEE 754 binary64 arithmetic rounding to nearest, as on x86-64 and ARM64, with or without fused multiply-add. Pure x87 builds (32-bit x86 without SSE2) use extended precision and are not covered.
  • Other C libraries: the exhaustive check ran on glibc; step 4 of the proof needs a correctly rounding printf, which glibc and musl both have, and the fallback relies on the stream using snprintf, as libstdc++ does.
  • Narrow test setup: one regional extract, warm cache, one VM.

https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT


Generated by Claude Code

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
@cldellow cldellow added the query-perf Query performance change; collected on all-changes label Nov 21, 2026 — with Claude
@cldellow cldellow added the human-reviewed Colin has reviewed this. label Nov 21, 2026
@cldellow

cldellow commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner Author

Colin's thoughts: Low Medium risk [revised due to feedback from @b1tw153), high confidence, high benefit. This is applying a well-known optimization to a common task (converting a double to string).

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 std::to_chars and still retain 85% of the speed improvement. This is a question for upstream.

@cldellow

cldellow commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner Author

@b1tw153 notes elsewhere:

one that caught my eye was Format output coordinates without general float formatting - #17. Node coordinates have to make the round trip from OSM planet data to Overpass XML with no changes to 7 decimal places so the XML output can be used for editing without node version churn. Maybe the change is fine, but that constraint makes it high risk.

This makes a stronger argument for moving to C++17, where we can be confident that std::to_chars is correct. We lose a bit of the speedup of the Fixed7 version but gain peace of mind.

@cldellow cldellow added the needs-followup Colin reviewed and wants Claude to iterate further, but didn't have spare agents available. label Nov 21, 2026
@mmd-osm

mmd-osm commented Nov 29, 2026

Copy link
Copy Markdown

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
@cldellow

cldellow commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner Author

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.

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

Labels

human-reviewed Colin has reviewed this. needs-followup Colin reviewed and wants Claude to iterate further, but didn't have spare agents available. query-perf Query performance change; collected on all-changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Coordinate formatting dominates large geometry outputs

3 participants