Skip to content

Use binary COPY for flex and middle tables - #2503

Open
leijurv wants to merge 4 commits into
osm2pgsql-dev:masterfrom
leijurv:binary-copy
Open

leijurv wants to merge 4 commits into
osm2pgsql-dev:masterfrom
leijurv:binary-copy

Conversation

@leijurv

@leijurv leijurv commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2286

This PR switches the Postgres COPY for the middle tables and most flex tables from the textual format to the binary format. This is a moderate win in decreasing CPU time that is otherwise spent on int-to-text-to-int, float-to-text-to-float, WKB hex, etc.

Details:

  • Each db_target_descr_t knows the binary versions of its column types, if present db_copy_mgr_t will seamlessly switch to binary format for the same calls (add_column, new_array, etc)
  • Binary mode checks each field's type from the list, asserting that it matches
  • Middle tables will always use binary mode. In particular, int8[] is supported, to make this possible.
  • Flex tables use binary mode if they only use the following types: text, boolean, int2/4/8, real, double precision, hstore, json, jsonb, direction, id columns, and all geometry types. It will fall back to text mode if user-defined SQL types are present, or if there is timestamp/timestamptz directly from Lua as an arbitrary string. While I could have supported that last possibility, there is a better alternative (Use timestamp column type in example configs #2502) that doesn't require complicated timestamp parsing code.
  • Pgsql output and gen are unchanged, still text.
  • Replace geometry check trigger by WHERE condition on COPY #2500 is supported

Changes to behavior:

  • No change for integers, doubles, text, json, hstore, arrays, timestamps, or WKB from OSM data.
  • If the Lua gives a double which is stored in PG as a real, currently text mode implicitly does fp64 -> text -> fp32. This causes rounding to happen twice. Binary mode will now round fp64 -> fp32 directly. Of course, one could reimplement the double rounding behavior, but I don't think this is good behavior to preserve. The effect is at most 1 ULP of difference, and it only happens when a fp64 landed exactly halfway between two fp32 values, which is extremely unlikely. A potential place where this could theoretically arise is in way_area - but in practice, there are none, in the full current planet, that have any difference here, and there probably never will be, as less than 1 in a billion doubles are like this. Out of range values like inf remain an error as in text mode.

Testing:

  • Lots of tests in test-db-copy-mgr.cpp
  • All ctest and BDD pass
  • Tested all examples in flex-config, and also osm carto. Imported with --slim -x and then updated with an .osc. (this is what exposed Fix reading attributes of nodes from the middle #2501). All table contents identical to master.

Performance:

  • Ryzen 9 3900X, Samsung 970 EVO Plus NVMe, Postgres 18.6, PostGIS 3.6.4
  • OSM Carto flex style. Nodes cached in RAM (no flat nodes.bin).
  • Cold restart every time
  • Alternating runs between this branch and master, taking the median of seven.
Extract (from geofabrik) Flags Wall clock time Postgres CPU, import phase Postgres CPU, total osm2pgsql CPU
Delaware --slim 12.74 -> 12.36 s (−3.0%) 7.45 -> 6.44 s (−13.6%) 13.03 -> 12.03 s (−7.7%) 6.92 -> 6.59 s (−4.8%)
Delaware --slim --drop 12.36 -> 12.02 s (−2.8%) 6.64 -> 5.69 s (−14.3%) 9.00 -> 8.05 s (−10.6%) 6.89 -> 6.57 s (−4.6%)
New Jersey --slim 83.81 -> 80.37 s (−4.1%) 47.66 -> 41.17 s (−13.6%) 86.74 -> 80.13 s (−7.6%) 48.11 -> 45.73 s (−4.9%)

So as we can see Postgres spends about 14% less CPU to ingest. The overall win to wall clock time is currently not so much because we are bottlenecked by the single threaded Lua processing time. The benefit from this PR is larger when combined with upcoming PRs... (teaser post credit scene 😺) (EDIT: this was teasing #2504)

@joto

joto commented Sep 26, 2026

Copy link
Copy Markdown
Collaborator

This looks very interesting. I'll need more time for looking into this, but here are a few things I wondered about when quickly reading though the code:

  • There are a lot of if (m_binary_types) { in the db-copy-mgr.hpp code. Have you considered using two separate implementations for instance with virtual classes or a templated class to keep the two apart? I am not sure it is worth it to separate this out, but it might make the code cleaner. Using virtual inheritance might be problematic due to the resulting overhead though.
  • The byteswap code in put_be() and put_be_at() uses a loop which I am not sure the compiler can see through and simplify. Maybe it does. There is some byteswap code in protozero and in libosmium, both libraries we use anyway, but not easy accessible. Medium term we probably want to switch to std::byteswap but that is only available in C++23.
  • There is a lot of casting going on before calling put_be() and then inside put_be() also. Sometimes it seems too complicated. But I haven't looked at all the details. It is hard to see what's going on due to all the casts, but a lot of them are probably necessary. Still I wonder if this could be simplified somehow?
  • Do we need the std::optional of the copy_field_type? Can't we just have an additional field type for that?

@leijurv

leijurv commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for the review!

  • We can't compile out the decision entirely, because the format is picked per table at runtime, so a template would relocate the branch not eliminate it. Because add_column is a member template, we can't use a virtual function there. For performance, the current branch should be perfectly predicted. The binary encoding could be relocated into its own class so that there is less interleaving though if that reads better?
  • Good point: 9e80748
  • Good point again: 9e80748
  • The optional has a small win in that it keeps a "no binary representation" sentinel/marker value out of a table's list of column types. If you like I can add an extra enum copy_field_type::none bu then every switch in the encoder would have to reject it. But that's not really expensive as it would fall through to throw_type_mismatch. This only affects binary_copy_type and two callers.

@leijurv

leijurv commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor Author

I apologize I have to correct my above comment, the paragraph beginning If the Lua gives a double which is stored in PG as a real, currently text mode implicitly does fp64 -> text -> fp32., where I claimed this didn't practically happen, that was incorrect.

Long explanation (click to expand) The exact scenario, where this PR causes a different result than master, is when a float64 is sent to Postgres and its mantissa takes the following form:

(1)???????????????????????10000000000000000000000000000

That's the implicit leading 1 bit, then 23 irrelevant bits, then a one, then 28 zeros. The odds of this happening to a uniformly random bits would be 1 in 2^29, which is why I (approximately) claimed as such above.

I also "verified" it by ensuring that the fp64->text and text->fp32 was consistent across all polygons in the planet:

gis=# select count(*) from planet_osm_polygon;
   count   
-----------
 854755728
(1 row)

gis=# select count(*) from planet_osm_polygon where st_area(way)::text::real = st_area(way)::real;
   count   
-----------
 854755728
(1 row)

Note that I can't check it on way_area because this rounding has already happened so these bits have been lost. So that's why I used st_area(way). So this is why I thought we had no practical differences from master to this PR.

Unfortunately, that was misleading, because PostGIS computes areas differently to Lua (which uses boost).

gis=# select st_area(way), st_area(way)::real, way_area from planet_osm_polygon where osm_id=258622451;
      st_area       |  st_area  | way_area  
--------------------+-----------+-----------
 236.50345608387994 | 236.50345 | 236.50346
(1 row)

That st_area has the following mantissa bits:

(1)1101100100000001110001001111111011101110011110010010

But, for this particular way, Lua gives us 236.50345611572266, which has a mantissa in binary of:

(1)1101100100000001110001010000000000000000000000000000

Note exactly 28 trailing zeros indeed.

gis=# select double precision '236.50345611572266'::real, double precision '236.50345611572266'::text::real;
  float4   |  float4   
-----------+-----------
 236.50345 | 236.50346
(1 row)

And, oh no, it does indeed round differently, we ended up precisely on the boundary between two float32s, we get 236.50345 in binary mode versus 236.50346 in text mode. 😿😿😿

The explanation here is that we have way_area as object:as_polygon():transform(3857):area() which internally calls boost::geometry::area(). That uses shoelace to compute the area, and a lot of precision is lost to cancellation as the coordinates here are already rather large (x ≈ −8.4e6 and y ≈ 4.7e6 metres). We usually don't care about this because we're going to downcast to a fp32 anyway. The relevant code can be found here. They just compute sum += (x1 + x2) * (y1 - y2). However, PostGIS uses a simple trick: they subtract out the first coordinate, to recenter all the math around zero, like: x = P2->x - x0; sum += x * (y2 - y1). Relevant code: here and here. The exact line where they center at zero is subtracting out x0 here. This gives them much greater precision, to the point where their mantissas look basically like you'd expect from random mantissas, see the below chart.

Due to this loss of precision in Boost, this rare case of 28 trailing zeros happens to about 1 in 2,000 ways (rather than 1 in 500,000,000 ways as in theory / as in PostGIS).

Here's a histogram of how many trailing bits of the mantissa are zero, across all polygons in Delaware.

way_area_mantissa_bits

The highlighted column alone is what has the difference in rounding (any more or fewer trailing zeros rounds equally). And even in that column it's not certain the rounding is different, it depends on further details on the float64 to string converter.

Bottom line: ~0.001% of polygons have their way_area change by 1/2^24 (0.00000596%)

To fix this and exactly match master, we could check for this case on every fp64 we send to postgres, and fall back to strtof(fmt::to_string(d)) if it matches this bit pattern. Or, we could accept that way_areas will be rounded a bit differently now. I'm happy either way!

@joto

joto commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator

Nobody should have code that depends on tiny changes in float values, that shouldn't be a problem. In practice the only typical use of floats I am aware of is for polygon areas and there it is only used to not render very small ones or something like that. Not worth thinking about the details.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Using binary format for COPY

2 participants