From b99f52805dede2ebbfdb87449a7a72f8c05f4e9f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 20:46:30 +0000 Subject: [PATCH 01/80] Reject non-matching ids with a bit filter before binary search Id_Predicate checks every object it is shown with std::binary_search over the sorted id list. Most objects it sees are not in the list: a tag query such as node[amenity=restaurant] finds the matching ids in the tag index, then reads every node block of each quadtile that holds one of them and tests each node against the ids. Add a small hashed bit filter (about 16 bits per id, at most 16 MiB) that rejects most absent ids with one bit test; the binary search still decides every id the filter lets through, so results do not change. Collect_Items now builds its predicate once instead of once per chunk. On a Nova Scotia extract (12.6M nodes), median CPU time per query with warm caches: nwr[amenity=restaurant] 160 ms -> 124 ms node[natural=peak] 183 ms -> 129 ms rel boundary with (._;>>;) 682 ms -> 571 ms Outputs are byte-identical. No change to the database format or the API. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT (cherry picked from commit 70f18bd9c3a92331da59b366ec66cacc5ba941e1) --- src/overpass_api/data/abstract_processing.h | 53 +++++++++++++++++++-- src/overpass_api/data/collect_members.h | 8 ++-- 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/src/overpass_api/data/abstract_processing.h b/src/overpass_api/data/abstract_processing.h index 143173665..396b83bcc 100644 --- a/src/overpass_api/data/abstract_processing.h +++ b/src/overpass_api/data/abstract_processing.h @@ -22,6 +22,9 @@ #include "../core/datatypes.h" #include "../statements/statement.h" #include "filenames.h" +#include +#include +#include //----------------------------------------------------------------------------- @@ -83,19 +86,61 @@ class Trivial_Predicate //----------------------------------------------------------------------------- +/* A one-bit-per-hash-slot filter over a set of ids. It answers "definitely + not in the set" with a single bit test, and "maybe in the set" otherwise. + It uses about 16 bits per id (at most 16 MiB), so a false "maybe" happens + for roughly 6% of absent ids while the cap is not reached. */ +class Id_Bit_Filter +{ +public: + template< typename Id_Type > + explicit Id_Bit_Filter(const std::vector< Id_Type >& ids) + { + unsigned log_bits = 6; + while (log_bits < 27 && (uint64(1) << log_bits) < uint64(ids.size())*16) + ++log_bits; + shift = 64 - log_bits; + bits.assign((uint64(1) << log_bits)/64, 0); + for (typename std::vector< Id_Type >::const_iterator it = ids.begin(); it != ids.end(); ++it) + { + uint64 h = slot(it->val()); + bits[h>>6] |= uint64(1) << (h & 63); + } + } + + bool maybe_contains(uint64 id) const + { + uint64 h = slot(id); + return (bits[h>>6] >> (h & 63)) & 1; + } + +private: + uint64 slot(uint64 id) const { return (id * 0x9E3779B97F4A7C15ull) >> shift; } + + std::vector< uint64 > bits; + unsigned shift; +}; + + template < class Object > class Id_Predicate { public: Id_Predicate(const std::vector< typename Object::Id_Type >& ids_) - : ids(ids_) {} - bool match(const Object& obj) const { return std::binary_search(ids.begin(), ids.end(), obj.id); } - bool match(const Handle< Object >& h) const { return std::binary_search(ids.begin(), ids.end(), h.id()); } - bool match(const Handle< Attic< Object > >& h) const { return std::binary_search(ids.begin(), ids.end(), h.id()); } + : ids(ids_), filter(std::make_shared< const Id_Bit_Filter >(ids_)) {} + bool match(const Object& obj) const { return contains(obj.id); } + bool match(const Handle< Object >& h) const { return contains(h.id()); } + bool match(const Handle< Attic< Object > >& h) const { return contains(h.id()); } bool possible() const { return !ids.empty(); } private: + // Most candidates are not in ids, so the filter rejects them before the + // binary search; the binary search keeps the answer exact. + bool contains(const typename Object::Id_Type& id) const + { return filter->maybe_contains(id.val()) && std::binary_search(ids.begin(), ids.end(), id); } + const std::vector< typename Object::Id_Type >& ids; + std::shared_ptr< const Id_Bit_Filter > filter; }; //----------------------------------------------------------------------------- diff --git a/src/overpass_api/data/collect_members.h b/src/overpass_api/data/collect_members.h index 9abd3b8c0..ab3c5aa52 100644 --- a/src/overpass_api/data/collect_members.h +++ b/src/overpass_api/data/collect_members.h @@ -176,7 +176,7 @@ class Collect_Items const Ranges< Index >& ranges_, const Statement& query_, Resource_Manager& rman_) : ids(&ids_), invert_ids(invert_ids_), ranges(ranges_), query(&query_), rman(&rman_), - min_idx(ranges_.empty() ? Index() : ranges_.begin().lower_bound()) {} + min_idx(ranges_.empty() ? Index() : ranges_.begin().lower_bound()), id_pred(ids_) {} bool get_chunk( std::map< Index, std::vector< Object > >& elements, @@ -189,6 +189,8 @@ class Collect_Items const Statement* query; Resource_Manager* rman; Index min_idx; + // Built once and reused for every chunk. + Id_Predicate< Object > id_pred; }; @@ -221,11 +223,11 @@ bool Collect_Items< Index, Object >::get_chunk( elements, attic_elements, Trivial_Predicate< Object >(), ranges, min_idx, *query, *rman); else return get_elements_by_id_from_db_generic( - elements, attic_elements, Not_Predicate< Object, Id_Predicate< Object > >(Id_Predicate< Object >(*ids)), + elements, attic_elements, Not_Predicate< Object, Id_Predicate< Object > >(id_pred), ranges, min_idx, *query, *rman); } return get_elements_by_id_from_db_generic( - elements, attic_elements, Id_Predicate< Object >(*ids), ranges, min_idx, *query, *rman); + elements, attic_elements, id_pred, ranges, min_idx, *query, *rman); } From e69776fde66c4803a5b9abd8af96712e321bef88 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 22:04:20 +0000 Subject: [PATCH 02/80] around: use fixed-size arrays for 3-D vectors The geometry helpers in around.cc (cartesian, sum, cross_prod, rescale) and the Prepared_Segment/Prepared_Point members used std::vector for 3-element vectors, so every intersection test allocated and freed several small heap buffers. On larger inputs around makes hundreds of millions of these tests. Use std::array. The arithmetic is unchanged, so results are identical. way(around.s0:100) with 282 ways in .s0 (Nova Scotia extract): 24.1 s -> 10.1 s CPU. around queries against small sets are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT (cherry picked from commit 5c4f531fa2b3b45392f918a0e70d76b34d0677ad) --- src/overpass_api/statements/around.cc | 46 +++++++++++++-------------- src/overpass_api/statements/around.h | 14 +++++--- 2 files changed, 33 insertions(+), 27 deletions(-) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index 43951f537..6c7b5192b 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -537,9 +537,9 @@ Around_Statement::~Around_Statement() } -std::vector< double > cartesian(double lat, double lon) +Vec3 cartesian(double lat, double lon) { - std::vector< double > result(3); + Vec3 result; result[0] = sin(lat/90.0*acos(0)); result[1] = cos(lat/90.0*acos(0))*sin(lon/90.0*acos(0)); @@ -549,7 +549,7 @@ std::vector< double > cartesian(double lat, double lon) } -void rescale(double a, std::vector< double >& v) +void rescale(double a, Vec3& v) { v[0] *= a; v[1] *= a; @@ -557,9 +557,9 @@ void rescale(double a, std::vector< double >& v) } -std::vector< double > sum(const std::vector< double >& v, const std::vector< double >& w) +Vec3 sum(const Vec3& v, const Vec3& w) { - std::vector< double > result(3); + Vec3 result; result[0] = v[0] + w[0]; result[1] = v[1] + w[1]; @@ -569,15 +569,15 @@ std::vector< double > sum(const std::vector< double >& v, const std::vector< dou } -double scalar_prod(const std::vector< double >& v, const std::vector< double >& w) +double scalar_prod(const Vec3& v, const Vec3& w) { return v[0]*w[0] + v[1]*w[1] + v[2]*w[2]; } -std::vector< double > cross_prod(const std::vector< double >& v, const std::vector< double >& w) +Vec3 cross_prod(const Vec3& v, const Vec3& w) { - std::vector< double > result(3); + Vec3 result; result[0] = v[1]*w[2] - v[2]*w[1]; result[1] = v[2]*w[0] - v[0]*w[2]; @@ -606,7 +606,7 @@ Prepared_Point::Prepared_Point } -double great_circle_line_dist(const Prepared_Segment& segment, const std::vector< double >& cartesian) +double great_circle_line_dist(const Prepared_Segment& segment, const Vec3& cartesian) { double scalar_prod_ = std::abs(scalar_prod(cartesian, segment.norm)) /sqrt(scalar_prod(segment.norm, segment.norm)); @@ -621,7 +621,7 @@ double great_circle_line_dist(const Prepared_Segment& segment, const std::vector double great_circle_line_dist(double llat1, double llon1, double llat2, double llon2, double plat, double plon) { - std::vector< double > norm = cross_prod(cartesian(llat1, llon1), cartesian(llat2, llon2)); + Vec3 norm = cross_prod(cartesian(llat1, llon1), cartesian(llat2, llon2)); double scalar_prod_ = std::abs(scalar_prod(cartesian(plat, plon), norm)) /sqrt(scalar_prod(norm, norm)); @@ -636,11 +636,11 @@ double great_circle_line_dist(double llat1, double llon1, double llat2, double l bool intersect(const Prepared_Segment& segment_a, const Prepared_Segment& segment_b) { - std::vector< double > intersection_pt = cross_prod(segment_a.norm, segment_b.norm); + Vec3 intersection_pt = cross_prod(segment_a.norm, segment_b.norm); rescale(1.0/sqrt(scalar_prod(intersection_pt, intersection_pt)), intersection_pt); - std::vector< double > asum = sum(segment_a.first_cartesian, segment_a.second_cartesian); - std::vector< double > bsum = sum(segment_b.first_cartesian, segment_b.second_cartesian); + Vec3 asum = sum(segment_a.first_cartesian, segment_a.second_cartesian); + Vec3 bsum = sum(segment_b.first_cartesian, segment_b.second_cartesian); return (std::abs(scalar_prod(asum, intersection_pt)) >= scalar_prod(asum, segment_a.first_cartesian) && std::abs(scalar_prod(bsum, intersection_pt)) >= scalar_prod(bsum, segment_b.first_cartesian)); @@ -650,18 +650,18 @@ bool intersect(const Prepared_Segment& segment_a, bool intersect(double alat1, double alon1, double alat2, double alon2, double blat1, double blon1, double blat2, double blon2) { - std::vector< double > a1 = cartesian(alat1, alon1); - std::vector< double > a2 = cartesian(alat2, alon2); - std::vector< double > norm_a = cross_prod(a1, a2); - std::vector< double > b1 = cartesian(blat1, blon1); - std::vector< double > b2 = cartesian(blat2, blon2); - std::vector< double > norm_b = cross_prod(b1, b2); + Vec3 a1 = cartesian(alat1, alon1); + Vec3 a2 = cartesian(alat2, alon2); + Vec3 norm_a = cross_prod(a1, a2); + Vec3 b1 = cartesian(blat1, blon1); + Vec3 b2 = cartesian(blat2, blon2); + Vec3 norm_b = cross_prod(b1, b2); - std::vector< double > intersection_pt = cross_prod(norm_a, norm_b); + Vec3 intersection_pt = cross_prod(norm_a, norm_b); rescale(1.0/sqrt(scalar_prod(intersection_pt, intersection_pt)), intersection_pt); - std::vector< double > asum = sum(a1, a2); - std::vector< double > bsum = sum(b1, b2); + Vec3 asum = sum(a1, a2); + Vec3 bsum = sum(b1, b2); return (std::abs(scalar_prod(asum, intersection_pt)) >= scalar_prod(asum, a1) && std::abs(scalar_prod(bsum, intersection_pt)) >= scalar_prod(bsum, b1)); @@ -887,7 +887,7 @@ bool Around_Statement::is_inside(double lat, double lon) const } } - std::vector< double > coord_cartesian = cartesian(lat, lon); + Vec3 coord_cartesian = cartesian(lat, lon); for (std::vector< Prepared_Segment >::const_iterator it = simple_segments.begin(); it != simple_segments.end(); ++it) { diff --git a/src/overpass_api/statements/around.h b/src/overpass_api/statements/around.h index d82f24b3c..1b6380aab 100644 --- a/src/overpass_api/statements/around.h +++ b/src/overpass_api/statements/around.h @@ -22,6 +22,7 @@ #include #include #include +#include #include #include "../data/collect_members.h" #include "../data/utils.h" @@ -29,15 +30,20 @@ #include "statement.h" +// A point or direction on the unit sphere, in Cartesian coordinates. A fixed-size +// array keeps the geometry tests free of heap allocations. +typedef std::array< double, 3 > Vec3; + + struct Prepared_Segment { double first_lat; double first_lon; double second_lat; double second_lon; - std::vector< double > first_cartesian; - std::vector< double > second_cartesian; - std::vector< double > norm; + Vec3 first_cartesian; + Vec3 second_cartesian; + Vec3 norm; Prepared_Segment(double first_lat, double first_lon, double second_lat, double second_lon); }; @@ -47,7 +53,7 @@ struct Prepared_Point { double lat; double lon; - std::vector< double > cartesian; + Vec3 cartesian; Prepared_Point(double lat, double lon); }; From 9e7e909636f58d34ad7d8f9481c3c15b87557ee4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 22:13:54 +0000 Subject: [PATCH 03/80] around: index the input set's geometry with a coarse grid 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 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT (cherry picked from commit 0e71678773df45ff6bc5f323e1ea39d87995cf9a) --- src/overpass_api/statements/around.cc | 145 +++++++++++++++++++++----- src/overpass_api/statements/around.h | 88 ++++++++++++++++ 2 files changed, 207 insertions(+), 26 deletions(-) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index 6c7b5192b..4e09d57bb 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -697,6 +697,99 @@ Ranges< Uint32_Index > Around_Statement::calc_ranges(const Set& input, Resource_ } +//----------------------------------------------------------------------------- + +/* Why reach boxes are enough. Let reach(X) be the bounding box of X widened by + (length of X + radius), where a point has length 0. Every exact test only passes + when the two objects' reach boxes overlap: + + - Point P near segment S (is_inside(lat, lon)): the test requires + great_circle_dist(P, first point of S) <= sqrt(len(S)^2 + radius^2) + <= len(S) + radius, so P lies in reach(S). + - Segment C near point Q (is_inside(segment), first loop): the same test with the + roles swapped puts Q in reach(C). + - Segments S and C intersect (intersect()): the crossing point lies on both arcs, + so within len(S) of S's first point and within len(C) of C's first point; it is + in both reach boxes. + + The widening uses a slightly larger distance than needed and the latitude closest + to the pole for the longitude scale, so the boxes are conservative. Boxes too + close to a pole, crossing the antimeridian or spanning many cells are never pruned. */ + +Reach_Grid::Box Reach_Grid::reach_box(double lat1, double lon1, double lat2, double lon2, double reach) +{ + Box box; + // great_circle_dist uses 10,000 km per quarter meridian, so 1 degree of latitude is + // 1e7/90 m. A point within distance d is within d/(1e7/90) degrees of latitude. + double margin_deg = (reach * 1.02 + 1.0) / (10.0*1000*1000/90.0); + box.south = std::min(lat1, lat2) - margin_deg; + box.north = std::max(lat1, lat2) + margin_deg; + double poleward = std::max(std::abs(box.south), std::abs(box.north)); + double lon_margin_deg = poleward < 80.0 ? margin_deg / cos(poleward/90.0*acos(0)) : 360.0; + box.west = std::min(lon1, lon2) - lon_margin_deg; + box.east = std::max(lon1, lon2) + lon_margin_deg; + box.usable = poleward < 80.0 && margin_deg < 5.0 && std::abs(lon1 - lon2) < 180.0 + && box.west >= -180.0 && box.east <= 180.0; + return box; +} + + +bool Reach_Grid::cell_range(const Box& box, int64& lat0, int64& lat1, int64& lon0, int64& lon1) +{ + if (!box.usable) + return false; + lat0 = (int64)floor(box.south / cell_size); + lat1 = (int64)floor(box.north / cell_size); + lon0 = (int64)floor(box.west / cell_size); + lon1 = (int64)floor(box.east / cell_size); + return (lat1 - lat0 + 1) * (lon1 - lon0 + 1) <= max_cells; +} + + +void Reach_Grid::clear() +{ + cells.clear(); + always.clear(); + total = 0; +} + + +void Reach_Grid::add(const Box& box, uint32 id) +{ + ++total; + int64 lat0, lat1, lon0, lon1; + if (!cell_range(box, lat0, lat1, lon0, lon1)) + { + always.push_back(id); + return; + } + for (int64 i = lat0; i <= lat1; ++i) + { + for (int64 j = lon0; j <= lon1; ++j) + cells[key(i, j)].push_back(id); + } +} + + +void Around_Statement::build_grids() +{ + point_grid.clear(); + for (uint32 i = 0; i < simple_lat_lons.size(); ++i) + { + const Prepared_Point& p = simple_lat_lons[i]; + point_grid.add(Reach_Grid::reach_box(p.lat, p.lon, p.lat, p.lon, radius), i); + } + segment_grid.clear(); + for (uint32 i = 0; i < simple_segments.size(); ++i) + { + const Prepared_Segment& s = simple_segments[i]; + double length = great_circle_dist(s.first_lat, s.first_lon, s.second_lat, s.second_lon); + segment_grid.add(Reach_Grid::reach_box( + s.first_lat, s.first_lon, s.second_lat, s.second_lon, length + radius), i); + } +} + + void add_coord(double lat, double lon, double radius, std::map< Uint32_Index, std::vector< Point_Double > >& radius_lat_lons, std::vector< Prepared_Point >& simple_lat_lons) @@ -835,11 +928,13 @@ void Around_Statement::calc_lat_lons(const Set& input, Statement& query, Resourc if (points.size() == 1) { add_coord(points[0].lat, points[0].lon, radius, radius_lat_lons, simple_lat_lons); + build_grids(); return; } else if (points.size() > 1) { add_way(points, radius, radius_lat_lons, simple_lat_lons, simple_segments); + build_grids(); return; } Request_Context context(&query, rman); @@ -869,6 +964,7 @@ void Around_Statement::calc_lat_lons(const Set& input, Statement& query, Resourc = relation_way_members(context, input.attic_relations, Ranges< Uint31_Index >::global()); add_ways(way_members, Way_Geometry_Store(way_members, query, rman)); } + build_grids(); } @@ -888,9 +984,9 @@ bool Around_Statement::is_inside(double lat, double lon) const } Vec3 coord_cartesian = cartesian(lat, lon); - for (std::vector< Prepared_Segment >::const_iterator - it = simple_segments.begin(); it != simple_segments.end(); ++it) + return segment_grid.any(Reach_Grid::reach_box(lat, lon, lat, lon, radius), [&](uint32 id) { + const Prepared_Segment* it = &simple_segments[id]; if (great_circle_line_dist(*it, coord_cartesian) <= radius) { double gcdist = great_circle_dist @@ -900,37 +996,34 @@ bool Around_Statement::is_inside(double lat, double lon) const great_circle_dist(lat, lon, it->second_lat, it->second_lon) <= limit) return true; } - } - - return false; + return false; + }); } bool Around_Statement::is_inside (double first_lat, double first_lon, double second_lat, double second_lon) const { Prepared_Segment segment(first_lat, first_lon, second_lat, second_lon); + double length = great_circle_dist(first_lat, first_lon, second_lat, second_lon); + Reach_Grid::Box box = Reach_Grid::reach_box(first_lat, first_lon, second_lat, second_lon, + length + radius); - for (std::vector< Prepared_Point >::const_iterator cit = simple_lat_lons.begin(); - cit != simple_lat_lons.end(); ++cit) - { - if (great_circle_line_dist(segment, cit->cartesian) <= radius) - { - double gcdist = great_circle_dist(first_lat, first_lon, second_lat, second_lon); - double limit = sqrt(gcdist*gcdist + radius*radius); - if (great_circle_dist(cit->lat, cit->lon, first_lat, first_lon) <= limit && - great_circle_dist(cit->lat, cit->lon, second_lat, second_lon) <= limit) - return true; - } - } - - for (std::vector< Prepared_Segment >::const_iterator - cit = simple_segments.begin(); cit != simple_segments.end(); ++cit) - { - if (intersect(*cit, segment)) - return true; - } - - return false; + if (point_grid.any(box, [&](uint32 id) + { + const Prepared_Point* cit = &simple_lat_lons[id]; + if (great_circle_line_dist(segment, cit->cartesian) <= radius) + { + double gcdist = great_circle_dist(first_lat, first_lon, second_lat, second_lon); + double limit = sqrt(gcdist*gcdist + radius*radius); + if (great_circle_dist(cit->lat, cit->lon, first_lat, first_lon) <= limit && + great_circle_dist(cit->lat, cit->lon, second_lat, second_lon) <= limit) + return true; + } + return false; + })) + return true; + + return segment_grid.any(box, [&](uint32 id) { return intersect(simple_segments[id], segment); }); } diff --git a/src/overpass_api/statements/around.h b/src/overpass_api/statements/around.h index 1b6380aab..0eefb4e24 100644 --- a/src/overpass_api/statements/around.h +++ b/src/overpass_api/statements/around.h @@ -23,6 +23,7 @@ #include #include #include +#include #include #include "../data/collect_members.h" #include "../data/utils.h" @@ -59,6 +60,89 @@ struct Prepared_Point }; +/* A coarse lat/lon grid over the points and segments of an around statement's input + set. It only narrows down which entries the exact tests need to look at; it never + decides a match itself. + + Each entry is filed under every cell its "reach box" covers: its bounding box widened + by its own length plus the radius. A point or segment can only pass any of the exact + tests against an entry if their reach boxes overlap (see around.cc), so looking up the + cells of a candidate's reach box finds every entry that could match it. Entries whose + reach box is too large to file, or lies near a pole or the antimeridian, are kept in + a list that every lookup includes. */ +class Reach_Grid +{ +public: + struct Box + { + double south, west, north, east; + bool usable; // false: too large, polar or crossing the antimeridian + }; + + static Box reach_box(double lat1, double lon1, double lat2, double lon2, double reach); + + void clear(); + void add(const Box& box, uint32 id); + + // Calls f(id) for every entry whose cells the box touches, plus the always-checked + // entries. Stops and returns true as soon as f returns true. An id can be passed + // more than once. + template< typename F > + bool any(const Box& box, F f) const; + +private: + static const int max_cells = 64; + static constexpr double cell_size = 0.01; + + static bool cell_range(const Box& box, int64& lat0, int64& lat1, int64& lon0, int64& lon1); + static int64 key(int64 lat_cell, int64 lon_cell) { return (lat_cell << 32) ^ (lon_cell & 0xffffffff); } + + std::unordered_map< int64, std::vector< uint32 > > cells; + std::vector< uint32 > always; + uint32 total = 0; +}; + + +template< typename F > +bool Reach_Grid::any(const Box& box, F f) const +{ + for (uint32 id : always) + { + if (f(id)) + return true; + } + int64 lat0, lat1, lon0, lon1; + if (!cell_range(box, lat0, lat1, lon0, lon1)) + { + // The box is too large to look up cell by cell: check every entry. + for (const auto& cell : cells) + { + for (uint32 id : cell.second) + { + if (f(id)) + return true; + } + } + return false; + } + for (int64 i = lat0; i <= lat1; ++i) + { + for (int64 j = lon0; j <= lon1; ++j) + { + auto it = cells.find(key(i, j)); + if (it == cells.end()) + continue; + for (uint32 id : it->second) + { + if (f(id)) + return true; + } + } + } + return false; +} + + class Around_Statement : public Output_Statement { public: @@ -146,6 +230,10 @@ class Around_Statement : public Output_Statement std::map< Uint32_Index, std::vector< Point_Double > > radius_lat_lons; std::vector< Prepared_Point > simple_lat_lons; std::vector< Prepared_Segment > simple_segments; + Reach_Grid point_grid; // ids are positions in simple_lat_lons + Reach_Grid segment_grid; // ids are positions in simple_segments + + void build_grids(); std::vector< Query_Constraint* > constraints; }; From efe5a9316628511debd6475246515a50146f219e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 22:30:57 +0000 Subject: [PATCH 04/80] around: check the query's time limit while filtering candidates The expensive around filters (filter_nodes_expensive, filter_ways_expensive, filter_relations_expensive) ran to completion before the statement's health check, so a slow around ignored the query's [timeout:] and kept a CPU busy until it finished. Call rman.health_check every 256 candidates (or relation members), so the query stops with the usual timeout error once its time is up. Nova Scotia extract: an around against a set reaching a national boundary relation, with [timeout:10], ran past 80-120 s; it now stops after 14 s with "Query timed out". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT (cherry picked from commit dfa21c68d23507539bf9054fdacedbbbe6db5376) --- src/overpass_api/statements/around.cc | 42 +++++++++++++++++++++------ 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index 4e09d57bb..b6938b251 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -224,8 +224,28 @@ void Around_Constraint::filter(Resource_Manager& rman, Set& into) } +/* Checks the query's time and memory limits every few hundred candidates, so that an + expensive around filter stops when the query runs out of time instead of running + to completion. health_check throws when a limit is exceeded. */ +class Periodic_Health_Check +{ +public: + Periodic_Health_Check(Resource_Manager& rman_, const Statement& stmt_) : rman(rman_), stmt(stmt_) {} + void tick() + { + if (++count % 256 == 0) + rman.health_check(stmt); + } + +private: + Resource_Manager& rman; + const Statement& stmt; + uint32 count = 0; +}; + + template< typename Node_Skeleton > -void filter_nodes_expensive(const Around_Statement& around, +void filter_nodes_expensive(const Around_Statement& around, Periodic_Health_Check& check, std::map< Uint32_Index, std::vector< Node_Skeleton > >& nodes) { for (typename std::map< Uint32_Index, std::vector< Node_Skeleton > >::iterator it = nodes.begin(); @@ -235,6 +255,7 @@ void filter_nodes_expensive(const Around_Statement& around, for (typename std::vector< Node_Skeleton >::const_iterator iit = it->second.begin(); iit != it->second.end(); ++iit) { + check.tick(); double lat(::lat(it->first.val(), iit->ll_lower)); double lon(::lon(it->first.val(), iit->ll_lower)); if (around.is_inside(lat, lon)) @@ -246,7 +267,7 @@ void filter_nodes_expensive(const Around_Statement& around, template< typename Way_Skeleton > -void filter_ways_expensive(const Around_Statement& around, +void filter_ways_expensive(const Around_Statement& around, Periodic_Health_Check& check, const Way_Geometry_Store& way_geometries, std::map< Uint31_Index, std::vector< Way_Skeleton > >& ways) { @@ -257,6 +278,7 @@ void filter_ways_expensive(const Around_Statement& around, for (typename std::vector< Way_Skeleton >::const_iterator iit = it->second.begin(); iit != it->second.end(); ++iit) { + check.tick(); if (around.is_inside(way_geometries.get_geometry(*iit))) local_into.push_back(*iit); } @@ -266,7 +288,7 @@ void filter_ways_expensive(const Around_Statement& around, template< typename Relation_Skeleton > -void filter_relations_expensive(const Around_Statement& around, +void filter_relations_expensive(const Around_Statement& around, Periodic_Health_Check& check, const std::vector< std::pair< Uint32_Index, const Node_Skeleton* > > node_members_by_id, const std::vector< std::pair< Uint31_Index, const Way_Skeleton* > > way_members_by_id, const Way_Geometry_Store& way_geometries, @@ -282,6 +304,7 @@ void filter_relations_expensive(const Around_Statement& around, for (std::vector< Relation_Entry >::const_iterator nit = iit->members.begin(); nit != iit->members.end(); ++nit) { + check.tick(); if (nit->type == Relation_Entry::NODE) { const std::pair< Uint32_Index, const Node_Skeleton* >* second_nd = @@ -318,12 +341,13 @@ void filter_relations_expensive(const Around_Statement& around, void Around_Constraint::filter(const Statement& query, Resource_Manager& rman, Set& into) { + Periodic_Health_Check check(rman, query); const Set* input = rman.get_set(around->get_source_name()); const Set empty; around->calc_lat_lons(input ? *input : empty, *around, rman); - filter_nodes_expensive(*around, into.nodes); - filter_ways_expensive(*around, Way_Geometry_Store(into.ways, query, rman), into.ways); + filter_nodes_expensive(*around, check, into.nodes); + filter_ways_expensive(*around, check, Way_Geometry_Store(into.ways, query, rman), into.ways); Request_Context context(&query, rman); { @@ -348,15 +372,15 @@ void Around_Constraint::filter(const Statement& query, Resource_Manager& rman, S = order_by_id(way_members_.current, Order_By_Way_Id()); // Retrieve all nodes referred by the ways. - filter_relations_expensive(*around, node_members_by_id, way_members_by_id, + filter_relations_expensive(*around, check, node_members_by_id, way_members_by_id, Way_Geometry_Store(way_members_.current, query, rman), into.relations); } if (!into.attic_nodes.empty()) - filter_nodes_expensive(*around, into.attic_nodes); + filter_nodes_expensive(*around, check, into.attic_nodes); if (!into.attic_ways.empty()) - filter_ways_expensive(*around, Way_Geometry_Store(into.attic_ways, query, rman), into.attic_ways); + filter_ways_expensive(*around, check, Way_Geometry_Store(into.attic_ways, query, rman), into.attic_ways); if (!into.attic_relations.empty()) { @@ -378,7 +402,7 @@ void Around_Constraint::filter(const Statement& query, Resource_Manager& rman, S std::vector< std::pair< Uint31_Index, const Way_Skeleton* > > way_members_by_id = order_attic_by_id(way_members_, Order_By_Way_Id()); - filter_relations_expensive(*around, node_members_by_id, way_members_by_id, + filter_relations_expensive(*around, check, node_members_by_id, way_members_by_id, Way_Geometry_Store(way_members_, query, rman), into.attic_relations); } From 87ddf8aa475ba0e82a8ad53541d310901bdaf346 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 23:48:33 +0000 Subject: [PATCH 05/80] around: let the tag index drive queries whose around area is large Around_Constraint chose prefer_ranges whenever the radius was under 2 km. The query statement then reads every object in around's index ranges and checks tag filters afterwards. A small radius around a large input set, such as long relations, still covers a large area, so a selective tag filter went unused. Like Bbox_Constraint, also look at the area: with more than 65536 node index tiles (about one square degree), return ids_useful so that the tag index selects candidates within the ranges. The filters are the same, so results are unchanged. Nova Scotia extract: rel(45.566265,-62.428420,45.586924,-62.388716)->.s0; node(around.s0:0)["footway"]; takes 2.24 s -> 0.08 s. The 9 relations in .s0 include a long trail and boundaries, so their extent covers much of the province. With radius 2000 the same query already took 0.42 s on master, because radius alone decided the strategy. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT (cherry picked from commit 79f3b3be24902fe5428131b61e7f81f39f108eb2) --- src/overpass_api/statements/around.cc | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index b6938b251..1f125a4c1 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -127,8 +127,7 @@ class Around_Constraint : public Query_Constraint public: Around_Constraint(Around_Statement& around_) : around(&around_), ranges_used(false) {} - Query_Filter_Strategy delivers_data(Resource_Manager& rman) - { return (around->get_radius() < 2000) ? prefer_ranges : ids_useful; } + Query_Filter_Strategy delivers_data(Resource_Manager& rman); bool get_ranges(Resource_Manager& rman, Ranges< Uint32_Index >& ranges); bool get_ranges(Resource_Manager& rman, Ranges< Uint31_Index >& ranges); @@ -143,6 +142,29 @@ class Around_Constraint : public Query_Constraint }; +/* Reading every object in the ranges and checking tags afterwards (prefer_ranges) only pays + off while the ranges are small. A small radius around a large input set, such as long + relations, can still cover a large area, so look at the area as well as the radius. Like + Bbox_Constraint, let the tag index select candidates (ids_useful) once the area exceeds + about one square degree: 65536 node index tiles of about 0.00275 by 0.0055 degrees. */ +Query_Filter_Strategy Around_Constraint::delivers_data(Resource_Manager& rman) +{ + if (around->get_radius() >= 2000) + return ids_useful; + + const Set* input = rman.get_set(around->get_source_name()); + Ranges< Uint32_Index > ranges = around->calc_ranges(input ? *input : Set(), rman); + uint64 tiles = 0; + for (auto it = ranges.begin(); it != ranges.end(); ++it) + { + tiles += uint64(it.upper_bound().val()) - it.lower_bound().val(); + if (tiles > 65536) + return ids_useful; + } + return prefer_ranges; +} + + bool Around_Constraint::get_ranges (Resource_Manager& rman, Ranges< Uint32_Index >& ranges) { From 974fb797d3287a7839aec2807ecb3e21d6c0fb5f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 00:25:28 +0000 Subject: [PATCH 06/80] Format output coordinates without general float formatting Every coordinate in the JSON, XML, CSV and custom output was written with out< 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 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT (cherry picked from commit cf56d04ee31c0a4339d112f5d38f9b5e98d61e14) --- src/Makefile.am | 1 + src/overpass_api/output_formats/fixed7.h | 88 +++++++++++++++++++ src/overpass_api/output_formats/output_csv.cc | 5 +- .../output_formats/output_custom.cc | 17 ++-- .../output_formats/output_json.cc | 69 +++++++-------- src/overpass_api/output_formats/output_xml.cc | 61 ++++++------- 6 files changed, 165 insertions(+), 76 deletions(-) create mode 100644 src/overpass_api/output_formats/fixed7.h diff --git a/src/Makefile.am b/src/Makefile.am index b074e52fe..df1f7172d 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -278,6 +278,7 @@ nobase_dist_HEADERS = \ overpass_api/osm-backend/way_updater.h\ overpass_api/output_formats/output_csv.h\ overpass_api/output_formats/output_custom.h\ + overpass_api/output_formats/fixed7.h\ overpass_api/output_formats/output_json.h\ overpass_api/output_formats/output_popup.h\ overpass_api/output_formats/output_xml.h\ diff --git a/src/overpass_api/output_formats/fixed7.h b/src/overpass_api/output_formats/fixed7.h new file mode 100644 index 000000000..5f1ead0d7 --- /dev/null +++ b/src/overpass_api/output_formats/fixed7.h @@ -0,0 +1,88 @@ +/** Copyright 2026 the Overpass API contributors + * + * This file is part of Overpass_API. + * + * Overpass_API is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * Overpass_API is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Overpass_API. If not, see . + */ + +#ifndef DE__OSM3S___OVERPASS_API__OUTPUT_FORMATS__FIXED7_H +#define DE__OSM3S___OVERPASS_API__OUTPUT_FORMATS__FIXED7_H + +#include +#include +#include +#include + + +/* Writes a coordinate with exactly the same characters as + out< 0 || len < 8) + { + digits[len++] = '0' + (n % 10); + n /= 10; + } + int pos = 0; + if (std::signbit(value)) + buf[pos++] = '-'; + for (int i = len - 1; i >= 7; --i) + buf[pos++] = digits[i]; + buf[pos++] = '.'; + for (int i = 6; i >= 0; --i) + buf[pos++] = digits[i]; + buf[pos] = 0; + return pos; +} + + +inline std::ostream& operator<<(std::ostream& out, const Fixed7& f) +{ + out.setf(std::ios::fixed, std::ios::floatfield); + out.precision(7); + char buf[64]; + out.write(buf, format_fixed7(buf, f.value)); + return out; +} + + +#endif diff --git a/src/overpass_api/output_formats/output_csv.cc b/src/overpass_api/output_formats/output_csv.cc index 79be9a647..26aec3591 100644 --- a/src/overpass_api/output_formats/output_csv.cc +++ b/src/overpass_api/output_formats/output_csv.cc @@ -18,6 +18,7 @@ #include "../../expat/escape_json.h" #include "output_csv.h" +#include "fixed7.h" bool Output_CSV::write_http_headers() @@ -197,13 +198,13 @@ void process_csv_line(int otype, const std::string& type, Id_Type id, const Opaq { if ((mode.mode & (Output_Mode::COORDS | Output_Mode::GEOMETRY | Output_Mode::BOUNDS | Output_Mode::CENTER)) && geometry.has_center()) - std::cout<first == "lon") { if ((mode.mode & (Output_Mode::COORDS | Output_Mode::GEOMETRY | Output_Mode::BOUNDS | Output_Mode::CENTER)) && geometry.has_center()) - std::cout< #include @@ -329,9 +330,9 @@ std::string process_coords(const std::string& raw_template, uint32 id, double la else if (raw_template.substr(new_pos, 8) == "{{{id}}}") result<* line = geometry.get_line_geometry(); for (std::vector< Point_Double >::const_iterator it = line->begin(); it != line->end(); ++it) std::cout<<(it == line->begin() ? "" : ",")<<"\n"<lon<<", " - <lat<<"]"; + <lon)<<", " + <lat)<<"]"; std::cout<<"\n"<begin() ? "" : ",")<<"\n"<::const_iterator it = iti->begin(); it != iti->end(); ++it) std::cout<<(it == iti->begin() ? "" : ",")<<"\n"<lon<<", " - <lat<<"]"; + <lon)<<", " + <lat)<<"]"; std::cout<<"\n"<\n\n"; } @@ -167,10 +168,10 @@ void print_bounds(const Opaque_Geometry& geometry, Output_Mode mode, bool& inner inner_tags_printed = true; } std::cout<<" \n"; } else if ((mode.mode & Output_Mode::CENTER) && geometry.has_center()) @@ -181,8 +182,8 @@ void print_bounds(const Opaque_Geometry& geometry, Output_Mode mode, bool& inner inner_tags_printed = true; } std::cout<<" \n"; } } @@ -219,8 +220,8 @@ void print_geometry(const Opaque_Geometry& geometry, Output_Mode mode, bool& inn const std::vector< Point_Double >* line = geometry.get_line_geometry(); for (std::vector< Point_Double >::const_iterator it = line->begin(); it != line->end(); ++it) std::cout<lat<<"\"" - " lon=\""<lon<<"\"" + " lat=\""<lat)<<"\"" + " lon=\""<lon)<<"\"" "/>\n"; } else if ((mode.mode & Output_Mode::GEOMETRY) && geometry.has_multiline_geometry()) @@ -237,8 +238,8 @@ void print_geometry(const Opaque_Geometry& geometry, Output_Mode mode, bool& inn std::cout<\n"; for (std::vector< Point_Double >::const_iterator it = iti->begin(); it != iti->end(); ++it) std::cout<lat<<"\"" - " lon=\""<lon<<"\"" + " lat=\""<lat)<<"\"" + " lon=\""<lon)<<"\"" "/>\n"; std::cout<\n"; } @@ -251,8 +252,8 @@ void print_geometry(const Opaque_Geometry& geometry, Output_Mode mode, bool& inn inner_tags_printed = true; } std::cout<\n"; } else if ((mode.mode & Output_Mode::BOUNDS) && geometry.has_bbox()) @@ -263,10 +264,10 @@ void print_geometry(const Opaque_Geometry& geometry, Output_Mode mode, bool& inn inner_tags_printed = true; } std::cout<<" \n"; } else if ((mode.mode & Output_Mode::CENTER) && geometry.has_center()) @@ -277,8 +278,8 @@ void print_geometry(const Opaque_Geometry& geometry, Output_Mode mode, bool& inn inner_tags_printed = true; } std::cout<\n"; } } @@ -298,8 +299,8 @@ void print_members(const Way_Skeleton& skel, const Opaque_Geometry& geometry, { std::cout<<" \n"; } } @@ -327,8 +328,8 @@ void print_members(const Relation_Skeleton& skel, const Opaque_Geometry& geometr if (skel.members[i].type == Relation_Entry::NODE) { if (geometry.has_faithful_relation_geometry() && geometry.relation_pos_is_valid(i)) - std::cout<<" lat=\""<\n"; } else if (skel.members[i].type == Relation_Entry::WAY) @@ -349,8 +350,8 @@ void print_members(const Relation_Skeleton& skel, const Opaque_Geometry& geometr for (uint j = 0; j < geometry.relation_way_size(i); ++j) { if (geometry.relation_pos_is_valid(i, j)) - std::cout<<" \n"; + std::cout<<" \n"; else std::cout<<" \n"; } @@ -377,8 +378,8 @@ void print_node(const Node_Skeleton& skel, std::cout<<" id=\""< Date: Sat, 21 Nov 2026 00:36:40 +0000 Subject: [PATCH 07/80] Collect relation node members and way nodes in one pass Down recursion over relations (>> always, and > when the input has relations) collected the relations' node members and the ways' nodes in two separate passes over the node blocks, then took the union. Blocks holding both kinds of node were read and decompressed twice. Add relation_and_way_node_members, which merges the two sorted id lists and the two range sets and reads the node blocks once. Use it for >> and for > on current data without a range restriction. The history path and localize's restricted-range path are unchanged. The result is the union of the two old results, as before. Nova Scotia extract, CPU time, alternating runs: rel[boundary=administrative][admin_level=4][name="Nova Scotia"]; (._;>>;); 714 ms -> 559 ms; node block reads 2570 -> 1490 (1489 distinct) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT (cherry picked from commit 8dba6b955ab0ed219569e369564da0f240293be9) --- src/overpass_api/data/collect_members.cc | 37 ++++++++++++++++++++++++ src/overpass_api/data/collect_members.h | 12 ++++++++ src/overpass_api/statements/recurse.cc | 11 ++----- 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/src/overpass_api/data/collect_members.cc b/src/overpass_api/data/collect_members.cc index be67d2d7b..8e02c33ce 100644 --- a/src/overpass_api/data/collect_members.cc +++ b/src/overpass_api/data/collect_members.cc @@ -674,6 +674,26 @@ Timeless< Uint32_Index, Node_Skeleton > paired_items_range( } +Timeless< Uint32_Index, Node_Skeleton > relation_and_way_node_members( + Request_Context& context, + const std::map< Uint31_Index, std::vector< Relation_Skeleton > >& relations, + const std::map< Uint31_Index, std::vector< Attic< Relation_Skeleton > > >& attic_relations, + const std::map< Uint31_Index, std::vector< Way_Skeleton > >& ways, + const std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > > >& attic_ways) +{ + // Both id lists are sorted and free of duplicates. + std::vector< Node::Id_Type > rel_ids = relation_node_member_ids(relations, attic_relations); + std::vector< Node::Id_Type > way_ids = way_nd_ids(ways, attic_ways, 0); + context.get_health_guard().check(); + std::vector< Node::Id_Type > ids; + ids.reserve(rel_ids.size() + way_ids.size()); + std::set_union(rel_ids.begin(), rel_ids.end(), way_ids.begin(), way_ids.end(), std::back_inserter(ids)); + + return paired_items_range(context, ids, + relation_node_member_indices(relations, attic_relations).union_(way_nd_indices(ways, attic_ways))); +} + + Timeless< Uint32_Index, Node_Skeleton > relation_node_members (Request_Context& context, const std::map< Uint31_Index, std::vector< Relation_Skeleton > >& relations, @@ -1065,6 +1085,23 @@ void add_nw_member_objects(Request_Context& context, const Set& input_set, Set& { Ranges< Uint32_Index > ranges_32(ranges_32_ ? *ranges_32_ : Ranges< Uint32_Index >::global()); Ranges< Uint31_Index > ranges_31(ranges_31_ ? *ranges_31_ : Ranges< Uint31_Index >::global()); + + if (context.get_desired_timestamp() == NOW && !ranges_32_) + { + // Collect the relations' node members and the ways' nodes in one pass over the node blocks. + relation_way_members(context, input_set.relations, {}, ranges_31, {}, true) + .swap(into.ways, into.attic_ways); + std::map< Uint31_Index, std::vector< Way_Skeleton > > source_ways = input_set.ways; + sort_second(source_ways); + sort_second(into.ways); + indexed_set_union(source_ways, into.ways); + Timeless< Uint32_Index, Node_Skeleton > nodes = relation_and_way_node_members( + context, input_set.relations, input_set.attic_relations, source_ways, {}); + nodes.current.swap(into.nodes); + sort_second(into.nodes); + return; + } + Timeless< Uint32_Index, Node_Skeleton > rel_nodes = relation_node_members(context, input_set.relations, input_set.attic_relations, ranges_32, {}, true); diff --git a/src/overpass_api/data/collect_members.h b/src/overpass_api/data/collect_members.h index ab3c5aa52..1de9773b6 100644 --- a/src/overpass_api/data/collect_members.h +++ b/src/overpass_api/data/collect_members.h @@ -746,6 +746,18 @@ Ranges< Uint31_Index > relation_way_member_indices Ranges< Uint32_Index > calc_node_children_ranges(const std::vector< uint32 >& way_rel_idxs); +/* The node members of the relations and the nodes of the ways, read in a single pass + over the node blocks. Equivalent to the union of relation_node_members(relations) and + way_members(ways) with global ranges, but blocks holding both kinds of node are read + and decompressed once instead of twice. */ +Timeless< Uint32_Index, Node_Skeleton > relation_and_way_node_members( + Request_Context& context, + const std::map< Uint31_Index, std::vector< Relation_Skeleton > >& relations, + const std::map< Uint31_Index, std::vector< Attic< Relation_Skeleton > > >& attic_relations, + const std::map< Uint31_Index, std::vector< Way_Skeleton > >& ways, + const std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > > >& attic_ways); + + Ranges< Uint32_Index > relation_node_member_indices( const std::map< Uint31_Index, std::vector< Relation_Skeleton > >& current_rels, const std::map< Uint31_Index, std::vector< Attic< Relation_Skeleton > > >& attic_rels); diff --git a/src/overpass_api/statements/recurse.cc b/src/overpass_api/statements/recurse.cc index e5d5de1c3..b42398ec5 100644 --- a/src/overpass_api/statements/recurse.cc +++ b/src/overpass_api/statements/recurse.cc @@ -1404,15 +1404,10 @@ void Recurse_Statement::execute(Resource_Manager& rman) source_ways.set_union(result_ways.swap(into.ways, into.attic_ways).sort()); result_ways.swap(into.ways, into.attic_ways); } - Timeless< Uint32_Index, Node_Skeleton > rel_nodes = relation_node_members( - context, into.relations, into.attic_relations, Ranges< Uint32_Index >::global(), {}, true); + // The relations' node members and the ways' nodes, in one pass over the node blocks. + Timeless< Uint32_Index, Node_Skeleton > rel_nodes = relation_and_way_node_members( + context, into.relations, into.attic_relations, source_ways.current, source_ways.attic); rel_nodes.sort(); - { - Timeless< Uint32_Index, Node_Skeleton > more_nodes - = way_members(context, source_ways.current, source_ways.attic, 0, - Ranges< Uint32_Index >::global(), {}, true); - rel_nodes.set_union(more_nodes.sort()); - } keep_matching_skeletons(rel_nodes.current, rel_nodes.attic, rman.get_desired_timestamp()); rel_nodes.swap(into.nodes, into.attic_nodes); } From 71283be95e56655ae41d50fc8dee4fbdd765a71c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 01:16:06 +0000 Subject: [PATCH 08/80] bbox filter: keep ways in inner tiles without loading their geometry Bbox_Filter::filter built a Way_Geometry_Store for every candidate way, reading the nodes of each one to test whether it really meets the box. A way whose index is a single tile (bit 31 clear) has all its nodes in that tile. If the tile lies inside the box, so do all of its nodes, and Bbox_Filter::matches accepts any way with a node inside. Keep such ways without loading their geometry; test only the rest. A tile's bounds are the positions decoded with the lowest and highest ll_lower. Boxes that cross the antimeridian, and the history path, are unchanged. Nova Scotia extract, CPU time, alternating runs: [out:csv(::count)]; way(44.60,-63.66,44.70,-63.52); out count; 263 ms -> 133 ms [out:csv(::count)]; way[highway](44.60,-63.66,44.70,-63.52); out count; 132 ms -> 109 ms Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT (cherry picked from commit 6586aea30d80fdac4252c0457ce9044d3df3777f) --- src/overpass_api/data/bbox_filter.cc | 39 ++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/data/bbox_filter.cc b/src/overpass_api/data/bbox_filter.cc index 4b75a5049..4504dd168 100644 --- a/src/overpass_api/data/bbox_filter.cc +++ b/src/overpass_api/data/bbox_filter.cc @@ -147,6 +147,35 @@ void filter_ways_expensive(const Bbox_Filter& filter, const Way_Geometry_Store& } +/* A way whose index is a single tile (bit 31 clear) has all its nodes in that tile. If + the tile lies inside the bbox, so do all of the way's nodes, and Bbox_Filter::matches + accepts any way with a node inside the bbox (single nodes via contains(), segments via + intersects()). Such ways can be kept without loading their geometry. + + Moves the vectors of those ways from ways to kept. A tile's bounds are the positions + decoded with the lowest and highest ll_lower; every node position in the tile lies + between them. Boxes crossing the antimeridian are left to the exact test. */ +template< typename Way_Skeleton > +void move_ways_in_inner_tiles(const Bbox_Double& bbox, + std::map< Uint31_Index, std::vector< Way_Skeleton > >& ways, + std::map< Uint31_Index, std::vector< Way_Skeleton > >& kept) +{ + if (!(bbox.west <= bbox.east)) + return; + + for (typename std::map< Uint31_Index, std::vector< Way_Skeleton > >::iterator it = ways.begin(); + it != ways.end(); ++it) + { + uint32 idx = it->first.val(); + if ((idx & 0x80000000) || it->second.empty()) + continue; + if (::lat(idx, 0) >= bbox.south && ::lat(idx, 0xffffffff) <= bbox.north + && ::lon(idx, 0) >= bbox.west && ::lon(idx, 0xffffffff) <= bbox.east) + kept[it->first].swap(it->second); + } +} + + template< typename Relation_Skeleton > void filter_relations_expensive(const Bbox_Filter& filter, const std::vector< std::pair< Uint32_Index, const Node_Skeleton* > > node_members_by_id, @@ -203,8 +232,14 @@ void Bbox_Filter::filter(const Statement& query, Resource_Manager& rman, Set& in if (!bbox.valid()) return; - //Process ways - filter_ways_expensive(*this, Way_Geometry_Store(into.ways, query, rman), into.ways); + //Process ways. Ways entirely within inner tiles need no geometry. + { + std::map< Uint31_Index, std::vector< Way_Skeleton > > kept; + move_ways_in_inner_tiles(bbox, into.ways, kept); + filter_ways_expensive(*this, Way_Geometry_Store(into.ways, query, rman), into.ways); + for (std::map< Uint31_Index, std::vector< Way_Skeleton > >::iterator it = kept.begin(); it != kept.end(); ++it) + into.ways[it->first].swap(it->second); + } Request_Context context(&query, rman); { From 844005b366b03fe83e7083d691c1c9119f990a06 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 03:48:04 +0000 Subject: [PATCH 09/80] area queries: decode area blocks once per tile, skip blocks out of range check_area_block decoded every vertex of an area block from its packed form each time it tested a coordinate, and area queries test many coordinates (nodes, way vertices, way segment midpoints) against the same blocks of a tile. Decoding dominated the test. Add Decoded_Area_Block, the block's vertices decoded once plus its longitude range, and a check_area_block overload on it. A coordinate outside the block's longitude range can't be affected by any of its segments, so the overload returns 0 for it without walking the block. The case logic is shared by both overloads through a template over vertex access, so the raw overload, still used by coord and polygon queries, decodes on the fly as before. Area_Query_Statement decodes each tile's blocks once, for its node and way tests. Nova Scotia extract with areas, CPU time, alternating runs: area[name="Halifax"][admin_level=8]->.a; way[highway](area.a); 1083 ms -> 648 ms area[name="Halifax Regional Municipality"]->.a; way[building](area.a); 2072 ms -> 1602 ms Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT (cherry picked from commit 515c60a2071f70f4f5328e08acc0d3b2928a84f9) --- src/overpass_api/statements/area_query.cc | 53 ++++++++++++--- src/overpass_api/statements/area_query.h | 3 + src/overpass_api/statements/coord_query.cc | 75 +++++++++++++++++++--- src/overpass_api/statements/coord_query.h | 16 +++++ 4 files changed, 130 insertions(+), 17 deletions(-) diff --git a/src/overpass_api/statements/area_query.cc b/src/overpass_api/statements/area_query.cc index 3e62b8799..abfc107cd 100644 --- a/src/overpass_api/statements/area_query.cc +++ b/src/overpass_api/statements/area_query.cc @@ -592,6 +592,15 @@ void Area_Query_Statement::collect_nodes areas[area_it.object().id].push_back(area_it.object()); ++area_it; } + // The same blocks decoded once for this tile, for the point-in-area tests below. + std::map< Area_Skeleton::Id_Type, std::vector< Coord_Query_Statement::Decoded_Area_Block > > decoded; + for (std::map< Area_Skeleton::Id_Type, std::vector< Area_Block > >::const_iterator it = areas.begin(); + it != areas.end(); ++it) + { + std::vector< Coord_Query_Statement::Decoded_Area_Block >& blocks = decoded[it->first]; + for (std::vector< Area_Block >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) + blocks.push_back(Coord_Query_Statement::Decoded_Area_Block(current_idx, *it2)); + } while (nodes_it != nodes.end() && nodes_it->first.val() < current_idx) { @@ -613,12 +622,13 @@ void Area_Query_Statement::collect_nodes it != areas.end(); ++it) { int inside = 0; - for (std::vector< Area_Block >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); - ++it2) + const std::vector< Coord_Query_Statement::Decoded_Area_Block >& blocks = decoded[it->first]; + for (std::vector< Coord_Query_Statement::Decoded_Area_Block >::const_iterator it2 = blocks.begin(); + it2 != blocks.end(); ++it2) { ++loop_count; - int check(Coord_Query_Statement::check_area_block(current_idx, *it2, ilat, ilon)); + int check(Coord_Query_Statement::check_area_block(*it2, ilat, ilon)); if (check == Coord_Query_Statement::HIT && add_border) { inside = 1; @@ -800,6 +810,13 @@ int intersects_inner(const Area_Block& string_a, const Area_Block& string_b) void has_inner_points(const Area_Block& string_a, const Area_Block& string_b, int& inside) +{ + has_inner_points(string_a, Coord_Query_Statement::Decoded_Area_Block(0, string_b), inside); +} + + +void has_inner_points(const Area_Block& string_a, const Coord_Query_Statement::Decoded_Area_Block& string_b, + int& inside) { std::vector< std::pair< uint32, uint32 > > coords_a; for (std::vector< uint64 >::const_iterator it = string_a.coors.begin(); it != string_a.coors.end(); ++it) @@ -812,7 +829,7 @@ void has_inner_points(const Area_Block& string_a, const Area_Block& string_b, in { uint32 ilat = (coords_a[i].first + coords_a[i+1].first)/2; uint32 ilon = (coords_a[i].second + coords_a[i+1].second)/2 + 0x80000000u; - int check = Coord_Query_Statement::check_area_block(0, string_b, ilat, ilon); + int check = Coord_Query_Statement::check_area_block(string_b, ilat, ilon); if (check & Coord_Query_Statement::HIT) inside = check; else if (check) @@ -875,6 +892,15 @@ void Area_Query_Statement::collect_ways areas[area_it.object().id].push_back(area_it.object()); ++area_it; } + // The same blocks decoded once for this tile, for the point-in-area tests below. + std::map< Area_Skeleton::Id_Type, std::vector< Coord_Query_Statement::Decoded_Area_Block > > decoded; + for (std::map< Area_Skeleton::Id_Type, std::vector< Area_Block > >::const_iterator it = areas.begin(); + it != areas.end(); ++it) + { + std::vector< Coord_Query_Statement::Decoded_Area_Block >& blocks = decoded[it->first]; + for (std::vector< Area_Block >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) + blocks.push_back(Coord_Query_Statement::Decoded_Area_Block(current_idx, *it2)); + } // check nodes while (nodes_it != way_coords_to_id.end() && nodes_it->first < current_idx) @@ -892,12 +918,13 @@ void Area_Query_Statement::collect_ways it != areas.end(); ++it) { int inside = 0; - for (std::vector< Area_Block >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); - ++it2) + const std::vector< Coord_Query_Statement::Decoded_Area_Block >& blocks = decoded[it->first]; + for (std::vector< Coord_Query_Statement::Decoded_Area_Block >::const_iterator it2 = blocks.begin(); + it2 != blocks.end(); ++it2) { ++loop_count; - int check(Coord_Query_Statement::check_area_block(current_idx, *it2, ilat, ilon)); + int check(Coord_Query_Statement::check_area_block(*it2, ilat, ilon)); if (check == Coord_Query_Statement::HIT) { inside = Coord_Query_Statement::HIT; @@ -913,6 +940,16 @@ void Area_Query_Statement::collect_ways ++nodes_it; } + // has_inner_points tests segment midpoints against the blocks decoded with ll_index 0. + std::map< Area_Skeleton::Id_Type, std::vector< Coord_Query_Statement::Decoded_Area_Block > > decoded_zero; + for (std::map< Area_Skeleton::Id_Type, std::vector< Area_Block > >::const_iterator it = areas.begin(); + it != areas.end(); ++it) + { + std::vector< Coord_Query_Statement::Decoded_Area_Block >& blocks = decoded_zero[it->first]; + for (std::vector< Area_Block >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) + blocks.push_back(Coord_Query_Statement::Decoded_Area_Block(0, *it2)); + } + // check segments for (std::vector< Area_Block >::const_iterator sit = way_segments[Uint31_Index(current_idx)].begin(); sit != way_segments[Uint31_Index(current_idx)].end(); ++sit) @@ -945,7 +982,7 @@ void Area_Query_Statement::collect_ways area_status[it2->id] = Coord_Query_Statement::HIT; break; } - has_inner_points(*sit, *it2, area_status[it2->id]); + has_inner_points(*sit, decoded_zero[it->first][it2 - it->second.begin()], area_status[it2->id]); } } for (std::map< Area::Id_Type, int >::const_iterator it = area_status.begin(); it != area_status.end(); ++it) diff --git a/src/overpass_api/statements/area_query.h b/src/overpass_api/statements/area_query.h index f47a3f047..4b1f6b2c2 100644 --- a/src/overpass_api/statements/area_query.h +++ b/src/overpass_api/statements/area_query.h @@ -22,6 +22,7 @@ #include "../data/collect_members.h" #include "../data/utils.h" #include "../data/way_geometry_store.h" +#include "coord_query.h" #include "statement.h" #include @@ -123,5 +124,7 @@ class Area_Query_Statement : public Output_Statement int intersects_inner(const Area_Block& string_a, const Area_Block& string_b); void has_inner_points(const Area_Block& string_a, const Area_Block& string_b, int& inside); +void has_inner_points(const Area_Block& string_a, const Coord_Query_Statement::Decoded_Area_Block& string_b, + int& inside); #endif diff --git a/src/overpass_api/statements/coord_query.cc b/src/overpass_api/statements/coord_query.cc index 136c96033..f9d131818 100644 --- a/src/overpass_api/statements/coord_query.cc +++ b/src/overpass_api/statements/coord_query.cc @@ -33,6 +33,7 @@ #include "../data/collect_items.h" #include "../data/tilewise_geometry.h" #include "coord_query.h" +#include bool Coord_Query_Statement::is_used_ = false; @@ -87,10 +88,36 @@ Coord_Query_Statement::Coord_Query_Statement the coordinates to the southern end of the block. If it is odd, the coordinate is inside the area, if not, they are not. */ -int Coord_Query_Statement::check_area_block - (uint32 ll_index, const Area_Block& area_block, - uint32 coord_lat, int32 coord_lon) +Coord_Query_Statement::Decoded_Area_Block::Decoded_Area_Block(uint32 ll_index, const Area_Block& area_block) + : min_lon(0), max_lon(0) +{ + lat.reserve(area_block.coors.size()); + lon.reserve(area_block.coors.size()); + for (std::vector< uint64 >::const_iterator it = area_block.coors.begin(); it != area_block.coors.end(); ++it) + { + lat.push_back(::ilat(ll_index | (((*it)>>32)&0xff), (*it & 0xffffffff))); + lon.push_back(::ilon(ll_index | (((*it)>>32)&0xff), (*it & 0xffffffff))); + } + if (!lon.empty()) + { + min_lon = *std::min_element(lon.begin(), lon.end()); + max_lon = *std::max_element(lon.begin(), lon.end()); + } +} + + +// The point-in-area test, shared by the raw and the decoded form of an area block. +// vertex(i, lat, lon) yields the decoded coordinates of the i-th of the block's n vertices. +template< typename Vertex > +int check_area_block_vertices(std::vector< uint64 >::size_type n, Vertex vertex, + uint32 coord_lat, int32 coord_lon) { + const int HIT = Coord_Query_Statement::HIT; + const int TOGGLE_EAST = Coord_Query_Statement::TOGGLE_EAST; + const int TOGGLE_WEST = Coord_Query_Statement::TOGGLE_WEST; + if (n == 0) + return 0; + // An area block is a chain of segments. We consider each // segment individually. This falls into different cases, determined by // the relative position of the intersection of the segment and a straight @@ -105,15 +132,14 @@ int Coord_Query_Statement::check_area_block // only either the western or the eastern side. We are part of the area if in the // end the western or eastern side have an odd state. int state = 0; - std::vector< uint64 >::const_iterator it(area_block.coors.begin()); - uint32 lat = ::ilat(ll_index | (((*it)>>32)&0xff), (*it & 0xffffffff)); - int32 lon = ::ilon(ll_index | (((*it)>>32)&0xff), (*it & 0xffffffff)); - while (++it != area_block.coors.end()) + uint32 lat; + int32 lon; + vertex(0, lat, lon); + for (std::vector< uint64 >::size_type i = 1; i < n; ++i) { uint32 last_lat = lat; int32 last_lon = lon; - lon = ::ilon(ll_index | (((*it)>>32)&0xff), (*it & 0xffffffff)); - lat = ::ilat(ll_index | (((*it)>>32)&0xff), (*it & 0xffffffff)); + vertex(i, lat, lon); if (last_lon < lon) { @@ -185,6 +211,37 @@ int Coord_Query_Statement::check_area_block } + +int Coord_Query_Statement::check_area_block + (const Decoded_Area_Block& area_block, uint32 coord_lat, int32 coord_lon) +{ + // No segment can affect a coordinate outside the block's longitude range: every case + // except (1) needs coord_lon within a segment's longitude span. So the result is 0. + if (area_block.lat.empty() || coord_lon < area_block.min_lon || coord_lon > area_block.max_lon) + return 0; + return check_area_block_vertices(area_block.lat.size(), + [&area_block](std::vector< uint64 >::size_type i, uint32& lat, int32& lon) + { + lat = area_block.lat[i]; + lon = area_block.lon[i]; + }, coord_lat, coord_lon); +} + + +int Coord_Query_Statement::check_area_block + (uint32 ll_index, const Area_Block& area_block, + uint32 coord_lat, int32 coord_lon) +{ + return check_area_block_vertices(area_block.coors.size(), + [ll_index, &area_block](std::vector< uint64 >::size_type i, uint32& lat, int32& lon) + { + uint64 c = area_block.coors[i]; + lat = ::ilat(ll_index | ((c>>32)&0xff), (c & 0xffffffff)); + lon = ::ilon(ll_index | ((c>>32)&0xff), (c & 0xffffffff)); + }, coord_lat, coord_lon); +} + + void register_coord(double lat, double lon, std::set< Uint31_Index >& req, std::map< Uint31_Index, std::vector< std::pair< double, double > > >& coord_per_req) { diff --git a/src/overpass_api/statements/coord_query.h b/src/overpass_api/statements/coord_query.h index ec9c83146..21c40ec17 100644 --- a/src/overpass_api/statements/coord_query.h +++ b/src/overpass_api/statements/coord_query.h @@ -45,6 +45,22 @@ class Coord_Query_Statement : public Output_Statement (uint32 ll_index, const Area_Block& area_block, uint32 coord_lat, int32 coord_lon); + /* An area block with its vertices decoded once, for testing many coordinates against + it. Decoding packed coordinates dominated the cost of testing each coordinate against + the raw block. */ + struct Decoded_Area_Block + { + Decoded_Area_Block(uint32 ll_index, const Area_Block& area_block); + std::vector< uint32 > lat; + std::vector< int32 > lon; + int32 min_lon; + int32 max_lon; + }; + // Same result as check_area_block(ll_index, area_block, coord_lat, coord_lon) for the block + // decoded with that ll_index. + static int check_area_block + (const Decoded_Area_Block& area_block, uint32 coord_lat, int32 coord_lon); + // Used as bitmasks. const static int HIT = 1; const static int TOGGLE_EAST = 2; From 8241b3c587dd455f77a7505914f17d514d242856 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 05:10:41 +0000 Subject: [PATCH 10/80] Meta_Collector: keep a tile's metadata in a sorted vector, not a std::set Meta_Collector loads the metadata of one index (tile) at a time and then only searches it. It kept the entries in a std::set, so every load paid one node allocation and a red-black tree insert per entry, and every lookup walked the tree. Queries that read metadata for many objects (out meta, newer, user filters) spent about a fifth of their time there. Now the entries are appended to a vector, sorted if needed (blocks are usually already in order), and searched with std::lower_bound. Duplicates are removed keeping the first, as std::set::insert did, and reset() still adds to the existing entries without clearing them, so lookups return the same entries as before. Callers use the returned pointer immediately, before the next get(), so a reallocation does not invalidate a pointer still in use. No change to the database format or the query API. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/data/meta_collector.h | 38 ++++++++++++++++++++------ 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/src/overpass_api/data/meta_collector.h b/src/overpass_api/data/meta_collector.h index 542fe79c5..6743d1d7b 100644 --- a/src/overpass_api/data/meta_collector.h +++ b/src/overpass_api/data/meta_collector.h @@ -19,6 +19,7 @@ #ifndef DE__OSM3S___OVERPASS_API__STATEMENTS__META_COLLECTOR_H #define DE__OSM3S___OVERPASS_API__STATEMENTS__META_COLLECTOR_H +#include #include #include #include @@ -67,9 +68,12 @@ struct Meta_Collector ::Range_Iterator* range_it; Index* current_index; Index* last_index; - std::set< OSM_Element_Metadata_Skeleton< Id_Type > > current_objects; + // Sorted by (ref, timestamp), without duplicates: a flat replacement for a std::set, + // which is filled once per index and then only searched. + std::vector< OSM_Element_Metadata_Skeleton< Id_Type > > current_objects; void update_current_objects(const Index&); + void sort_current_objects(); }; @@ -162,9 +166,10 @@ void Meta_Collector< Index, Id_Type >::reset() current_index = new Index(db_it->index()); while (!(*db_it == meta_db->discrete_end()) && (*current_index == db_it->index())) { - current_objects.insert(db_it->object()); + current_objects.push_back(db_it->object()); ++(*db_it); } + sort_current_objects(); } else { @@ -175,9 +180,10 @@ void Meta_Collector< Index, Id_Type >::reset() current_index = new Index(range_it->index()); while (!(*range_it == meta_db->range_end()) && (*current_index == range_it->index())) { - current_objects.insert(range_it->object()); + current_objects.push_back(range_it->object()); ++(*range_it); } + sort_current_objects(); } } @@ -197,9 +203,10 @@ void Meta_Collector< Index, Id_Type >::update_current_objects(const Index& index *current_index = db_it->index(); while (!(*db_it == meta_db->discrete_end()) && (*current_index == db_it->index())) { - current_objects.insert(db_it->object()); + current_objects.push_back(db_it->object()); ++(*db_it); } + sort_current_objects(); } else if (range_it) { @@ -209,13 +216,26 @@ void Meta_Collector< Index, Id_Type >::update_current_objects(const Index& index *current_index = range_it->index(); while (!(*range_it == meta_db->range_end()) && (*current_index == range_it->index())) { - current_objects.insert(range_it->object()); + current_objects.push_back(range_it->object()); ++(*range_it); } + sort_current_objects(); } } +template< typename Index, typename Id_Type > +void Meta_Collector< Index, Id_Type >::sort_current_objects() +{ + // Keep the first of equal elements, as std::set::insert did. + if (!std::is_sorted(current_objects.begin(), current_objects.end())) + std::stable_sort(current_objects.begin(), current_objects.end()); + current_objects.erase(std::unique(current_objects.begin(), current_objects.end(), + [](const OSM_Element_Metadata_Skeleton< Id_Type >& a, const OSM_Element_Metadata_Skeleton< Id_Type >& b) + { return !(a < b) && !(b < a); }), current_objects.end()); +} + + template< typename Index, typename Id_Type > const OSM_Element_Metadata_Skeleton< Id_Type >* Meta_Collector< Index, Id_Type >::get (const Index& index, Id_Type ref) @@ -228,8 +248,8 @@ const OSM_Element_Metadata_Skeleton< Id_Type >* Meta_Collector< Index, Id_Type > if (current_index && *current_index < index) update_current_objects(index); - typename std::set< OSM_Element_Metadata_Skeleton< Id_Type > >::iterator it - = current_objects.lower_bound(OSM_Element_Metadata_Skeleton< Id_Type >(ref)); + auto it = std::lower_bound(current_objects.begin(), current_objects.end(), + OSM_Element_Metadata_Skeleton< Id_Type >(ref)); if (it != current_objects.end() && it->ref == ref) return &*it; else @@ -249,8 +269,8 @@ const OSM_Element_Metadata_Skeleton< Id_Type >* Meta_Collector< Index, Id_Type > if (current_index && *current_index < index) update_current_objects(index); - typename std::set< OSM_Element_Metadata_Skeleton< Id_Type > >::iterator it - = current_objects.lower_bound(OSM_Element_Metadata_Skeleton< Id_Type >(ref, timestamp)); + auto it = std::lower_bound(current_objects.begin(), current_objects.end(), + OSM_Element_Metadata_Skeleton< Id_Type >(ref, timestamp)); if (it == current_objects.begin()) return 0; --it; From 62b76a2ef2355d43ace399d4a3183c45ce4d298d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 07:10:51 +0000 Subject: [PATCH 11/80] around grid: test each entry once per lookup, tighter reach for segments 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 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/around.cc | 58 ++++++++++++++++++++++----- src/overpass_api/statements/around.h | 38 ++++++++++++------ 2 files changed, 73 insertions(+), 23 deletions(-) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index 1f125a4c1..8a69b7c7b 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -745,23 +745,44 @@ Ranges< Uint32_Index > Around_Statement::calc_ranges(const Set& input, Resource_ //----------------------------------------------------------------------------- -/* Why reach boxes are enough. Let reach(X) be the bounding box of X widened by - (length of X + radius), where a point has length 0. Every exact test only passes - when the two objects' reach boxes overlap: +/* Why reach boxes are enough. Let reach(X) be the bounding box of X's endpoints + widened by segment_reach(len(X), radius): the radius plus twice the most a + great-circle arc of that length can bulge out of its endpoints' bounding box, plus + one metre. A point has length 0. Every exact test only passes when the two objects' + reach boxes overlap: - Point P near segment S (is_inside(lat, lon)): the test requires - great_circle_dist(P, first point of S) <= sqrt(len(S)^2 + radius^2) - <= len(S) + radius, so P lies in reach(S). + great_circle_line_dist(S, P) <= radius, and P within sqrt(len(S)^2 + radius^2) of + both endpoints of S. The second condition keeps P's foot on S's great circle + within sqrt(len(S)^2 + radius^2) - len(S) <= radius beyond either endpoint. So P + is within about 2 * radius of the arc S, hence within the arc's bounding box, + which lies within S's endpoint box widened by the bulge, widened by 2 * radius. + Overlap needs only one of the two boxes to be widened by that much; each is + widened by radius, so together they cover it. - Segment C near point Q (is_inside(segment), first loop): the same test with the - roles swapped puts Q in reach(C). + roles swapped. - Segments S and C intersect (intersect()): the crossing point lies on both arcs, - so within len(S) of S's first point and within len(C) of C's first point; it is - in both reach boxes. + so within each arc's bounding box, which lies within its endpoint box widened by + the bulge. The widening uses a slightly larger distance than needed and the latitude closest to the pole for the longitude scale, so the boxes are conservative. Boxes too close to a pole, crossing the antimeridian or spanning many cells are never pruned. */ +double Reach_Grid::segment_reach(double length, double radius, double lat1, double lat2) +{ + // A great-circle arc of length L deviates in latitude from its endpoints' bounding + // box by at most about L^2 * tan(latitude) / (8 * R). Beyond 50 km, or near a pole, + // keep the much wider bound of the arc's own length. + double poleward = std::max(std::abs(lat1), std::abs(lat2)); + if (length > 50000.0 || poleward >= 80.0) + return length + radius; + const double earth_radius = 10.0*1000*1000/acos(0); // as in great_circle_dist + double bulge = length * length * tan(poleward/90.0*acos(0)) / (8.0 * earth_radius); + return radius + 2.0 * bulge + 1.0; +} + + Reach_Grid::Box Reach_Grid::reach_box(double lat1, double lon1, double lat2, double lon2, double reach) { Box box; @@ -796,6 +817,9 @@ void Reach_Grid::clear() { cells.clear(); always.clear(); + filed.clear(); + seen.clear(); + lookup = 0; total = 0; } @@ -814,6 +838,18 @@ void Reach_Grid::add(const Box& box, uint32 id) for (int64 j = lon0; j <= lon1; ++j) cells[key(i, j)].push_back(id); } + filed.push_back(id); + if (seen.size() <= id) + seen.resize(id + 1, 0); +} + + +bool Reach_Grid::first_visit(uint32 id) const +{ + if (seen[id] == lookup) + return false; + seen[id] = lookup; + return true; } @@ -830,8 +866,8 @@ void Around_Statement::build_grids() { const Prepared_Segment& s = simple_segments[i]; double length = great_circle_dist(s.first_lat, s.first_lon, s.second_lat, s.second_lon); - segment_grid.add(Reach_Grid::reach_box( - s.first_lat, s.first_lon, s.second_lat, s.second_lon, length + radius), i); + segment_grid.add(Reach_Grid::reach_box(s.first_lat, s.first_lon, s.second_lat, s.second_lon, + Reach_Grid::segment_reach(length, radius, s.first_lat, s.second_lat)), i); } } @@ -1052,7 +1088,7 @@ bool Around_Statement::is_inside Prepared_Segment segment(first_lat, first_lon, second_lat, second_lon); double length = great_circle_dist(first_lat, first_lon, second_lat, second_lon); Reach_Grid::Box box = Reach_Grid::reach_box(first_lat, first_lon, second_lat, second_lon, - length + radius); + Reach_Grid::segment_reach(length, radius, first_lat, second_lat)); if (point_grid.any(box, [&](uint32 id) { diff --git a/src/overpass_api/statements/around.h b/src/overpass_api/statements/around.h index 0eefb4e24..6b8713159 100644 --- a/src/overpass_api/statements/around.h +++ b/src/overpass_api/statements/around.h @@ -19,6 +19,7 @@ #ifndef DE__OSM3S___OVERPASS_API__STATEMENTS__AROUND_H #define DE__OSM3S___OVERPASS_API__STATEMENTS__AROUND_H +#include #include #include #include @@ -65,7 +66,8 @@ struct Prepared_Point decides a match itself. Each entry is filed under every cell its "reach box" covers: its bounding box widened - by its own length plus the radius. A point or segment can only pass any of the exact + by the radius plus a small margin for the bulge of a great-circle arc (see + segment_reach). A point or segment can only pass any of the exact tests against an entry if their reach boxes overlap (see around.cc), so looking up the cells of a candidate's reach box finds every entry that could match it. Entries whose reach box is too large to file, or lies near a pole or the antimeridian, are kept in @@ -84,9 +86,12 @@ class Reach_Grid void clear(); void add(const Box& box, uint32 id); - // Calls f(id) for every entry whose cells the box touches, plus the always-checked - // entries. Stops and returns true as soon as f returns true. An id can be passed - // more than once. + // The reach to use for a segment of the given length: the radius plus a margin for + // how far a great-circle arc can bulge out of its endpoints' bounding box. + static double segment_reach(double length, double radius, double lat1, double lat2); + + // Calls f(id) once for every entry whose cells the box touches, plus the + // always-checked entries. Stops and returns true as soon as f returns true. template< typename F > bool any(const Box& box, F f) const; @@ -99,7 +104,14 @@ class Reach_Grid std::unordered_map< int64, std::vector< uint32 > > cells; std::vector< uint32 > always; + std::vector< uint32 > filed; // every id filed in cells, once each uint32 total = 0; + + // An entry filed in several cells is passed to f only once per lookup: seen[id] holds + // the number of the last lookup that passed it. + mutable std::vector< uint32 > seen; + mutable uint32 lookup = 0; + bool first_visit(uint32 id) const; }; @@ -114,17 +126,19 @@ bool Reach_Grid::any(const Box& box, F f) const int64 lat0, lat1, lon0, lon1; if (!cell_range(box, lat0, lat1, lon0, lon1)) { - // The box is too large to look up cell by cell: check every entry. - for (const auto& cell : cells) + // The box is too large to look up cell by cell: check every filed entry once. + for (uint32 id : filed) { - for (uint32 id : cell.second) - { - if (f(id)) - return true; - } + if (f(id)) + return true; } return false; } + if (++lookup == 0) + { + std::fill(seen.begin(), seen.end(), 0); + lookup = 1; + } for (int64 i = lat0; i <= lat1; ++i) { for (int64 j = lon0; j <= lon1; ++j) @@ -134,7 +148,7 @@ bool Reach_Grid::any(const Box& box, F f) const continue; for (uint32 id : it->second) { - if (f(id)) + if (first_visit(id) && f(id)) return true; } } From d28dddc55f3bc3d58b199c190629a58bce725881 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 07:10:51 +0000 Subject: [PATCH 12/80] around: take candidate ranges for relation inputs from their members around's geometry for a relation in its input set is that of the relation's direct node and way members (calc_lat_lons). The candidate ranges, though, came from the relation's own index, which for a long route or a boundary is a compound index covering its whole extent: every object in that area became a candidate and had its geometry loaded and tested. calc_ranges now takes the ranges of the current relations' node members and the parent ranges of their way members, expanded by the radius as before. These cover all of the geometry the exact test uses, so results are unchanged. Attic relations keep their own index. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/around.cc | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index 8a69b7c7b..6ab600981 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -734,12 +734,27 @@ Ranges< Uint32_Index > Around_Statement::calc_ranges(const Set& input, Resource_ return expand(calc_children(ranges(ways)), radius); } else + { + // The geometry of a relation is that of its direct node and way members (see + // calc_lat_lons), so take the ranges from their indexes. A relation's own index + // covers its whole extent, which for a long route or a boundary is a large area. + Ranges< Uint32_Index > member_node_ranges; + Ranges< Uint31_Index > member_way_ranges; + if (!input.relations.empty()) + { + Request_Context context(this, rman); + member_node_ranges = ranges(relation_node_members( + context, input.relations, {}, Ranges< Uint32_Index >::global(), {}, true).current); + member_way_ranges = ranges(relation_way_members( + context, input.relations, {}, Ranges< Uint31_Index >::global(), {}, true).current); + } return expand( - ranges(input.nodes).union_(ranges(input.attic_nodes)).union_( + ranges(input.nodes).union_(ranges(input.attic_nodes)).union_(member_node_ranges).union_( calc_children( ranges(input.ways).union_(ranges(input.attic_ways)).union_( - ranges(input.relations).union_(ranges(input.attic_relations))))), + member_way_ranges.union_(ranges(input.attic_relations))))), radius); + } } From 8e02d2c86d1ec77d8f9d6c2d8bfc21518a935aca Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:25:31 +0000 Subject: [PATCH 13/80] user: compute the ids of touched objects once per query For uid_touched and user_touched, User_Constraint scanned all of the users' current and attic metadata (touched_ids_by_users) in get_node_ids, get_way_ids and get_relation_ids, and again in filter. When the query engine used both, as it does when these filters choose the candidates, every metadata block was decompressed twice. Inside a loop, both scans repeated in every iteration. The touched ids depend only on the users, so they are the same for the whole query. The constraint now keeps them after first use, and both callers share them. A list longer than 2M ids (16 MB) is not kept: it is handed over or dropped after use, as before, so a prolific user's ids never stay in memory longer than they did. calc_ranges_both, which computed the same ranges as calc_ranges_32 and calc_ranges_31 together, is no longer needed. On the Nova Scotia history database, with N a user id: [out:csv(::count)]; nwr(uid_touched:N)(44.60,-63.66,44.70,-63.52); out count; drops from 2.02 s to 1.20 s, and a foreach over 76 cafes running nwr(around.it:100)(uid_touched:N) from 126 s to 6 s, with identical output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/user.cc | 151 +++++++++++++++++++--------- 1 file changed, 102 insertions(+), 49 deletions(-) diff --git a/src/overpass_api/statements/user.cc b/src/overpass_api/statements/user.cc index a4fea93b6..5f7805f84 100644 --- a/src/overpass_api/statements/user.cc +++ b/src/overpass_api/statements/user.cc @@ -52,6 +52,34 @@ class User_Constraint : public Query_Constraint private: User_Statement* user; + + // The ids of the objects the users touched depend only on the users, so they are + // the same for the whole query. They are kept after first use and shared by + // get_*_ids and filter, which otherwise each read all of the users' metadata. + // Lists longer than max_kept_ids are not kept, so a prolific user's list never + // stays in memory longer than before. + static const std::size_t max_kept_ids = 2*1024*1024; + bool node_ids_known = false; + bool way_ids_known = false; + bool relation_ids_known = false; + std::vector< Node_Skeleton::Id_Type > touched_node_ids; + std::vector< Way_Skeleton::Id_Type > touched_way_ids; + std::vector< Relation_Skeleton::Id_Type > touched_relation_ids; + + const std::vector< Node_Skeleton::Id_Type >& touched_nodes(Resource_Manager& rman); + const std::vector< Way_Skeleton::Id_Type >& touched_ways(Resource_Manager& rman); + const std::vector< Relation_Skeleton::Id_Type >& touched_relations(Resource_Manager& rman); + + // Drops a list that is too long to keep, so that it is computed again when needed. + template< typename Id_Type > + static void release_if_large(std::vector< Id_Type >& ids, bool& known) + { + if (ids.size() > max_kept_ids) + { + std::vector< Id_Type >().swap(ids); + known = false; + } + } }; @@ -186,31 +214,6 @@ void calc_ranges_31 } -void calc_ranges_both - (Ranges< Uint32_Index >& node_req, Ranges< Uint31_Index >& other_req, - const std::set< Uint32_Index >& user_ids, Transaction& transaction) -{ - - Block_Backend< Uint32_Index, Uint31_Index, std::set< Uint32_Index >::const_iterator > user_db - (transaction.data_index(meta_settings().USER_INDICES)); - for (auto user_it = user_db.discrete_begin(user_ids.begin(), user_ids.end()); - !(user_it == user_db.discrete_end()); ++user_it) - { - if ((user_it.object().val() & 0x80000000) == 0) - { - node_req.push_back(Uint32_Index(user_it.object().val()), Uint32_Index(user_it.object().val() + 0x100)); - other_req.push_back(Uint31_Index(user_it.object().val()), Uint31_Index(user_it.object().val() + 0x100)); - } - else if ((user_it.object().val() & 0xff) == 0) - other_req.push_back(Uint31_Index(user_it.object().val()), Uint31_Index(user_it.object().val() + 0x100)); - else - other_req.push_back(Uint31_Index(user_it.object().val()), Uint31_Index(user_it.object().val() + 1)); - } - node_req.sort(); - other_req.sort(); -} - - void User_Constraint::filter(const Statement& query, Resource_Manager& rman, Set& into) { std::set< Uint32_Index > user_ids = user->get_ids(*rman.get_transaction()); @@ -235,25 +238,21 @@ void User_Constraint::filter(const Statement& query, Resource_Manager& rman, Set } else { - Ranges< Uint32_Index > node_ranges; - Ranges< Uint31_Index > other_ranges; - calc_ranges_both(node_ranges, other_ranges, user->get_ids(*rman.get_transaction()), *rman.get_transaction()); - if (!into.nodes.empty() || !into.attic_nodes.empty()) Timeless< Uint32_Index, Node_Skeleton >{ into.nodes, into.attic_nodes }.filter_by_id( - touched_ids_by_users< Uint32_Index, Node_Skeleton >( - rman, node_ranges, user->get_ids(*rman.get_transaction()))) + touched_nodes(rman)) .swap(into.nodes, into.attic_nodes); + release_if_large(touched_node_ids, node_ids_known); if (!into.ways.empty() || !into.attic_ways.empty()) Timeless< Uint31_Index, Way_Skeleton >{ into.ways, into.attic_ways }.filter_by_id( - touched_ids_by_users< Uint31_Index, Way_Skeleton >( - rman, other_ranges, user->get_ids(*rman.get_transaction()))) + touched_ways(rman)) .swap(into.ways, into.attic_ways); + release_if_large(touched_way_ids, way_ids_known); if (!into.relations.empty() || !into.attic_relations.empty()) Timeless< Uint31_Index, Relation_Skeleton >{ into.relations, into.attic_relations }.filter_by_id( - touched_ids_by_users< Uint31_Index, Relation_Skeleton >( - rman, other_ranges, user->get_ids(*rman.get_transaction()))) + touched_relations(rman)) .swap(into.relations, into.attic_relations); + release_if_large(touched_relation_ids, relation_ids_known); } into.areas.clear(); @@ -434,15 +433,61 @@ bool User_Constraint::get_ranges(Resource_Manager& rman, Ranges< Uint31_Index >& } -bool User_Constraint::get_node_ids(Resource_Manager& rman, std::vector< Node_Skeleton::Id_Type >& ids) +const std::vector< Node_Skeleton::Id_Type >& User_Constraint::touched_nodes(Resource_Manager& rman) { - if (user->get_criterion() == User_Statement::touched) + if (!node_ids_known) { Ranges< Uint32_Index > node_ranges; calc_ranges_32(node_ranges, user->get_ids(*rman.get_transaction()), *rman.get_transaction()); + touched_node_ids = touched_ids_by_users< Uint32_Index, Node_Skeleton >( + rman, node_ranges, user->get_ids(*rman.get_transaction())); + node_ids_known = true; + } + return touched_node_ids; +} - touched_ids_by_users< Uint32_Index, Node_Skeleton >( - rman, node_ranges, user->get_ids(*rman.get_transaction())).swap(ids); + +const std::vector< Way_Skeleton::Id_Type >& User_Constraint::touched_ways(Resource_Manager& rman) +{ + if (!way_ids_known) + { + Ranges< Uint31_Index > other_ranges; + calc_ranges_31(other_ranges, user->get_ids(*rman.get_transaction()), *rman.get_transaction()); + touched_way_ids = touched_ids_by_users< Uint31_Index, Way_Skeleton >( + rman, other_ranges, user->get_ids(*rman.get_transaction())); + way_ids_known = true; + } + return touched_way_ids; +} + + +const std::vector< Relation_Skeleton::Id_Type >& User_Constraint::touched_relations(Resource_Manager& rman) +{ + if (!relation_ids_known) + { + Ranges< Uint31_Index > other_ranges; + calc_ranges_31(other_ranges, user->get_ids(*rman.get_transaction()), *rman.get_transaction()); + touched_relation_ids = touched_ids_by_users< Uint31_Index, Relation_Skeleton >( + rman, other_ranges, user->get_ids(*rman.get_transaction())); + relation_ids_known = true; + } + return touched_relation_ids; +} + + +bool User_Constraint::get_node_ids(Resource_Manager& rman, std::vector< Node_Skeleton::Id_Type >& ids) +{ + if (user->get_criterion() == User_Statement::touched) + { + touched_nodes(rman); + if (touched_node_ids.size() > max_kept_ids) + { + // Too long to keep: hand it over, as before this list was kept. + ids.swap(touched_node_ids); + node_ids_known = false; + } + else + ids = touched_node_ids; return true; } return false; @@ -453,11 +498,15 @@ bool User_Constraint::get_way_ids(Resource_Manager& rman, std::vector< Way_Skele { if (user->get_criterion() == User_Statement::touched) { - Ranges< Uint31_Index > other_ranges; - calc_ranges_31(other_ranges, user->get_ids(*rman.get_transaction()), *rman.get_transaction()); - - touched_ids_by_users< Uint31_Index, Way_Skeleton >( - rman, other_ranges, user->get_ids(*rman.get_transaction())).swap(ids); + touched_ways(rman); + if (touched_way_ids.size() > max_kept_ids) + { + // Too long to keep: hand it over, as before this list was kept. + ids.swap(touched_way_ids); + way_ids_known = false; + } + else + ids = touched_way_ids; return true; } return false; @@ -468,11 +517,15 @@ bool User_Constraint::get_relation_ids(Resource_Manager& rman, std::vector< Rela { if (user->get_criterion() == User_Statement::touched) { - Ranges< Uint31_Index > other_ranges; - calc_ranges_31(other_ranges, user->get_ids(*rman.get_transaction()), *rman.get_transaction()); - - touched_ids_by_users< Uint31_Index, Relation_Skeleton >( - rman, other_ranges, user->get_ids(*rman.get_transaction())).swap(ids); + touched_relations(rman); + if (touched_relation_ids.size() > max_kept_ids) + { + // Too long to keep: hand it over, as before this list was kept. + ids.swap(touched_relation_ids); + relation_ids_known = false; + } + else + ids = touched_relation_ids; return true; } return false; From 6a5256537bcebeb5eea5601e78655d3cf52c166f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:36:22 +0000 Subject: [PATCH 14/80] query: run metadata-only filters before geometry filters Query_Statement::apply_all_filters runs each constraint's expensive filter in the order the constraints appear in the query. newer and the user filters (uid, user, uid_touched, user_touched) are expensive filters too, but they only read metadata. When a bbox, around or area constraint came first, its filter built geometry for every candidate, and only then did the metadata filter discard most of them. A new Query_Constraint::filter_reads_only_metadata() marks such filters, and apply_all_filters runs them first. Every filter only removes elements, so the order does not change the result. On the Nova Scotia history database: [out:csv(::count)]; way(43.3,-66.5,47.1,-59.6)(newer:"2026-11-08T00:00:00Z"); out count; drops from 6.3 s to 1.3 s, the time the same query already took with newer written first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/newer.cc | 1 + src/overpass_api/statements/query.cc | 13 ++++++++++++- src/overpass_api/statements/statement.h | 5 +++++ src/overpass_api/statements/user.cc | 1 + 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/overpass_api/statements/newer.cc b/src/overpass_api/statements/newer.cc index 5a0068356..a13e25bfa 100644 --- a/src/overpass_api/statements/newer.cc +++ b/src/overpass_api/statements/newer.cc @@ -38,6 +38,7 @@ class Newer_Constraint : public Query_Constraint Query_Filter_Strategy delivers_data(Resource_Manager& rman) { return ids_required; } void filter(const Statement& query, Resource_Manager& rman, Set& into); + bool filter_reads_only_metadata() const override { return true; } virtual ~Newer_Constraint() {} private: diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index 76b2d190f..202496b07 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -905,9 +905,20 @@ void Query_Statement::apply_all_filters( set_progress(8); rman.health_check(*this); + // All filters only remove elements, so their order does not change the result. + // Metadata-only filters go first, so that geometry is built for fewer elements. for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); it != constraints.end(); ++it) - (*it)->filter(*this, rman, into); + { + if ((*it)->filter_reads_only_metadata()) + (*it)->filter(*this, rman, into); + } + for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); + it != constraints.end(); ++it) + { + if (!(*it)->filter_reads_only_metadata()) + (*it)->filter(*this, rman, into); + } } diff --git a/src/overpass_api/statements/statement.h b/src/overpass_api/statements/statement.h index 7f162c781..11d30153f 100644 --- a/src/overpass_api/statements/statement.h +++ b/src/overpass_api/statements/statement.h @@ -120,6 +120,11 @@ class Query_Constraint // to minimize the number of elements that need to be processed. virtual void filter(const Statement& query, Resource_Manager& rman, Set& into) {} + // True if the expensive filter only looks at the elements' metadata, never at + // their geometry. Such filters run before the others: reading metadata costs far + // less than building geometry, so they shrink the set before geometry is built. + virtual bool filter_reads_only_metadata() const { return false; } + virtual ~Query_Constraint() {} }; diff --git a/src/overpass_api/statements/user.cc b/src/overpass_api/statements/user.cc index 5f7805f84..329572373 100644 --- a/src/overpass_api/statements/user.cc +++ b/src/overpass_api/statements/user.cc @@ -48,6 +48,7 @@ class User_Constraint : public Query_Constraint bool get_relation_ids(Resource_Manager& rman, std::vector< Relation_Skeleton::Id_Type >& ids) override; void filter(const Statement& query, Resource_Manager& rman, Set& into) override; + bool filter_reads_only_metadata() const override { return true; } virtual ~User_Constraint() {} private: From b7d862b6a26e2a35d80ed392ac68d59ecf8beb7d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 14:02:01 +0000 Subject: [PATCH 15/80] around: skip index entries without objects when computing candidate ranges around computes its candidate ranges from the indexes of its input set. The helper took every key of the set's maps, including keys whose vector is empty. Filters leave such keys behind: a query at a past date, for example, clears the vectors of objects not valid at that date but keeps their indexes. For relations those are often coarse compound indexes covering a large area, so an input set with no objects at all could make around read every way or node in that area. On the Nova Scotia history database, where .s0 holds one way at the date plus relation entries emptied by the date filter: [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; drops from 21.3 s to 0.16 s. Empty vectors hold no geometry, so results are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/around.cc | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index 6ab600981..421777f0d 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -35,13 +35,20 @@ template < class TIndex, class TObject > Ranges< TIndex > ranges(const std::map< TIndex, std::vector< TObject > >& elems) { + // Indexes whose vector is empty hold no objects and contribute no geometry. Filters + // often leave such entries behind, e.g. for attic data at other dates, and for + // relations they can be coarse indexes covering large areas, so skip them. Ranges< TIndex > result; - if (elems.empty()) + typename std::map< TIndex, std::vector< TObject > >::const_iterator it = elems.begin(); + while (it != elems.end() && it->second.empty()) + ++it; + if (it == elems.end()) return result; - std::pair< TIndex, TIndex > range = std::make_pair(elems.begin()->first, inc(elems.begin()->first)); - for (typename std::map< TIndex, std::vector< TObject > >::const_iterator - it = elems.begin(); it != elems.end(); ++it) + std::pair< TIndex, TIndex > range = std::make_pair(it->first, inc(it->first)); + for (; it != elems.end(); ++it) { + if (it->second.empty()) + continue; if (!(range.second < it->first)) range.second = inc(it->first); else @@ -52,7 +59,7 @@ Ranges< TIndex > ranges(const std::map< TIndex, std::vector< TObject > >& elems) } result.push_back(range.first, range.second); result.sort(); - + return result; } From eaa97d27a8bd3c81eb5cd17d3993b3c7a6631233 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:50:03 +0000 Subject: [PATCH 16/80] area and poly queries: decode each block once per tile for the segment tests intersects_inner and has_inner_points decoded their blocks into fresh vectors on every call. In the segment tests of area and polygon queries they run for every pair of a way-segment block and an area block in a tile, so the same blocks were decoded, and their vectors allocated and freed, over and over. For poly: every polygon segment is its own block, so a long way segment was decoded again for each polygon segment in its tile. Each block is now decoded once per tile (decode_coords), and intersects_inner and has_inner_points take the decoded coordinates instead of raw blocks. These segment tests were their only callers, so the raw-block versions are removed. The tests themselves are unchanged, so results are the same. On the Nova Scotia area database, the osmnx-shaped query [out:json][timeout:180];(way["highway"]["area"!~"yes"]["access"!~"private"] ["highway"!~""]["motor_vehicle"!~"no"]["motorcar"!~"no"] ["service"!~""](poly:'');>;);out; drops from 1.28 s to 0.66 s against the area block decoding change it builds on. The exclusion lists and the boundary are given in full in bench/queries-tools/ t08_osmnx_graph_drive.ql on the bench-tools branch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/area_query.cc | 42 ++++++++++---------- src/overpass_api/statements/area_query.h | 10 +++-- src/overpass_api/statements/polygon_query.cc | 15 ++++++- 3 files changed, 39 insertions(+), 28 deletions(-) diff --git a/src/overpass_api/statements/area_query.cc b/src/overpass_api/statements/area_query.cc index abfc107cd..443dc7e6a 100644 --- a/src/overpass_api/statements/area_query.cc +++ b/src/overpass_api/statements/area_query.cc @@ -758,18 +758,18 @@ inline int longitude_a_intersects_inner } -int intersects_inner(const Area_Block& string_a, const Area_Block& string_b) +void decode_coords(const Area_Block& block, Decoded_Coords& coords) { - std::vector< std::pair< uint32, uint32 > > coords_a; - for (std::vector< uint64 >::const_iterator it = string_a.coors.begin(); it != string_a.coors.end(); ++it) - coords_a.push_back(std::make_pair(::ilat(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)), - ::ilon(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)))); + coords.clear(); + coords.reserve(block.coors.size()); + for (std::vector< uint64 >::const_iterator it = block.coors.begin(); it != block.coors.end(); ++it) + coords.push_back(std::make_pair(::ilat(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)), + ::ilon(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)))); +} - std::vector< std::pair< uint32, uint32 > > coords_b; - for (std::vector< uint64 >::const_iterator it = string_b.coors.begin(); it != string_b.coors.end(); ++it) - coords_b.push_back(std::make_pair(::ilat(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)), - ::ilon(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)))); +int intersects_inner(const Decoded_Coords& coords_a, const Decoded_Coords& coords_b) +{ for (std::vector< std::pair< uint32, uint32 > >::size_type i = 0; i < coords_a.size()-1; ++i) { if (coords_a[i].second < coords_a[i+1].second) @@ -809,19 +809,9 @@ int intersects_inner(const Area_Block& string_a, const Area_Block& string_b) } -void has_inner_points(const Area_Block& string_a, const Area_Block& string_b, int& inside) -{ - has_inner_points(string_a, Coord_Query_Statement::Decoded_Area_Block(0, string_b), inside); -} - - -void has_inner_points(const Area_Block& string_a, const Coord_Query_Statement::Decoded_Area_Block& string_b, +void has_inner_points(const Decoded_Coords& coords_a, const Coord_Query_Statement::Decoded_Area_Block& string_b, int& inside) { - std::vector< std::pair< uint32, uint32 > > coords_a; - for (std::vector< uint64 >::const_iterator it = string_a.coors.begin(); it != string_a.coors.end(); ++it) - coords_a.push_back(std::make_pair(::ilat(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)), - ::ilon(uint32((*it>>32)&0xff), uint32(*it & 0xffffffffull)))); // Check additionally the middle of the segment to also get segments // that run through the area @@ -942,18 +932,26 @@ void Area_Query_Statement::collect_ways // has_inner_points tests segment midpoints against the blocks decoded with ll_index 0. std::map< Area_Skeleton::Id_Type, std::vector< Coord_Query_Statement::Decoded_Area_Block > > decoded_zero; + std::map< Area_Skeleton::Id_Type, std::vector< Decoded_Coords > > area_coords; for (std::map< Area_Skeleton::Id_Type, std::vector< Area_Block > >::const_iterator it = areas.begin(); it != areas.end(); ++it) { std::vector< Coord_Query_Statement::Decoded_Area_Block >& blocks = decoded_zero[it->first]; + std::vector< Decoded_Coords >& coords = area_coords[it->first]; for (std::vector< Area_Block >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) + { blocks.push_back(Coord_Query_Statement::Decoded_Area_Block(0, *it2)); + coords.push_back(Decoded_Coords()); + decode_coords(*it2, coords.back()); + } } // check segments + Decoded_Coords sit_coords; for (std::vector< Area_Block >::const_iterator sit = way_segments[Uint31_Index(current_idx)].begin(); sit != way_segments[Uint31_Index(current_idx)].end(); ++sit) { + decode_coords(*sit, sit_coords); std::map< Area::Id_Type, int > area_status; for (std::map< Area_Skeleton::Id_Type, std::vector< Area_Block > >::const_iterator it = areas.begin(); it != areas.end(); ++it) @@ -968,7 +966,7 @@ void Area_Query_Statement::collect_ways // The endpoints are properly handled via the point-in-area test // Check additionally the middle of the segment to also get segments // that run through the area - int intersect = intersects_inner(*sit, *it2); + int intersect = intersects_inner(sit_coords, area_coords[it->first][it2 - it->second.begin()]); if (intersect == Coord_Query_Statement::INTERSECT) { ways_inside[Way::Id_Type(sit->id)] = true; @@ -982,7 +980,7 @@ void Area_Query_Statement::collect_ways area_status[it2->id] = Coord_Query_Statement::HIT; break; } - has_inner_points(*sit, decoded_zero[it->first][it2 - it->second.begin()], area_status[it2->id]); + has_inner_points(sit_coords, decoded_zero[it->first][it2 - it->second.begin()], area_status[it2->id]); } } for (std::map< Area::Id_Type, int >::const_iterator it = area_status.begin(); it != area_status.end(); ++it) diff --git a/src/overpass_api/statements/area_query.h b/src/overpass_api/statements/area_query.h index 4b1f6b2c2..3737118d9 100644 --- a/src/overpass_api/statements/area_query.h +++ b/src/overpass_api/statements/area_query.h @@ -121,10 +121,12 @@ class Area_Query_Statement : public Output_Statement }; -int intersects_inner(const Area_Block& string_a, const Area_Block& string_b); - -void has_inner_points(const Area_Block& string_a, const Area_Block& string_b, int& inside); -void has_inner_points(const Area_Block& string_a, const Coord_Query_Statement::Decoded_Area_Block& string_b, +// The coordinates of an Area_Block as (ilat, ilon) pairs, decoded once so that the tests +// below can run against many other blocks without decoding again. +typedef std::vector< std::pair< uint32, uint32 > > Decoded_Coords; +void decode_coords(const Area_Block& block, Decoded_Coords& coords); +int intersects_inner(const Decoded_Coords& coords_a, const Decoded_Coords& coords_b); +void has_inner_points(const Decoded_Coords& coords_a, const Coord_Query_Statement::Decoded_Area_Block& string_b, int& inside); #endif diff --git a/src/overpass_api/statements/polygon_query.cc b/src/overpass_api/statements/polygon_query.cc index 8a215789d..e967759e6 100644 --- a/src/overpass_api/statements/polygon_query.cc +++ b/src/overpass_api/statements/polygon_query.cc @@ -452,6 +452,15 @@ void Polygon_Query_Statement::collect_ways areas.push_back(block); ++area_it; } + // The same segments decoded once for this tile, for the segment tests below. + std::vector< Decoded_Coords > area_coords(areas.size()); + std::vector< Coord_Query_Statement::Decoded_Area_Block > areas_decoded; + areas_decoded.reserve(areas.size()); + for (std::vector< Area_Block >::size_type i = 0; i < areas.size(); ++i) + { + decode_coords(areas[i], area_coords[i]); + areas_decoded.push_back(Coord_Query_Statement::Decoded_Area_Block(0, areas[i])); + } // check nodes while (nodes_it != way_coords_to_id.end() && nodes_it->first < current_idx) @@ -486,9 +495,11 @@ void Polygon_Query_Statement::collect_ways } // check segments + Decoded_Coords sit_coords; for (std::vector< Area_Block >::const_iterator sit = way_segments[Uint31_Index(current_idx)].begin(); sit != way_segments[Uint31_Index(current_idx)].end(); ++sit) { + decode_coords(*sit, sit_coords); int inside = 0; for (std::vector< Area_Block >::const_iterator it = areas.begin(); it != areas.end(); ++it) @@ -498,7 +509,7 @@ void Polygon_Query_Statement::collect_ways // The endpoints are properly handled via the point-in-area test // Check additionally the middle of the segment to also get segments // that run through the area - int intersect = intersects_inner(*sit, *it); + int intersect = intersects_inner(sit_coords, area_coords[it - areas.begin()]); if (intersect == Coord_Query_Statement::INTERSECT) { ways_inside[Way::Id_Type(sit->id)] = true; @@ -512,7 +523,7 @@ void Polygon_Query_Statement::collect_ways inside = 0; break; } - has_inner_points(*sit, *it, inside); + has_inner_points(sit_coords, areas_decoded[it - areas.begin()], inside); } if ((inside && (!(inside & Coord_Query_Statement::HIT))) || (inside && add_border)) From fba6d6e75b72a8459a0c9fe157e26e84d19ffeb2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:06:58 +0000 Subject: [PATCH 17/80] Geometry stores: keep member node positions in 16 bytes, not 40 Way_Geometry_Store and Relation_Geometry_Store looked up member node coordinates in a std::vector< Node >. Node carries a tag vector, so each entry took 40 bytes, and the vector grew by push_back while the map of Node_Skeletons it was copied from was still alive. They now keep a std::vector< Node_Position > (id, ll_upper, ll_lower: 16 bytes), reserved to its exact size, and free the source map index by index while copying. make_geometry becomes a template so make_area can keep passing Nodes. The stores are built by bbox filters on ways and relations, around on ways, and out geom/center/bb. Peak RSS on the Nova Scotia extract: way(42,-67.6,47.5,-58); out count; 1119 MB -> 592 MB [out:json]; way[highway]; out geom; 294 MB -> 178 MB [out:xml]; rel(42,-67.6,47.5,-58); out body; 337 MB -> 191 MB [out:json]; nwr[name]; out center; 268 MB -> 205 MB Outputs are unchanged. The new vector holds one entry per node found, the same count as the vector it replaces, so its bound is lower than before. Memory accounting for [maxsize:] is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/core/type_node.h | 21 +++++++++ src/overpass_api/data/collect_members.cc | 26 ++-------- src/overpass_api/data/collect_members.h | 47 ++++++++++++++++++- .../data/relation_geometry_store.cc | 32 ++++--------- .../data/relation_geometry_store.h | 2 +- src/overpass_api/data/way_geometry_store.cc | 8 +--- src/overpass_api/data/way_geometry_store.h | 2 +- 7 files changed, 82 insertions(+), 56 deletions(-) diff --git a/src/overpass_api/core/type_node.h b/src/overpass_api/core/type_node.h index 3bda1e9a6..5b126d7d6 100644 --- a/src/overpass_api/core/type_node.h +++ b/src/overpass_api/core/type_node.h @@ -58,12 +58,33 @@ struct Node }; +// A node's id and position without Node's tag vector, so it takes 16 bytes instead of 40. +// The geometry stores keep many of these to look up the coordinates of way and relation members. +struct Node_Position +{ + typedef Node::Id_Type Id_Type; + + Id_Type id; + uint32 index; + uint32 ll_lower_; + + Node_Position(Id_Type id_, uint32 ll_upper_, uint32 ll_lower__) + : id(id_), index(ll_upper_), ll_lower_(ll_lower__) + {} +}; + + struct Node_Comparator_By_Id { bool operator() (const Node& a, const Node& b) { return (a.id.val() < b.id.val()); } + bool operator() (const Node_Position& a, const Node_Position& b) + { + return (a.id.val() < b.id.val()); + } + bool operator() (const Node* a, const Node* b) { return (a->id.val() < b->id.val()); diff --git a/src/overpass_api/data/collect_members.cc b/src/overpass_api/data/collect_members.cc index 8e02c33ce..f10438445 100644 --- a/src/overpass_api/data/collect_members.cc +++ b/src/overpass_api/data/collect_members.cc @@ -857,26 +857,6 @@ bool add_way_to_area_blocks(const std::vector< Quad_Coord >& coords, } -std::vector< Quad_Coord > make_geometry(const Way_Skeleton& way, const std::vector< Node >& nodes) -{ - std::vector< Quad_Coord > result; - - for (std::vector< Node::Id_Type >::const_iterator it3(way.nds.begin()); - it3 != way.nds.end(); ++it3) - { - const Node* node = binary_search_for_id(nodes, *it3); - if (node == 0) - { - result.clear(); - return result; - } - result.push_back(Quad_Coord(node->index, node->ll_lower_)); - } - - return result; -} - - std::vector< Uint31_Index > segment_idxs(const std::vector< Quad_Coord >& geometry) { std::vector< uint32 > nd_idxs; @@ -962,7 +942,7 @@ void filter_ways_by_ranges(std::map< Uint31_Index, std::vector< Attic< Way_Skele void keep_matching_skeletons - (std::vector< Node >& result, + (std::vector< Node_Position >& result, const std::map< Uint32_Index, std::vector< Node_Skeleton > >& current, const std::map< Uint32_Index, std::vector< Attic< Node_Skeleton > > >& attic, uint64 timestamp) @@ -996,7 +976,7 @@ void keep_matching_skeletons for (std::vector< Node_Skeleton >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { if (timestamp_by_id[it2->id] == NOW) - result.push_back(Node(it2->id, it->first.val(), it2->ll_lower)); + result.push_back(Node_Position(it2->id, it->first.val(), it2->ll_lower)); } } @@ -1007,7 +987,7 @@ void keep_matching_skeletons it2 != it->second.end(); ++it2) { if (timestamp_by_id[it2->id] == it2->timestamp) - result.push_back(Node(it2->id, it->first.val(), it2->ll_lower)); + result.push_back(Node_Position(it2->id, it->first.val(), it2->ll_lower)); } } diff --git a/src/overpass_api/data/collect_members.h b/src/overpass_api/data/collect_members.h index 1de9773b6..1212cc083 100644 --- a/src/overpass_api/data/collect_members.h +++ b/src/overpass_api/data/collect_members.h @@ -123,7 +123,26 @@ bool add_way_to_area_blocks(const std::vector< Quad_Coord >& coords, uint32 id, std::map< Uint31_Index, std::vector< Area_Block > >& areas); -std::vector< Quad_Coord > make_geometry(const Way_Skeleton& way, const std::vector< Node >& nodes); +// nodes must be sorted by id. Node_Type is Node or Node_Position. +template< typename Node_Type > +std::vector< Quad_Coord > make_geometry(const Way_Skeleton& way, const std::vector< Node_Type >& nodes) +{ + std::vector< Quad_Coord > result; + + for (std::vector< Node::Id_Type >::const_iterator it3(way.nds.begin()); + it3 != way.nds.end(); ++it3) + { + const Node_Type* node = binary_search_for_id(nodes, *it3); + if (node == 0) + { + result.clear(); + return result; + } + result.push_back(Quad_Coord(node->index, node->ll_lower_)); + } + + return result; +} void filter_ways_by_ranges(std::map< Uint31_Index, std::vector< Way_Skeleton > >& ways, @@ -610,8 +629,32 @@ void keep_matching_skeletons } +// Appends the nodes of skels to result as Node_Positions and empties skels as it goes, +// so the two copies don't coexist in full. result is not sorted. +template< typename Skeleton > +void move_to_node_positions( + std::map< Uint32_Index, std::vector< Skeleton > >& skels, std::vector< Node_Position >& result) +{ + std::size_t count = 0; + for (typename std::map< Uint32_Index, std::vector< Skeleton > >::const_iterator it = skels.begin(); + it != skels.end(); ++it) + count += it->second.size(); + result.reserve(result.size() + count); + + for (typename std::map< Uint32_Index, std::vector< Skeleton > >::iterator it = skels.begin(); + it != skels.end(); ++it) + { + for (typename std::vector< Skeleton >::const_iterator iit = it->second.begin(); + iit != it->second.end(); ++iit) + result.push_back(Node_Position(iit->id, it->first.val(), iit->ll_lower)); + std::vector< Skeleton >().swap(it->second); + } + skels.clear(); +} + + void keep_matching_skeletons - (std::vector< Node >& result, + (std::vector< Node_Position >& result, const std::map< Uint32_Index, std::vector< Node_Skeleton > >& current, const std::map< Uint32_Index, std::vector< Attic< Node_Skeleton > > >& attic, uint64 timestamp); diff --git a/src/overpass_api/data/relation_geometry_store.cc b/src/overpass_api/data/relation_geometry_store.cc index 94dbf4f6f..c0650b86e 100644 --- a/src/overpass_api/data/relation_geometry_store.cc +++ b/src/overpass_api/data/relation_geometry_store.cc @@ -48,13 +48,7 @@ Relation_Geometry_Store::Relation_Geometry_Store = relation_node_members(context, relations, {}, node_ranges, {}, true); // Order node ids by id. - for (std::map< Uint32_Index, std::vector< Node_Skeleton > >::iterator it = node_members.current.begin(); - it != node_members.current.end(); ++it) - { - for (std::vector< Node_Skeleton >::const_iterator iit = it->second.begin(); - iit != it->second.end(); ++iit) - nodes.push_back(Node(iit->id, it->first.val(), iit->ll_lower)); - } + move_to_node_positions(node_members.current, nodes); sort(nodes.begin(), nodes.end(), Node_Comparator_By_Id()); Ranges< Uint31_Index > way_ranges(south <= north @@ -99,20 +93,14 @@ Relation_Geometry_Store::Relation_Geometry_Store auto nodes_by_idx = relation_node_members(context, {}, relations, node_ranges, {}, true); // Order node ids by id. - for (std::map< Uint32_Index, std::vector< Node_Skeleton > >::iterator it = nodes_by_idx.current.begin(); - it != nodes_by_idx.current.end(); ++it) - { - for (std::vector< Node_Skeleton >::const_iterator iit = it->second.begin(); - iit != it->second.end(); ++iit) - nodes.push_back(Node(iit->id, it->first.val(), iit->ll_lower)); - } - for (std::map< Uint32_Index, std::vector< Attic< Node_Skeleton > > >::iterator it = nodes_by_idx.attic.begin(); - it != nodes_by_idx.attic.end(); ++it) - { - for (std::vector< Attic< Node_Skeleton > >::const_iterator iit = it->second.begin(); - iit != it->second.end(); ++iit) - nodes.push_back(Node(iit->id, it->first.val(), iit->ll_lower)); - } + std::size_t count = 0; + for (auto it = nodes_by_idx.current.begin(); it != nodes_by_idx.current.end(); ++it) + count += it->second.size(); + for (auto it = nodes_by_idx.attic.begin(); it != nodes_by_idx.attic.end(); ++it) + count += it->second.size(); + nodes.reserve(count); + move_to_node_positions(nodes_by_idx.current, nodes); + move_to_node_positions(nodes_by_idx.attic, nodes); sort(nodes.begin(), nodes.end(), Node_Comparator_By_Id()); Ranges< Uint31_Index > way_ranges(south <= north @@ -161,7 +149,7 @@ std::vector< std::vector< Quad_Coord > > Relation_Geometry_Store::get_geometry { if (it->type == Relation_Entry::NODE) { - const Node* node = binary_search_for_id(nodes, it->ref); + const Node_Position* node = binary_search_for_id(nodes, it->ref); if (node == 0 || !matches_bbox(node->index, node->ll_lower_)) result.push_back(std::vector< Quad_Coord >(1, Quad_Coord(0u, 0u))); else diff --git a/src/overpass_api/data/relation_geometry_store.h b/src/overpass_api/data/relation_geometry_store.h index 4428e528b..81335ce95 100644 --- a/src/overpass_api/data/relation_geometry_store.h +++ b/src/overpass_api/data/relation_geometry_store.h @@ -43,7 +43,7 @@ class Relation_Geometry_Store std::vector< std::vector< Quad_Coord > > get_geometry(const Relation_Skeleton& relation) const; private: - std::vector< Node > nodes; + std::vector< Node_Position > nodes; std::vector< Way_Skeleton > ways; Way_Geometry_Store* way_geometry_store; diff --git a/src/overpass_api/data/way_geometry_store.cc b/src/overpass_api/data/way_geometry_store.cc index 2c539aa00..2136a8025 100644 --- a/src/overpass_api/data/way_geometry_store.cc +++ b/src/overpass_api/data/way_geometry_store.cc @@ -89,13 +89,7 @@ Way_Geometry_Store::Way_Geometry_Store std::map< Uint32_Index, std::vector< Node_Skeleton > > way_members_ = small_way_members(&query, rman, ways); // Order node ids by id. - for (std::map< Uint32_Index, std::vector< Node_Skeleton > >::iterator it = way_members_.begin(); - it != way_members_.end(); ++it) - { - for (std::vector< Node_Skeleton >::const_iterator iit = it->second.begin(); - iit != it->second.end(); ++iit) - nodes.push_back(Node(iit->id, it->first.val(), iit->ll_lower)); - } + move_to_node_positions(way_members_, nodes); sort(nodes.begin(), nodes.end(), Node_Comparator_By_Id()); } diff --git a/src/overpass_api/data/way_geometry_store.h b/src/overpass_api/data/way_geometry_store.h index 651ad8e13..00395dee5 100644 --- a/src/overpass_api/data/way_geometry_store.h +++ b/src/overpass_api/data/way_geometry_store.h @@ -40,7 +40,7 @@ class Way_Geometry_Store std::vector< Quad_Coord > get_geometry(const Way_Skeleton& way) const; private: - std::vector< Node > nodes; + std::vector< Node_Position > nodes; }; From 9076b4badf3c24fb20ace3f3bd747cf03341dbe9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:46:29 +0000 Subject: [PATCH 18/80] filter_attic_elements: per-index timestamps in a sorted vector, not a std::map Queries at a past date ([date:], and the old side of [diff:]/[adiff:]) pass every candidate through filter_attic_elements, which kept a std::map< Id_Type, std::pair< uint64, uint64 > > per index with one entry per candidate. Each entry is a red-black tree node of about 64 bytes. They are now a vector of (id, timestamps) pairs, 24 bytes each, sorted by id with stable_sort; for repeated ids the last entry added is kept, as repeated assignment to the map did. Lookups use binary search. Peak RSS and CPU on a Nova Scotia full-history database (2006 to 2026-11-15, imported with --keep-attic): [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; node(42,-67.6,47.5,-58); out count; 1272 MB -> 846 MB, CPU 11.9 s -> 9.8 s [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; node(44.4,-64.0,45.0,-63.0); node(around:5)[amenity]; out count; 356 MB -> 320 MB, CPU 5.1 s -> 4.3 s [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; nwr[amenity](44.60,-63.66,44.70,-63.52); out count; 87 MB -> 74 MB, CPU unchanged CPU is the median of 5 alternating runs per build. Outputs are unchanged. The vectors hold one entry per candidate, as the maps did, at 24 instead of about 64 bytes. Queries at the current date don't run this code. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/data/collect_members.h | 89 ++++++++++++++++++------- 1 file changed, 64 insertions(+), 25 deletions(-) diff --git a/src/overpass_api/data/collect_members.h b/src/overpass_api/data/collect_members.h index 1212cc083..bd267cb9b 100644 --- a/src/overpass_api/data/collect_members.h +++ b/src/overpass_api/data/collect_members.h @@ -25,6 +25,7 @@ #include "collect_items.h" #include "filenames.h" +#include #include #include #include @@ -250,6 +251,39 @@ bool Collect_Items< Index, Object >::get_chunk( } +// Sorts entries by id and keeps only the last entry of each id, in the order they were added, +// like repeated assignments to a std::map. +template< typename Id_Type, typename Value > +void sort_keeping_last_per_id(std::vector< std::pair< Id_Type, Value > >& entries) +{ + std::stable_sort(entries.begin(), entries.end(), + [](const std::pair< Id_Type, Value >& a, const std::pair< Id_Type, Value >& b) + { return a.first < b.first; }); + typename std::vector< std::pair< Id_Type, Value > >::iterator kept = entries.begin(); + for (typename std::vector< std::pair< Id_Type, Value > >::iterator it = entries.begin(); + it != entries.end(); ++it) + { + if (it + 1 != entries.end() && (it + 1)->first == it->first) + continue; + *kept++ = *it; + } + entries.erase(kept, entries.end()); +} + + +// Returns the value stored for id in entries sorted by sort_keeping_last_per_id, or 0. +template< typename Id_Type, typename Value > +Value* find_timestamps(std::vector< std::pair< Id_Type, Value > >& entries, const Id_Type& id) +{ + typename std::vector< std::pair< Id_Type, Value > >::iterator it = std::lower_bound( + entries.begin(), entries.end(), id, + [](const std::pair< Id_Type, Value >& a, const Id_Type& b) { return a.first < b; }); + if (it != entries.end() && it->first == id) + return &it->second; + return 0; +} + + template< typename Index, typename Skeleton > void filter_attic_elements (Resource_Manager& rman, uint64 timestamp, @@ -315,26 +349,29 @@ void filter_attic_elements // Confirm elements that are backed by meta data // Update element's expiration timestamp if a meta exists that is older than the current // expiration date and younger than timestamp - std::map< Index, std::map< typename Skeleton::Id_Type, std::pair< uint64, uint64 > > > - timestamp_by_id_by_idx; + // Per index, the entries are sorted by id with one entry per id. A sorted vector takes + // 24 bytes per element where a std::map took a tree node of about 64 bytes. + typedef std::pair< typename Skeleton::Id_Type, std::pair< uint64, uint64 > > Timestamps_Entry; + std::map< Index, std::vector< Timestamps_Entry > > timestamp_by_id_by_idx; for (typename std::map< Index, std::vector< Skeleton > >::const_iterator it = current.begin(); it != current.end(); ++it) { - std::map< typename Skeleton::Id_Type, std::pair< uint64, uint64 > >& entry - = timestamp_by_id_by_idx[it->first]; + std::vector< Timestamps_Entry >& entry = timestamp_by_id_by_idx[it->first]; for (typename std::vector< Skeleton >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) - entry[it2->id] = std::make_pair(0, NOW); + entry.push_back(Timestamps_Entry(it2->id, std::make_pair(0, NOW))); } for (typename std::map< Index, std::vector< Attic< Skeleton > > >::const_iterator it = attic.begin(); it != attic.end(); ++it) { - std::map< typename Skeleton::Id_Type, std::pair< uint64, uint64 > >& entry - = timestamp_by_id_by_idx[it->first]; + std::vector< Timestamps_Entry >& entry = timestamp_by_id_by_idx[it->first]; for (typename std::vector< Attic< Skeleton > >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) - entry[it2->id] = std::make_pair(0, it2->timestamp); + entry.push_back(Timestamps_Entry(it2->id, std::make_pair(0, it2->timestamp))); } + for (typename std::map< Index, std::vector< Timestamps_Entry > >::iterator + it = timestamp_by_id_by_idx.begin(); it != timestamp_by_id_by_idx.end(); ++it) + sort_keeping_last_per_id(it->second); Block_Backend< Index, OSM_Element_Metadata_Skeleton< typename Skeleton::Id_Type >, typename std::vector< Index >::const_iterator > @@ -343,13 +380,14 @@ void filter_attic_elements for (auto it = attic_meta_db.discrete_begin(idx_set.begin(), idx_set.end()); !(it == attic_meta_db.discrete_end()); ++it) { - auto tit = timestamp_by_id_by_idx[it.index()].find(it.object().ref); - if (tit != timestamp_by_id_by_idx[it.index()].end()) + std::pair< uint64, uint64 >* tit + = find_timestamps(timestamp_by_id_by_idx[it.index()], it.object().ref); + if (tit) { if (timestamp < it.object().timestamp) - tit->second.second = std::min(tit->second.second, it.object().timestamp); + tit->second = std::min(tit->second, it.object().timestamp); else - tit->second.first = std::max(tit->second.first, it.object().timestamp); + tit->first = std::max(tit->first, it.object().timestamp); } } @@ -362,13 +400,14 @@ void filter_attic_elements for (auto it = meta_db.discrete_begin(idx_set.begin(), idx_set.end()); !(it == meta_db.discrete_end()); ++it) { - auto tit = timestamp_by_id_by_idx[it.index()].find(it.object().ref); - if (tit != timestamp_by_id_by_idx[it.index()].end()) + std::pair< uint64, uint64 >* tit + = find_timestamps(timestamp_by_id_by_idx[it.index()], it.object().ref); + if (tit) { if (timestamp < it.object().timestamp) - tit->second.second = std::min(tit->second.second, it.object().timestamp); + tit->second = std::min(tit->second, it.object().timestamp); else - tit->second.first = std::max(tit->second.first, it.object().timestamp); + tit->first = std::max(tit->first, it.object().timestamp); } } @@ -377,18 +416,18 @@ void filter_attic_elements it != current.end(); ++it) { std::vector< Skeleton > result; - std::map< typename Skeleton::Id_Type, std::pair< uint64, uint64 > >& entry - = timestamp_by_id_by_idx[it->first]; + std::vector< Timestamps_Entry >& entry = timestamp_by_id_by_idx[it->first]; for (typename std::vector< Skeleton >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (entry[it2->id].first > 0) + const std::pair< uint64, uint64 >* timestamps = find_timestamps(entry, it2->id); + if (timestamps && timestamps->first > 0) { - if (entry[it2->id].second == NOW) + if (timestamps->second == NOW) result.push_back(*it2); else - attic[it->first].push_back(Attic< Skeleton >(*it2, entry[it2->id].second)); + attic[it->first].push_back(Attic< Skeleton >(*it2, timestamps->second)); } } @@ -400,16 +439,16 @@ void filter_attic_elements it != attic.end(); ++it) { std::vector< Attic< Skeleton > > result; - std::map< typename Skeleton::Id_Type, std::pair< uint64, uint64 > >& entry - = timestamp_by_id_by_idx[it->first]; + std::vector< Timestamps_Entry >& entry = timestamp_by_id_by_idx[it->first]; for (typename std::vector< Attic< Skeleton > >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (entry[it2->id].first > 0) + const std::pair< uint64, uint64 >* timestamps = find_timestamps(entry, it2->id); + if (timestamps && timestamps->first > 0) { result.push_back(*it2); - result.back().timestamp = entry[it2->id].second; + result.back().timestamp = timestamps->second; } } From e888b4fa169e793613e13b44e57e42afea71e721 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 16:49:02 +0000 Subject: [PATCH 19/80] poly queries: test nodes against blocks decoded once per tile Polygon_Query_Statement::collect_nodes and collect_ways test every node in a tile against every polygon segment in that tile with the raw Area_Block overload of check_area_block, which decodes each vertex on the fly and has no early exit. Area queries switched their node tests to blocks decoded once per tile (Decoded_Area_Block), whose test returns at once when the node's longitude is outside the block's range; poly: queries did not. Both functions now decode each polygon segment once per tile with the tile's index and use the decoded overload. The test is unchanged, so results are the same. On the Nova Scotia area database, with the 1,041-point outer ring of relation 9092218 (given in bench/queries-tools/ t08_osmnx_graph_drive.ql on the bench-tools branch): [out:csv(::count)];node["amenity"](poly:'');out count; 3.64 s -> 0.89 s [out:csv(::count)];node(poly:'');out count; 3.20 s -> 0.58 s and osmnx's road-network query (t08 in that directory) drops by 16%. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/polygon_query.cc | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/statements/polygon_query.cc b/src/overpass_api/statements/polygon_query.cc index e967759e6..76cd0b4d6 100644 --- a/src/overpass_api/statements/polygon_query.cc +++ b/src/overpass_api/statements/polygon_query.cc @@ -361,6 +361,11 @@ void Polygon_Query_Statement::collect_nodes(std::map< Uint32_Index, std::vector< areas.push_back(block); ++area_it; } + // The same segments decoded once for this tile, for the node tests below. + std::vector< Coord_Query_Statement::Decoded_Area_Block > areas_in_tile; + areas_in_tile.reserve(areas.size()); + for (std::vector< Area_Block >::const_iterator ait = areas.begin(); ait != areas.end(); ++ait) + areas_in_tile.push_back(Coord_Query_Statement::Decoded_Area_Block(current_idx, *ait)); while (nodes_it != nodes.end() && nodes_it->first.val() < current_idx) { @@ -383,7 +388,7 @@ void Polygon_Query_Statement::collect_nodes(std::map< Uint32_Index, std::vector< for (std::vector< Area_Block >::const_iterator it = areas.begin(); it != areas.end(); ++it) { - int check(Coord_Query_Statement::check_area_block(current_idx, *it, ilat, ilon)); + int check(Coord_Query_Statement::check_area_block(areas_in_tile[it - areas.begin()], ilat, ilon)); if (check == Coord_Query_Statement::HIT && add_border) { inside = 1; @@ -452,6 +457,11 @@ void Polygon_Query_Statement::collect_ways areas.push_back(block); ++area_it; } + // The same segments decoded once for this tile, for the node tests below. + std::vector< Coord_Query_Statement::Decoded_Area_Block > areas_in_tile; + areas_in_tile.reserve(areas.size()); + for (std::vector< Area_Block >::const_iterator ait = areas.begin(); ait != areas.end(); ++ait) + areas_in_tile.push_back(Coord_Query_Statement::Decoded_Area_Block(current_idx, *ait)); // The same segments decoded once for this tile, for the segment tests below. std::vector< Decoded_Coords > area_coords(areas.size()); std::vector< Coord_Query_Statement::Decoded_Area_Block > areas_decoded; @@ -479,7 +489,7 @@ void Polygon_Query_Statement::collect_ways for (std::vector< Area_Block >::const_iterator it2 = areas.begin(); it2 != areas.end(); ++it2) { - int check(Coord_Query_Statement::check_area_block(current_idx, *it2, ilat, ilon)); + int check(Coord_Query_Statement::check_area_block(areas_in_tile[it2 - areas.begin()], ilat, ilon)); if (check == Coord_Query_Statement::HIT) { inside = Coord_Query_Statement::HIT; From c0317c389b5eb8c5bb15f671a16e10182ddbd2be Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 17:07:13 +0000 Subject: [PATCH 20/80] area and poly queries: skip the segment test when bounding boxes don't overlap In the segment tests of area and poly: queries, intersects_inner runs for every pair of a way-segment block and an area block in a tile. It can only return non-zero, an intersection or a touch, if the two chains of segments touch, which requires their bounding boxes to overlap. Each decoded block now gets its bounding box once per tile (Coords_Bounds), and the test is skipped for pairs whose boxes don't overlap. has_inner_points still runs for every pair: its ray casting counts segments anywhere south of the point. On the Nova Scotia area database, osmnx's road-network query for Halifax (t08 in bench/queries-tools/ on the bench-tools branch, a poly: filter with the 1,041-point boundary of relation 9092218) drops from 498 ms to 450 ms, and [out:csv(::count)]; area[name="Halifax"][admin_level=8]->.a; way[highway](area.a); out count; from 537 ms to 498 ms. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/area_query.cc | 20 +++++++++++++++++++- src/overpass_api/statements/area_query.h | 13 +++++++++++++ src/overpass_api/statements/polygon_query.cc | 7 ++++++- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/statements/area_query.cc b/src/overpass_api/statements/area_query.cc index 443dc7e6a..067a3727a 100644 --- a/src/overpass_api/statements/area_query.cc +++ b/src/overpass_api/statements/area_query.cc @@ -31,6 +31,7 @@ #include "../core/index_computations.h" #include "../data/collect_members.h" #include "../data/tilewise_geometry.h" +#include #include "area_query.h" #include "coord_query.h" #include "make_area.h" @@ -768,6 +769,19 @@ void decode_coords(const Area_Block& block, Decoded_Coords& coords) } +Coords_Bounds::Coords_Bounds(const Decoded_Coords& coords) + : min_lat(0xffffffffu), max_lat(0), min_lon(0xffffffffu), max_lon(0) +{ + for (Decoded_Coords::const_iterator it = coords.begin(); it != coords.end(); ++it) + { + min_lat = std::min(min_lat, it->first); + max_lat = std::max(max_lat, it->first); + min_lon = std::min(min_lon, it->second); + max_lon = std::max(max_lon, it->second); + } +} + + int intersects_inner(const Decoded_Coords& coords_a, const Decoded_Coords& coords_b) { for (std::vector< std::pair< uint32, uint32 > >::size_type i = 0; i < coords_a.size()-1; ++i) @@ -933,6 +947,7 @@ void Area_Query_Statement::collect_ways // has_inner_points tests segment midpoints against the blocks decoded with ll_index 0. std::map< Area_Skeleton::Id_Type, std::vector< Coord_Query_Statement::Decoded_Area_Block > > decoded_zero; std::map< Area_Skeleton::Id_Type, std::vector< Decoded_Coords > > area_coords; + std::map< Area_Skeleton::Id_Type, std::vector< Coords_Bounds > > area_bounds; for (std::map< Area_Skeleton::Id_Type, std::vector< Area_Block > >::const_iterator it = areas.begin(); it != areas.end(); ++it) { @@ -943,6 +958,7 @@ void Area_Query_Statement::collect_ways blocks.push_back(Coord_Query_Statement::Decoded_Area_Block(0, *it2)); coords.push_back(Decoded_Coords()); decode_coords(*it2, coords.back()); + area_bounds[it->first].push_back(Coords_Bounds(coords.back())); } } @@ -952,6 +968,7 @@ void Area_Query_Statement::collect_ways sit != way_segments[Uint31_Index(current_idx)].end(); ++sit) { decode_coords(*sit, sit_coords); + Coords_Bounds sit_bounds(sit_coords); std::map< Area::Id_Type, int > area_status; for (std::map< Area_Skeleton::Id_Type, std::vector< Area_Block > >::const_iterator it = areas.begin(); it != areas.end(); ++it) @@ -966,7 +983,8 @@ void Area_Query_Statement::collect_ways // The endpoints are properly handled via the point-in-area test // Check additionally the middle of the segment to also get segments // that run through the area - int intersect = intersects_inner(sit_coords, area_coords[it->first][it2 - it->second.begin()]); + int intersect = sit_bounds.overlaps(area_bounds[it->first][it2 - it->second.begin()]) + ? intersects_inner(sit_coords, area_coords[it->first][it2 - it->second.begin()]) : 0; if (intersect == Coord_Query_Statement::INTERSECT) { ways_inside[Way::Id_Type(sit->id)] = true; diff --git a/src/overpass_api/statements/area_query.h b/src/overpass_api/statements/area_query.h index 3737118d9..12f27cf37 100644 --- a/src/overpass_api/statements/area_query.h +++ b/src/overpass_api/statements/area_query.h @@ -126,6 +126,19 @@ class Area_Query_Statement : public Output_Statement typedef std::vector< std::pair< uint32, uint32 > > Decoded_Coords; void decode_coords(const Area_Block& block, Decoded_Coords& coords); int intersects_inner(const Decoded_Coords& coords_a, const Decoded_Coords& coords_b); + +// The bounding box of decoded coordinates. Two chains of segments can only touch, and so +// intersects_inner can only return non-zero, if their bounding boxes overlap. +struct Coords_Bounds +{ + uint32 min_lat, max_lat, min_lon, max_lon; + explicit Coords_Bounds(const Decoded_Coords& coords); + bool overlaps(const Coords_Bounds& rhs) const + { + return !(max_lat < rhs.min_lat || rhs.max_lat < min_lat + || max_lon < rhs.min_lon || rhs.max_lon < min_lon); + } +}; void has_inner_points(const Decoded_Coords& coords_a, const Coord_Query_Statement::Decoded_Area_Block& string_b, int& inside); diff --git a/src/overpass_api/statements/polygon_query.cc b/src/overpass_api/statements/polygon_query.cc index 76cd0b4d6..70184f9f8 100644 --- a/src/overpass_api/statements/polygon_query.cc +++ b/src/overpass_api/statements/polygon_query.cc @@ -464,11 +464,14 @@ void Polygon_Query_Statement::collect_ways areas_in_tile.push_back(Coord_Query_Statement::Decoded_Area_Block(current_idx, *ait)); // The same segments decoded once for this tile, for the segment tests below. std::vector< Decoded_Coords > area_coords(areas.size()); + std::vector< Coords_Bounds > area_bounds; + area_bounds.reserve(areas.size()); std::vector< Coord_Query_Statement::Decoded_Area_Block > areas_decoded; areas_decoded.reserve(areas.size()); for (std::vector< Area_Block >::size_type i = 0; i < areas.size(); ++i) { decode_coords(areas[i], area_coords[i]); + area_bounds.push_back(Coords_Bounds(area_coords[i])); areas_decoded.push_back(Coord_Query_Statement::Decoded_Area_Block(0, areas[i])); } @@ -510,6 +513,7 @@ void Polygon_Query_Statement::collect_ways sit != way_segments[Uint31_Index(current_idx)].end(); ++sit) { decode_coords(*sit, sit_coords); + Coords_Bounds sit_bounds(sit_coords); int inside = 0; for (std::vector< Area_Block >::const_iterator it = areas.begin(); it != areas.end(); ++it) @@ -519,7 +523,8 @@ void Polygon_Query_Statement::collect_ways // The endpoints are properly handled via the point-in-area test // Check additionally the middle of the segment to also get segments // that run through the area - int intersect = intersects_inner(sit_coords, area_coords[it - areas.begin()]); + int intersect = sit_bounds.overlaps(area_bounds[it - areas.begin()]) + ? intersects_inner(sit_coords, area_coords[it - areas.begin()]) : 0; if (intersect == Coord_Query_Statement::INTERSECT) { ways_inside[Way::Id_Type(sit->id)] = true; From 6e0fba2a9ceea77d99e52201e0ea90c4533c0f48 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 18:27:18 +0000 Subject: [PATCH 21/80] collect_items_range: keep the result size up to date instead of recounting it collect_items_range checks the query's memory limit every 256K objects with eval_map(result), which walks the whole result map. A scan over a large area builds a map with many indexes, so each check got slower as the result grew. It also looked up the result entry for every object (result[index]), although objects arrive ordered by index. The loop now starts from eval_map(result) and adds what eval_map would charge for each object and each new index, so every check sees the same value without walking the map. It keeps an iterator to the entry it last appended to. The charges per object now live next to eval_map (eval_object_size, eval_index_size), and eval_map uses them. On the Nova Scotia history database: [out:csv(::count)]; nwr(newer:"2026-11-08T00:00:00Z")(43.3,-66.5,47.1,-59.6); out count; drops from 4.96 s to 4.05 s. The memory accounting is unchanged: for three queries at 20 [maxsize:] values each, both builds pass or fail alike and report the same size. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/data/collect_items.h | 20 +++++++++++++++++-- src/overpass_api/dispatch/resource_manager.cc | 14 ++++++------- src/overpass_api/dispatch/resource_manager.h | 12 +++++++++++ 3 files changed, 37 insertions(+), 9 deletions(-) diff --git a/src/overpass_api/data/collect_items.h b/src/overpass_api/data/collect_items.h index 2964d7061..4a89a4246 100644 --- a/src/overpass_api/data/collect_items.h +++ b/src/overpass_api/data/collect_items.h @@ -524,6 +524,10 @@ bool collect_items_range(Request_Context& context, { uint32 count = 0; bool too_much_data = false; + // The size eval_map would report for result, kept up to date as objects are added, + // and the entry objects were last added to: objects arrive ordered by index. + uint64 result_size = eval_map(result); + typename std::map< Index, std::vector< Object > >::iterator last = result.end(); for (auto it = current_db.range_begin(shortened); !(it == current_db.range_end()); ++it) { @@ -535,11 +539,23 @@ bool collect_items_range(Request_Context& context, if (++count >= 256*1024) { count = 0; - too_much_data = context.get_health_guard().check(0, eval_map(result)); + too_much_data = context.get_health_guard().check(0, result_size); cur_idx = it.index(); } if (predicate.match(it.handle())) - result[it.index()].push_back(it.object()); + { + if (last == result.end() || !(last->first == it.index())) + { + last = result.lower_bound(it.index()); + if (last == result.end() || it.index() < last->first) + { + last = result.insert(last, std::make_pair(it.index(), std::vector< Object >())); + result_size += eval_index_size; + } + } + last->second.push_back(it.object()); + result_size += eval_object_size((const Object*)0); + } } return false; diff --git a/src/overpass_api/dispatch/resource_manager.cc b/src/overpass_api/dispatch/resource_manager.cc index 56ed22da6..30bd7d5ec 100644 --- a/src/overpass_api/dispatch/resource_manager.cc +++ b/src/overpass_api/dispatch/resource_manager.cc @@ -29,7 +29,7 @@ uint64 eval_map(const std::map< Uint32_Index, std::vector< Node_Skeleton > >& no uint64 size(0); for (std::map< Uint32_Index, std::vector< Node_Skeleton > >::const_iterator it(nodes.begin()); it != nodes.end(); ++it) - size += it->second.size()*8 + 64; + size += it->second.size()*eval_object_size((const Node_Skeleton*)0) + eval_index_size; return size; } @@ -39,7 +39,7 @@ uint64 eval_map(const std::map< Uint31_Index, std::vector< Way_Skeleton > >& way uint64 size(0); for (std::map< Uint31_Index, std::vector< Way_Skeleton > >::const_iterator it(ways.begin()); it != ways.end(); ++it) - size += it->second.size()*128 + 64; + size += it->second.size()*eval_object_size((const Way_Skeleton*)0) + eval_index_size; return size; } @@ -49,7 +49,7 @@ uint64 eval_map(const std::map< Uint31_Index, std::vector< Relation_Skeleton > > uint64 size(0); for (std::map< Uint31_Index, std::vector< Relation_Skeleton > >::const_iterator it(relations.begin()); it != relations.end(); ++it) - size += it->second.size()*192 + 64; + size += it->second.size()*eval_object_size((const Relation_Skeleton*)0) + eval_index_size; return size; } @@ -59,7 +59,7 @@ uint64 eval_map(const std::map< Uint32_Index, std::vector< Attic< Node_Skeleton uint64 size(0); for (std::map< Uint32_Index, std::vector< Attic< Node_Skeleton > > >::const_iterator it(nodes.begin()); it != nodes.end(); ++it) - size += it->second.size()*16 + 64; + size += it->second.size()*eval_object_size((const Attic< Node_Skeleton >*)0) + eval_index_size; return size; } @@ -69,7 +69,7 @@ uint64 eval_map(const std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > uint64 size(0); for (std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > > >::const_iterator it(ways.begin()); it != ways.end(); ++it) - size += it->second.size()*136 + 64; + size += it->second.size()*eval_object_size((const Attic< Way_Skeleton >*)0) + eval_index_size; return size; } @@ -79,7 +79,7 @@ uint64 eval_map(const std::map< Uint31_Index, std::vector< Attic< Relation_Skele uint64 size(0); for (std::map< Uint31_Index, std::vector< Attic< Relation_Skeleton > > >::const_iterator it(relations.begin()); it != relations.end(); ++it) - size += it->second.size()*200 + 64; + size += it->second.size()*eval_object_size((const Attic< Relation_Skeleton >*)0) + eval_index_size; return size; } @@ -89,7 +89,7 @@ uint64 eval_map(const std::map< Uint31_Index, std::vector< Area_Skeleton > >& ar uint64 size(0); for (std::map< Uint31_Index, std::vector< Area_Skeleton > >::const_iterator it(areas.begin()); it != areas.end(); ++it) - size += it->second.size()*128 + 64; + size += it->second.size()*eval_object_size((const Area_Skeleton*)0) + eval_index_size; return size; } diff --git a/src/overpass_api/dispatch/resource_manager.h b/src/overpass_api/dispatch/resource_manager.h index b897dc821..c502676a8 100644 --- a/src/overpass_api/dispatch/resource_manager.h +++ b/src/overpass_api/dispatch/resource_manager.h @@ -207,6 +207,18 @@ class Resource_Manager }; +// eval_map charges eval_index_size bytes per index plus eval_object_size per object. +// Keeping these in one place lets loops that only add objects keep the same total +// up to date instead of walking the whole map. +const uint64 eval_index_size = 64; +inline uint64 eval_object_size(const Node_Skeleton*) { return 8; } +inline uint64 eval_object_size(const Way_Skeleton*) { return 128; } +inline uint64 eval_object_size(const Relation_Skeleton*) { return 192; } +inline uint64 eval_object_size(const Attic< Node_Skeleton >*) { return 16; } +inline uint64 eval_object_size(const Attic< Way_Skeleton >*) { return 136; } +inline uint64 eval_object_size(const Attic< Relation_Skeleton >*) { return 200; } +inline uint64 eval_object_size(const Area_Skeleton*) { return 128; } + uint64 eval_map(const std::map< Uint32_Index, std::vector< Node_Skeleton > >& nodes); uint64 eval_map(const std::map< Uint31_Index, std::vector< Way_Skeleton > >& ways); uint64 eval_map(const std::map< Uint31_Index, std::vector< Relation_Skeleton > >& relations); From c3f7dc924f140e02045aa8c0e17354fc365cae2b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 18:58:57 +0000 Subject: [PATCH 22/80] Segment pre-check: allow the 1-unit latitude slack intersects_inner uses The bounding-box pre-check skipped intersects_inner whenever two chains' boxes didn't overlap. But for parallel segments, ordered_intersects_inner returns HIT when an endpoint lies within 1 unit of latitude of the other segment's line. So two east-west segments that overlap in longitude and lie 1 unit apart in latitude touch (HIT) though their boxes don't overlap, and the pre-check turned that HIT into 0. The callers act on HIT: with add_border the way is kept, otherwise the area is marked HIT and has_inner_points is skipped for it. Coords_Bounds::overlaps now allows a latitude gap of up to 1 unit, with a comment explaining why it must not be simplified to a plain box overlap. Longitude needs no slack: ordered_a_intersects_inner and longitude_a_intersects_inner require overlapping longitude ranges before they test anything. Tested with the functions of area_query.cc in a standalone harness: case intersects_inner pre-check before after east-west, overlapping lon, 1 unit apart HIT 0 HIT same, 2 units apart 0 0 0 crossing segments INTERSECT INTERSECT INTERSECT Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 --- src/overpass_api/statements/area_query.h | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/overpass_api/statements/area_query.h b/src/overpass_api/statements/area_query.h index 12f27cf37..5a62abb50 100644 --- a/src/overpass_api/statements/area_query.h +++ b/src/overpass_api/statements/area_query.h @@ -127,15 +127,25 @@ typedef std::vector< std::pair< uint32, uint32 > > Decoded_Coords; void decode_coords(const Area_Block& block, Decoded_Coords& coords); int intersects_inner(const Decoded_Coords& coords_a, const Decoded_Coords& coords_b); -// The bounding box of decoded coordinates. Two chains of segments can only touch, and so -// intersects_inner can only return non-zero, if their bounding boxes overlap. +// The bounding box of decoded coordinates, to skip intersects_inner for pairs of chains +// that can't intersect or touch. struct Coords_Bounds { uint32 min_lat, max_lat, min_lon, max_lon; explicit Coords_Bounds(const Decoded_Coords& coords); + + // False only if intersects_inner(this chain, rhs chain) must return 0. + // + // The latitude test deliberately allows a gap of up to 1 unit. Don't simplify it to a + // plain box overlap: for parallel segments, ordered_intersects_inner returns HIT when an + // endpoint lies within 1 unit of latitude of the other segment's line. Two east-west + // segments 1 unit apart touch by that rule, though their boxes don't overlap. + // Longitude needs no slack: ordered_a_intersects_inner and longitude_a_intersects_inner + // require overlapping longitude ranges before they test anything. bool overlaps(const Coords_Bounds& rhs) const { - return !(max_lat < rhs.min_lat || rhs.max_lat < min_lat + return !((max_lat < rhs.min_lat && rhs.min_lat - max_lat > 1) + || (rhs.max_lat < min_lat && min_lat - rhs.max_lat > 1) || max_lon < rhs.min_lon || rhs.max_lon < min_lon); } }; From e1e42d4192dbf3a19a4f1a751acca758f40bd520 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 17:23:26 +0000 Subject: [PATCH 23/80] Collect_Items: cap chunk size, and chunk queries at a past date Query_Statement collects candidates in chunks and filters each chunk before collecting the next. Two things made the chunks far larger than needed: - At the current date, a chunk ended only when its accounted size reached half the remaining [maxsize:] budget: about 256 MiB accounted at the default 512 MiB. eval_map counts a node as 8 bytes, so that is up to 32 million nodes, which take much more memory in fact. - At a past date, collect_items_by_timestamp called the size check but discarded its result: too_much_data stayed false, so these queries were never chunked. A chunk now also ends once its accounted size reaches 64 MiB (8 million nodes or 512k ways), and the history path acts on the size check. The resume logic is the existing one, used until now when a chunk reached the budget. Peak RSS, CPU as the median of alternating runs (7 plain, 5 history, 3 for the last query), against upstream/master: [out:csv(::count)]; way(42,-67.6,47.5,-58); out count; 1093 MB -> 602 MB, CPU x0.98 (Nova Scotia extract) [out:csv(::count)]; nwr(newer:"2026-11-08T00:00:00Z")(43.3,-66.5,47.1,-59.6); out count; 531 MB -> 256 MB, CPU x0.92 (Nova Scotia full-history database) [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; 1494 MB -> 596 MB, CPU x0.95 (same) The benchmark queries are unchanged in memory and CPU (totals x0.99 plain, x0.97 history); none of them collects more than a chunk. Outputs are unchanged. Memory accounting for [maxsize:] is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/data/collect_items.h | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/overpass_api/data/collect_items.h b/src/overpass_api/data/collect_items.h index 4a89a4246..52bc19b7c 100644 --- a/src/overpass_api/data/collect_items.h +++ b/src/overpass_api/data/collect_items.h @@ -60,6 +60,12 @@ void reconstruct_items( class Statement; +// A chunk of collected elements also ends once its accounted size (as eval_map counts it) reaches +// this, so a query whose filters drop most candidates doesn't hold all of them at once when its +// [maxsize:] budget is large. 64 MiB accounted is 8M nodes or 512k ways. +const uint64 MAX_CHUNK_ACCOUNTED_SIZE = 64ull*1024*1024; + + class Health_Guard { public: @@ -265,8 +271,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, if (++count >= 128*1024) { count = 0; - health_guard.check(0, eval_map(result)); - health_guard.check(0, eval_map(attic_result)); + uint64 chunk_size = eval_map(result) + eval_map(attic_result); + too_much_data = health_guard.check(0, chunk_size) || chunk_size >= MAX_CHUNK_ACCOUNTED_SIZE; } Index index = (attic_begin == attic_end || @@ -311,8 +317,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, if (++count >= 128*1024) { count = 0; - health_guard.check(0, eval_map(result)); - health_guard.check(0, eval_map(attic_result)); + uint64 chunk_size = eval_map(result) + eval_map(attic_result); + too_much_data = health_guard.check(0, chunk_size) || chunk_size >= MAX_CHUNK_ACCOUNTED_SIZE; } Index index = (attic_begin == attic_end || @@ -396,8 +402,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, if (++count >= 128*1024) { count = 0; - health_guard.check(0, eval_map(result)); - health_guard.check(0, eval_map(attic_result)); + uint64 chunk_size = eval_map(result) + eval_map(attic_result); + too_much_data = health_guard.check(0, chunk_size) || chunk_size >= MAX_CHUNK_ACCOUNTED_SIZE; } Index index = (attic_begin == attic_end || @@ -539,7 +545,8 @@ bool collect_items_range(Request_Context& context, if (++count >= 256*1024) { count = 0; - too_much_data = context.get_health_guard().check(0, result_size); + too_much_data = context.get_health_guard().check(0, result_size) + || result_size >= MAX_CHUNK_ACCOUNTED_SIZE; cur_idx = it.index(); } if (predicate.match(it.handle())) From 2faf872d5cea2b9d9d59ba4bcd21f652b033f44d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 17:01:51 +0000 Subject: [PATCH 24/80] keep_matching_skeletons: valid-until timestamps in a sorted vector, not a std::map For a query at a past date, keep_matching_skeletons picks the version of each element valid at that date. All three overloads built a std::map< Id_Type, uint64 > with a tree node (about 48 bytes) per id. The value the map ends up with per id doesn't depend on insertion order: NOW if a current version exists, else the earliest attic timestamp after the date, else 0. The new Valid_Until_By_Id collects (id, candidate) pairs in a vector (16 bytes each), sorts it once, keeps the smallest nonzero candidate per id, and answers lookups by binary search. Attic versions that ended at or before the date aren't stored, since they can't be the valid one. The Node overload also reserves its result exactly: one element per id with a valid version. This runs whenever way or relation geometry, relation members or recursion are needed at a past date. Peak RSS and CPU (median of alternating runs: 3 per query, 5 for the history benchmark) on a Nova Scotia full-history database, against upstream/master: [date:"2018-01-01T00:00:00Z"][out:json]; way[highway]; out geom; 236 MB -> 195 MB, CPU x0.97 [date:"2018-01-01T00:00:00Z"][out:xml]; rel(42,-67.6,47.5,-58); out body; 324 MB -> 256 MB, CPU x0.99 [date:"2018-01-01T00:00:00Z"][out:json]; nwr[name]; out center; 266 MB -> 256 MB, CPU x0.96 The history benchmark queries are unchanged (CPU total x1.00, RSS within 1 MB). Outputs are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/data/collect_members.cc | 16 ++--- src/overpass_api/data/collect_members.h | 91 +++++++++++++++++++----- 2 files changed, 80 insertions(+), 27 deletions(-) diff --git a/src/overpass_api/data/collect_members.cc b/src/overpass_api/data/collect_members.cc index f10438445..6b1d57861 100644 --- a/src/overpass_api/data/collect_members.cc +++ b/src/overpass_api/data/collect_members.cc @@ -947,7 +947,7 @@ void keep_matching_skeletons const std::map< Uint32_Index, std::vector< Attic< Node_Skeleton > > >& attic, uint64 timestamp) { - std::map< Node_Skeleton::Id_Type, uint64 > timestamp_by_id; + Valid_Until_By_Id< Node_Skeleton::Id_Type > timestamp_by_id(timestamp); result.clear(); @@ -955,7 +955,7 @@ void keep_matching_skeletons it != current.end(); ++it) { for (std::vector< Node_Skeleton >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) - timestamp_by_id[it2->id] = NOW; + timestamp_by_id.add_current(it2->id); } for (std::map< Uint32_Index, std::vector< Attic< Node_Skeleton > > >::const_iterator it = attic.begin(); @@ -963,19 +963,17 @@ void keep_matching_skeletons { for (std::vector< Attic >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) - { - uint64& stored_timestamp = timestamp_by_id[it2->id]; - if (it2->timestamp > timestamp && (stored_timestamp == 0 || stored_timestamp > it2->timestamp)) - stored_timestamp = it2->timestamp; - } + timestamp_by_id.add_attic(it2->id, it2->timestamp); } + timestamp_by_id.finish(); + result.reserve(timestamp_by_id.count_valid()); for (std::map< Uint32_Index, std::vector< Node_Skeleton > >::const_iterator it = current.begin(); it != current.end(); ++it) { for (std::vector< Node_Skeleton >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (timestamp_by_id[it2->id] == NOW) + if (timestamp_by_id.get(it2->id) == NOW) result.push_back(Node_Position(it2->id, it->first.val(), it2->ll_lower)); } } @@ -986,7 +984,7 @@ void keep_matching_skeletons for (std::vector< Attic >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (timestamp_by_id[it2->id] == it2->timestamp) + if (timestamp_by_id.get(it2->id) == it2->timestamp) result.push_back(Node_Position(it2->id, it->first.val(), it2->ll_lower)); } } diff --git a/src/overpass_api/data/collect_members.h b/src/overpass_api/data/collect_members.h index bd267cb9b..b875e9403 100644 --- a/src/overpass_api/data/collect_members.h +++ b/src/overpass_api/data/collect_members.h @@ -566,6 +566,67 @@ inline std::vector< Way::Id_Type > relation_way_member_ids } +// For each id, the end of validity of the version valid at a past date: NOW for the current +// version, else the earliest attic timestamp after that date, else 0 (no valid version). +// This is what a std::map< Id_Type, uint64 > filled by the same rules held, in a sorted vector +// of 16-byte entries instead of a tree node of about 48 bytes per id. +template< typename Id_Type > +class Valid_Until_By_Id +{ +public: + Valid_Until_By_Id(uint64 timestamp_) : timestamp(timestamp_), valid_count(0) {} + + void add_current(const Id_Type& id) { entries.push_back(std::make_pair(id, NOW)); } + + // Versions that ended at or before the date can't be the valid one, so they aren't stored: + // an id without entries reads as 0, like an id whose entries are all 0. + void add_attic(const Id_Type& id, uint64 attic_timestamp) + { + if (attic_timestamp > timestamp) + entries.push_back(std::make_pair(id, attic_timestamp)); + } + + // Call once after adding all entries: keeps per id the smallest nonzero value, else 0. + void finish() + { + std::sort(entries.begin(), entries.end()); + typename std::vector< std::pair< Id_Type, uint64 > >::iterator kept = entries.begin(); + typename std::vector< std::pair< Id_Type, uint64 > >::iterator it = entries.begin(); + while (it != entries.end()) + { + typename std::vector< std::pair< Id_Type, uint64 > >::iterator run_end = it; + uint64 valid_until = 0; + while (run_end != entries.end() && run_end->first == it->first) + { + if (valid_until == 0) + valid_until = run_end->second; + ++run_end; + } + if (valid_until != 0) + ++valid_count; + *kept++ = std::make_pair(it->first, valid_until); + it = run_end; + } + entries.erase(kept, entries.end()); + } + + uint64 get(const Id_Type& id) const + { + typename std::vector< std::pair< Id_Type, uint64 > >::const_iterator it = std::lower_bound( + entries.begin(), entries.end(), std::make_pair(id, uint64(0))); + return (it != entries.end() && it->first == id) ? it->second : 0; + } + + // The number of ids that have a valid version, i.e. the number of skeletons kept. + std::size_t count_valid() const { return valid_count; } + +private: + uint64 timestamp; + std::size_t valid_count; + std::vector< std::pair< Id_Type, uint64 > > entries; +}; + + template< typename Index, typename Skeleton > void keep_matching_skeletons (std::map< Index, std::vector< Skeleton > >& current, @@ -578,30 +639,27 @@ void keep_matching_skeletons return; } - std::map< typename Skeleton::Id_Type, uint64 > timestamp_by_id; + Valid_Until_By_Id< typename Skeleton::Id_Type > timestamp_by_id(timestamp); for (auto it = current.begin(); it != current.end(); ++it) { for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) - timestamp_by_id[it2->id] = NOW; + timestamp_by_id.add_current(it2->id); } for (auto it = attic.begin(); it != attic.end(); ++it) { for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) - { - uint64& stored_timestamp = timestamp_by_id[it2->id]; - if (it2->timestamp > timestamp && (stored_timestamp == 0 || stored_timestamp > it2->timestamp)) - stored_timestamp = it2->timestamp; - } + timestamp_by_id.add_attic(it2->id, it2->timestamp); } + timestamp_by_id.finish(); for (auto it = current.begin(); it != current.end(); ++it) { std::vector< Skeleton > local_into; for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (timestamp_by_id[it2->id] == NOW) + if (timestamp_by_id.get(it2->id) == NOW) local_into.push_back(*it2); } local_into.swap(it->second); @@ -612,7 +670,7 @@ void keep_matching_skeletons std::vector< Attic< Skeleton > > local_into; for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (timestamp_by_id[it2->id] == it2->timestamp) + if (timestamp_by_id.get(it2->id) == it2->timestamp) local_into.push_back(*it2); } local_into.swap(it->second); @@ -627,32 +685,29 @@ void keep_matching_skeletons const std::map< Index, std::vector< Attic< Skeleton > > >& attic, uint64 timestamp) { - std::map< typename Skeleton::Id_Type, uint64 > timestamp_by_id; + Valid_Until_By_Id< typename Skeleton::Id_Type > timestamp_by_id(timestamp); result.clear(); for (auto it = current.begin(); it != current.end(); ++it) { for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) - timestamp_by_id[it2->id] = NOW; + timestamp_by_id.add_current(it2->id); } for (auto it = attic.begin(); it != attic.end(); ++it) { for (typename std::vector< Attic< Skeleton > >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) - { - uint64& stored_timestamp = timestamp_by_id[it2->id]; - if (it2->timestamp > timestamp && (stored_timestamp == 0 || stored_timestamp > it2->timestamp)) - stored_timestamp = it2->timestamp; - } + timestamp_by_id.add_attic(it2->id, it2->timestamp); } + timestamp_by_id.finish(); for (auto it = current.begin(); it != current.end(); ++it) { for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (timestamp_by_id[it2->id] == NOW) + if (timestamp_by_id.get(it2->id) == NOW) result[it->first].push_back(Attic< Skeleton >(*it2, NOW)); } } @@ -661,7 +716,7 @@ void keep_matching_skeletons { for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) { - if (timestamp_by_id[it2->id] == it2->timestamp) + if (timestamp_by_id.get(it2->id) == it2->timestamp) result[it->first].push_back(Attic< Skeleton >(*it2, it2->timestamp)); } } From c3e1681b8c60ec3b56402e6659f5d8856c006b26 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 19:45:24 +0000 Subject: [PATCH 25/80] user: keep touched ids for the whole query, whatever their number The previous commit kept the touched ids only for lists of up to 2M ids, so the most prolific users, likely the ones queried most, still had their metadata read twice. Upstream already holds a full id list from get_node_ids while filter builds a second one, so keeping one list costs no more than that for nodes. The way and relation lists are smaller, and the bound is removed. On the Nova Scotia history database, for the user with the most edits in the extract (N their user id): [out:csv(::count)]; nwr(uid_touched:N)(44.60,-63.66,44.70,-63.52); out count; drops from 1.99 s to 1.22 s (it was 2.20 s with the bound). Peak RSS goes from 75.9 to 85.1 MB. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/user.cc | 47 ++--------------------------- 1 file changed, 3 insertions(+), 44 deletions(-) diff --git a/src/overpass_api/statements/user.cc b/src/overpass_api/statements/user.cc index 329572373..e4a21c18c 100644 --- a/src/overpass_api/statements/user.cc +++ b/src/overpass_api/statements/user.cc @@ -57,9 +57,6 @@ class User_Constraint : public Query_Constraint // The ids of the objects the users touched depend only on the users, so they are // the same for the whole query. They are kept after first use and shared by // get_*_ids and filter, which otherwise each read all of the users' metadata. - // Lists longer than max_kept_ids are not kept, so a prolific user's list never - // stays in memory longer than before. - static const std::size_t max_kept_ids = 2*1024*1024; bool node_ids_known = false; bool way_ids_known = false; bool relation_ids_known = false; @@ -70,17 +67,6 @@ class User_Constraint : public Query_Constraint const std::vector< Node_Skeleton::Id_Type >& touched_nodes(Resource_Manager& rman); const std::vector< Way_Skeleton::Id_Type >& touched_ways(Resource_Manager& rman); const std::vector< Relation_Skeleton::Id_Type >& touched_relations(Resource_Manager& rman); - - // Drops a list that is too long to keep, so that it is computed again when needed. - template< typename Id_Type > - static void release_if_large(std::vector< Id_Type >& ids, bool& known) - { - if (ids.size() > max_kept_ids) - { - std::vector< Id_Type >().swap(ids); - known = false; - } - } }; @@ -243,17 +229,14 @@ void User_Constraint::filter(const Statement& query, Resource_Manager& rman, Set Timeless< Uint32_Index, Node_Skeleton >{ into.nodes, into.attic_nodes }.filter_by_id( touched_nodes(rman)) .swap(into.nodes, into.attic_nodes); - release_if_large(touched_node_ids, node_ids_known); if (!into.ways.empty() || !into.attic_ways.empty()) Timeless< Uint31_Index, Way_Skeleton >{ into.ways, into.attic_ways }.filter_by_id( touched_ways(rman)) .swap(into.ways, into.attic_ways); - release_if_large(touched_way_ids, way_ids_known); if (!into.relations.empty() || !into.attic_relations.empty()) Timeless< Uint31_Index, Relation_Skeleton >{ into.relations, into.attic_relations }.filter_by_id( touched_relations(rman)) .swap(into.relations, into.attic_relations); - release_if_large(touched_relation_ids, relation_ids_known); } into.areas.clear(); @@ -480,15 +463,7 @@ bool User_Constraint::get_node_ids(Resource_Manager& rman, std::vector< Node_Ske { if (user->get_criterion() == User_Statement::touched) { - touched_nodes(rman); - if (touched_node_ids.size() > max_kept_ids) - { - // Too long to keep: hand it over, as before this list was kept. - ids.swap(touched_node_ids); - node_ids_known = false; - } - else - ids = touched_node_ids; + ids = touched_nodes(rman); return true; } return false; @@ -499,15 +474,7 @@ bool User_Constraint::get_way_ids(Resource_Manager& rman, std::vector< Way_Skele { if (user->get_criterion() == User_Statement::touched) { - touched_ways(rman); - if (touched_way_ids.size() > max_kept_ids) - { - // Too long to keep: hand it over, as before this list was kept. - ids.swap(touched_way_ids); - way_ids_known = false; - } - else - ids = touched_way_ids; + ids = touched_ways(rman); return true; } return false; @@ -518,15 +485,7 @@ bool User_Constraint::get_relation_ids(Resource_Manager& rman, std::vector< Rela { if (user->get_criterion() == User_Statement::touched) { - touched_relations(rman); - if (touched_relation_ids.size() > max_kept_ids) - { - // Too long to keep: hand it over, as before this list was kept. - ids.swap(touched_relation_ids); - relation_ids_known = false; - } - else - ids = touched_relation_ids; + ids = touched_relations(rman); return true; } return false; From ce7409481b3ef191d2e105cca99414238d26ca42 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 19:44:16 +0000 Subject: [PATCH 26/80] Collect relation node members and way nodes in one pass at past dates Down recursion (>) over relations collected the relations' node members and the ways' nodes in two separate passes over the node blocks, then took the union. The current-data case already does it in one pass. At a past date ([date:], or the old side of [diff:]), it still read every node block twice, current and attic files, and both passes also read the node metadata that attic queries use to check versions. add_nw_member_objects now uses relation_and_way_node_members, which handles attic relations and ways, for dates too, unless a range restriction is given (local). It merges the two id lists and the two range sets, then reads the node blocks once. The final keep_matching_skeletons step picks the version valid at the date, as before. On the Nova Scotia history database: [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; rel[route=hiking]; (._;>;); out count; drops from 1.78 s to 1.13 s, with identical output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/data/collect_members.cc | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/overpass_api/data/collect_members.cc b/src/overpass_api/data/collect_members.cc index 6b1d57861..b6911e784 100644 --- a/src/overpass_api/data/collect_members.cc +++ b/src/overpass_api/data/collect_members.cc @@ -1080,8 +1080,13 @@ void add_nw_member_objects(Request_Context& context, const Set& input_set, Set& return; } - Timeless< Uint32_Index, Node_Skeleton > rel_nodes - = relation_node_members(context, input_set.relations, input_set.attic_relations, ranges_32, {}, true); + // For a date without a range restriction, the relations' node members are collected below, + // in the same pass over the node blocks as the ways' nodes. + bool one_pass = !ranges_32_; + Timeless< Uint32_Index, Node_Skeleton > rel_nodes; + if (!one_pass) + rel_nodes = relation_node_members( + context, input_set.relations, input_set.attic_relations, ranges_32, {}, true); if (context.get_desired_timestamp() == NOW) { @@ -1114,8 +1119,10 @@ void add_nw_member_objects(Request_Context& context, const Set& input_set, Set& indexed_set_union(all_ways.current, source_ways); indexed_set_union(all_ways.attic, source_attic_ways); - Timeless< Uint32_Index, Node_Skeleton > more_nodes - = way_members(context, all_ways.current, all_ways.attic, 0, Ranges< Uint32_Index >::global(), {}, true); + Timeless< Uint32_Index, Node_Skeleton > more_nodes = one_pass + ? relation_and_way_node_members( + context, input_set.relations, input_set.attic_relations, all_ways.current, all_ways.attic) + : way_members(context, all_ways.current, all_ways.attic, 0, Ranges< Uint32_Index >::global(), {}, true); more_nodes.sort(); sort_second(into.nodes); sort_second(into.attic_nodes); From 2cd9448831571da427aebbada14a9044cf849442 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 20:24:20 +0000 Subject: [PATCH 27/80] filter_attic_elements: build and use the timestamps one index at a time filter_attic_elements built the valid-from/valid-until timestamps of every candidate in every index first, then read the attic and current metadata for all indexes, then filtered. All the timestamps were held at once: 24 bytes per candidate, plus growth slack. The metadata files are read with discrete iterators in index order, so the function now walks the indexes in order and, for each, builds that index's timestamps, advances both metadata iterators over that index, filters its current and attic elements, and reuses the vector for the next index. The updates per entry are the same min/max operations, so their order doesn't matter. Current elements that expired before now still move to the index's attic vector, which is created if needed, and are then kept with the same timestamp as before. Peak RSS and CPU (median of alternating runs: 3 per query, 5 for the history benchmark) on a Nova Scotia full-history database, against the sorted-vector version of this function: [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; node(42,-67.6,47.5,-58); out count; 826 MB -> 466 MB, CPU x0.89 (1272 MB on upstream/master) [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; node(44.4,-64.0,45.0,-63.0); node(around:5)[amenity]; out count; 312 MB -> 291 MB, CPU x0.94 The history benchmark queries are unchanged in memory (CPU total x0.98). Outputs are unchanged. The only new allocation is one index's timestamps at a time. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/data/collect_members.h | 155 ++++++++++++------------ 1 file changed, 79 insertions(+), 76 deletions(-) diff --git a/src/overpass_api/data/collect_members.h b/src/overpass_api/data/collect_members.h index b875e9403..3e6d12785 100644 --- a/src/overpass_api/data/collect_members.h +++ b/src/overpass_api/data/collect_members.h @@ -349,110 +349,113 @@ void filter_attic_elements // Confirm elements that are backed by meta data // Update element's expiration timestamp if a meta exists that is older than the current // expiration date and younger than timestamp - // Per index, the entries are sorted by id with one entry per id. A sorted vector takes - // 24 bytes per element where a std::map took a tree node of about 64 bytes. + // The meta files are read in index order, so this works one index at a time: only one + // index's timestamps are held at once. Per index, the entries are sorted by id with one + // entry per id. typedef std::pair< typename Skeleton::Id_Type, std::pair< uint64, uint64 > > Timestamps_Entry; - std::map< Index, std::vector< Timestamps_Entry > > timestamp_by_id_by_idx; - for (typename std::map< Index, std::vector< Skeleton > >::const_iterator it = current.begin(); - it != current.end(); ++it) - { - std::vector< Timestamps_Entry >& entry = timestamp_by_id_by_idx[it->first]; - for (typename std::vector< Skeleton >::const_iterator it2 = it->second.begin(); - it2 != it->second.end(); ++it2) - entry.push_back(Timestamps_Entry(it2->id, std::make_pair(0, NOW))); - } - for (typename std::map< Index, std::vector< Attic< Skeleton > > >::const_iterator it = attic.begin(); - it != attic.end(); ++it) - { - std::vector< Timestamps_Entry >& entry = timestamp_by_id_by_idx[it->first]; - for (typename std::vector< Attic< Skeleton > >::const_iterator it2 = it->second.begin(); - it2 != it->second.end(); ++it2) - entry.push_back(Timestamps_Entry(it2->id, std::make_pair(0, it2->timestamp))); - } - for (typename std::map< Index, std::vector< Timestamps_Entry > >::iterator - it = timestamp_by_id_by_idx.begin(); it != timestamp_by_id_by_idx.end(); ++it) - sort_keeping_last_per_id(it->second); Block_Backend< Index, OSM_Element_Metadata_Skeleton< typename Skeleton::Id_Type >, typename std::vector< Index >::const_iterator > attic_meta_db(rman.get_transaction()->data_index (attic_meta_file_properties< Skeleton >())); - for (auto it = attic_meta_db.discrete_begin(idx_set.begin(), idx_set.end()); - !(it == attic_meta_db.discrete_end()); ++it) - { - std::pair< uint64, uint64 >* tit - = find_timestamps(timestamp_by_id_by_idx[it.index()], it.object().ref); - if (tit) - { - if (timestamp < it.object().timestamp) - tit->second = std::min(tit->second, it.object().timestamp); - else - tit->first = std::max(tit->first, it.object().timestamp); - } - } + auto attic_meta_it = attic_meta_db.discrete_begin(idx_set.begin(), idx_set.end()); - // Same thing with current meta data Block_Backend< Index, OSM_Element_Metadata_Skeleton< typename Skeleton::Id_Type >, typename std::vector< Index >::const_iterator > meta_db(rman.get_transaction()->data_index (current_meta_file_properties< Skeleton >())); + auto meta_it = meta_db.discrete_begin(idx_set.begin(), idx_set.end()); - for (auto it = meta_db.discrete_begin(idx_set.begin(), idx_set.end()); - !(it == meta_db.discrete_end()); ++it) + std::vector< Timestamps_Entry > entry; + for (typename std::vector< Index >::const_iterator idx = idx_set.begin(); idx != idx_set.end(); ++idx) { - std::pair< uint64, uint64 >* tit - = find_timestamps(timestamp_by_id_by_idx[it.index()], it.object().ref); - if (tit) + typename std::map< Index, std::vector< Skeleton > >::iterator cit = current.find(*idx); + typename std::map< Index, std::vector< Attic< Skeleton > > >::iterator ait = attic.find(*idx); + + entry.clear(); + if (cit != current.end()) { - if (timestamp < it.object().timestamp) - tit->second = std::min(tit->second, it.object().timestamp); - else - tit->first = std::max(tit->first, it.object().timestamp); + for (typename std::vector< Skeleton >::const_iterator it2 = cit->second.begin(); + it2 != cit->second.end(); ++it2) + entry.push_back(Timestamps_Entry(it2->id, std::make_pair(0, NOW))); } - } - - // Filter current: only keep elements that have already existed at timestamp - for (typename std::map< Index, std::vector< Skeleton > >::iterator it = current.begin(); - it != current.end(); ++it) - { - std::vector< Skeleton > result; - std::vector< Timestamps_Entry >& entry = timestamp_by_id_by_idx[it->first]; + if (ait != attic.end()) + { + for (typename std::vector< Attic< Skeleton > >::const_iterator it2 = ait->second.begin(); + it2 != ait->second.end(); ++it2) + entry.push_back(Timestamps_Entry(it2->id, std::make_pair(0, it2->timestamp))); + } + sort_keeping_last_per_id(entry); - for (typename std::vector< Skeleton >::const_iterator it2 = it->second.begin(); - it2 != it->second.end(); ++it2) + while (!(attic_meta_it == attic_meta_db.discrete_end()) && attic_meta_it.index() < *idx) + ++attic_meta_it; + for (; !(attic_meta_it == attic_meta_db.discrete_end()) && attic_meta_it.index() == *idx; + ++attic_meta_it) { - const std::pair< uint64, uint64 >* timestamps = find_timestamps(entry, it2->id); - if (timestamps && timestamps->first > 0) + std::pair< uint64, uint64 >* tit = find_timestamps(entry, attic_meta_it.object().ref); + if (tit) { - if (timestamps->second == NOW) - result.push_back(*it2); + if (timestamp < attic_meta_it.object().timestamp) + tit->second = std::min(tit->second, attic_meta_it.object().timestamp); else - attic[it->first].push_back(Attic< Skeleton >(*it2, timestamps->second)); + tit->first = std::max(tit->first, attic_meta_it.object().timestamp); } } - result.swap(it->second); - } - - // Filter attic: only keep elements that have already existed at timestamp - for (typename std::map< Index, std::vector< Attic< Skeleton > > >::iterator it = attic.begin(); - it != attic.end(); ++it) - { - std::vector< Attic< Skeleton > > result; - std::vector< Timestamps_Entry >& entry = timestamp_by_id_by_idx[it->first]; + // Same thing with current meta data + while (!(meta_it == meta_db.discrete_end()) && meta_it.index() < *idx) + ++meta_it; + for (; !(meta_it == meta_db.discrete_end()) && meta_it.index() == *idx; ++meta_it) + { + std::pair< uint64, uint64 >* tit = find_timestamps(entry, meta_it.object().ref); + if (tit) + { + if (timestamp < meta_it.object().timestamp) + tit->second = std::min(tit->second, meta_it.object().timestamp); + else + tit->first = std::max(tit->first, meta_it.object().timestamp); + } + } - for (typename std::vector< Attic< Skeleton > >::const_iterator it2 = it->second.begin(); - it2 != it->second.end(); ++it2) + // Filter current: only keep elements that have already existed at timestamp + if (cit != current.end()) { - const std::pair< uint64, uint64 >* timestamps = find_timestamps(entry, it2->id); - if (timestamps && timestamps->first > 0) + std::vector< Skeleton > result; + for (typename std::vector< Skeleton >::const_iterator it2 = cit->second.begin(); + it2 != cit->second.end(); ++it2) { - result.push_back(*it2); - result.back().timestamp = timestamps->second; + const std::pair< uint64, uint64 >* timestamps = find_timestamps(entry, it2->id); + if (timestamps && timestamps->first > 0) + { + if (timestamps->second == NOW) + result.push_back(*it2); + else + { + if (ait == attic.end()) + ait = attic.insert(std::make_pair(*idx, std::vector< Attic< Skeleton > >())).first; + ait->second.push_back(Attic< Skeleton >(*it2, timestamps->second)); + } + } } + result.swap(cit->second); } - result.swap(it->second); + // Filter attic: only keep elements that have already existed at timestamp + if (ait != attic.end()) + { + std::vector< Attic< Skeleton > > result; + for (typename std::vector< Attic< Skeleton > >::const_iterator it2 = ait->second.begin(); + it2 != ait->second.end(); ++it2) + { + const std::pair< uint64, uint64 >* timestamps = find_timestamps(entry, it2->id); + if (timestamps && timestamps->first > 0) + { + result.push_back(*it2); + result.back().timestamp = timestamps->second; + } + } + result.swap(ait->second); + } } } } From fed254ea1ef52ba613278231fefed211f9d04d29 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 21:16:29 +0000 Subject: [PATCH 28/80] changed: collect only the ids other constraints allow When a query has several constraints, Query_Statement intersects the id lists they return. changed's list came from reading the changelog from the start date to the end date and keeping one id per change, whatever the other constraints allowed. For changed:"T" it holds every change since T, which isn't counted toward [maxsize:]. Query_Constraint gets narrows_by_known_ids() and get_*_ids_within(), whose defaults keep the old behaviour. Query_Statement asks constraints that narrow by known ids after the others, and passes the explicit ids those allow, if any. Changed_Constraint then keeps only changelog ids in that list. It still reads the same changelog entries. Its filter() runs on the collected elements as before, so results don't change. Peak RSS and CPU (median of 5 alternating runs) on a Nova Scotia full-history database, against upstream/master: [out:csv(::count)]; node(id:834791230,904610765)(changed:"2010-10-25T12:15:57Z"); out count; 264 MB -> 8.4 MB, CPU x0.53 (same with the filters in the other order) [out:csv(::count)]; node["amenity"="cafe"](changed:"2010-10-25T12:15:57Z"); out count; 264 MB -> 8.9 MB, CPU x0.58 [out:csv(::count)]; way(id:24000000,25000000,26000000)(changed:"2010-10-25T12:15:57Z"); out count; 24 MB -> 8.4 MB, CPU x0.84 A bounding box gives no ids, so node(bbox)(changed:"T") is unchanged. The benchmark queries are unchanged (CPU totals x0.97 plain, x1.00 history). Outputs are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/statements/changed.cc | 48 +++++++++++++++ src/overpass_api/statements/query.cc | 80 +++++++++++++------------ src/overpass_api/statements/statement.h | 16 +++++ 3 files changed, 105 insertions(+), 39 deletions(-) diff --git a/src/overpass_api/statements/changed.cc b/src/overpass_api/statements/changed.cc index 733294b66..a2197d485 100644 --- a/src/overpass_api/statements/changed.cc +++ b/src/overpass_api/statements/changed.cc @@ -141,6 +141,17 @@ struct Trivial_Id_Predicate }; +template< typename Id_Type > +struct Known_Ids_Predicate +{ + Known_Ids_Predicate(const std::vector< Id_Type >& known_) : known(&known_) {} + bool operator()(Id_Type id) const { return std::binary_search(known->begin(), known->end(), id); } + +private: + const std::vector< Id_Type >* known; +}; + + template< typename Index, typename Skeleton > struct Ids_In_Set_Predicate { @@ -196,6 +207,16 @@ class Changed_Constraint : public Query_Constraint bool get_relation_ids (Resource_Manager& rman, std::vector< Relation_Skeleton::Id_Type >& ids); + // The changelog holds an entry per change, so a full id list can be far larger than the + // explicit ids other constraints allow. + bool narrows_by_known_ids() const { return true; } + bool get_node_ids_within(Resource_Manager& rman, + const std::vector< Node_Skeleton::Id_Type >& known, std::vector< Node_Skeleton::Id_Type >& ids); + bool get_way_ids_within(Resource_Manager& rman, + const std::vector< Way_Skeleton::Id_Type >& known, std::vector< Way_Skeleton::Id_Type >& ids); + bool get_relation_ids_within(Resource_Manager& rman, + const std::vector< Relation_Skeleton::Id_Type >& known, std::vector< Relation_Skeleton::Id_Type >& ids); + void filter(Resource_Manager& rman, Set& into); virtual ~Changed_Constraint() {} @@ -228,6 +249,33 @@ bool Changed_Constraint::get_relation_ids(Resource_Manager& rman, std::vector< R } +bool Changed_Constraint::get_node_ids_within(Resource_Manager& rman, + const std::vector< Node_Skeleton::Id_Type >& known, std::vector< Node_Skeleton::Id_Type >& ids) +{ + ids = collect_changed_elements< Uint32_Index, Node_Skeleton >( + stmt->get_since(rman), stmt->get_until(rman), Known_Ids_Predicate< Node_Skeleton::Id_Type >(known), rman); + return true; +} + + +bool Changed_Constraint::get_way_ids_within(Resource_Manager& rman, + const std::vector< Way_Skeleton::Id_Type >& known, std::vector< Way_Skeleton::Id_Type >& ids) +{ + ids = collect_changed_elements< Uint31_Index, Way_Skeleton >( + stmt->get_since(rman), stmt->get_until(rman), Known_Ids_Predicate< Way_Skeleton::Id_Type >(known), rman); + return true; +} + + +bool Changed_Constraint::get_relation_ids_within(Resource_Manager& rman, + const std::vector< Relation_Skeleton::Id_Type >& known, std::vector< Relation_Skeleton::Id_Type >& ids) +{ + ids = collect_changed_elements< Uint31_Index, Relation_Skeleton >( + stmt->get_since(rman), stmt->get_until(rman), Known_Ids_Predicate< Relation_Skeleton::Id_Type >(known), rman); + return true; +} + + void Changed_Constraint::filter(Resource_Manager& rman, Set& into) { if (!stmt->trivial()) diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index 202496b07..5c19216d6 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -929,6 +929,38 @@ void filter_elems_for_closed_ways(Set& arg) } +// Restricts ids to the ids every constraint allows. Constraints whose id lists are expensive to +// build are asked last and get the explicit ids the others allow, if any, so they can leave out +// the rest. +template< typename Id > +void restrict_to_constraint_ids( + const std::vector< Query_Constraint* >& constraints, Resource_Manager& rman, + bool (Query_Constraint::*get_ids)(Resource_Manager&, std::vector< Id >&), + bool (Query_Constraint::*get_ids_within)(Resource_Manager&, const std::vector< Id >&, std::vector< Id >&), + Id_Constraint< Id >& ids, Answer_State& answer_state) +{ + for (int pass = 0; pass < 2; ++pass) + { + for (std::vector< Query_Constraint* >::const_iterator it = constraints.begin(); + it != constraints.end() && answer_state < data_collected; ++it) + { + if ((*it)->narrows_by_known_ids() != (pass == 1)) + continue; + std::vector< Id > constraint_ids; + bool restricts = (pass == 1 && !ids.invert) + ? ((*it)->*get_ids_within)(rman, ids.ids, constraint_ids) + : ((*it)->*get_ids)(rman, constraint_ids); + if (restricts) + { + ids.restrict_to(constraint_ids); + if (ids.empty()) + answer_state = data_collected; + } + } + } +} + + void Query_Statement::execute(Resource_Manager& rman) { Cpu_Timer cpu(rman, 1); @@ -1018,47 +1050,17 @@ void Query_Statement::execute(Resource_Manager& rman) rman.health_check(*this); if ((type & QUERY_NODE) && check_keys_late == prefer_ranges) - { - for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); - it != constraints.end() && node_answer_state < data_collected; ++it) - { - std::vector< Node::Id_Type > constraint_node_ids; - if ((*it)->get_node_ids(rman, constraint_node_ids)) - { - node_ids.restrict_to(constraint_node_ids); - if (node_ids.empty()) - node_answer_state = data_collected; - } - } - } + restrict_to_constraint_ids< Node::Id_Type >(constraints, rman, + &Query_Constraint::get_node_ids, &Query_Constraint::get_node_ids_within, + node_ids, node_answer_state); if ((type & QUERY_WAY) && check_keys_late == prefer_ranges) - { - for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); - it != constraints.end() && way_answer_state < data_collected; ++it) - { - std::vector< Way::Id_Type > constraint_way_ids; - if ((*it)->get_way_ids(rman, constraint_way_ids)) - { - way_ids.restrict_to(constraint_way_ids); - if (way_ids.empty()) - way_answer_state = data_collected; - } - } - } + restrict_to_constraint_ids< Way::Id_Type >(constraints, rman, + &Query_Constraint::get_way_ids, &Query_Constraint::get_way_ids_within, + way_ids, way_answer_state); if ((type & QUERY_RELATION) && check_keys_late == prefer_ranges) - { - for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); - it != constraints.end() && relation_answer_state < data_collected; ++it) - { - std::vector< Relation::Id_Type > constraint_relation_ids; - if ((*it)->get_relation_ids(rman, constraint_relation_ids)) - { - relation_ids.restrict_to(constraint_relation_ids); - if (relation_ids.empty()) - relation_answer_state = data_collected; - } - } - } + restrict_to_constraint_ids< Relation::Id_Type >(constraints, rman, + &Query_Constraint::get_relation_ids, &Query_Constraint::get_relation_ids_within, + relation_ids, relation_answer_state); if ((type & QUERY_AREA) && check_keys_late == prefer_ranges) { for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); diff --git a/src/overpass_api/statements/statement.h b/src/overpass_api/statements/statement.h index 11d30153f..0f4e75e6d 100644 --- a/src/overpass_api/statements/statement.h +++ b/src/overpass_api/statements/statement.h @@ -101,6 +101,22 @@ class Query_Constraint (Resource_Manager& rman, std::vector< Area_Skeleton::Id_Type >& ids) { return false; } + // A constraint whose id lists are expensive to build returns true. Query_Statement then asks + // it after the other constraints, through the get_*_ids_within functions, and passes the ids + // those allow. + virtual bool narrows_by_known_ids() const { return false; } + // Like get_*_ids, but may leave out ids that aren't in known (sorted), since the caller + // intersects the result with known anyway. The defaults ignore known. + virtual bool get_node_ids_within(Resource_Manager& rman, + const std::vector< Node_Skeleton::Id_Type >& known, std::vector< Node_Skeleton::Id_Type >& ids) + { return get_node_ids(rman, ids); } + virtual bool get_way_ids_within(Resource_Manager& rman, + const std::vector< Way_Skeleton::Id_Type >& known, std::vector< Way_Skeleton::Id_Type >& ids) + { return get_way_ids(rman, ids); } + virtual bool get_relation_ids_within(Resource_Manager& rman, + const std::vector< Relation_Skeleton::Id_Type >& known, std::vector< Relation_Skeleton::Id_Type >& ids) + { return get_relation_ids(rman, ids); } + virtual bool get_data(const Statement& query, Resource_Manager& rman, Set& into, const Ranges< Uint32_Index >& ranges, const std::vector< Node::Id_Type >& ids, From bfe6b2b956ed4bc300b2688d935229017f2168a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 22:21:50 +0000 Subject: [PATCH 29/80] bbox query: collect and filter nodes in chunks at a past date A standalone node(bbox) at a past date loaded every current node and every attic version in the box at once, and only then removed the versions not valid at the date. Those candidates can be much larger than the result. At a past date, Bbox_Query_Statement now collects through Collect_Items in chunks, filters each chunk (bbox and date) and moves its vectors into the result. Chunks end at index boundaries, so an index is normally new to the result; otherwise its elements are appended. Indexes left empty by filtering are kept, as before, since eval_map counts them. At the current date the code path is unchanged: there the candidates are essentially the result. This needs the chunk cap (Collect_Items: cap chunk size, and chunk queries at a past date): before it, collection at a past date never ended a chunk. Peak RSS and CPU (median of 3 alternating runs) on a Nova Scotia full-history database, against the chunk cap alone: [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; node(42,-67.6,47.5,-58); out count; 1243 MB -> 679 MB, CPU x0.86 [date:"2012-01-01T00:00:00Z"][out:csv(::id;false)]; node(42,-67.6,47.5,-58); out ids; 1317 MB -> 587 MB, CPU x0.84 [date:"2021-03-01T00:00:00Z"][out:csv(::id;false)]; node(42,-67.6,47.5,-58); out ids; 1173 MB -> 1101 MB, CPU x0.90 (the result is 11.5 million nodes) Smaller boxes and current-date queries are unchanged. Outputs are unchanged. The only new allocation is one chunk's candidates at a time. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/statements/bbox_query.cc | 49 +++++++++++++++++++++-- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/src/overpass_api/statements/bbox_query.cc b/src/overpass_api/statements/bbox_query.cc index 48e461de1..fd6f88226 100644 --- a/src/overpass_api/statements/bbox_query.cc +++ b/src/overpass_api/statements/bbox_query.cc @@ -224,6 +224,27 @@ const Ranges< Uint31_Index >& Bbox_Query_Statement::get_ranges_31() } +namespace +{ + // Moves the vectors of from into into, keeping indices left empty by filtering, as the + // unchunked path does (eval_map counts them). Chunks end at index boundaries, so an index is + // normally new to into; if not, its elements are appended. + template< typename Index, typename Object > + void move_into(std::map< Index, std::vector< Object > >& into, std::map< Index, std::vector< Object > >& from) + { + for (typename std::map< Index, std::vector< Object > >::iterator it = from.begin(); it != from.end(); ++it) + { + std::vector< Object >& target = into[it->first]; + if (target.empty()) + target.swap(it->second); + else + target.insert(target.end(), it->second.begin(), it->second.end()); + } + from.clear(); + } +} + + void Bbox_Query_Statement::execute(Resource_Manager& rman) { Set into; @@ -231,10 +252,30 @@ void Bbox_Query_Statement::execute(Resource_Manager& rman) Bbox_Constraint constraint(*this); Ranges< Uint32_Index > ranges; constraint.get_ranges(rman, ranges); - get_elements_from_db< Uint32_Index, Node_Skeleton >(ranges, *this, rman) - .swap(into.nodes, into.attic_nodes); - constraint.filter(rman, into); - filter_attic_elements(rman, rman.get_desired_timestamp(), into.nodes, into.attic_nodes); + if (rman.get_desired_timestamp() == NOW) + { + get_elements_from_db< Uint32_Index, Node_Skeleton >(ranges, *this, rman) + .swap(into.nodes, into.attic_nodes); + constraint.filter(rman, into); + filter_attic_elements(rman, rman.get_desired_timestamp(), into.nodes, into.attic_nodes); + } + else + { + // At a past date the candidates include every attic version in the box, far more than the + // result, so they are collected and filtered in chunks. + std::vector< Node_Skeleton::Id_Type > no_ids; + Collect_Items< Uint32_Index, Node_Skeleton > db_reader(no_ids, true, ranges, *this, rman); + Set chunk; + bool more = true; + while (more) + { + more = db_reader.get_chunk(chunk.nodes, chunk.attic_nodes); + constraint.filter(rman, chunk); + filter_attic_elements(rman, rman.get_desired_timestamp(), chunk.nodes, chunk.attic_nodes); + move_into(into.nodes, chunk.nodes); + move_into(into.attic_nodes, chunk.attic_nodes); + } + } transfer_output(rman, into); rman.health_check(*this); From 5741a2d17ef43acc70449fb13b9cc939eac531bf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 21:42:14 +0000 Subject: [PATCH 30/80] around: weight the time-limit check by the work done, and check inside long ways The previous commit checked the query's limits once every 256 candidates. A candidate's cost varies widely, though: testing a way compares each of its points and segments with every point and segment of the input. A few long ways, such as power lines, tested against a large input took seconds each, so a query could run far past its limit without reaching a check, or without reaching 256 candidates at all. The check now counts work: about one unit per comparison of a candidate point or segment with an input point or segment, and health_check runs after every 64k units. is_inside on a way geometry takes the check and ticks it for every point and segment it tests, also for the ways of candidate relations. Fuzz queries run with [timeout:2] that overran it on the previous commit: [timeout:2][maxsize:536870912][out:json]; nwr(poly:'45.022514 -62.084016 45.018789 -62.092687 45.022668 -62.090289 45.018580 -62.117998 45.011347 -62.109236 45.009554 -62.100983') [!"lanes:backward"]->.s0; way.s0(44.767175,-64.509913,45.015063,-64.090581)->.s1; way(around.s0:0)["voltage"~"^6"]->.s2; .s0 out ids 42; .s1 out ids; .s2 out count; stopped after 9.1 s, now after 2.9 s, on the Nova Scotia extract. Queries that finish are unaffected, and their run time is unchanged within noise. On all-changes, which has the around grid, the work per test is capped at 1,024 units: the grid narrows each test to nearby entries, so counting the whole input ran health_check on nearly every candidate and cost 9% on a query around nine large relations. The commit on its own branch, without the grid, has no cap. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/around.cc | 33 ++++++++++++++++++--------- src/overpass_api/statements/around.h | 11 ++++++++- 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index 421777f0d..eb9cd0773 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -253,23 +253,30 @@ void Around_Constraint::filter(Resource_Manager& rman, Set& into) } -/* Checks the query's time and memory limits every few hundred candidates, so that an +/* Checks the query's time and memory limits after every 64k units of work, so that an expensive around filter stops when the query runs out of time instead of running - to completion. health_check throws when a limit is exceeded. */ + to completion. A unit is about one comparison of a candidate's point or segment with + a point or segment of the input. Counting candidates alone isn't enough: a single long + way tested against a large input can take seconds. health_check throws when a limit + is exceeded. */ class Periodic_Health_Check { public: Periodic_Health_Check(Resource_Manager& rman_, const Statement& stmt_) : rman(rman_), stmt(stmt_) {} - void tick() + void tick(uint64 work = 1) { - if (++count % 256 == 0) + work_done += work; + if (work_done >= 64*1024) + { + work_done = 0; rman.health_check(stmt); + } } private: Resource_Manager& rman; const Statement& stmt; - uint32 count = 0; + uint64 work_done = 0; }; @@ -284,7 +291,7 @@ void filter_nodes_expensive(const Around_Statement& around, Periodic_Health_Chec for (typename std::vector< Node_Skeleton >::const_iterator iit = it->second.begin(); iit != it->second.end(); ++iit) { - check.tick(); + check.tick(around.comparisons_per_test()); double lat(::lat(it->first.val(), iit->ll_lower)); double lon(::lon(it->first.val(), iit->ll_lower)); if (around.is_inside(lat, lon)) @@ -307,8 +314,8 @@ void filter_ways_expensive(const Around_Statement& around, Periodic_Health_Check for (typename std::vector< Way_Skeleton >::const_iterator iit = it->second.begin(); iit != it->second.end(); ++iit) { - check.tick(); - if (around.is_inside(way_geometries.get_geometry(*iit))) + check.tick(around.comparisons_per_test()); + if (around.is_inside(way_geometries.get_geometry(*iit), &check)) local_into.push_back(*iit); } it->second.swap(local_into); @@ -333,7 +340,7 @@ void filter_relations_expensive(const Around_Statement& around, Periodic_Health_ for (std::vector< Relation_Entry >::const_iterator nit = iit->members.begin(); nit != iit->members.end(); ++nit) { - check.tick(); + check.tick(around.comparisons_per_test()); if (nit->type == Relation_Entry::NODE) { const std::pair< Uint32_Index, const Node_Skeleton* >* second_nd = @@ -355,7 +362,7 @@ void filter_relations_expensive(const Around_Statement& around, Periodic_Health_ binary_search_for_pair_id(way_members_by_id, nit->ref32()); if (!second_nd) continue; - if (around.is_inside(way_geometries.get_geometry(*second_nd->second))) + if (around.is_inside(way_geometries.get_geometry(*second_nd->second), &check)) { local_into.push_back(*iit); break; @@ -1131,7 +1138,7 @@ bool Around_Statement::is_inside } -bool Around_Statement::is_inside(const std::vector< Quad_Coord >& way_geometry) const +bool Around_Statement::is_inside(const std::vector< Quad_Coord >& way_geometry, Periodic_Health_Check* check) const { std::vector< Quad_Coord >::const_iterator nit = way_geometry.begin(); if (nit == way_geometry.end()) @@ -1143,6 +1150,8 @@ bool Around_Statement::is_inside(const std::vector< Quad_Coord >& way_geometry) double second_lat(::lat(it->ll_upper, it->ll_lower)); double second_lon(::lon(it->ll_upper, it->ll_lower)); + if (check) + check->tick(comparisons_per_test()); if (is_inside(second_lat, second_lon)) return true; } @@ -1155,6 +1164,8 @@ bool Around_Statement::is_inside(const std::vector< Quad_Coord >& way_geometry) double second_lat(::lat(nit->ll_upper, nit->ll_lower)); double second_lon(::lon(nit->ll_upper, nit->ll_lower)); + if (check) + check->tick(comparisons_per_test()); if (is_inside(first_lat, first_lon, second_lat, second_lon)) return true; diff --git a/src/overpass_api/statements/around.h b/src/overpass_api/statements/around.h index 6b8713159..eadab4f51 100644 --- a/src/overpass_api/statements/around.h +++ b/src/overpass_api/statements/around.h @@ -157,6 +157,9 @@ bool Reach_Grid::any(const Box& box, F f) const } +class Periodic_Health_Check; + + class Around_Statement : public Output_Statement { public: @@ -192,7 +195,13 @@ class Around_Statement : public Output_Statement bool is_inside(double lat, double lon) const; bool is_inside(double first_lat, double first_lon, double second_lat, double second_lon) const; - bool is_inside(const std::vector< Quad_Coord >& way_geometry) const; + // With check, ticks it for every point and segment of the way tested. + bool is_inside(const std::vector< Quad_Coord >& way_geometry, Periodic_Health_Check* check = 0) const; + // About how many comparisons testing one point or segment against the input takes. + // The grid (Reach_Grid) narrows a test to nearby entries, so the input's size + // overstates it; the cap keeps the time-limit check from running on every test. + uint64 comparisons_per_test() const + { return std::min< uint64 >(simple_lat_lons.size() + simple_segments.size() + 1, 1024); } double get_radius() const { return radius; } From e9d268b44c18e064df5b366a3c5c435865b33641 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 19:59:56 +0000 Subject: [PATCH 31/80] around: take candidate ranges for relations at a past date from their members The previous commit took around's candidate ranges for current relations in the input set from their members' indexes. Relations at a past date ([date:] and [diff:] queries) still contributed their own index, which for a long route or a boundary covers its whole extent. They now contribute the ranges of the members calc_lat_lons uses for their geometry: their node members and their way members as of the date. Results are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/around.cc | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index eb9cd0773..03cdbe788 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -762,11 +762,19 @@ Ranges< Uint32_Index > Around_Statement::calc_ranges(const Set& input, Resource_ member_way_ranges = ranges(relation_way_members( context, input.relations, {}, Ranges< Uint31_Index >::global(), {}, true).current); } + // The same for relations at a past date, with the members calc_lat_lons uses for them. + if (!input.attic_relations.empty()) + { + Request_Context context(this, rman); + member_node_ranges = member_node_ranges.union_(ranges(relation_node_members( + context, input.attic_relations, relation_node_member_indices({}, input.attic_relations)))); + member_way_ranges = member_way_ranges.union_(ranges(relation_way_members( + context, input.attic_relations, Ranges< Uint31_Index >::global()))); + } return expand( ranges(input.nodes).union_(ranges(input.attic_nodes)).union_(member_node_ranges).union_( calc_children( - ranges(input.ways).union_(ranges(input.attic_ways)).union_( - member_way_ranges.union_(ranges(input.attic_relations))))), + ranges(input.ways).union_(ranges(input.attic_ways)).union_(member_way_ranges))), radius); } } From 36b8967669ca0b7317b07f8f04e6e85641ebfe06 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 20:23:21 +0000 Subject: [PATCH 32/80] around: look up the input relations' members once per input calc_ranges runs several times per execution of an around filter: for the query's candidate ranges, twice in the cheap filter, and up to four times in the exact filter. Since the previous commits, each run looked up the input relations' node and way members to compute their index ranges. On the query below, that was 6 lookups per execution and about a fifth of its run time. The member ranges depend only on which relations are in the input and on the date, so Around_Statement keeps them with those ids, the relations' timestamps at a past date, and the date, and computes them again only when one of those changes. In a foreach loop, a new input relation triggers a new lookup. On the Nova Scotia extract: [out:csv(::count)]; rel(45.566265,-62.428420,45.586924,-62.388716)->.s0; node(around.s0:0)["footway"]; out count; drops from 0.50 s to 0.44 s, with identical output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/around.cc | 52 +++++++++++++++++++++------ src/overpass_api/statements/around.h | 16 +++++++++ 2 files changed, 57 insertions(+), 11 deletions(-) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index 03cdbe788..41f5c16c2 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -748,35 +748,65 @@ Ranges< Uint32_Index > Around_Statement::calc_ranges(const Set& input, Resource_ return expand(calc_children(ranges(ways)), radius); } else + { + Ranges< Uint32_Index > relation_node_ranges; + Ranges< Uint31_Index > relation_way_ranges; + member_ranges(input, rman, relation_node_ranges, relation_way_ranges); + return expand( + ranges(input.nodes).union_(ranges(input.attic_nodes)).union_(relation_node_ranges).union_( + calc_children( + ranges(input.ways).union_(ranges(input.attic_ways)).union_(relation_way_ranges))), + radius); + } +} + + +void Around_Statement::member_ranges(const Set& input, Resource_Manager& rman, + Ranges< Uint32_Index >& node_ranges, Ranges< Uint31_Index >& way_ranges) const +{ + std::vector< Relation_Skeleton::Id_Type > relations; + for (auto it = input.relations.begin(); it != input.relations.end(); ++it) + for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) + relations.push_back(it2->id); + std::vector< std::pair< Relation_Skeleton::Id_Type, uint64 > > attic_relations; + for (auto it = input.attic_relations.begin(); it != input.attic_relations.end(); ++it) + for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2) + attic_relations.push_back(std::make_pair(it2->id, it2->timestamp)); + + if (!member_ranges_known || member_ranges_timestamp != rman.get_desired_timestamp() + || member_ranges_relations != relations || member_ranges_attic_relations != attic_relations) { // The geometry of a relation is that of its direct node and way members (see // calc_lat_lons), so take the ranges from their indexes. A relation's own index // covers its whole extent, which for a long route or a boundary is a large area. - Ranges< Uint32_Index > member_node_ranges; - Ranges< Uint31_Index > member_way_ranges; + Ranges< Uint32_Index > new_node_ranges; + Ranges< Uint31_Index > new_way_ranges; if (!input.relations.empty()) { Request_Context context(this, rman); - member_node_ranges = ranges(relation_node_members( + new_node_ranges = ranges(relation_node_members( context, input.relations, {}, Ranges< Uint32_Index >::global(), {}, true).current); - member_way_ranges = ranges(relation_way_members( + new_way_ranges = ranges(relation_way_members( context, input.relations, {}, Ranges< Uint31_Index >::global(), {}, true).current); } // The same for relations at a past date, with the members calc_lat_lons uses for them. if (!input.attic_relations.empty()) { Request_Context context(this, rman); - member_node_ranges = member_node_ranges.union_(ranges(relation_node_members( + new_node_ranges = new_node_ranges.union_(ranges(relation_node_members( context, input.attic_relations, relation_node_member_indices({}, input.attic_relations)))); - member_way_ranges = member_way_ranges.union_(ranges(relation_way_members( + new_way_ranges = new_way_ranges.union_(ranges(relation_way_members( context, input.attic_relations, Ranges< Uint31_Index >::global()))); } - return expand( - ranges(input.nodes).union_(ranges(input.attic_nodes)).union_(member_node_ranges).union_( - calc_children( - ranges(input.ways).union_(ranges(input.attic_ways)).union_(member_way_ranges))), - radius); + member_node_ranges.swap(new_node_ranges); + member_way_ranges.swap(new_way_ranges); + member_ranges_relations.swap(relations); + member_ranges_attic_relations.swap(attic_relations); + member_ranges_timestamp = rman.get_desired_timestamp(); + member_ranges_known = true; } + node_ranges = member_node_ranges; + way_ranges = member_way_ranges; } diff --git a/src/overpass_api/statements/around.h b/src/overpass_api/statements/around.h index eadab4f51..77d189e5b 100644 --- a/src/overpass_api/statements/around.h +++ b/src/overpass_api/statements/around.h @@ -191,6 +191,22 @@ class Around_Statement : public Output_Statement Ranges< Uint32_Index > calc_ranges(const Set& input_nodes, Resource_Manager& rman) const; + private: + // The index ranges of the input relations' members, which calc_ranges needs. It runs + // several times per execution, so they are kept, together with what they depend on: + // the date, the ids of the current relations, and the ids and timestamps of the + // relations at a past date. + void member_ranges(const Set& input, Resource_Manager& rman, + Ranges< Uint32_Index >& node_ranges, Ranges< Uint31_Index >& way_ranges) const; + mutable bool member_ranges_known = false; + mutable uint64 member_ranges_timestamp = 0; + mutable std::vector< Relation_Skeleton::Id_Type > member_ranges_relations; + mutable std::vector< std::pair< Relation_Skeleton::Id_Type, uint64 > > member_ranges_attic_relations; + mutable Ranges< Uint32_Index > member_node_ranges; + mutable Ranges< Uint31_Index > member_way_ranges; + + public: + void calc_lat_lons(const Set& input_nodes, Statement& query, Resource_Manager& rman); bool is_inside(double lat, double lon) const; From 3a0fdd7d4d1cb62da33a26379e53eaff095cfcf3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 01:10:54 +0000 Subject: [PATCH 33/80] Collect_Items: count elements, not only indexes, in way and relation history collection The way and relation overloads of collect_items_by_timestamp counted one step per index, and the size check runs every 128K steps. An extract with fewer way or relation indexes than that never reached the check, so these collections never ended a chunk at a past date, and the chunk cap didn't apply to them. They now also add each index's element count, so the check runs every 128K or so elements, as in the generic overload. Peak RSS and CPU (median of 3 alternating runs) on a Nova Scotia full-history database, on all-changes without and with this commit: [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; way(42,-67.6,47.5,-58); out count; 444 MB -> 336 MB, CPU x0.82 (706 MB on upstream/master) [date:"2024-09-01T00:00:00Z"][out:csv(::id;false)]; way(42,-67.6,47.5,-58); out ids; 458 MB -> 338 MB, CPU x0.85 The history benchmark queries are unchanged. Outputs are unchanged on every query measured, the history fuzz and a targeted grid. Splitting relations into chunks can remove a false positive of the relation bbox filter at a past date (cldellow/Overpass-API#105): the filter may match a relation on a later version of a member way, but only when another relation in the same set makes that version's index part of the search. A smaller set can only drop such matches, never a correct one, since the version valid at the date is always collected when it lies in the box. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/data/collect_items.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/overpass_api/data/collect_items.h b/src/overpass_api/data/collect_items.h index 52bc19b7c..3cf0ebd7e 100644 --- a/src/overpass_api/data/collect_items.h +++ b/src/overpass_api/data/collect_items.h @@ -337,6 +337,9 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, filter_items_by_timestamp(timestamp_by_id, result[index]); filter_items_by_timestamp(timestamp_by_id, attic_result[index]); + // Count elements, not only indexes, so the size check above runs every 128K or so elements: + // a whole extract can have fewer way or relation indexes than that. + count += result[index].size() + attic_result[index].size(); //check_for_duplicated_objects< Relation_Skeleton >(timestamp_by_id, rman); } @@ -422,6 +425,9 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, filter_items_by_timestamp(timestamp_by_id, result[index]); filter_items_by_timestamp(timestamp_by_id, attic_result[index]); + // Count elements, not only indexes, so the size check above runs every 128K or so elements: + // a whole extract can have fewer way or relation indexes than that. + count += result[index].size() + attic_result[index].size(); //check_for_duplicated_objects< Way_Skeleton >(timestamp_by_id, rman); } From cb088cb907322404208419b74df2ca50fcf059bf Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:15:47 +0000 Subject: [PATCH 34/80] bbox query: count the accumulated result in the chunk loop's size checks Collecting a past-date node(bbox) in chunks made each size check during collection count only the current chunk: the accumulated result is a local Set, not on the runtime stack, so health_check didn't see it until the final check. A query whose result exceeds [maxsize:] still failed, but only after building the whole result in memory. Before chunking, every check counted all candidates and such a query failed early. Pass the result's accounted size as extra space to a health check after each chunk. The final check counts the same data, so no query's outcome changes; queries over the limit fail sooner. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/statements/bbox_query.cc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/overpass_api/statements/bbox_query.cc b/src/overpass_api/statements/bbox_query.cc index fd6f88226..9de0d9ed6 100644 --- a/src/overpass_api/statements/bbox_query.cc +++ b/src/overpass_api/statements/bbox_query.cc @@ -274,6 +274,9 @@ void Bbox_Query_Statement::execute(Resource_Manager& rman) filter_attic_elements(rman, rman.get_desired_timestamp(), chunk.nodes, chunk.attic_nodes); move_into(into.nodes, chunk.nodes); move_into(into.attic_nodes, chunk.attic_nodes); + // into is not on the runtime stack, so count it here: a result over [maxsize:] then fails + // as soon as it is, not after the whole result is built. + rman.health_check(*this, 0, eval_map(into.nodes) + eval_map(into.attic_nodes)); } } From bff1c658f382b477c6c915820dc7ac48275d1884 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 04:06:04 +0000 Subject: [PATCH 35/80] print: reserve the id-sorted element references exactly To print in id order (every out mode except qt), collect_items_by_id puts one reference per element in a vector and sorts it. The vector grew by push_back, so it doubled up to about twice the needed size, and while it grew the old copy existed too. For 11.5 million attic nodes the 24-byte references need 276 MB but peaked at 604 MB. Count the elements first and reserve exactly. The count is one pass over the index map; output is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/statements/print.cc | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/overpass_api/statements/print.cc b/src/overpass_api/statements/print.cc index 9d5e92c6a..c173bb085 100644 --- a/src/overpass_api/statements/print.cc +++ b/src/overpass_api/statements/print.cc @@ -438,11 +438,25 @@ struct Maybe_Attic_Ref }; +// Number of elements in a set, so that the id-sorted references below can be reserved exactly: +// grown by doubling, they reach up to about twice their size, plus the old copy while they grow. +template< class Index, class Object > +std::size_t count_items(const std::map< Index, std::vector< Object > >& items) +{ + std::size_t count = 0; + for (typename std::map< Index, std::vector< Object > >::const_iterator + it(items.begin()); it != items.end(); ++it) + count += it->second.size(); + return count; +} + + template< class Index, class Object > std::vector< std::pair< const Object*, uint32 > > collect_items_by_id( const std::map< Index, std::vector< Object > >& items) { std::vector< std::pair< const Object*, uint32 > > items_by_id; + items_by_id.reserve(count_items(items)); for (typename std::map< Index, std::vector< Object > >::const_iterator it(items.begin()); it != items.end(); ++it) @@ -464,6 +478,7 @@ std::vector< Maybe_Attic_Ref< Index, Object > > collect_items_by_id( const std::map< Index, std::vector< Attic< Object > > >& attic_items) { std::vector< Maybe_Attic_Ref< Index, Object > > items_by_id; + items_by_id.reserve(count_items(items) + count_items(attic_items)); for (typename std::map< Index, std::vector< Object > >::const_iterator it(items.begin()); it != items.end(); ++it) { From 0126a31f6569ba130ca55e859eed47a2aa474b4f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 04:39:22 +0000 Subject: [PATCH 36/80] collect_items_by_timestamp: keep the result size up to date instead of recounting it The previous commit replaced the memory-limit recount in collect_items_range for current data with a running total. collect_items_by_timestamp, which collects objects at a past date, still called eval_map on its whole result maps every 128K objects or indexes. A scan builds an entry for every index it visits, even one without matches, so on wide scans each recount walked hundreds of thousands of entries, and the recounts added up to a fifth of the run time. All three overloads now keep the sizes eval_map would report, updating them with the size change of the current index's entries. The limit check sees the same values as before, so the same queries fail. On the Nova Scotia full-history database: [date:"2018-01-01T00:00:00Z"][out:csv(::count)]; way(42,-67.6,47.5,-58); out count; drops from 20.6 s to 15.0 s, with identical output. On all-changes, the size check is the chunk-cap version of the Collect_Items chunk-cap commit: it compares the sum of the two running sizes with the limit and with the chunk cap, where it summed two eval_map calls before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/data/collect_items.h | 39 ++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/src/overpass_api/data/collect_items.h b/src/overpass_api/data/collect_items.h index 3cf0ebd7e..ec6a20203 100644 --- a/src/overpass_api/data/collect_items.h +++ b/src/overpass_api/data/collect_items.h @@ -254,6 +254,15 @@ void check_for_duplicated_objects( } +// The size eval_map counts for the entry of m at idx, or 0 if m has none. +template< typename Index, typename Object > +uint64 eval_entry(const std::map< Index, std::vector< Object > >& m, const Index& idx) +{ + auto it = m.find(idx); + return it == m.end() ? 0 : eval_index_size + it->second.size()*eval_object_size((const Object*)0); +} + + template < class Index, class Object, class Current_Iterator, class Attic_Iterator, class Predicate > bool collect_items_by_timestamp(Health_Guard&& health_guard, Current_Iterator current_begin, Current_Iterator current_end, @@ -263,6 +272,10 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, std::map< Index, std::vector< Attic< Object > > >& attic_result) { uint32 count = 0; + // The sizes eval_map would report for result and attic_result, kept up to date per index + // instead of recounted: recounting walks the whole maps. + uint64 result_size = eval_map(result); + uint64 attic_size = eval_map(attic_result); while (!(current_begin == current_end) || !(attic_begin == attic_end)) { std::vector< std::pair< typename Object::Id_Type, uint64 > > timestamp_by_id; @@ -271,7 +284,7 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, if (++count >= 128*1024) { count = 0; - uint64 chunk_size = eval_map(result) + eval_map(attic_result); + uint64 chunk_size = result_size + attic_size; too_much_data = health_guard.check(0, chunk_size) || chunk_size >= MAX_CHUNK_ACCOUNTED_SIZE; } Index index = @@ -284,6 +297,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, return true; } + uint64 result_before = eval_entry(result, index); + uint64 attic_before = eval_entry(attic_result, index); reconstruct_items( current_begin, current_end, index, predicate, result[index], timestamp_by_id, timestamp, count); reconstruct_items( @@ -293,6 +308,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, filter_items_by_timestamp(timestamp_by_id, result[index]); filter_items_by_timestamp(timestamp_by_id, attic_result[index]); + result_size += eval_entry(result, index) - result_before; + attic_size += eval_entry(attic_result, index) - attic_before; //check_for_duplicated_objects< Object >(timestamp_by_id, rman); } @@ -309,6 +326,10 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, std::map< Index, std::vector< Attic< Relation_Skeleton > > >& attic_result) { uint32 count = 0; + // The sizes eval_map would report for result and attic_result, kept up to date per index + // instead of recounted: recounting walks the whole maps. + uint64 result_size = eval_map(result); + uint64 attic_size = eval_map(attic_result); while (!(current_begin == current_end) || !(attic_begin == attic_end)) { std::vector< std::pair< Relation_Skeleton::Id_Type, uint64 > > timestamp_by_id; @@ -317,7 +338,7 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, if (++count >= 128*1024) { count = 0; - uint64 chunk_size = eval_map(result) + eval_map(attic_result); + uint64 chunk_size = result_size + attic_size; too_much_data = health_guard.check(0, chunk_size) || chunk_size >= MAX_CHUNK_ACCOUNTED_SIZE; } Index index = @@ -330,6 +351,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, return true; } + uint64 result_before = eval_entry(result, index); + uint64 attic_before = eval_entry(attic_result, index); reconstruct_items(health_guard, current_begin, current_end, attic_begin, attic_end, index, predicate, result[index], attic_result[index], timestamp_by_id, timestamp); @@ -337,6 +360,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, filter_items_by_timestamp(timestamp_by_id, result[index]); filter_items_by_timestamp(timestamp_by_id, attic_result[index]); + result_size += eval_entry(result, index) - result_before; + attic_size += eval_entry(attic_result, index) - attic_before; // Count elements, not only indexes, so the size check above runs every 128K or so elements: // a whole extract can have fewer way or relation indexes than that. count += result[index].size() + attic_result[index].size(); @@ -397,6 +422,10 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, std::map< Index, std::vector< Attic< Way_Skeleton > > >& attic_result) { uint32 count = 0; + // The sizes eval_map would report for result and attic_result, kept up to date per index + // instead of recounted: recounting walks the whole maps. + uint64 result_size = eval_map(result); + uint64 attic_size = eval_map(attic_result); while (!(current_begin == current_end) || !(attic_begin == attic_end)) { std::vector< std::pair< Way_Skeleton::Id_Type, uint64 > > timestamp_by_id; @@ -405,7 +434,7 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, if (++count >= 128*1024) { count = 0; - uint64 chunk_size = eval_map(result) + eval_map(attic_result); + uint64 chunk_size = result_size + attic_size; too_much_data = health_guard.check(0, chunk_size) || chunk_size >= MAX_CHUNK_ACCOUNTED_SIZE; } Index index = @@ -418,6 +447,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, return true; } + uint64 result_before = eval_entry(result, index); + uint64 attic_before = eval_entry(attic_result, index); reconstruct_items(health_guard, current_begin, current_end, attic_begin, attic_end, index, predicate, result[index], attic_result[index], timestamp_by_id, timestamp); @@ -425,6 +456,8 @@ bool collect_items_by_timestamp(Health_Guard&& health_guard, filter_items_by_timestamp(timestamp_by_id, result[index]); filter_items_by_timestamp(timestamp_by_id, attic_result[index]); + result_size += eval_entry(result, index) - result_before; + attic_size += eval_entry(attic_result, index) - attic_before; // Count elements, not only indexes, so the size check above runs every 128K or so elements: // a whole extract can have fewer way or relation indexes than that. count += result[index].size() + attic_result[index].size(); From 90a899ef047a92832171048969e5376412454a47 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 05:40:43 +0000 Subject: [PATCH 37/80] tag_store: remove placeholder tags only from the entries just collected collect_attic_tags collects the tags of objects at a past date for one coarse index, then removes the empty placeholder tags. It did so by walking all of tags_by_id. Tag_Store::prefetch_chunk calls it once per coarse index with the same tags_by_id, which grows over the calls, so each call walked every entry collected so far: quadratic in the number of coarse indexes. It now cleans only the entries it added to. The others were cleaned by the call that added to them, so the result is the same. On the Nova Scotia full-history database: [date:"2018-01-01T00:00:00Z"][out:json]; way[highway]; out geom; drops from 14.3 s to 12.8 s against upstream master, with identical output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/data/tag_store.h | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/overpass_api/data/tag_store.h b/src/overpass_api/data/tag_store.h index d1f565233..458861a02 100644 --- a/src/overpass_api/data/tag_store.h +++ b/src/overpass_api/data/tag_store.h @@ -123,6 +123,10 @@ void collect_attic_tags ++attic_tag_it; } + // The entries of tags_by_id this call adds to. Only these can hold empty placeholder tags + // afterwards: tags_by_id accumulates over the calls for a chunk, and earlier calls removed theirs. + std::vector< std::vector< std::pair< std::string, std::string > >* > touched; + // Actually take for each object and key of the multiple versions only the oldest valid version for (typename std::map< Attic< Id_Type >, std::vector< std::pair< std::string, std::string > > > ::const_iterator @@ -135,6 +139,7 @@ void collect_attic_tags while (it_id != it_id_end) { std::vector< std::pair< std::string, std::string > >& obj_vec = tags_by_id[*it_id]; + touched.push_back(&obj_vec); std::vector< std::pair< std::string, std::string > >::const_iterator last_added_it = it->second.end(); for (std::vector< std::pair< std::string, std::string > >::const_iterator it_source = it->second.begin(); it_source != it->second.end(); ++it_source) @@ -167,17 +172,15 @@ void collect_attic_tags } // Remove empty tags. They are placeholders for tags added later than each timestamp in question. - for (typename std::map< Id_Type, std::vector< std::pair< std::string, std::string > > > - ::iterator - it_obj = tags_by_id.begin(); it_obj != tags_by_id.end(); ++it_obj) + for (auto obj_vec : touched) { for (typename std::vector< std::pair< std::string, std::string > >::size_type - i = 0; i < it_obj->second.size(); ) + i = 0; i < obj_vec->size(); ) { - if (it_obj->second[i].second == void_tag_value()) + if ((*obj_vec)[i].second == void_tag_value()) { - it_obj->second[i] = it_obj->second.back(); - it_obj->second.pop_back(); + (*obj_vec)[i] = obj_vec->back(); + obj_vec->pop_back(); } else ++i; From e2a8b44e0496f781e2280a3b06f0daff17421581 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 05:13:17 +0000 Subject: [PATCH 38/80] Filter bbox and past-date results in place, without vector slack filter_by_bbox and filter_attic_elements built each index's filtered result in a new vector by push_back and swapped it in. The kept vector carried up to twice its size in slack from doubling, and the input vector, itself grown by push_back, briefly existed alongside it. Compact each index's vector in place instead, keeping the order, then shrink it to its size. Kept elements are moved only when their slot changes, so ways and relations no longer copy their member vectors when nothing is removed. Output is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/data/bbox_filter.cc | 14 +++++++++---- src/overpass_api/data/collect_members.h | 28 +++++++++++++++++-------- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/src/overpass_api/data/bbox_filter.cc b/src/overpass_api/data/bbox_filter.cc index 4504dd168..6940e2010 100644 --- a/src/overpass_api/data/bbox_filter.cc +++ b/src/overpass_api/data/bbox_filter.cc @@ -45,8 +45,9 @@ void filter_by_bbox(const Bbox_Double& bbox, std::map< Index, std::vector< Coord for (typename std::map< Index, std::vector< Coord > >::iterator it = nodes.begin(); it != nodes.end(); ++it) { - std::vector< Coord > local_into; - for (typename std::vector< Coord >::const_iterator iit = it->second.begin(); + // Compact in place, keeping the order, and drop the slack left by growing the vector. + typename std::vector< Coord >::iterator out = it->second.begin(); + for (typename std::vector< Coord >::iterator iit = it->second.begin(); iit != it->second.end(); ++iit) { uint32 lat(::ilat(it->first.val(), iit->ll_lower)); @@ -54,9 +55,14 @@ void filter_by_bbox(const Bbox_Double& bbox, std::map< Index, std::vector< Coord if ((lat >= south) && (lat <= north) && (((lon >= west) && (lon <= east)) || ((east < west) && ((lon >= west) || (lon <= east))))) - local_into.push_back(*iit); + { + if (out != iit) + *out = *iit; + ++out; + } } - it->second.swap(local_into); + it->second.erase(out, it->second.end()); + it->second.shrink_to_fit(); } } diff --git a/src/overpass_api/data/collect_members.h b/src/overpass_api/data/collect_members.h index 3e6d12785..ece30d9cc 100644 --- a/src/overpass_api/data/collect_members.h +++ b/src/overpass_api/data/collect_members.h @@ -420,15 +420,20 @@ void filter_attic_elements // Filter current: only keep elements that have already existed at timestamp if (cit != current.end()) { - std::vector< Skeleton > result; - for (typename std::vector< Skeleton >::const_iterator it2 = cit->second.begin(); + // Compact in place, keeping the order, and drop the slack left by growing the vector. + typename std::vector< Skeleton >::iterator out = cit->second.begin(); + for (typename std::vector< Skeleton >::iterator it2 = cit->second.begin(); it2 != cit->second.end(); ++it2) { const std::pair< uint64, uint64 >* timestamps = find_timestamps(entry, it2->id); if (timestamps && timestamps->first > 0) { if (timestamps->second == NOW) - result.push_back(*it2); + { + if (out != it2) + *out = std::move(*it2); + ++out; + } else { if (ait == attic.end()) @@ -437,24 +442,29 @@ void filter_attic_elements } } } - result.swap(cit->second); + cit->second.erase(out, cit->second.end()); + cit->second.shrink_to_fit(); } // Filter attic: only keep elements that have already existed at timestamp if (ait != attic.end()) { - std::vector< Attic< Skeleton > > result; - for (typename std::vector< Attic< Skeleton > >::const_iterator it2 = ait->second.begin(); + // Compact in place, as above. + typename std::vector< Attic< Skeleton > >::iterator out = ait->second.begin(); + for (typename std::vector< Attic< Skeleton > >::iterator it2 = ait->second.begin(); it2 != ait->second.end(); ++it2) { const std::pair< uint64, uint64 >* timestamps = find_timestamps(entry, it2->id); if (timestamps && timestamps->first > 0) { - result.push_back(*it2); - result.back().timestamp = timestamps->second; + if (out != it2) + *out = std::move(*it2); + out->timestamp = timestamps->second; + ++out; } } - result.swap(ait->second); + ait->second.erase(out, ait->second.end()); + ait->second.shrink_to_fit(); } } } From e9eb5dec433f7241a1c6a7dd723b0fb0c292f65a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 05:13:19 +0000 Subject: [PATCH 39/80] Tag_Store: generate the id list once, and keep only a chunk's attic tags Chunked output (tags_by_id, tags_by_id_attic) calls prefetch_chunk for every chunk of 1M nodes or 512k ways or relations, always with the same set. Each call ran generate_ids_by_coarse over the whole set again, appending every id to the lists from earlier chunks and then sorting and deduplicating them: twice the lists' memory and a full sort on every chunk. Generate them on the first call only. The attic overload also never cleared tags_by_id, unlike the current one, so the tags of all earlier chunks stayed in memory, and the pass that removes placeholder tags walked all of them once per coarse index. Clear it at the start of each chunk. Chunks are split by id, so no element's tags are needed in a later chunk. Output is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/data/tag_store.h | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/overpass_api/data/tag_store.h b/src/overpass_api/data/tag_store.h index 458861a02..dd44aabdd 100644 --- a/src/overpass_api/data/tag_store.h +++ b/src/overpass_api/data/tag_store.h @@ -306,8 +306,11 @@ void Tag_Store< Index, Object >::prefetch_chunk(const std::map< Index, std::vect { tags_by_id.clear(); - //generate std::set of relevant coarse indices - generate_ids_by_coarse(ids_by_coarse, elems); + // The coarse indices and ids of the whole set, needed for every chunk. elems is the same set on + // every call, so they are generated once: generating them again appended every id a second + // time before deduplicating, which cost time and twice their memory on each chunk. + if (ids_by_coarse.empty()) + generate_ids_by_coarse(ids_by_coarse, elems); Block_Backend< Tag_Index_Local, typename Object::Id_Type > items_db (transaction->data_index(current_local_tags_file_properties< Object >())); @@ -356,8 +359,10 @@ template< typename Index, typename Object > void Tag_Store< Index, Object >::prefetch_chunk(const std::map< Index, std::vector< Attic< Object > > >& attic_items, typename Object::Id_Type lower_id_bound, typename Object::Id_Type upper_id_bound) { - //generate std::set of relevant coarse indices - generate_ids_by_coarse(attic_ids_by_coarse, attic_items); + // As for current elements: only this chunk's tags are needed, and the ids once. + tags_by_id.clear(); + if (attic_ids_by_coarse.empty()) + generate_ids_by_coarse(attic_ids_by_coarse, attic_items); Block_Backend< Tag_Index_Local, typename Object::Id_Type > current_tags_db (transaction->data_index(current_local_tags_file_properties< Object >())); From 438043becaac3d95e4cf5dd2debab35dac26044e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 14:19:44 +0000 Subject: [PATCH 40/80] area and poly queries: build each way's geometry once in collect_ways Area_Query_Statement::collect_ways and Polygon_Query_Statement::collect_ways built every candidate way's geometry twice, in two consecutive loops over the same ways: once to split it into segment blocks, once to index its coordinates. Each build looks up every node of the way by binary search. The two loops are now one, which builds each geometry once and feeds both. The insertion order into both structures is unchanged. On the Nova Scotia extract with the standard area rules run, against upstream master, in 25 alternating pairs: [out:csv(::count)]; area[name="Halifax Regional Municipality"]->.a; way[building](area.a); out count; takes 5% less CPU (95% CI 4-6%; faster in 24 of 25 pairs), with identical output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/area_query.cc | 8 ++------ src/overpass_api/statements/polygon_query.cc | 10 +++------- 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/src/overpass_api/statements/area_query.cc b/src/overpass_api/statements/area_query.cc index 067a3727a..c5189f545 100644 --- a/src/overpass_api/statements/area_query.cc +++ b/src/overpass_api/statements/area_query.cc @@ -856,19 +856,15 @@ void Area_Query_Statement::collect_ways std::map< Way::Id_Type, bool > ways_inside; + // Build each way's geometry once, for both its segments and its coordinates. std::map< Uint31_Index, std::vector< Area_Block > > way_segments; - for (typename std::map< Uint31_Index, std::vector< Way_Skeleton > >::iterator it = ways.begin(); it != ways.end(); ++it) - { - for (typename std::vector< Way_Skeleton >::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) - add_way_to_area_blocks(way_geometries.get_geometry(*it2), it2->id.val(), way_segments); - } - std::map< uint32, std::vector< std::pair< uint32, Way::Id_Type > > > way_coords_to_id; for (typename std::map< Uint31_Index, std::vector< Way_Skeleton > >::iterator it = ways.begin(); it != ways.end(); ++it) { for (typename std::vector< Way_Skeleton >::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { std::vector< Quad_Coord > coords = way_geometries.get_geometry(*it2); + add_way_to_area_blocks(coords, it2->id.val(), way_segments); for (std::vector< Quad_Coord >::const_iterator it3 = coords.begin(); it3 != coords.end(); ++it3) way_coords_to_id[it3->ll_upper].push_back(std::make_pair(it3->ll_lower, it2->id)); } diff --git a/src/overpass_api/statements/polygon_query.cc b/src/overpass_api/statements/polygon_query.cc index 70184f9f8..c7f2353cd 100644 --- a/src/overpass_api/statements/polygon_query.cc +++ b/src/overpass_api/statements/polygon_query.cc @@ -418,7 +418,9 @@ void Polygon_Query_Statement::collect_ways const Way_Geometry_Store& way_geometries, bool add_border, const Statement& query, Resource_Manager& rman) { + // Build each way's geometry once, for both its coordinates and its segments. std::map< uint32, std::vector< std::pair< uint32, Way::Id_Type > > > way_coords_to_id; + std::map< Uint31_Index, std::vector< Area_Block > > way_segments; for (typename std::map< Uint31_Index, std::vector< Way_Skeleton > >::iterator it = ways.begin(); it != ways.end(); ++it) { for (typename std::vector< Way_Skeleton >::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) @@ -426,6 +428,7 @@ void Polygon_Query_Statement::collect_ways std::vector< Quad_Coord > coords = way_geometries.get_geometry(*it2); for (std::vector< Quad_Coord >::const_iterator it3 = coords.begin(); it3 != coords.end(); ++it3) way_coords_to_id[it3->ll_upper].push_back(std::make_pair(it3->ll_lower, it2->id)); + add_way_to_area_blocks(coords, it2->id.val(), way_segments); } } @@ -433,13 +436,6 @@ void Polygon_Query_Statement::collect_ways std::vector< Aligned_Segment >::const_iterator area_it = segments.begin(); - std::map< Uint31_Index, std::vector< Area_Block > > way_segments; - for (typename std::map< Uint31_Index, std::vector< Way_Skeleton > >::iterator it = ways.begin(); it != ways.end(); ++it) - { - for (typename std::vector< Way_Skeleton >::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) - add_way_to_area_blocks(way_geometries.get_geometry(*it2), it2->id.val(), way_segments); - } - std::map< Way::Id_Type, bool > ways_inside; // Fill node_status with the area related status of each node and segment From 958d3fcd76286446c8ac786b33e28a03aa2e9787 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 15:07:44 +0000 Subject: [PATCH 41/80] tag_store: find tag entries' ids with a forward cursor instead of a binary search collect_tags and collect_tags_framed read every local tag entry of a coarse index and keep those whose object id is in the coarse index's sorted id list. Each entry was checked with a binary search over the whole list. The entries of one tag come in ascending id order, so the lookup now gallops forward from where the previous one ended, and starts over from the beginning when an id isn't greater than the one before the cursor. The result is the same as the binary search for any order of entries. On the Nova Scotia extract, against upstream master, in 25 alternating pairs: [out:xml]; nwr(44.640,-63.590,44.655,-63.570); (._;>;); out meta; takes 9% less CPU (95% CI 6-12%; faster in 23 of 25 pairs), with identical output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/data/tag_store.h | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/overpass_api/data/tag_store.h b/src/overpass_api/data/tag_store.h index dd44aabdd..9b4ba51e6 100644 --- a/src/overpass_api/data/tag_store.h +++ b/src/overpass_api/data/tag_store.h @@ -222,6 +222,24 @@ void collect_attic_tags } +// Whether the sorted ids contain id. cursor is where the previous lookup ended: the tag entries of +// one tag come in ascending id order, so the search gallops forward from there, and starts over +// only when id isn't greater than the id before the cursor. +template< class Id_Type > +bool contains_from_cursor(const std::vector< Id_Type >& ids, + typename std::vector< Id_Type >::const_iterator& cursor, const Id_Type& id) +{ + if (cursor != ids.begin() && !(*(cursor - 1) < id)) + cursor = ids.begin(); + typename std::vector< Id_Type >::size_type remaining = ids.end() - cursor; + typename std::vector< Id_Type >::size_type bound = 1; + while (bound < remaining && cursor[bound] < id) + bound *= 2; + cursor = std::lower_bound(cursor + bound/2, cursor + std::min(bound, remaining), id); + return cursor != ids.end() && !(id < *cursor); +} + + template< class Id_Type > void collect_tags (std::map< Id_Type, std::vector< std::pair< std::string, std::string > > >& tags_by_id, @@ -229,13 +247,14 @@ void collect_tags typename Block_Backend< Tag_Index_Local, Id_Type >::Range_Iterator& tag_it, const std::vector< Id_Type >& ids, uint32 coarse_index) { + typename std::vector< Id_Type >::const_iterator cursor = ids.begin(); while ((!(tag_it == items_db.range_end())) && (((tag_it.index().index) & 0x7fffff00) < coarse_index)) ++tag_it; while ((!(tag_it == items_db.range_end())) && (((tag_it.index().index) & 0x7fffff00) == coarse_index)) { - if ((binary_search(ids.begin(), ids.end(), tag_it.object()))) + if (contains_from_cursor(ids, cursor, tag_it.object())) tags_by_id[tag_it.object()].push_back (std::make_pair(tag_it.index().key, tag_it.index().value)); ++tag_it; @@ -252,6 +271,8 @@ void collect_tags_framed uint32 coarse_index, Id_Type lower_id_bound, Id_Type upper_id_bound) { + const std::vector< Id_Type >& ids = ids_by_coarse[coarse_index]; + typename std::vector< Id_Type >::const_iterator cursor = ids.begin(); while ((!(tag_it == items_db.range_end())) && (((tag_it.index().index) & 0x7fffff00) < coarse_index)) ++tag_it; @@ -260,8 +281,7 @@ void collect_tags_framed { if (!(tag_it.object() < lower_id_bound) && (tag_it.object() < upper_id_bound) && - (binary_search(ids_by_coarse[coarse_index].begin(), - ids_by_coarse[coarse_index].end(), tag_it.object()))) + contains_from_cursor(ids, cursor, tag_it.object())) tags_by_id[tag_it.object()].push_back (std::make_pair(tag_it.index().key, tag_it.index().value)); ++tag_it; From 7e235b15b179d57669ff266f477daf10f9c2a2a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 14:16:06 +0000 Subject: [PATCH 42/80] Tag_Store: keep only a chunk's ids when printing in chunks Chunked output (tags_by_id, tags_by_id_attic) prints 1M nodes or 512k ways or relations at a time, and prefetch_chunk loads only that chunk's tags. It still kept the ids of the whole set, per coarse index, and filtered them by the chunk's id bounds while collecting. On a whole- province `out` of 12.6M nodes these lists were 145 MB of the peak. Generate them per chunk from the elements within the bounds instead. They then hold at most one chunk's ids, and the tag range query covers only the coarse indices that have elements in the chunk. Output is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/core/type_tags.h | 55 +++++++++++++++++++++++++++++++ src/overpass_api/data/tag_store.h | 14 ++++---- 2 files changed, 61 insertions(+), 8 deletions(-) diff --git a/src/overpass_api/core/type_tags.h b/src/overpass_api/core/type_tags.h index bc3cdf0f6..e3e03be2e 100644 --- a/src/overpass_api/core/type_tags.h +++ b/src/overpass_api/core/type_tags.h @@ -325,6 +325,61 @@ void generate_ids_by_coarse } +// As generate_ids_by_coarse, but only for the elements with ids in [lower_id_bound, upper_id_bound), +// so that a chunk of output needs the ids of that chunk only. +template< class TIndex, class TObject > +void generate_ids_by_coarse + (std::map< uint32, std::vector< typename TObject::Id_Type > >& ids_by_coarse, + const std::map< TIndex, std::vector< TObject > >& items, + typename TObject::Id_Type lower_id_bound, typename TObject::Id_Type upper_id_bound) +{ + for (typename std::map< TIndex, std::vector< TObject > >::const_iterator + it(items.begin()); it != items.end(); ++it) + { + for (typename std::vector< TObject >::const_iterator it2(it->second.begin()); + it2 != it->second.end(); ++it2) + { + if (!(it2->id < lower_id_bound) && it2->id < upper_id_bound) + ids_by_coarse[it->first.val() & 0x7fffff00].push_back(it2->id); + } + } + + for (typename std::map< uint32, std::vector< typename TObject::Id_Type > >::iterator + it = ids_by_coarse.begin(); it != ids_by_coarse.end(); ++it) + { + std::sort(it->second.begin(), it->second.end()); + it->second.erase(std::unique(it->second.begin(), it->second.end()), it->second.end()); + } +} + + +template< class TIndex, class TObject > +void generate_ids_by_coarse + (std::map< uint32, std::vector< Attic< typename TObject::Id_Type > > >& ids_by_coarse, + const std::map< TIndex, std::vector< TObject > >& items, + typename TObject::Id_Type lower_id_bound, typename TObject::Id_Type upper_id_bound) +{ + for (typename std::map< TIndex, std::vector< TObject > >::const_iterator + it(items.begin()); it != items.end(); ++it) + { + for (typename std::vector< TObject >::const_iterator it2(it->second.begin()); + it2 != it->second.end(); ++it2) + { + if (!(it2->id < lower_id_bound) && it2->id < upper_id_bound) + ids_by_coarse[it->first.val() & 0x7fffff00].push_back + (Attic< typename TObject::Id_Type >(it2->id, it2->timestamp)); + } + } + + for (typename std::map< uint32, std::vector< Attic< typename TObject::Id_Type > > >::iterator + it = ids_by_coarse.begin(); it != ids_by_coarse.end(); ++it) + { + std::sort(it->second.begin(), it->second.end()); + it->second.erase(std::unique(it->second.begin(), it->second.end()), it->second.end()); + } +} + + struct Tag_Index_Global_Until756 { std::string key; diff --git a/src/overpass_api/data/tag_store.h b/src/overpass_api/data/tag_store.h index 9b4ba51e6..904cc90c0 100644 --- a/src/overpass_api/data/tag_store.h +++ b/src/overpass_api/data/tag_store.h @@ -326,11 +326,9 @@ void Tag_Store< Index, Object >::prefetch_chunk(const std::map< Index, std::vect { tags_by_id.clear(); - // The coarse indices and ids of the whole set, needed for every chunk. elems is the same set on - // every call, so they are generated once: generating them again appended every id a second - // time before deduplicating, which cost time and twice their memory on each chunk. - if (ids_by_coarse.empty()) - generate_ids_by_coarse(ids_by_coarse, elems); + // The coarse indices and ids of this chunk's elements only: no other tags are collected. + ids_by_coarse.clear(); + generate_ids_by_coarse(ids_by_coarse, elems, lower_id_bound, upper_id_bound); Block_Backend< Tag_Index_Local, typename Object::Id_Type > items_db (transaction->data_index(current_local_tags_file_properties< Object >())); @@ -379,10 +377,10 @@ template< typename Index, typename Object > void Tag_Store< Index, Object >::prefetch_chunk(const std::map< Index, std::vector< Attic< Object > > >& attic_items, typename Object::Id_Type lower_id_bound, typename Object::Id_Type upper_id_bound) { - // As for current elements: only this chunk's tags are needed, and the ids once. + // As for current elements: only this chunk's tags and ids are needed. tags_by_id.clear(); - if (attic_ids_by_coarse.empty()) - generate_ids_by_coarse(attic_ids_by_coarse, attic_items); + attic_ids_by_coarse.clear(); + generate_ids_by_coarse(attic_ids_by_coarse, attic_items, lower_id_bound, upper_id_bound); Block_Backend< Tag_Index_Local, typename Object::Id_Type > current_tags_db (transaction->data_index(current_local_tags_file_properties< Object >())); From df835cf1e774c46945098dc2047792436f33f271 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 14:46:36 +0000 Subject: [PATCH 43/80] print: reference id-sorted elements in 8 bytes To print in id order, every out mode except qt puts one reference per element in a vector and sorts it. A reference was a pointer and the element's index, 16 bytes, or 24 when the set has attic elements, which also carried the element's timestamp. For an out of 11.5M nodes at a past date that was 277 MB. Reference each element instead by the number of its index's entry in a table of the set's non-empty vectors, current ones first, and its position in that vector: two 32-bit numbers. The index, the object and the timestamp of an attic element are read from the table and the set. The references are filled in the same order as before and sorted with the same std::sort by id, so elements with equal ids stay in the same order. Output is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/statements/print.cc | 180 ++++++++++++++------------- 1 file changed, 94 insertions(+), 86 deletions(-) diff --git a/src/overpass_api/statements/print.cc b/src/overpass_api/statements/print.cc index c173bb085..c8955119d 100644 --- a/src/overpass_api/statements/print.cc +++ b/src/overpass_api/statements/print.cc @@ -413,31 +413,6 @@ void tags_quadtile_attic_ } -template< class TComp > -struct Skeleton_Comparator_By_Id { - bool operator() (const std::pair< const TComp*, uint32 >& a, - const std::pair< const TComp*, uint32 >& b) - { - return (a.first->id < b.first->id); - } -}; - - -template< typename Index, typename Object > -struct Maybe_Attic_Ref -{ -public: - Maybe_Attic_Ref(Index idx_, const Object* obj_, uint64 timestamp_) - : idx(idx_), obj(obj_), timestamp(timestamp_) {} - - Index idx; - const Object* obj; - uint64 timestamp; - - bool operator<(const Maybe_Attic_Ref& rhs) const { return obj->id < rhs.obj->id; } -}; - - // Number of elements in a set, so that the id-sorted references below can be reserved exactly: // grown by doubling, they reach up to about twice their size, plus the old copy while they grow. template< class Index, class Object > @@ -451,52 +426,85 @@ std::size_t count_items(const std::map< Index, std::vector< Object > >& items) } +// The elements of a set in id order, current elements and then attic elements for equal ids as +// std::sort leaves them. Each element is referenced in 8 bytes: the number of its index's entry in a +// table of the set's non-empty vectors, current ones first, and its position in that vector. A +// pointer and an index took 16 bytes per element, and 24 with the timestamp of an attic element. template< class Index, class Object > -std::vector< std::pair< const Object*, uint32 > > collect_items_by_id( - const std::map< Index, std::vector< Object > >& items) +class Items_By_Id { - std::vector< std::pair< const Object*, uint32 > > items_by_id; - items_by_id.reserve(count_items(items)); +public: + Items_By_Id(const std::map< Index, std::vector< Object > >& items) + { + refs.reserve(count_items(items)); + add_entries(current, items); + sort_refs(); + } - for (typename std::map< Index, std::vector< Object > >::const_iterator - it(items.begin()); it != items.end(); ++it) + Items_By_Id(const std::map< Index, std::vector< Object > >& items, + const std::map< Index, std::vector< Attic< Object > > >& attic_items) { - for (typename std::vector< Object >::const_iterator it2(it->second.begin()); - it2 != it->second.end(); ++it2) - items_by_id.push_back(std::make_pair(&(*it2), it->first.val())); + refs.reserve(count_items(items) + count_items(attic_items)); + add_entries(current, items); + add_entries(attic, attic_items); + sort_refs(); } - sort(items_by_id.begin(), items_by_id.end(), - Skeleton_Comparator_By_Id< Object >()); - return items_by_id; -} + std::size_t size() const { return refs.size(); } + const Object& obj(std::size_t i) const { return get(refs[i]); } + Index idx(std::size_t i) const + { + return refs[i].entry < current.size() ? current[refs[i].entry].first + : attic[refs[i].entry - current.size()].first; + } + // NOW for a current element. + uint64 timestamp(std::size_t i) const + { + return refs[i].entry < current.size() ? NOW + : attic[refs[i].entry - current.size()].second[refs[i].pos].timestamp; + } +private: + struct Ref + { + Ref(uint32 entry_, uint32 pos_) : entry(entry_), pos(pos_) {} + uint32 entry; + uint32 pos; + }; -template< class Index, class Object > -std::vector< Maybe_Attic_Ref< Index, Object > > collect_items_by_id( - const std::map< Index, std::vector< Object > >& items, - const std::map< Index, std::vector< Attic< Object > > >& attic_items) -{ - std::vector< Maybe_Attic_Ref< Index, Object > > items_by_id; - items_by_id.reserve(count_items(items) + count_items(attic_items)); - for (typename std::map< Index, std::vector< Object > >::const_iterator - it(items.begin()); it != items.end(); ++it) + std::vector< std::pair< Index, const Object* > > current; + std::vector< std::pair< Index, const Attic< Object >* > > attic; + std::vector< Ref > refs; + + const Object& get(const Ref& ref) const { - for (typename std::vector< Object >::const_iterator it2(it->second.begin()); - it2 != it->second.end(); ++it2) - items_by_id.push_back(Maybe_Attic_Ref< Index, Object >(it->first, &(*it2), NOW)); + return ref.entry < current.size() ? current[ref.entry].second[ref.pos] + : attic[ref.entry - current.size()].second[ref.pos]; } - for (typename std::map< Index, std::vector< Attic< Object > > >::const_iterator - it(attic_items.begin()); it != attic_items.end(); ++it) + + // Appends the references in the order of the set, as before, so that equal ids keep their order. + template< class Elem > + void add_entries(std::vector< std::pair< Index, const Elem* > >& entries, + const std::map< Index, std::vector< Elem > >& items) { - for (typename std::vector< Attic< Object > >::const_iterator it2(it->second.begin()); - it2 != it->second.end(); ++it2) - items_by_id.push_back(Maybe_Attic_Ref< Index, Object >(it->first, &(*it2), it2->timestamp)); + for (typename std::map< Index, std::vector< Elem > >::const_iterator + it(items.begin()); it != items.end(); ++it) + { + if (it->second.empty()) + continue; + uint32 entry = current.size() + attic.size(); + entries.push_back(std::make_pair(it->first, &it->second.front())); + for (uint32 pos = 0; pos < it->second.size(); ++pos) + refs.push_back(Ref(entry, pos)); + } } - sort(items_by_id.begin(), items_by_id.end()); - return items_by_id; -} + void sort_refs() + { + std::sort(refs.begin(), refs.end(), + [this](const Ref& a, const Ref& b) { return get(a).id < get(b).id; }); + } +}; template< class Index, class Object > @@ -504,14 +512,14 @@ void by_id (const std::map< Index, std::vector< Object > >& items, Output_Handler& output, Transaction& transaction, Extra_Data& extra_data, uint32 limit, uint32& element_count) { - std::vector< std::pair< const Object*, uint32 > > items_by_id = collect_items_by_id(items); + Items_By_Id< Index, Object > items_by_id(items); // iterate over the result for (uint32 i(0); i < items_by_id.size(); ++i) { if (++element_count > limit) return; - print_item(extra_data, output, items_by_id[i].second, *(items_by_id[i].first)); + print_item(extra_data, output, items_by_id.idx(i).val(), items_by_id.obj(i)); } } @@ -523,18 +531,18 @@ void by_id Output_Handler& output, Transaction& transaction, Extra_Data& extra_data, uint32 limit, uint32& element_count) { - std::vector< Maybe_Attic_Ref< Index, Object > > items_by_id = collect_items_by_id(items, attic_items); + Items_By_Id< Index, Object > items_by_id(items, attic_items); // iterate over the result for (uint32 i(0); i < items_by_id.size(); ++i) { if (++element_count > limit) return; - if (items_by_id[i].timestamp == NOW) - print_item(extra_data, output, items_by_id[i].idx.val(), *items_by_id[i].obj); + if (items_by_id.timestamp(i) == NOW) + print_item(extra_data, output, items_by_id.idx(i).val(), items_by_id.obj(i)); else - print_item(extra_data, output, items_by_id[i].idx.val(), - Attic< Object >(*items_by_id[i].obj, items_by_id[i].timestamp)); + print_item(extra_data, output, items_by_id.idx(i).val(), + Attic< Object >(items_by_id.obj(i), items_by_id.timestamp(i))); } } @@ -612,7 +620,7 @@ void tags_by_id Resource_Manager& rman, Meta_Collector< Index, typename Object::Id_Type >* meta_printer, Tag_Store< Index, Object >& tag_store, uint32 limit, uint32& element_count) { - std::vector< std::pair< const Object*, uint32 > > items_by_id = collect_items_by_id(items); + Items_By_Id< Index, Object > items_by_id(items); // iterate over the result for (typename Object::Id_Type id_pos; id_pos < items_by_id.size(); id_pos += FLUSH_SIZE) @@ -620,13 +628,13 @@ void tags_by_id // Disable health_check: This ensures that a result will be always printed completely //rman.health_check(*this); - typename Object::Id_Type lower_id_bound(items_by_id[id_pos.val()].first->id); + typename Object::Id_Type lower_id_bound(items_by_id.obj(id_pos.val()).id); typename Object::Id_Type upper_id_bound; if (id_pos + FLUSH_SIZE < items_by_id.size()) - upper_id_bound = items_by_id[(id_pos + FLUSH_SIZE).val()].first->id; + upper_id_bound = items_by_id.obj((id_pos + FLUSH_SIZE).val()).id; else { - upper_id_bound = items_by_id[items_by_id.size()-1].first->id; + upper_id_bound = items_by_id.obj(items_by_id.size()-1).id; ++upper_id_bound; } @@ -648,10 +656,10 @@ void tags_by_id return; typename std::set< OSM_Element_Metadata_Skeleton< typename Object::Id_Type > >::const_iterator meta_it = metadata.lower_bound(OSM_Element_Metadata_Skeleton< typename Object::Id_Type > - (items_by_id[i.val()].first->id)); - print_item(extra_data, output, items_by_id[i.val()].second, *(items_by_id[i.val()].first), - tag_store.get(Index(items_by_id[i.val()].second), *items_by_id[i.val()].first), - (meta_it != metadata.end() && meta_it->ref == items_by_id[i.val()].first->id) ? + (items_by_id.obj(i.val()).id)); + print_item(extra_data, output, items_by_id.idx(i.val()).val(), items_by_id.obj(i.val()), + tag_store.get(items_by_id.idx(i.val()), items_by_id.obj(i.val())), + (meta_it != metadata.end() && meta_it->ref == items_by_id.obj(i.val()).id) ? &*meta_it : 0); } } @@ -666,7 +674,7 @@ void tags_by_id_attic Extra_Data& extra_data, uint32 FLUSH_SIZE, Output_Handler& output, Resource_Manager& rman, Transaction& transaction, uint32 limit, uint32& element_count) { - std::vector< Maybe_Attic_Ref< Index, Object > > items_by_id = collect_items_by_id(current_items, attic_items); + Items_By_Id< Index, Object > items_by_id(current_items, attic_items); Tag_Store< Index, Object > current_tag_store(transaction); Tag_Store< Index, Object > attic_tag_store(transaction); @@ -681,13 +689,13 @@ void tags_by_id_attic // Disable health_check: This ensures that a result will be always printed completely //rman.health_check(*this); - typename Object::Id_Type lower_id_bound(items_by_id[id_pos.val()].obj->id); + typename Object::Id_Type lower_id_bound(items_by_id.obj(id_pos.val()).id); typename Object::Id_Type upper_id_bound; if (id_pos + FLUSH_SIZE < items_by_id.size()) - upper_id_bound = items_by_id[(id_pos + FLUSH_SIZE).val()].obj->id; + upper_id_bound = items_by_id.obj((id_pos + FLUSH_SIZE).val()).id; else { - upper_id_bound = items_by_id[items_by_id.size()-1].obj->id; + upper_id_bound = items_by_id.obj(items_by_id.size()-1).id; ++upper_id_bound; } @@ -710,24 +718,24 @@ void tags_by_id_attic { if (++element_count > limit) return; - if (items_by_id[i.val()].timestamp == NOW) + if (items_by_id.timestamp(i.val()) == NOW) { typename std::set< OSM_Element_Metadata_Skeleton< typename Object::Id_Type > >::const_iterator meta_it = only_current_metadata.lower_bound(OSM_Element_Metadata_Skeleton< typename Object::Id_Type > - (items_by_id[i.val()].obj->id)); - print_item(extra_data, output, items_by_id[i.val()].idx.val(), *items_by_id[i.val()].obj, - current_tag_store.get(items_by_id[i.val()].idx, *items_by_id[i.val()].obj), - (meta_it != only_current_metadata.end() && meta_it->ref == items_by_id[i.val()].obj->id) ? + (items_by_id.obj(i.val()).id)); + print_item(extra_data, output, items_by_id.idx(i.val()).val(), items_by_id.obj(i.val()), + current_tag_store.get(items_by_id.idx(i.val()), items_by_id.obj(i.val())), + (meta_it != only_current_metadata.end() && meta_it->ref == items_by_id.obj(i.val()).id) ? &*meta_it : 0); } else { typename std::set< OSM_Element_Metadata_Skeleton< typename Object::Id_Type > >::const_iterator meta_it = find_matching_metadata(attic_metadata, - items_by_id[i.val()].obj->id, items_by_id[i.val()].timestamp); - print_item(extra_data, output, items_by_id[i.val()].idx.val(), - Attic< Object >(*items_by_id[i.val()].obj, items_by_id[i.val()].timestamp), - attic_tag_store.get(items_by_id[i.val()].idx, *items_by_id[i.val()].obj), + items_by_id.obj(i.val()).id, items_by_id.timestamp(i.val())); + print_item(extra_data, output, items_by_id.idx(i.val()).val(), + Attic< Object >(items_by_id.obj(i.val()), items_by_id.timestamp(i.val())), + attic_tag_store.get(items_by_id.idx(i.val()), items_by_id.obj(i.val())), meta_it != attic_metadata.end() ? &*meta_it : 0); } } From f89c5c93ff2fc8aceb6367478a064c1ba8b300df Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 17:15:25 +0000 Subject: [PATCH 44/80] print: look up current and attic references the same way The 8-byte references kept current and attic vectors in two tables, so every comparison in the sort branched on the kind of element. Keep one table instead, with each vector's first element (its Object part) and the size of its elements, and find an element by its position times that size. On a whole-province out ids of 12.6M current nodes this takes the sort's extra cost from about 10% of the query's CPU to about 1%, and to about 7% for 11.5M nodes at a past date. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/overpass_api/statements/print.cc | 45 +++++++++++++++++----------- 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/src/overpass_api/statements/print.cc b/src/overpass_api/statements/print.cc index c8955119d..f92f05c3e 100644 --- a/src/overpass_api/statements/print.cc +++ b/src/overpass_api/statements/print.cc @@ -437,7 +437,8 @@ class Items_By_Id Items_By_Id(const std::map< Index, std::vector< Object > >& items) { refs.reserve(count_items(items)); - add_entries(current, items); + add_entries(items); + current_count = entries.size(); sort_refs(); } @@ -445,23 +446,20 @@ class Items_By_Id const std::map< Index, std::vector< Attic< Object > > >& attic_items) { refs.reserve(count_items(items) + count_items(attic_items)); - add_entries(current, items); - add_entries(attic, attic_items); + add_entries(items); + current_count = entries.size(); + add_entries(attic_items); sort_refs(); } std::size_t size() const { return refs.size(); } const Object& obj(std::size_t i) const { return get(refs[i]); } - Index idx(std::size_t i) const - { - return refs[i].entry < current.size() ? current[refs[i].entry].first - : attic[refs[i].entry - current.size()].first; - } + Index idx(std::size_t i) const { return entries[refs[i].entry].idx; } // NOW for a current element. uint64 timestamp(std::size_t i) const { - return refs[i].entry < current.size() ? NOW - : attic[refs[i].entry - current.size()].second[refs[i].pos].timestamp; + return refs[i].entry < current_count ? NOW + : static_cast< const Attic< Object >& >(get(refs[i])).timestamp; } private: @@ -472,28 +470,39 @@ class Items_By_Id uint32 pos; }; - std::vector< std::pair< Index, const Object* > > current; - std::vector< std::pair< Index, const Attic< Object >* > > attic; + // The address of the Object part of the vector's first element, and the size of its elements: + // that of Object for current elements, of Attic< Object > for attic elements. Looking up both + // kinds the same way keeps the sort's comparisons free of branches. + struct Entry + { + Entry(const char* first_, uint32 size_, Index idx_) : first(first_), size(size_), idx(idx_) {} + const char* first; + uint32 size; + Index idx; + }; + + std::vector< Entry > entries; + std::size_t current_count; std::vector< Ref > refs; const Object& get(const Ref& ref) const { - return ref.entry < current.size() ? current[ref.entry].second[ref.pos] - : attic[ref.entry - current.size()].second[ref.pos]; + const Entry& entry = entries[ref.entry]; + return *reinterpret_cast< const Object* >(entry.first + std::size_t(ref.pos) * entry.size); } // Appends the references in the order of the set, as before, so that equal ids keep their order. template< class Elem > - void add_entries(std::vector< std::pair< Index, const Elem* > >& entries, - const std::map< Index, std::vector< Elem > >& items) + void add_entries(const std::map< Index, std::vector< Elem > >& items) { for (typename std::map< Index, std::vector< Elem > >::const_iterator it(items.begin()); it != items.end(); ++it) { if (it->second.empty()) continue; - uint32 entry = current.size() + attic.size(); - entries.push_back(std::make_pair(it->first, &it->second.front())); + uint32 entry = entries.size(); + const Object& first = it->second.front(); + entries.push_back(Entry(reinterpret_cast< const char* >(&first), sizeof(Elem), it->first)); for (uint32 pos = 0; pos < it->second.size(); ++pos) refs.push_back(Ref(entry, pos)); } From ea395d14568d80b373205ed9942f584f6d1bffe9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 04:47:37 +0000 Subject: [PATCH 45/80] query: narrow ranges to the candidates' cells inside them, not all candidates When tag filters select candidate ids from the global tag index, each id comes with its coarse index (256 tiles), and intersect_ranges narrows the query's ranges to the candidates' cells. It skipped that whenever the candidates outnumbered the cells the ranges span. But the candidates are every match in the database, and many share a cell, so the test skipped the narrowing for any tag with more matches anywhere than the ranges have cells. For around with a large radius, which takes this path, it was skipped for nearly every tag: a 25 km circle spans about 27 cells, and a tag with 56 matches in the circle had 398 cells elsewhere in the province. intersect_ranges now keeps only the candidates' cells that overlap the ranges, deduplicated, and compares their number with the ranges' cells. When there are more candidates than the ranges have tiles, it returns the ranges unchanged as before, since nearly every cell holds a candidate then and the filtering would cost more than it saves. On the Nova Scotia extract with the area rules run, against upstream master, in 25 alternating pairs: [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; (benchmark query p04: nine statements around one point) takes 8% less CPU (95% CI 3-13%), with identical output. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/query.cc | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index 5c19216d6..79666428b 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -835,10 +835,32 @@ Ranges< Index > intersect_ranges(const Ranges< Index >& range_a, std::vector< In for (auto it = range_a.begin(); it != range_a.end(); ++it) sum += difference(it.lower_bound(), it.upper_bound()); - if (sum/256 < range_vec.size()) + // range_vec holds the coarse index (256 tiles) of every candidate in the database, many sharing + // a cell. Count only the distinct cells that overlap range_a: comparing all candidates with + // range_a's cells skipped the intersection for any tag with more matches anywhere than range_a + // has cells, however few of them lie in range_a. + // With more candidates than range_a has tiles, nearly every cell holds one anyway, and + // filtering them would cost more than it saves. + if (sum < range_vec.size()) return range_a; - std::sort(range_vec.begin(), range_vec.end()); + std::vector< std::pair< Index, Index > > bounds; + for (auto it = range_a.begin(); it != range_a.end(); ++it) + bounds.push_back(std::make_pair(it.lower_bound(), it.upper_bound())); + std::vector< Index > inside; + for (auto it = range_vec.begin(); it != range_vec.end(); ++it) + { + auto b = std::upper_bound(bounds.begin(), bounds.end(), *it, + [](const Index& x, const std::pair< Index, Index >& r) { return x < r.second; }); + if (b != bounds.end() && b->first < Index(it->val() + 0x100)) + inside.push_back(*it); + } + std::sort(inside.begin(), inside.end()); + inside.erase(std::unique(inside.begin(), inside.end()), inside.end()); + range_vec.swap(inside); + + if (sum/256 < range_vec.size()) + return range_a; auto it_a = range_a.begin(); auto it_vec = range_vec.begin(); From dc3d2edc1b89c5decccc15dda10c1c668ec90443 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 05:11:12 +0000 Subject: [PATCH 46/80] query: merge overlapping ranges before filtering the candidates' cells The previous commit found the candidates' cells inside range_a with a binary search over range_a's upper bounds, which assumes the ranges don't overlap. They can: Ranges::union_ merges two sorted lists without merging overlapping entries, and an area filter's node ranges come from such a union. The search then dropped cells that do overlap range_a, and their candidates were lost. On the Nova Scotia extract with the area rules run, the CI fuzz run caught it with seed 1, query 420, whose part is_in(45.962213,-60.877275)->.s2; node(area.s2)["crossing"="informal"]; lost one node. The ranges are now sorted and merged before the search. Query 420 and the 200 queries of its shard (seed 1, queries 400-599, areas,complete) give the same output as upstream master again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/query.cc | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index 79666428b..cc3b37a99 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -844,9 +844,20 @@ Ranges< Index > intersect_ranges(const Ranges< Index >& range_a, std::vector< In if (sum < range_vec.size()) return range_a; - std::vector< std::pair< Index, Index > > bounds; + // range_a can hold overlapping ranges (Ranges::union_ doesn't merge them), so merge them + // here: the search below needs upper bounds that increase. + std::vector< std::pair< Index, Index > > raw; for (auto it = range_a.begin(); it != range_a.end(); ++it) - bounds.push_back(std::make_pair(it.lower_bound(), it.upper_bound())); + raw.push_back(std::make_pair(it.lower_bound(), it.upper_bound())); + std::sort(raw.begin(), raw.end()); + std::vector< std::pair< Index, Index > > bounds; + for (auto it = raw.begin(); it != raw.end(); ++it) + { + if (!bounds.empty() && !(bounds.back().second < it->first)) + bounds.back().second = std::max(bounds.back().second, it->second); + else + bounds.push_back(*it); + } std::vector< Index > inside; for (auto it = range_vec.begin(); it != range_vec.end(); ++it) { From 36ae3d4480e3bb827c05f484e40d7450d37676bd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 05:41:05 +0000 Subject: [PATCH 47/80] around: build a polyline's candidate range directly For a polyline (two or more coordinate pairs), Around_Statement::calc_ranges built a one-entry map with an empty Way_Skeleton vector only to reuse the ranges() helper. The previous commit makes ranges() skip entries without objects, so the polyline got no candidate ranges and around returned nothing. Build the range directly instead. On the Geofabrik Nova Scotia extract, node(around:200,45.135040,-63.352082,45.133858,-63.354463,45.135744,-63.356929) returned 0 elements; upstream/master and this commit return 538. Fixes #161. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/around.cc | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index 41f5c16c2..b004beffb 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -736,16 +736,15 @@ Ranges< Uint32_Index > Around_Statement::calc_ranges(const Set& input, Resource_ else if (points.size() > 1) { std::vector< uint32 > nd_idxs; - std::map< Uint31_Index, std::vector< Way_Skeleton > > ways; - std::pair< Uint31_Index, std::vector< Way_Skeleton > > way; for (std::vector< Point_Double >::const_iterator it = points.begin(); it != points.end(); ++it) nd_idxs.push_back(::ll_upper_(it->lat, it->lon)); + // Build the polyline's range directly: ranges() skips entries without objects. Uint31_Index idx = Way::calc_index(nd_idxs); - way = std::make_pair(idx, std::vector< Way_Skeleton >()); - ways.insert(way); - return expand(calc_children(ranges(ways)), radius); + Ranges< Uint31_Index > way_ranges; + way_ranges.push_back(idx, inc(idx)); + return expand(calc_children(way_ranges), radius); } else { From 3518ebd51417af3f377b74b687cfe2bcda7eeb98 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 03:56:47 +0000 Subject: [PATCH 48/80] block iterators: compare index entries in place instead of decoding them Range_Idx_Assessor::is_relevant and Discrete_Idx_Assessor::is_relevant decide, for each index entry the block iterator reaches, whether it lies in the requested ranges or set. Both built an Index object from the raw entry to compare it. For Tag_Index_Local that allocates two std::string (key and value) per entry, only to compare and discard them; reading local tags for output or late tag checks walks every tag entry in the cells it touches. The index types already compare against a raw entry with less(void*) and leq(void*), which File_Blocks uses to find blocks. The assessors now use them: !(idx < bound) is bound.leq(ptr), and *it < idx is it->less(ptr). (all-changes already looks up the cell's ids once in collect_tags_framed, so that part of the original commit is dropped here.) On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM, median CPU of 3 runs against master: [out:json][timeout:300]; (node["telecom"="data_center"]; way["telecom"="data_center"]; ); out center tags; 0.79 s -> 0.57 s [out:json][timeout:420]; (node["amenity"="fuel"](40.5,-80.0,46.6,-69.7); way["amenity"="fuel"](40.5,-80.0,46.6,-69.7); ); out center; 10.73 s -> 9.27 s Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit 3aad99468ee56d88c14b6eb9405cec11920b1a3a) --- src/template_db/block_backend.h | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/template_db/block_backend.h b/src/template_db/block_backend.h index 910ebbce0..3824b32e8 100644 --- a/src/template_db/block_backend.h +++ b/src/template_db/block_backend.h @@ -331,10 +331,9 @@ struct Discrete_Idx_Assessor bool is_relevant(uint8* ptr) { - Index idx((void*)ptr); - while (index_it != index_end && *index_it < idx) + while (index_it != index_end && index_it->less((void*)ptr)) ++index_it; - return index_it != index_end && *index_it == idx; + return index_it != index_end && index_it->leq((void*)ptr); } private: @@ -406,10 +405,10 @@ struct Range_Idx_Assessor bool is_relevant(uint8* ptr) { - Index idx((void*)ptr); - while (index_it != index_end && !(idx < index_it.upper_bound())) + // bound.leq(ptr) is !(idx < bound) for the index stored at ptr. + while (index_it != index_end && index_it.upper_bound().leq((void*)ptr)) ++index_it; - return index_it != index_end && !(idx < index_it.lower_bound()) && idx < index_it.upper_bound(); + return index_it != index_end && index_it.lower_bound().leq((void*)ptr); } private: From 20f8ec5cc4f073f8b8c16debeda13b72e46f2314 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 03:56:47 +0000 Subject: [PATCH 49/80] block iterators: decode index entries and objects without a heap allocation Idx_Handle (and Handle, which the block iterators use for objects) decoded the entry under the iterator on first access with new Object(ptr), and deleted it when the iterator moved on. Every index() and object() call on a fresh entry thus cost a heap allocation and a free, even for 4-byte types such as Uint32_Index and for fixed-size skeletons. Idx_Handle now decodes into aligned storage inside the handle with placement new and runs the destructor in clear(). It also adds the missing return *this to Idx_Handle::operator=. On a US northeast full-history extract (Geofabrik), warm cache, 4-core VM, median CPU of 3 runs against master: [out:json][timeout:300]; (node["telecom"="data_center"]; way["telecom"="data_center"]; ); out center tags; 0.66 s -> 0.46 s (rel['seamark:type']; >; way['seamark:type']; >; node['seamark:type']; ); out meta; 5.41 s -> 4.56 s Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit 29beded130e9200c2258823435271c5b06a76ca2) --- src/template_db/block_backend.h | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/template_db/block_backend.h b/src/template_db/block_backend.h index 3824b32e8..5c2be0209 100644 --- a/src/template_db/block_backend.h +++ b/src/template_db/block_backend.h @@ -25,6 +25,8 @@ #include #include +#include +#include #include @@ -35,18 +37,17 @@ struct Idx_Handle : obj(0), ptr_to_raw(0) {} ~Idx_Handle() { - delete obj; + clear(); } void set_ptr(uint8* ptr) { - delete obj; - obj = 0; + clear(); ptr_to_raw = ptr; } const Object& object() const { if (!obj) - obj = new Object(ptr_to_raw); + obj = new (&storage) Object(ptr_to_raw); return *obj; } uint8* get_ptr_to_raw() const @@ -59,9 +60,18 @@ struct Idx_Handle Idx_Handle& operator=(const Idx_Handle& rhs) { set_ptr(rhs.ptr_to_raw); + return *this; } private: + void clear() + { + if (obj) + obj->~Object(); + obj = 0; + } + + mutable typename std::aligned_storage< sizeof(Object), alignof(Object) >::type storage; mutable Object* obj; uint8* ptr_to_raw; }; From 63cecf05d6397127c8af6eae6c65dbe300e78fdf Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:05:03 +0000 Subject: [PATCH 50/80] diff: move tags and geometry into the *_With_Context records Set_Comparison builds a Node_, Way_ or Relation_With_Context for every element of a diff. Their constructors took tags (and, for ways and relations, geometry) by value or const reference and copied them into the member. The callers pass "tags ? *tags : std::vector<...>()", a temporary copy, so each element's tags and geometry were copied twice. The constructors now take tags and geometry by value and move them into the members, so the temporary moves in and each is copied once. On a US northeast full-history extract (Geofabrik), instruction counts (valgrind callgrind) against master: [diff:"2024-01-01T00:00:00Z","2026-11-01T00:00:00Z"]; way["highway"](42.34,-71.08,42.36,-71.05); out geom; 7.901 G -> 7.881 G (-0.25%) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit 3f1548c7ee28a62b952b57921d8710b0a504bb84) --- src/overpass_api/data/diff_set.h | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/overpass_api/data/diff_set.h b/src/overpass_api/data/diff_set.h index 9301a7440..9ed07e465 100644 --- a/src/overpass_api/data/diff_set.h +++ b/src/overpass_api/data/diff_set.h @@ -43,7 +43,7 @@ struct Node_With_Context uint64 expiration_date_, OSM_Element_Metadata_Skeleton< Node_Skeleton::Id_Type > meta_ = OSM_Element_Metadata_Skeleton< Node_Skeleton::Id_Type >(), Tag_Container tags_ = Tag_Container()) - : idx(idx_), elem(elem_), expiration_date(expiration_date_), meta(meta_), tags(tags_) {} + : idx(idx_), elem(elem_), expiration_date(expiration_date_), meta(meta_), tags(std::move(tags_)) {} bool operator<(const Node_With_Context& e) const { @@ -65,11 +65,12 @@ struct Way_With_Context Tag_Container tags; std::vector< Quad_Coord > geometry; - Way_With_Context(Uint31_Index idx_, Way_Skeleton elem_, const std::vector< Quad_Coord >& geometry_, + Way_With_Context(Uint31_Index idx_, Way_Skeleton elem_, std::vector< Quad_Coord > geometry_, uint64 expiration_date_, OSM_Element_Metadata_Skeleton< Way_Skeleton::Id_Type > meta_ = OSM_Element_Metadata_Skeleton< Way_Skeleton::Id_Type >(), Tag_Container tags_ = Tag_Container()) - : idx(idx_), elem(elem_), expiration_date(expiration_date_), meta(meta_), tags(tags_), geometry(geometry_) {} + : idx(idx_), elem(elem_), expiration_date(expiration_date_), meta(meta_), + tags(std::move(tags_)), geometry(std::move(geometry_)) {} bool operator<(const Way_With_Context& e) const { @@ -92,11 +93,12 @@ struct Relation_With_Context std::vector< std::vector< Quad_Coord > > geometry; Relation_With_Context(Uint31_Index idx_, Relation_Skeleton elem_, - const std::vector< std::vector< Quad_Coord > >& geometry_, + std::vector< std::vector< Quad_Coord > > geometry_, uint64 expiration_date_, OSM_Element_Metadata_Skeleton< Relation_Skeleton::Id_Type > meta_ = OSM_Element_Metadata_Skeleton< Relation_Skeleton::Id_Type >(), Tag_Container tags_ = Tag_Container()) - : idx(idx_), elem(elem_), expiration_date(expiration_date_), meta(meta_), tags(tags_), geometry(geometry_) {} + : idx(idx_), elem(elem_), expiration_date(expiration_date_), meta(meta_), + tags(std::move(tags_)), geometry(std::move(geometry_)) {} bool operator<(const Relation_With_Context& e) const { From 77f7956cd1452e700672be6bd7b1900d496ee63d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:05:03 +0000 Subject: [PATCH 51/80] diff: pass the input set's derived elements to compute_deriveds by reference Set_Comparison::compute_deriveds took the input set's derived elements (std::map< Uint31_Index, std::vector< Derived_Structure > >) by value, copying the whole map once per diff. It only reads it, so it now takes a const reference. Derived elements come from make and convert, so only diffs over them copy anything. On a US northeast full-history extract (Geofabrik), instruction counts (valgrind callgrind) against master: [diff:"2024-01-01T00:00:00Z","2026-11-01T00:00:00Z"]; nwr["amenity"](42.34,-71.08,42.36,-71.05); convert item ::id=id(), name=t["name"], amenity=t["amenity"]; out; 17.678 G -> 17.675 G (-0.01%) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit 9152919c22a181c3891fa9b11d398f625555a654) --- src/overpass_api/data/set_comparison.cc | 2 +- src/overpass_api/data/set_comparison.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/data/set_comparison.cc b/src/overpass_api/data/set_comparison.cc index 3db91e234..b3d261fa3 100644 --- a/src/overpass_api/data/set_comparison.cc +++ b/src/overpass_api/data/set_comparison.cc @@ -998,7 +998,7 @@ bool Derived_Structure_Handle::operator<(const Derived_Structure_Handle& rhs) co } -void Set_Comparison::compute_deriveds(std::map< Uint31_Index, std::vector< Derived_Structure > > rhs_deriveds) +void Set_Comparison::compute_deriveds(const std::map< Uint31_Index, std::vector< Derived_Structure > >& rhs_deriveds) { std::vector< Derived_Structure_Handle > lhs_handles; for (std::map< Uint31_Index, std::vector< Derived_Structure > >::const_iterator diff --git a/src/overpass_api/data/set_comparison.h b/src/overpass_api/data/set_comparison.h index 6715b1fd2..e52527c4f 100644 --- a/src/overpass_api/data/set_comparison.h +++ b/src/overpass_api/data/set_comparison.h @@ -145,7 +145,7 @@ class Set_Comparison void clear_ways(Resource_Manager& rman, bool add_deletion_information = false); void clear_relations(Resource_Manager& rman, bool add_deletion_information = false); - void compute_deriveds(std::map< Uint31_Index, std::vector< Derived_Structure > > rhs_deriveds); + void compute_deriveds(const std::map< Uint31_Index, std::vector< Derived_Structure > >& rhs_deriveds); const Set& lhs_set() const { return lhs_set_; } uint64 lhs_timestamp() const { return lhs_timestamp_; } From 2a36c2e1016ca5a8edb7e21311735a9e7c365330 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:05:03 +0000 Subject: [PATCH 52/80] collect_items: remember the last result slot while collecting The collect_items_* loops added each matching object with result[it.index()].push_back(...), a std::map lookup per object. Block iterators deliver runs of objects with the same index, so the lookup nearly always finds the slot found for the previous object. Indexed_Appender keeps an iterator to the last slot and looks the map up only when the index changes, inserting with a hint at the end. It replaces the lookup in collect_items_discrete, collect_items_range and collect_items_flat (7 loops). On all-changes, the NOW loop of collect_items_range already keeps its last slot (with the running size), so it keeps that code and the appender covers the other 5. On a US northeast full-history extract (Geofabrik), instruction counts (valgrind callgrind) against master: node["amenity"](42.3,-71.15,42.4,-71.0); out meta; 3.239 G -> 3.131 G (-3.4%) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 --- src/overpass_api/data/collect_items.h | 37 +++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/src/overpass_api/data/collect_items.h b/src/overpass_api/data/collect_items.h index ec6a20203..4a9f55748 100644 --- a/src/overpass_api/data/collect_items.h +++ b/src/overpass_api/data/collect_items.h @@ -35,6 +35,28 @@ inline uint64 timestamp_of(const Way_Skeleton& skel) { return NOW; } inline uint64 timestamp_of(const Relation_Skeleton& skel) { return NOW; } + +// Appends to std::map< Index, std::vector< Object > > entries, remembering the last slot: +// block iterators deliver runs of objects with the same index. +template< typename Index, typename Object > +struct Indexed_Appender +{ + Indexed_Appender(std::map< Index, std::vector< Object > >& target_) + : target(&target_), last(target_.end()) {} + + void push_back(const Index& idx, const Object& obj) + { + if (last == target->end() || !(last->first == idx)) + last = target->insert(target->end(), std::make_pair(idx, std::vector< Object >())); + last->second.push_back(obj); + } + +private: + std::map< Index, std::vector< Object > >* target; + typename std::map< Index, std::vector< Object > >::iterator last; +}; + + template < class Index, class Object, class Iterator, class Predicate > void reconstruct_items( Iterator& it, const Iterator& end, Index index, @@ -476,10 +498,11 @@ void collect_items_discrete(Transaction& transaction, { Block_Backend< Index, Object, typename Container::const_iterator > db (transaction.data_index(&file_properties)); + Indexed_Appender< Index, Object > append(result); for (auto it = db.discrete_begin(req.begin(), req.end()); !(it == db.discrete_end()); ++it) { if (predicate.match(it.handle())) - result[it.index()].push_back(it.object()); + append.push_back(it.index(), it.object()); } } @@ -495,10 +518,11 @@ void collect_items_discrete(Request_Context& context, context.data_index(current_skeleton_file_properties< Object >())); if (timestamp == NOW) { + Indexed_Appender< Index, Object > append(result); for (auto it = current_db.discrete_begin(req.begin(), req.end()); !(it == current_db.discrete_end()); ++it) { if (predicate.match(it.handle())) - result[it.index()].push_back(it.object()); + append.push_back(it.index(), it.object()); } } else @@ -536,10 +560,11 @@ Timeless< Index, Object > collect_items_range(Request_Context& context, (context.data_index(current_skeleton_file_properties< Object >())); if (context.get_desired_timestamp() == NOW) { + Indexed_Appender< Index, Object > append(result.current); for (auto it = current_db.range_begin(ranges); !(it == current_db.range_end()); ++it) { if (predicate.match(it.handle())) - result.current[it.index()].push_back(it.object()); + append.push_back(it.index(), it.object()); } } else @@ -627,6 +652,7 @@ void collect_items_flat(Request_Context& context, { uint32 count = 0; Block_Backend< Index, Object > db(context.data_index(&file_properties)); + Indexed_Appender< Index, Object > append(result); for (typename Block_Backend< Index, Object >::Flat_Iterator it(db.flat_begin()); !(it == db.flat_end()); ++it) { @@ -636,7 +662,7 @@ void collect_items_flat(Request_Context& context, context.get_health_guard().check(0, eval_map(result)); } if (predicate.match(it.handle())) - result[it.index()].push_back(it.object()); + append.push_back(it.index(), it.object()); } } @@ -653,6 +679,7 @@ void collect_items_flat( if (context.get_desired_timestamp() == NOW) { uint32 count = 0; + Indexed_Appender< Index, Object > append(result); for (auto it = current_db.flat_begin(); !(it == current_db.flat_end()); ++it) { if (++count >= 256*1024) @@ -661,7 +688,7 @@ void collect_items_flat( context.get_health_guard().check(0, eval_map(result)); } if (predicate.match(it.handle())) - result[it.index()].push_back(it.object()); + append.push_back(it.index(), it.object()); } } else From b791bc753971e8ed77f7eae944c93ec7b9e946fb Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:05:03 +0000 Subject: [PATCH 53/80] local tags: read an entry's cell from the raw index instead of decoding it Loops over local tag entries (collect_tags and collect_tags_framed in tag_store.h, filter_ids_by_tags, and the late tag checks in query.cc) test (tag_it.index().index & 0x7fffff00) against the cell they scan. index() decodes the whole Tag_Index_Local, key and value strings included, so every entry the loops skip over, or stop at, is decoded just to read its cell. The block iterator now exposes the raw index entry (index_raw()), and tag_coarse_index(it) reads the cell from it the way Tag_Index_Local's constructor does. Key and value are decoded only for entries the loops use. On a US northeast full-history extract (Geofabrik), instruction counts (valgrind callgrind) against master: [out:json][timeout:300]; (node["telecom"="data_center"]; way["telecom"="data_center"]; ); out center tags; 6.112 G -> 5.668 G (-7.3%) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit 8c6067a41041ea74e9c2289005aa6d857a8cc3a3) --- src/overpass_api/core/type_tags.h | 9 +++++++++ src/overpass_api/data/filter_ids_by_tags.h | 4 ++-- src/overpass_api/data/tag_store.h | 16 ++++++++-------- src/overpass_api/statements/query.cc | 16 ++++++++-------- src/template_db/block_backend.h | 4 ++++ 5 files changed, 31 insertions(+), 18 deletions(-) diff --git a/src/overpass_api/core/type_tags.h b/src/overpass_api/core/type_tags.h index e3e03be2e..c40b4785e 100644 --- a/src/overpass_api/core/type_tags.h +++ b/src/overpass_api/core/type_tags.h @@ -239,6 +239,15 @@ struct Tag_Index_Local }; +// The cell part of a Tag_Index_Local entry's index, read from the raw entry under a block +// iterator: (it.index().index & 0x7fffff00) without decoding the key and value. +template< typename Iterator > +inline uint32 tag_coarse_index(const Iterator& it) +{ + return ((*((uint32*)it.index_raw() + 1))<<8) & 0x7fffff00; +} + + inline const std::string& void_tag_value() { static std::string void_value = " "; diff --git a/src/overpass_api/data/filter_ids_by_tags.h b/src/overpass_api/data/filter_ids_by_tags.h index afa2b24cb..c21791533 100644 --- a/src/overpass_api/data/filter_ids_by_tags.h +++ b/src/overpass_api/data/filter_ids_by_tags.h @@ -364,10 +364,10 @@ void filter_ids_by_tags while (true) { bool current_finished = - (tag_it == items_db.range_end() || ((tag_it.index().index) & 0x7fffff00) != coarse_index); + (tag_it == items_db.range_end() || (tag_coarse_index(tag_it)) != coarse_index); bool attic_finished = (attic_tag_it == attic_items_db.range_end() - || ((attic_tag_it.index().index) & 0x7fffff00) != coarse_index); + || (tag_coarse_index(attic_tag_it)) != coarse_index); if (!attic_finished && (current_finished || attic_tag_it.index().key < tag_it.index().key)) { diff --git a/src/overpass_api/data/tag_store.h b/src/overpass_api/data/tag_store.h index 904cc90c0..1d506648f 100644 --- a/src/overpass_api/data/tag_store.h +++ b/src/overpass_api/data/tag_store.h @@ -90,10 +90,10 @@ void collect_attic_tags // Collect all id-matched tag information from the current tags while ((!(current_tag_it == current_items_db.range_end())) && - (((current_tag_it.index().index) & 0x7fffff00) < coarse_index)) + ((tag_coarse_index(current_tag_it)) < coarse_index)) ++current_tag_it; while ((!(current_tag_it == current_items_db.range_end())) && - (((current_tag_it.index().index) & 0x7fffff00) == coarse_index)) + ((tag_coarse_index(current_tag_it)) == coarse_index)) { typename std::vector< Attic< Id_Type > >::const_iterator it_id = std::lower_bound(id_vec.begin(), id_vec.end(), Attic< Id_Type >(current_tag_it.object(), 0ull)); @@ -108,10 +108,10 @@ void collect_attic_tags // Collect all id-matched tag information that is younger than the respective timestamp from the attic tags while ((!(attic_tag_it == attic_items_db.range_end())) && - (((attic_tag_it.index().index) & 0x7fffff00) < coarse_index)) + ((tag_coarse_index(attic_tag_it)) < coarse_index)) ++attic_tag_it; while ((!(attic_tag_it == attic_items_db.range_end())) && - (((attic_tag_it.index().index) & 0x7fffff00) == coarse_index)) + ((tag_coarse_index(attic_tag_it)) == coarse_index)) { typename std::vector< Attic< Id_Type > >::const_iterator it_id = std::lower_bound(id_vec.begin(), id_vec.end(), Attic< Id_Type >(attic_tag_it.object(), 0ull)); @@ -249,10 +249,10 @@ void collect_tags { typename std::vector< Id_Type >::const_iterator cursor = ids.begin(); while ((!(tag_it == items_db.range_end())) && - (((tag_it.index().index) & 0x7fffff00) < coarse_index)) + ((tag_coarse_index(tag_it)) < coarse_index)) ++tag_it; while ((!(tag_it == items_db.range_end())) && - (((tag_it.index().index) & 0x7fffff00) == coarse_index)) + ((tag_coarse_index(tag_it)) == coarse_index)) { if (contains_from_cursor(ids, cursor, tag_it.object())) tags_by_id[tag_it.object()].push_back @@ -274,10 +274,10 @@ void collect_tags_framed const std::vector< Id_Type >& ids = ids_by_coarse[coarse_index]; typename std::vector< Id_Type >::const_iterator cursor = ids.begin(); while ((!(tag_it == items_db.range_end())) && - (((tag_it.index().index) & 0x7fffff00) < coarse_index)) + ((tag_coarse_index(tag_it)) < coarse_index)) ++tag_it; while ((!(tag_it == items_db.range_end())) && - (((tag_it.index().index) & 0x7fffff00) == coarse_index)) + ((tag_coarse_index(tag_it)) == coarse_index)) { if (!(tag_it.object() < lower_id_bound) && (tag_it.object() < upper_id_bound) && diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index cc3b37a99..035a23847 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -209,7 +209,7 @@ void filter_ids_by_ntags key_it = keys.begin(); while ((!(tag_it == items_db.range_end())) && - (((tag_it.index().index) & 0x7fffff00) == coarse_index)) + ((tag_coarse_index(tag_it)) == coarse_index)) { if (tag_it.index().key != last_key) { @@ -260,7 +260,7 @@ void filter_ids_by_ntags ++tag_it; } while ((!(tag_it == items_db.range_end())) && - (((tag_it.index().index) & 0x7fffff00) == coarse_index)) + ((tag_coarse_index(tag_it)) == coarse_index)) ++tag_it; sort(removed_ids.begin(), removed_ids.end()); @@ -291,18 +291,18 @@ void filter_ids_by_ntags timestamps[*it]; while ((!(tag_it == items_db.range_end())) && - ((tag_it.index().index) & 0x7fffff00) == coarse_index && + (tag_coarse_index(tag_it)) == coarse_index && tag_it.index().key < key_it->first) ++tag_it; while ((!(attic_tag_it == attic_items_db.range_end())) && - ((attic_tag_it.index().index) & 0x7fffff00) == coarse_index && + (tag_coarse_index(attic_tag_it)) == coarse_index && attic_tag_it.index().key < key_it->first) ++attic_tag_it; bool valid = false; std::string last_value = void_tag_value() + " "; while ((!(tag_it == items_db.range_end())) && - ((tag_it.index().index) & 0x7fffff00) == coarse_index && + (tag_coarse_index(tag_it)) == coarse_index && tag_it.index().key == key_it->first) { if (std::binary_search(new_ids.begin(), new_ids.end(), tag_it.object())) @@ -330,7 +330,7 @@ void filter_ids_by_ntags last_value = void_tag_value() + " "; while ((!(attic_tag_it == attic_items_db.range_end())) && - ((attic_tag_it.index().index) & 0x7fffff00) == coarse_index && + (tag_coarse_index(attic_tag_it)) == coarse_index && attic_tag_it.index().key == key_it->first) { if (std::binary_search(new_ids.begin(), new_ids.end(), Id_Type(attic_tag_it.object()))) @@ -373,10 +373,10 @@ void filter_ids_by_ntags } } while ((!(tag_it == items_db.range_end())) && - ((tag_it.index().index) & 0x7fffff00) == coarse_index) + (tag_coarse_index(tag_it)) == coarse_index) ++tag_it; while ((!(attic_tag_it == attic_items_db.range_end())) && - ((attic_tag_it.index().index) & 0x7fffff00) == coarse_index) + (tag_coarse_index(attic_tag_it)) == coarse_index) ++attic_tag_it; } diff --git a/src/template_db/block_backend.h b/src/template_db/block_backend.h index 5c2be0209..4defdf0e0 100644 --- a/src/template_db/block_backend.h +++ b/src/template_db/block_backend.h @@ -104,6 +104,10 @@ struct Block_Backend_Basic_Iterator { return idx_cache.object(); } + uint8* index_raw() const + { + return idx_cache.get_ptr_to_raw(); + } const Object& object() { return obj_cache.object(); From 55d0e4199726665183038c96e1ee394ac0f3b295 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 04:59:07 +0000 Subject: [PATCH 54/80] area queries: skip the way-area pass when the input holds no way-areas 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 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/statements/area_query.cc | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/statements/area_query.cc b/src/overpass_api/statements/area_query.cc index c5189f545..a1897604f 100644 --- a/src/overpass_api/statements/area_query.cc +++ b/src/overpass_api/statements/area_query.cc @@ -190,12 +190,17 @@ std::map< Uint31_Index, std::vector< Way_Skeleton > > ways_contained_in( Tilewise_Const_Area_Iterator tai(potential_areas->ways, potential_areas->attic_ways, stmt, rman); std::map< Uint31_Index, std::vector< Way_Skeleton > > result; + if (tai.is_end()) + return result; + Tilewise_Way_Iterator twi(ways, std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > > >(), stmt, rman); while (!twi.is_end()) { while (!tai.is_end() && tai.get_idx() < twi.get_idx()) tai.next(); - if (tai.is_end() || twi.get_idx() < tai.get_idx()) + if (tai.is_end()) + break; + if (twi.get_idx() < tai.get_idx()) { twi.next(); continue; @@ -230,12 +235,17 @@ std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > > > ways_contained_in Tilewise_Const_Area_Iterator tai(potential_areas->ways, potential_areas->attic_ways, stmt, rman); std::map< Uint31_Index, std::vector< Attic< Way_Skeleton > > > result; + if (tai.is_end()) + return result; + Tilewise_Way_Iterator twi(std::map< Uint31_Index, std::vector< Way_Skeleton > >(), ways, stmt, rman); while (!twi.is_end()) { while (!tai.is_end() && tai.get_idx() < twi.get_idx()) tai.next(); - if (tai.is_end() || twi.get_idx() < tai.get_idx()) + if (tai.is_end()) + break; + if (twi.get_idx() < tai.get_idx()) { twi.next(); continue; From 51f760662c48d645e4cbe73134aff4f4db5a9099 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:16:43 +0000 Subject: [PATCH 55/80] Collect_Items: end a chunk at 16 MiB accounted, not 64 MiB 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 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit 4b95ce362128201ee17abaee75b1fca9e0feabd0) --- src/overpass_api/data/collect_items.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/data/collect_items.h b/src/overpass_api/data/collect_items.h index 4a9f55748..6ae979de9 100644 --- a/src/overpass_api/data/collect_items.h +++ b/src/overpass_api/data/collect_items.h @@ -84,8 +84,8 @@ class Statement; // A chunk of collected elements also ends once its accounted size (as eval_map counts it) reaches // this, so a query whose filters drop most candidates doesn't hold all of them at once when its -// [maxsize:] budget is large. 64 MiB accounted is 8M nodes or 512k ways. -const uint64 MAX_CHUNK_ACCOUNTED_SIZE = 64ull*1024*1024; +// [maxsize:] budget is large. 16 MiB accounted is 2M nodes or 128k ways. +const uint64 MAX_CHUNK_ACCOUNTED_SIZE = 16ull*1024*1024; class Health_Guard From 00aa56c025da2c206ce808fa9f2168fcddd1e8be Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:16:43 +0000 Subject: [PATCH 56/80] query: build the late tag check's ids one cell at a time 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 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit d4cc14a807427266d0d452fdc18c85eb419b3bba) --- src/overpass_api/statements/query.cc | 38 +++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index 035a23847..88a724f75 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -450,6 +450,23 @@ void filter_by_ids( } +template< class TIndex, class TObject > +void fill_cell_ids(std::vector< typename TObject::Id_Type >& ids, + typename std::map< TIndex, std::vector< TObject > >::const_iterator& item_it, + const std::map< TIndex, std::vector< TObject > >& items, uint32 coarse_index) +{ + while (item_it != items.end() && (item_it->first.val() & 0x7fffff00) == coarse_index) + { + for (typename std::vector< TObject >::const_iterator eit = item_it->second.begin(); + eit != item_it->second.end(); ++eit) + ids.push_back(eit->id); + ++item_it; + } + std::sort(ids.begin(), ids.end()); + ids.erase(std::unique(ids.begin(), ids.end()), ids.end()); +} + + template< class TIndex, class TObject > void Query_Statement::filter_by_tags (std::map< TIndex, std::vector< TObject > >& items, @@ -461,11 +478,23 @@ void Query_Statement::filter_by_tags && key_nregexes.empty() && key_nvalues.empty()) return; - // generate set of relevant coarse indices + // One entry per coarse index, but its ids are filled in only when that cell is filtered, so the + // candidates' ids are never all held at once. std::map< uint32, std::vector< typename TObject::Id_Type > > ids_by_coarse; - generate_ids_by_coarse(ids_by_coarse, items); + for (typename std::map< TIndex, std::vector< TObject > >::const_iterator it = items.begin(); it != items.end(); ++it) + ids_by_coarse.insert(ids_by_coarse.end(), std::make_pair(it->first.val() & 0x7fffff00, + std::vector< typename TObject::Id_Type >())); if (timestamp != NOW) - generate_ids_by_coarse(ids_by_coarse, *attic_items); + { + for (typename std::map< TIndex, std::vector< Attic< TObject > > >::const_iterator it = attic_items->begin(); + it != attic_items->end(); ++it) + ids_by_coarse.insert(std::make_pair(it->first.val() & 0x7fffff00, + std::vector< typename TObject::Id_Type >())); + } + typename std::map< TIndex, std::vector< TObject > >::const_iterator cell_item_it = items.begin(); + typename std::map< TIndex, std::vector< Attic< TObject > > >::const_iterator cell_attic_it; + if (attic_items) + cell_attic_it = attic_items->begin(); // formulate range query Ranges< Tag_Index_Local > ranges = formulate_range_query(ids_by_coarse); @@ -501,6 +530,7 @@ void Query_Statement::filter_by_tags coarse_count = 0; rman.health_check(*this); } + fill_cell_ids(it->second, cell_item_it, items, it->first); filter_ids_by_tags(key_union, regkey_regexes, items_db, tag_it, it->first, it->second); } } @@ -518,6 +548,8 @@ void Query_Statement::filter_by_tags coarse_count = 0; rman.health_check(*this); } + fill_cell_ids(it->second, cell_item_it, items, it->first); + fill_cell_ids(it->second, cell_attic_it, *attic_items, it->first); filter_ids_by_tags(key_union, regkey_regexes, timestamp, items_db, tag_it, attic_items_db, attic_tag_it, it->first, it->second); } From 54e269f181ef62869ddb4195690b7e69155ce744 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 16:16:43 +0000 Subject: [PATCH 57/80] tag filters at a past date: don't add every candidate to the timestamp 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 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit 563e4b57ba016cc0b613fa7470bd9e2677c7596f) --- src/overpass_api/data/filter_ids_by_tags.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/data/filter_ids_by_tags.h b/src/overpass_api/data/filter_ids_by_tags.h index c21791533..9104a9307 100644 --- a/src/overpass_api/data/filter_ids_by_tags.h +++ b/src/overpass_api/data/filter_ids_by_tags.h @@ -216,8 +216,8 @@ struct Tag_Entry_Listener_Value_Regex : public Tag_Entry_Listener< Id_Type > std::vector< Id_Type > result; for (typename std::vector< Id_Type >::const_iterator it = new_ids.begin(); it != new_ids.end(); ++it) { - std::pair< uint64, uint64 >& timestamp_ref = timestamps[*it]; - if (0 < timestamp_ref.first && timestamp_ref.first <= timestamp_ref.second) + typename std::map< Id_Type, std::pair< uint64, uint64 > >::const_iterator found = timestamps.find(*it); + if (found != timestamps.end() && 0 < found->second.first && found->second.first <= found->second.second) result.push_back(*it); } std::sort(result.begin(), result.end()); From 013e411c605aa1770488b2dd11d48bd1134ef519 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 20:48:12 +0000 Subject: [PATCH 58/80] query: run (if:) filters that need geometry after the other filters 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 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit 9acbe90cc5b2bdbdf848c286c93357e207f9815c) --- src/overpass_api/statements/filter.cc | 5 +++++ src/overpass_api/statements/query.cc | 11 +++++++++-- src/overpass_api/statements/statement.h | 1 + 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/statements/filter.cc b/src/overpass_api/statements/filter.cc index 9eb6d7ecc..cd66816b3 100644 --- a/src/overpass_api/statements/filter.cc +++ b/src/overpass_api/statements/filter.cc @@ -34,6 +34,11 @@ class Filter_Constraint : public Query_Constraint bool get_ranges(Resource_Manager& rman, Ranges< Uint31_Index >& ranges) { return false; } void filter(Resource_Manager& rman, Set& into) {} void filter(const Statement& query, Resource_Manager& rman, Set& into); + bool filter_needs_geometry() const override + { + return stmt && stmt->get_criterion() + && (stmt->get_criterion()->request_context().object_usage & Set_Usage::GEOMETRY); + } virtual ~Filter_Constraint() {} private: diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index 88a724f75..9878c3f54 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -971,7 +971,8 @@ void Query_Statement::apply_all_filters( rman.health_check(*this); // All filters only remove elements, so their order does not change the result. - // Metadata-only filters go first, so that geometry is built for fewer elements. + // Metadata-only filters go first, so that geometry is built for fewer elements, and (if:) + // filters that need geometry go last, after the other filters have built theirs. for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); it != constraints.end(); ++it) { @@ -981,7 +982,13 @@ void Query_Statement::apply_all_filters( for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); it != constraints.end(); ++it) { - if (!(*it)->filter_reads_only_metadata()) + if (!(*it)->filter_reads_only_metadata() && !(*it)->filter_needs_geometry()) + (*it)->filter(*this, rman, into); + } + for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); + it != constraints.end(); ++it) + { + if (!(*it)->filter_reads_only_metadata() && (*it)->filter_needs_geometry()) (*it)->filter(*this, rman, into); } } diff --git a/src/overpass_api/statements/statement.h b/src/overpass_api/statements/statement.h index 0f4e75e6d..d6012ce1a 100644 --- a/src/overpass_api/statements/statement.h +++ b/src/overpass_api/statements/statement.h @@ -140,6 +140,7 @@ class Query_Constraint // their geometry. Such filters run before the others: reading metadata costs far // less than building geometry, so they shrink the set before geometry is built. virtual bool filter_reads_only_metadata() const { return false; } + virtual bool filter_needs_geometry() const { return false; } virtual ~Query_Constraint() {} }; From b62782b4b9ad3f950343b28818beb3b7675cdfa6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 20:48:13 +0000 Subject: [PATCH 59/80] changed: reuse the ids found within the known ids in filter() 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 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit 4c30af0f783f489657c3b1dd2c04ce1d2dd0722e) --- src/overpass_api/statements/changed.cc | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/overpass_api/statements/changed.cc b/src/overpass_api/statements/changed.cc index a2197d485..b1bc4a0f4 100644 --- a/src/overpass_api/statements/changed.cc +++ b/src/overpass_api/statements/changed.cc @@ -222,6 +222,14 @@ class Changed_Constraint : public Query_Constraint private: Changed_Statement* stmt; + // The ids get_*_ids_within found, kept for filter(): elements outside the known ids fail + // another constraint anyway, so filter() needn't read the changelog again. + std::vector< Node_Skeleton::Id_Type > node_ids_within; + std::vector< Way_Skeleton::Id_Type > way_ids_within; + std::vector< Relation_Skeleton::Id_Type > relation_ids_within; + bool node_ids_within_valid = false; + bool way_ids_within_valid = false; + bool relation_ids_within_valid = false; }; @@ -229,6 +237,7 @@ bool Changed_Constraint::get_node_ids(Resource_Manager& rman, std::vector< Node_ { ids = collect_changed_elements< Uint32_Index, Node_Skeleton >( stmt->get_since(rman), stmt->get_until(rman), Trivial_Id_Predicate< Node_Skeleton::Id_Type >(), rman); + node_ids_within_valid = false; return true; } @@ -237,6 +246,7 @@ bool Changed_Constraint::get_way_ids(Resource_Manager& rman, std::vector< Way_Sk { ids = collect_changed_elements< Uint31_Index, Way_Skeleton >( stmt->get_since(rman), stmt->get_until(rman), Trivial_Id_Predicate< Way_Skeleton::Id_Type >(), rman); + way_ids_within_valid = false; return true; } @@ -245,6 +255,7 @@ bool Changed_Constraint::get_relation_ids(Resource_Manager& rman, std::vector< R { ids = collect_changed_elements< Uint31_Index, Relation_Skeleton >( stmt->get_since(rman), stmt->get_until(rman), Trivial_Id_Predicate< Relation_Skeleton::Id_Type >(), rman); + relation_ids_within_valid = false; return true; } @@ -254,6 +265,8 @@ bool Changed_Constraint::get_node_ids_within(Resource_Manager& rman, { ids = collect_changed_elements< Uint32_Index, Node_Skeleton >( stmt->get_since(rman), stmt->get_until(rman), Known_Ids_Predicate< Node_Skeleton::Id_Type >(known), rman); + node_ids_within = ids; + node_ids_within_valid = true; return true; } @@ -263,6 +276,8 @@ bool Changed_Constraint::get_way_ids_within(Resource_Manager& rman, { ids = collect_changed_elements< Uint31_Index, Way_Skeleton >( stmt->get_since(rman), stmt->get_until(rman), Known_Ids_Predicate< Way_Skeleton::Id_Type >(known), rman); + way_ids_within = ids; + way_ids_within_valid = true; return true; } @@ -272,6 +287,8 @@ bool Changed_Constraint::get_relation_ids_within(Resource_Manager& rman, { ids = collect_changed_elements< Uint31_Index, Relation_Skeleton >( stmt->get_since(rman), stmt->get_until(rman), Known_Ids_Predicate< Relation_Skeleton::Id_Type >(known), rman); + relation_ids_within = ids; + relation_ids_within_valid = true; return true; } @@ -280,7 +297,7 @@ void Changed_Constraint::filter(Resource_Manager& rman, Set& into) { if (!stmt->trivial()) { - std::vector< Node_Skeleton::Id_Type > ids = + std::vector< Node_Skeleton::Id_Type > ids = node_ids_within_valid ? node_ids_within : collect_changed_elements< Uint32_Index, Node_Skeleton > (stmt->get_since(rman), stmt->get_until(rman), Ids_In_Set_Predicate< Uint32_Index, Node_Skeleton >(into.nodes, into.attic_nodes), rman); @@ -291,7 +308,7 @@ void Changed_Constraint::filter(Resource_Manager& rman, Set& into) if (!stmt->trivial()) { - std::vector< Way_Skeleton::Id_Type > ids = + std::vector< Way_Skeleton::Id_Type > ids = way_ids_within_valid ? way_ids_within : collect_changed_elements< Uint31_Index, Way_Skeleton > (stmt->get_since(rman), stmt->get_until(rman), Ids_In_Set_Predicate< Uint31_Index, Way_Skeleton >(into.ways, into.attic_ways), rman); @@ -302,7 +319,7 @@ void Changed_Constraint::filter(Resource_Manager& rman, Set& into) if (!stmt->trivial()) { - std::vector< Relation_Skeleton::Id_Type > ids = + std::vector< Relation_Skeleton::Id_Type > ids = relation_ids_within_valid ? relation_ids_within : collect_changed_elements< Uint31_Index, Relation_Skeleton > (stmt->get_since(rman), stmt->get_until(rman), Ids_In_Set_Predicate< Uint31_Index, Relation_Skeleton >(into.relations, into.attic_relations), rman); From 3289cfa2fd0ce8c9a06d0912b49f3d7fc70fa84c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 21:23:01 +0000 Subject: [PATCH 60/80] union: keep decompressed blocks while statements will re-read them 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 --- src/overpass_api/dispatch/resource_manager.h | 2 + src/overpass_api/statements/query.cc | 12 +++ src/overpass_api/statements/query.h | 3 + src/overpass_api/statements/union.cc | 48 ++++++++++++ src/template_db/block_cache.h | 79 ++++++++++++++++++++ src/template_db/file_blocks.h | 20 +++++ src/template_db/transaction.h | 9 +++ src/template_db/types.h | 8 ++ 8 files changed, 181 insertions(+) create mode 100644 src/template_db/block_cache.h diff --git a/src/overpass_api/dispatch/resource_manager.h b/src/overpass_api/dispatch/resource_manager.h index c502676a8..77ee330fe 100644 --- a/src/overpass_api/dispatch/resource_manager.h +++ b/src/overpass_api/dispatch/resource_manager.h @@ -159,6 +159,8 @@ class Resource_Manager bool health_check(const Statement& stmt, uint32 extra_time = 0, uint64 extra_space = 0); + uint64 get_max_allowed_space() const { return max_allowed_space; } + void set_limits(uint32 max_allowed_time_, uint64 max_allowed_space_) { max_allowed_time = max_allowed_time_; diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index 9878c3f54..1ee393fd6 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -97,6 +97,18 @@ Query_Statement::~Query_Statement() } +std::string Query_Statement::block_signature() const +{ + std::string result = to_string(type); + for (std::vector< Statement* >::const_iterator it = substatements.begin(); it != substatements.end(); ++it) + { + if (*it && !dynamic_cast< Has_Kv_Statement* >(*it)) + result += (*it)->dump_ql_in_query(""); + } + return result; +} + + void Query_Statement::add_statement(Statement* statement, std::string text) { assure_no_text(text, this->get_name()); diff --git a/src/overpass_api/statements/query.h b/src/overpass_api/statements/query.h index 9634ccafc..e4047d396 100644 --- a/src/overpass_api/statements/query.h +++ b/src/overpass_api/statements/query.h @@ -83,6 +83,9 @@ class Query_Statement : public Output_Statement static bool area_query_exists() { return area_query_exists_; } + // The query's type and its filters other than tag filters, as QL, e.g. "node(around:100,51.0,7.0)". + std::string block_signature() const; + static std::string to_string(int type) { if (type == QUERY_NODE) diff --git a/src/overpass_api/statements/union.cc b/src/overpass_api/statements/union.cc index 323522429..9d88162b8 100644 --- a/src/overpass_api/statements/union.cc +++ b/src/overpass_api/statements/union.cc @@ -26,6 +26,9 @@ #include "../data/abstract_processing.h" #include "../data/utils.h" +#include "../../template_db/block_cache.h" +#include "../../template_db/transaction.h" +#include "query.h" #include "union.h" @@ -63,8 +66,53 @@ void Union_Statement::add_statement(Statement* statement, std::string text) } +namespace +{ + // Query statements of one type with the same filters apart from tag filters read the same blocks. + bool rereads_expected(const std::vector< Statement* >& substatements) + { + std::map< std::string, int > count; + for (std::vector< Statement* >::const_iterator it = substatements.begin(); it != substatements.end(); ++it) + { + const Query_Statement* query = dynamic_cast< const Query_Statement* >(*it); + if (query && ++count[query->block_signature()] >= 2) + return true; + } + return false; + } + + struct Rereads_Expected_Guard + { + Rereads_Expected_Guard(Resource_Manager& rman, bool active) + { + if (!active) + return; + // A quarter of [maxsize:], outside its accounting like other auxiliary structures. + uint64 limit = rman.get_max_allowed_space() > 0 ? rman.get_max_allowed_space()/4 : 32ull*1024*1024; + Transaction* transactions[] = { rman.get_transaction(), rman.get_area_transaction() }; + for (Transaction* transaction : transactions) + { + Block_Cache* cache = transaction ? transaction->block_cache() : 0; + if (cache) + { + cache->begin_rereads(limit); + caches.push_back(cache); + } + } + } + ~Rereads_Expected_Guard() + { + for (Block_Cache* cache : caches) + cache->end_rereads(); + } + std::vector< Block_Cache* > caches; + }; +} + + void Union_Statement::execute(Resource_Manager& rman) { + Rereads_Expected_Guard guard(rman, rereads_expected(substatements)); rman.push_stack_frame(); rman.move_outward(get_result_name(), get_result_name()); diff --git a/src/template_db/block_cache.h b/src/template_db/block_cache.h new file mode 100644 index 000000000..43c92e886 --- /dev/null +++ b/src/template_db/block_cache.h @@ -0,0 +1,79 @@ +/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al. + * + * This file is part of Overpass_API. + * + * Overpass_API is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * Overpass_API is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Overpass_API. If not, see . + */ + +#ifndef DE__OSM3S___TEMPLATE_DB__BLOCK_CACHE_H +#define DE__OSM3S___TEMPLATE_DB__BLOCK_CACHE_H + +#include "types.h" + +#include +#include +#include + + +// Decompressed blocks of a transaction's read-only files, kept while a statement runs that will +// re-read them. Nothing is evicted; once limit bytes are kept, further blocks are not. +class Block_Cache +{ +public: + Block_Cache() : rereads_expected(0), bytes(0), limit(0) {} + + void begin_rereads(uint64 limit_) + { + if (rereads_expected == 0 || limit_ < limit) + limit = limit_; + ++rereads_expected; + } + void end_rereads() { --rereads_expected; } + + const std::vector< uint8 >* find(const void* file, uint32 pos) const + { + if (blocks.empty()) + return 0; + std::map< std::pair< const void*, uint32 >, std::vector< uint8 > >::const_iterator it + = blocks.find(std::make_pair(file, pos)); + return it == blocks.end() ? 0 : &it->second; + } + + void offer(const void* file, uint32 pos, const uint8* data, uint64 size) + { + if (rereads_expected > 0 && bytes + size <= limit) + { + blocks[std::make_pair(file, pos)].assign(data, data + size); + bytes += size; + } + } + + void clear() + { + blocks.clear(); + bytes = 0; + } + +private: + Block_Cache(const Block_Cache&); + Block_Cache& operator=(const Block_Cache&); + + int rereads_expected; + uint64 bytes; + uint64 limit; + std::map< std::pair< const void*, uint32 >, std::vector< uint8 > > blocks; +}; + + +#endif diff --git a/src/template_db/file_blocks.h b/src/template_db/file_blocks.h index b214b52f0..07308f38f 100644 --- a/src/template_db/file_blocks.h +++ b/src/template_db/file_blocks.h @@ -19,6 +19,7 @@ #ifndef DE__OSM3S___TEMPLATE_DB__FILE_BLOCKS_H #define DE__OSM3S___TEMPLATE_DB__FILE_BLOCKS_H +#include "block_cache.h" #include "file_blocks_index.h" #include "types.h" #include "lz4_wrapper.h" @@ -818,6 +819,21 @@ uint64* File_Blocks< TIndex, TIterator >::read_block_ if (sigterm_status()) throw File_Error(0, "-", "SIGTERM received"); + // Blocks read without the index check continue a large object and don't start with their size. + Block_Cache* cache = rd_idx && check_idx && compression_method != File_Blocks_Index_Base::NO_COMPRESSION + ? rd_idx->block_cache : 0; + if (cache) + { + const std::vector< uint8 >* cached = cache->find(rd_idx, block.pos()); + if (cached) + { + memcpy(buffer_, &(*cached)[0], cached->size()); + ++read_count_; + ++global_read_counter(); + return buffer_; + } + } + if (compression_method == File_Blocks_Index_Base::NO_COMPRESSION) { data_file.seek((int64)(block.pos()) * block_size, "File_Blocks::read_block::1"); @@ -871,6 +887,10 @@ uint64* File_Blocks< TIndex, TIterator >::read_block_ out<<"File_Blocks::read_block: Index inconsistent at offset "<<((int64)(block.pos()) * block_size + 8); throw File_Error(block.pos(), rd_idx ? rd_idx->get_data_file_name() : wr_idx->get_data_file_name(), out.str()); } + if (cache) + // Readers stop at the block's used size, its first word; keep only those bytes. + cache->offer(rd_idx, block.pos(), (const uint8*)buffer_, + std::min< uint64 >(std::max< uint32 >(*(uint32*)buffer_, 8), (uint64)block_size * compression_factor)); ++read_count_; ++global_read_counter(); return buffer_; diff --git a/src/template_db/transaction.h b/src/template_db/transaction.h index c9931e03e..101092362 100644 --- a/src/template_db/transaction.h +++ b/src/template_db/transaction.h @@ -19,6 +19,7 @@ #ifndef DE__OSM3S___TEMPLATE_DB__TRANSACTION_H #define DE__OSM3S___TEMPLATE_DB__TRANSACTION_H +#include "block_cache.h" #include "random_file.h" #include @@ -34,6 +35,7 @@ class Transaction virtual File_Blocks_Index_Base* data_index(const File_Properties*) = 0; virtual Random_File_Index* random_index(const File_Properties*) = 0; virtual std::string get_db_dir() const = 0; + virtual Block_Cache* block_cache() { return 0; } }; @@ -49,6 +51,7 @@ class Nonsynced_Transaction : public Transaction void flush(); std::string get_db_dir() const { return db_dir; } + Block_Cache* block_cache() { return &block_cache_; } private: std::map< const File_Properties*, File_Blocks_Index_Base* > @@ -58,6 +61,7 @@ class Nonsynced_Transaction : public Transaction Access_Mode access_mode; bool use_shadow; std::string file_name_extension, db_dir; + Block_Cache block_cache_; }; @@ -89,6 +93,7 @@ inline void Nonsynced_Transaction::flush() it = random_files.begin(); it != random_files.end(); ++it) delete it->second; random_files.clear(); + block_cache_.clear(); } @@ -102,7 +107,11 @@ inline File_Blocks_Index_Base* Nonsynced_Transaction::data_index File_Blocks_Index_Base* data_index = fp->new_data_index(access_mode, use_shadow, db_dir, file_name_extension); if (data_index != 0) + { + if (access_mode == Access_Mode::readonly) + data_index->block_cache = &block_cache_; data_files[fp] = data_index; + } return data_index; } diff --git a/src/template_db/types.h b/src/template_db/types.h index 969a6d815..4118f8910 100644 --- a/src/template_db/types.h +++ b/src/template_db/types.h @@ -71,8 +71,13 @@ struct File_Properties_Exception }; +class Block_Cache; + + struct File_Blocks_Index_Base { + File_Blocks_Index_Base() : block_cache(0) {} + virtual bool empty() const = 0; virtual ~File_Blocks_Index_Base() {} @@ -88,6 +93,9 @@ struct File_Blocks_Index_Base static const int ZLIB_COMPRESSION = 1; static const int LZ4_COMPRESSION = 2; static const unsigned int IDX_HEADER_LENGTH = 8; + + // Set by the transaction for read-only files. + Block_Cache* block_cache; }; From 0c8a58686bb14a2da116f85114b246477c3ad6a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 07:15:45 +0000 Subject: [PATCH 61/80] tags: run tag index regexes once per key and value, not per element 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; --- src/overpass_api/data/tags_global_reader.h | 45 ++++++++++++++++++++-- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/src/overpass_api/data/tags_global_reader.h b/src/overpass_api/data/tags_global_reader.h index 929fc930d..ad1a1fe53 100644 --- a/src/overpass_api/data/tags_global_reader.h +++ b/src/overpass_api/data/tags_global_reader.h @@ -22,6 +22,7 @@ #include #include +#include #include @@ -283,6 +284,42 @@ struct Trivial_Regex }; +// Tests tag index entries against a key and a value regex. The entries come sorted by key and value, +// so consecutive entries mostly repeat both: only evaluate the regexes when one of them changes. +template< typename Key_Regex, typename Val_Regex > +class Tag_Entry_Matcher +{ +public: + Tag_Entry_Matcher(const Key_Regex& key_regex, const Val_Regex& val_regex) + : key_regex_(key_regex), val_regex_(val_regex), valid_(false), matches_(false) {} + + template< typename Index > + bool matches(const Index& index) + { + // Without regexes (key=value lookups) there is nothing worth remembering. + if (std::is_same< Key_Regex, Trivial_Regex >::value && std::is_same< Val_Regex, Trivial_Regex >::value) + return index.value != void_tag_value(); + + if (!valid_ || index.value != value_ || index.key != key_) + { + key_ = index.key; + value_ = index.value; + matches_ = key_regex_.matches(key_) && value_ != void_tag_value() && val_regex_.matches(value_); + valid_ = true; + } + return matches_; + } + +private: + const Key_Regex& key_regex_; + const Val_Regex& val_regex_; + std::string key_; + std::string value_; + bool valid_; + bool matches_; +}; + + template< typename Id_Type, typename Iterator, typename Key_Regex, typename Val_Regex > void filter_id_list( std::vector< std::pair< Id_Type, Uint31_Index > >& new_ids, bool& filtered, @@ -291,11 +328,11 @@ void filter_id_list( { std::vector< std::pair< Id_Type, Uint31_Index > > old_ids; old_ids.swap(new_ids); + Tag_Entry_Matcher< Key_Regex, Val_Regex > matcher(key_regex, val_regex); for (Iterator it = begin; !(it == end); ++it) { - if (key_regex.matches(it.index().key) && it.index().value != void_tag_value() - && val_regex.matches(it.index().value) && (!filtered || + if (matcher.matches(it.index()) && (!filtered || std::binary_search(old_ids.begin(), old_ids.end(), std::make_pair(it.object().id, Uint31_Index(0u))))) new_ids.push_back(std::make_pair(it.object().id, it.object().idx)); @@ -320,11 +357,11 @@ void filter_id_list( { std::vector< Id_Type > old_ids; old_ids.swap(new_ids); + Tag_Entry_Matcher< Key_Regex, Val_Regex > matcher(key_regex, val_regex); for (Iterator it = begin; !(it == end); ++it) { - if (key_regex.matches(it.index().key) && it.index().value != void_tag_value() - && val_regex.matches(it.index().value) && + if (matcher.matches(it.index()) && (!filtered || std::binary_search(old_ids.begin(), old_ids.end(), it.object()))) new_ids.push_back(it.object()); } From 631fca71e8601d6205df017a9dce5aeb2ce7dcc3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 07:29:56 +0000 Subject: [PATCH 62/80] query: read only the checked keys' tag entries in late tag checks 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; --- src/overpass_api/core/type_tags.h | 16 ++++++++++++++++ src/overpass_api/statements/query.cc | 12 +++++++----- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/overpass_api/core/type_tags.h b/src/overpass_api/core/type_tags.h index c40b4785e..8d8f651a3 100644 --- a/src/overpass_api/core/type_tags.h +++ b/src/overpass_api/core/type_tags.h @@ -277,6 +277,22 @@ Ranges< Tag_Index_Local > formulate_range_query(const std::map< uint32, Value >& } +// The tag entries of only the given keys, which must be sorted, in the given coarse indices. +// key + '\0' sorts after every entry of key and before any longer key that starts with it. +template< class Value, class Key_Container > +Ranges< Tag_Index_Local > formulate_range_query( + const std::map< uint32, Value >& coarse_indices, const Key_Container& keys) +{ + Ranges< Tag_Index_Local > ranges; + for (typename std::map< uint32, Value >::const_iterator it = coarse_indices.begin(); it != coarse_indices.end(); ++it) + { + for (typename Key_Container::const_iterator kit = keys.begin(); kit != keys.end(); ++kit) + ranges.push_back({ it->first, kit->first, "" }, { it->first, kit->first + std::string(1, '\0'), "" }); + } + return ranges; +} + + template< class TIndex, class TObject > void generate_ids_by_coarse (std::map< uint32, std::vector< typename TObject::Id_Type > >& ids_by_coarse, diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index 1ee393fd6..91dd74aae 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -508,9 +508,6 @@ void Query_Statement::filter_by_tags if (attic_items) cell_attic_it = attic_items->begin(); - // formulate range query - Ranges< Tag_Index_Local > ranges = formulate_range_query(ids_by_coarse); - // prepare straight keys std::map< std::string, std::pair< std::string, std::vector< Regular_Expression* > > > key_union; for (std::vector< std::string >::const_iterator it = keys.begin(); it != keys.end(); @@ -523,6 +520,10 @@ void Query_Statement::filter_by_tags it = key_regexes.begin(); it != key_regexes.end(); ++it) key_union[it->first].second.push_back(it->second); + // formulate range query: read only the entries of these keys, unless a key regex must see every key + Ranges< Tag_Index_Local > ranges = regkey_regexes.empty() + ? formulate_range_query(ids_by_coarse, key_union) : formulate_range_query(ids_by_coarse); + // iterate over the result std::map< TIndex, std::vector< TObject > > result; std::map< TIndex, std::vector< Attic< TObject > > > attic_result; @@ -586,7 +587,8 @@ void Query_Statement::filter_by_tags result.clear(); attic_result.clear(); coarse_count = 0; - auto ntag_it = items_db.range_begin(ranges); + Ranges< Tag_Index_Local > nranges = formulate_range_query(ids_by_coarse, nkey_union); + auto ntag_it = items_db.range_begin(nranges); if (timestamp == NOW) { @@ -605,7 +607,7 @@ void Query_Statement::filter_by_tags { Block_Backend< Tag_Index_Local, Attic< typename TObject::Id_Type > > attic_items_db (transaction.data_index(attic_file_prop)); - auto attic_ntag_it = attic_items_db.range_begin(ranges); + auto attic_ntag_it = attic_items_db.range_begin(nranges); for (typename std::map< uint32, std::vector< typename TObject::Id_Type > >::iterator it = ids_by_coarse.begin(); it != ids_by_coarse.end(); ++it) From 2100eab572ed3cedfc575d9ee747246527615fd7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 07:29:32 +0000 Subject: [PATCH 63/80] regex: match plain word alternations without the regex library 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; --- src/overpass_api/data/regular_expression.h | 97 ++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/src/overpass_api/data/regular_expression.h b/src/overpass_api/data/regular_expression.h index 31083c8cf..242770c67 100644 --- a/src/overpass_api/data/regular_expression.h +++ b/src/overpass_api/data/regular_expression.h @@ -25,6 +25,7 @@ #include #include +#include struct Regular_Expression_Error @@ -55,6 +56,14 @@ class Regular_Expression if (strategy == call_library) { + literal_mode = parse_literals(regex, literals); + if (literal_mode != no_literals && !case_sensitive) + { + for (std::vector< std::string >::iterator it = literals.begin(); it != literals.end(); ++it) + *it = ascii_lower(*it); + } + literal_case_sensitive = case_sensitive; + setlocale(LC_ALL, "C.UTF-8"); int case_flag = case_sensitive ? 0 : REG_ICASE; int error_no = regcomp(&preg, regex.c_str(), REG_EXTENDED|REG_NOSUB|case_flag); @@ -78,6 +87,8 @@ class Regular_Expression // if (is_cache_available && line == prev_line) // return prev_result; + if (literal_mode != no_literals && is_ascii(line)) + return matches_literals(line); bool result = (regexec(&preg, line.c_str(), 0, 0, 0) == 0); // is_cache_available = true; @@ -88,11 +99,97 @@ class Regular_Expression } private: + // Patterns that are only plain ASCII words separated by '|', either unanchored + // ("cafe|bar": the value contains one of them) or anchored as a whole ("^(cafe|bar)$" + // or "^cafe$": the value is one of them), are matched without the library for ASCII + // values. For those, the result is the same, also with REG_ICASE. Other values go to + // the library, so its handling of non-ASCII text is unchanged. + enum Literal_Mode { no_literals, contains_literal, equals_literal }; + + static bool is_literal_char(char c) + { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') + || c == ' ' || c == '_' || c == '-' || c == ':' || c == ';' || c == ',' || c == '\'' || c == '&' || c == '/'; + } + + static bool is_ascii(const std::string& s) + { + for (std::string::const_iterator it = s.begin(); it != s.end(); ++it) + { + if ((unsigned char)*it >= 0x80 || *it == 0) + return false; + } + return true; + } + + static std::string ascii_lower(std::string s) + { + for (std::string::iterator it = s.begin(); it != s.end(); ++it) + { + if (*it >= 'A' && *it <= 'Z') + *it += 'a' - 'A'; + } + return s; + } + + static Literal_Mode parse_literals(const std::string& regex, std::vector< std::string >& literals) + { + std::string body = regex; + Literal_Mode mode = contains_literal; + if (body.size() >= 2 && body[0] == '^' && body[body.size()-1] == '$') + { + body = body.substr(1, body.size() - 2); + if (body.size() >= 2 && body[0] == '(' && body[body.size()-1] == ')') + body = body.substr(1, body.size() - 2); + else if (body.find('|') != std::string::npos) + // "^a|b$" means "^a" or "b$". + return no_literals; + mode = equals_literal; + } + std::string::size_type start = 0; + while (true) + { + std::string::size_type end = body.find('|', start); + std::string literal = body.substr(start, end == std::string::npos ? std::string::npos : end - start); + if (literal.empty()) + return no_literals; + for (std::string::const_iterator it = literal.begin(); it != literal.end(); ++it) + { + if (!is_literal_char(*it)) + return no_literals; + } + literals.push_back(literal); + if (end == std::string::npos) + return mode; + start = end + 1; + } + } + + bool matches_literals(const std::string& line) const + { + if (literal_case_sensitive) + return matches_literals_exactly(line); + return matches_literals_exactly(ascii_lower(line)); + } + + bool matches_literals_exactly(const std::string& value) const + { + for (std::vector< std::string >::const_iterator it = literals.begin(); it != literals.end(); ++it) + { + if (literal_mode == equals_literal ? value == *it : value.find(*it) != std::string::npos) + return true; + } + return false; + } + Regular_Expression(const Regular_Expression&); const Regular_Expression& operator=(const Regular_Expression&); regex_t preg; Strategy strategy; + Literal_Mode literal_mode = no_literals; + bool literal_case_sensitive = true; + std::vector< std::string > literals; // mutable bool cache_available; // mutable std::string prev_line; // mutable bool prev_result; From ed5c1dc145ec955407e0b9b6b31c314c49dc57b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 20:03:40 +0000 Subject: [PATCH 64/80] tags: remove redundant sorts of the candidate ids for late tag checks 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 --- src/overpass_api/core/type_tags.h | 6 ------ src/overpass_api/data/filter_ids_by_tags.h | 3 ++- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/src/overpass_api/core/type_tags.h b/src/overpass_api/core/type_tags.h index 8d8f651a3..1ce0c59ce 100644 --- a/src/overpass_api/core/type_tags.h +++ b/src/overpass_api/core/type_tags.h @@ -315,9 +315,6 @@ void generate_ids_by_coarse std::sort(ids_by_coarse_.begin(), ids_by_coarse_.end()); ids_by_coarse_.erase(std::unique(ids_by_coarse_.begin(), ids_by_coarse_.end()), ids_by_coarse_.end()); } - for (typename std::map< uint32, std::vector< typename TObject::Id_Type > >::iterator - it = ids_by_coarse.begin(); it != ids_by_coarse.end(); ++it) - std::sort(it->second.begin(), it->second.end()); } @@ -344,9 +341,6 @@ void generate_ids_by_coarse std::sort(ids_by_coarse_.begin(), ids_by_coarse_.end()); ids_by_coarse_.erase(std::unique(ids_by_coarse_.begin(), ids_by_coarse_.end()), ids_by_coarse_.end()); } - for (typename std::map< uint32, std::vector< Attic< typename TObject::Id_Type > > >::iterator - it = ids_by_coarse.begin(); it != ids_by_coarse.end(); ++it) - std::sort(it->second.begin(), it->second.end()); } diff --git a/src/overpass_api/data/filter_ids_by_tags.h b/src/overpass_api/data/filter_ids_by_tags.h index 9104a9307..683d04f6c 100644 --- a/src/overpass_api/data/filter_ids_by_tags.h +++ b/src/overpass_api/data/filter_ids_by_tags.h @@ -64,7 +64,8 @@ void filter_ids_by_tags key_relevant = true; old_ids.clear(); old_ids.swap(new_ids); - sort(old_ids.begin(), old_ids.end()); + if (!std::is_sorted(old_ids.begin(), old_ids.end())) + sort(old_ids.begin(), old_ids.end()); } matched_by_key_regexes.clear(); From 235f7824fa99b1c2fb7b435f62e661553bbd68a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:07:11 +0000 Subject: [PATCH 65/80] bbox: don't load the geometry of ways whose index lies inside the bbox 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; --- src/overpass_api/data/bbox_filter.cc | 63 +++++++++++++--------------- 1 file changed, 28 insertions(+), 35 deletions(-) diff --git a/src/overpass_api/data/bbox_filter.cc b/src/overpass_api/data/bbox_filter.cc index 6940e2010..fea693fcc 100644 --- a/src/overpass_api/data/bbox_filter.cc +++ b/src/overpass_api/data/bbox_filter.cc @@ -153,35 +153,6 @@ void filter_ways_expensive(const Bbox_Filter& filter, const Way_Geometry_Store& } -/* A way whose index is a single tile (bit 31 clear) has all its nodes in that tile. If - the tile lies inside the bbox, so do all of the way's nodes, and Bbox_Filter::matches - accepts any way with a node inside the bbox (single nodes via contains(), segments via - intersects()). Such ways can be kept without loading their geometry. - - Moves the vectors of those ways from ways to kept. A tile's bounds are the positions - decoded with the lowest and highest ll_lower; every node position in the tile lies - between them. Boxes crossing the antimeridian are left to the exact test. */ -template< typename Way_Skeleton > -void move_ways_in_inner_tiles(const Bbox_Double& bbox, - std::map< Uint31_Index, std::vector< Way_Skeleton > >& ways, - std::map< Uint31_Index, std::vector< Way_Skeleton > >& kept) -{ - if (!(bbox.west <= bbox.east)) - return; - - for (typename std::map< Uint31_Index, std::vector< Way_Skeleton > >::iterator it = ways.begin(); - it != ways.end(); ++it) - { - uint32 idx = it->first.val(); - if ((idx & 0x80000000) || it->second.empty()) - continue; - if (::lat(idx, 0) >= bbox.south && ::lat(idx, 0xffffffff) <= bbox.north - && ::lon(idx, 0) >= bbox.west && ::lon(idx, 0xffffffff) <= bbox.east) - kept[it->first].swap(it->second); - } -} - - template< typename Relation_Skeleton > void filter_relations_expensive(const Bbox_Filter& filter, const std::vector< std::pair< Uint32_Index, const Node_Skeleton* > > node_members_by_id, @@ -233,19 +204,41 @@ void filter_relations_expensive(const Bbox_Filter& filter, } +// Whether the whole area of a way or relation index lies in the bbox. Every node of a way +// with that index is then in the bbox, so the way matches without loading its geometry. +bool contains_index_area(const Bbox_Double& bbox, Uint31_Index idx) +{ + if (bbox.west > bbox.east || bbox.east - bbox.west >= 180.) + return false; + + std::pair< Uint32_Index, Uint32_Index > bounds = calc_bbox_bounds(idx); + uint32 south_west = bounds.first.val(); + uint32 north_east = bounds.second.val() - 1; + return bbox.south <= ::lat(south_west, 0u) && ::lat(north_east, 0xffffffffu) <= bbox.north + && bbox.west <= ::lon(south_west, 0u) && ::lon(north_east, 0xffffffffu) <= bbox.east; +} + + void Bbox_Filter::filter(const Statement& query, Resource_Manager& rman, Set& into) const { if (!bbox.valid()) return; - //Process ways. Ways entirely within inner tiles need no geometry. + //Process ways: only those whose index area isn't inside the bbox need their geometry + std::map< Uint31_Index, std::vector< Way_Skeleton > > ways_inside; + for (auto it = into.ways.begin(); it != into.ways.end(); ) { - std::map< Uint31_Index, std::vector< Way_Skeleton > > kept; - move_ways_in_inner_tiles(bbox, into.ways, kept); - filter_ways_expensive(*this, Way_Geometry_Store(into.ways, query, rman), into.ways); - for (std::map< Uint31_Index, std::vector< Way_Skeleton > >::iterator it = kept.begin(); it != kept.end(); ++it) - into.ways[it->first].swap(it->second); + if (contains_index_area(bbox, it->first)) + { + ways_inside[it->first].swap(it->second); + it = into.ways.erase(it); + } + else + ++it; } + filter_ways_expensive(*this, Way_Geometry_Store(into.ways, query, rman), into.ways); + for (auto it = ways_inside.begin(); it != ways_inside.end(); ++it) + into.ways[it->first].swap(it->second); Request_Context context(&query, rman); { From d9e2a5df88e67c8740107d20d61967d93dfed896 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:27:44 +0000 Subject: [PATCH 66/80] around: don't load the geometry of ways whose index lies within the radius 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; --- src/overpass_api/statements/around.cc | 60 +++++++++++++++++++++++++++ src/overpass_api/statements/around.h | 1 + 2 files changed, 61 insertions(+) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index b004beffb..4169eb84b 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -383,7 +383,22 @@ void Around_Constraint::filter(const Statement& query, Resource_Manager& rman, S around->calc_lat_lons(input ? *input : empty, *around, rman); filter_nodes_expensive(*around, check, into.nodes); + + // Only the ways whose index area isn't within the radius need their geometry + std::map< Uint31_Index, std::vector< Way_Skeleton > > ways_inside; + for (auto it = into.ways.begin(); it != into.ways.end(); ) + { + if (around->contains_index_area(it->first)) + { + ways_inside[it->first].swap(it->second); + it = into.ways.erase(it); + } + else + ++it; + } filter_ways_expensive(*around, check, Way_Geometry_Store(into.ways, query, rman), into.ways); + for (auto it = ways_inside.begin(); it != ways_inside.end(); ++it) + into.ways[it->first].swap(it->second); Request_Context context(&query, rman); { @@ -1116,6 +1131,51 @@ void Around_Statement::calc_lat_lons(const Set& input, Statement& query, Resourc } +// Whether the whole area of a way or relation index lies within the radius of one of the points. +// Every node of a way with that index is then inside, so the way matches without its geometry. +// Over a lat/lon box narrower than 180 degrees, the distance to a point is greatest at a corner: +// along a parallel or a meridian it grows towards the ends. +bool Around_Statement::contains_index_area(Uint31_Index idx) const +{ + if (radius <= 1. || !simple_segments.empty() || simple_lat_lons.empty() || simple_lat_lons.size() > 64) + return false; + + std::pair< Uint32_Index, Uint32_Index > bounds = calc_bbox_bounds(idx); + uint32 south_west = bounds.first.val(); + uint32 north_east = bounds.second.val() - 1; + double south = ::lat(south_west, 0u); + double north = ::lat(north_east, 0xffffffffu); + double west = ::lon(south_west, 0u); + double east = ::lon(north_east, 0xffffffffu); + if (east - west >= 180. || east < west) + return false; + + // A margin of 1 m against rounding. + double limit = radius - 1.; + for (std::vector< Prepared_Point >::const_iterator it = simple_lat_lons.begin(); it != simple_lat_lons.end(); ++it) + { + // is_inside only finds a point in the tiles add_coord registered it for: those of this bbox. + double point_south = it->lat - radius*(360.0/(40000.0*1000.0)); + double point_north = it->lat + radius*(360.0/(40000.0*1000.0)); + double scale_lat = it->lat > 0.0 ? point_north : point_south; + if (std::abs(scale_lat) >= 89.9) + continue; + double point_west = it->lon - radius*(360.0/(40000.0*1000.0))/cos(scale_lat/90.0*acos(0)); + double point_east = it->lon + radius*(360.0/(40000.0*1000.0))/cos(scale_lat/90.0*acos(0)); + if (point_west < -180. || point_east > 180. + || south < point_south || north > point_north || west < point_west || east > point_east) + continue; + + if (great_circle_dist(it->lat, it->lon, south, west) <= limit + && great_circle_dist(it->lat, it->lon, south, east) <= limit + && great_circle_dist(it->lat, it->lon, north, west) <= limit + && great_circle_dist(it->lat, it->lon, north, east) <= limit) + return true; + } + return false; +} + + bool Around_Statement::is_inside(double lat, double lon) const { std::map< Uint32_Index, std::vector< Point_Double > >::const_iterator mit diff --git a/src/overpass_api/statements/around.h b/src/overpass_api/statements/around.h index 77d189e5b..fb411e804 100644 --- a/src/overpass_api/statements/around.h +++ b/src/overpass_api/statements/around.h @@ -219,6 +219,7 @@ class Around_Statement : public Output_Statement uint64 comparisons_per_test() const { return std::min< uint64 >(simple_lat_lons.size() + simple_segments.size() + 1, 1024); } + bool contains_index_area(Uint31_Index idx) const; double get_radius() const { return radius; } template< typename Node_Skeleton > From bf412ad0ec6ff6b073e5625105c16a273477b21b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:06:55 +0000 Subject: [PATCH 67/80] around: skip points too far apart in latitude before the distance test 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; --- src/overpass_api/statements/around.cc | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/overpass_api/statements/around.cc b/src/overpass_api/statements/around.cc index 4169eb84b..2f5d3aeab 100644 --- a/src/overpass_api/statements/around.cc +++ b/src/overpass_api/statements/around.cc @@ -1178,6 +1178,11 @@ bool Around_Statement::contains_index_area(Uint31_Index idx) const bool Around_Statement::is_inside(double lat, double lon) const { + // A great-circle distance is at least the difference in latitude, which great_circle_dist + // counts as 10,000 km per 90 degrees. Points farther apart than radius + 1 m in latitude + // can't match; the metre covers rounding in great_circle_dist. + const double max_lat_diff = (radius + 1.)*(90./(10.*1000.*1000.)); + std::map< Uint32_Index, std::vector< Point_Double > >::const_iterator mit = radius_lat_lons.find(::ll_upper_(lat, lon)); if (mit != radius_lat_lons.end()) @@ -1185,6 +1190,8 @@ bool Around_Statement::is_inside(double lat, double lon) const for (std::vector< Point_Double >::const_iterator cit = mit->second.begin(); cit != mit->second.end(); ++cit) { + if (std::abs(cit->lat - lat) > max_lat_diff) + continue; if ((radius > 0 && great_circle_dist(cit->lat, cit->lon, lat, lon) <= radius) || (std::abs(cit->lat - lat) < 1e-7 && std::abs(cit->lon - lon) < 1e-7)) return true; From 9f4813ce5fc1a8b34dd4b84dc9443058d32fc69d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:14:44 +0000 Subject: [PATCH 68/80] recurse: handle wr(bn) in the query constraint 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)[...];). --- src/overpass_api/statements/recurse.cc | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/overpass_api/statements/recurse.cc b/src/overpass_api/statements/recurse.cc index b42398ec5..b937a49d8 100644 --- a/src/overpass_api/statements/recurse.cc +++ b/src/overpass_api/statements/recurse.cc @@ -591,7 +591,7 @@ Ranges< Uint31_Index > Recurse_Constraint::get_way_ranges(Resource_Manager& rman if (stmt->get_type() == RECURSE_RELATION_WAY || stmt->get_type() == RECURSE_RELATION_NWR || stmt->get_type() == RECURSE_RELATION_NW || stmt->get_type() == RECURSE_RELATION_WR) return relation_way_member_indices(input->relations, input->attic_relations); - else if (stmt->get_type() == RECURSE_NODE_WAY) + else if (stmt->get_type() == RECURSE_NODE_WAY || stmt->get_type() == RECURSE_NODE_WR) return extract_parent_indices(input->nodes, input->attic_nodes); return Ranges< Uint31_Index >::global(); @@ -604,7 +604,7 @@ Ranges< Uint31_Index > Recurse_Constraint::get_relation_ranges(Resource_Manager& if (!input) return Ranges< Uint31_Index >(); - if (stmt->get_type() == RECURSE_NODE_RELATION) + if (stmt->get_type() == RECURSE_NODE_RELATION || stmt->get_type() == RECURSE_NODE_WR) return extract_parent_indices(input->nodes, input->attic_nodes); else if (stmt->get_type() == RECURSE_WAY_RELATION) return extract_parent_indices(input->ways, input->attic_ways); @@ -697,7 +697,8 @@ bool Recurse_Constraint::get_data relation_relation_members( context, input->relations, input->attic_relations, ranges, ids, invert_ids, &role_id) .swap(into.relations, into.attic_relations); - else if (stmt->get_type() == RECURSE_NODE_RELATION) + else if (stmt->get_type() == RECURSE_NODE_RELATION + || (stmt->get_type() == RECURSE_NODE_WR && type == QUERY_RELATION)) collect_relations( query, rman, input->nodes, input->attic_nodes, Relation_Entry::NODE, ids, invert_ids, role_id) .swap(into.relations, into.attic_relations); @@ -753,10 +754,12 @@ bool Recurse_Constraint::get_data rel_rels.swap(into.relations, into.attic_relations); } } - else if (stmt->get_type() == RECURSE_NODE_WAY) + else if (stmt->get_type() == RECURSE_NODE_WAY + || (stmt->get_type() == RECURSE_NODE_WR && type == QUERY_WAY)) collect_ways(context, input->nodes, input->attic_nodes, stmt->get_pos(), ids, invert_ids) .swap(into.ways, into.attic_ways); - else if (stmt->get_type() == RECURSE_NODE_RELATION) + else if (stmt->get_type() == RECURSE_NODE_RELATION + || (stmt->get_type() == RECURSE_NODE_WR && type == QUERY_RELATION)) collect_relations(query, rman, input->nodes, input->attic_nodes, Relation_Entry::NODE, ids, invert_ids) .swap(into.relations, into.attic_relations); else if (stmt->get_type() == RECURSE_WAY_RELATION) @@ -923,8 +926,8 @@ void Recurse_Constraint::filter(Resource_Manager& rman, Set& into) .filter_items(Id_Predicate< Way_Skeleton >( relation_way_member_ids(input->relations, input->attic_relations))) .swap(into.ways, into.attic_ways); - else if (stmt->get_type() == RECURSE_NODE_WAY || stmt->get_type() == RECURSE_UP - || stmt->get_type() == RECURSE_UP_REL) + else if (stmt->get_type() == RECURSE_NODE_WAY || stmt->get_type() == RECURSE_NODE_WR + || stmt->get_type() == RECURSE_UP || stmt->get_type() == RECURSE_UP_REL) Timeless< Uint31_Index, Way_Skeleton >{}.swap(into.ways, into.attic_ways) .filter_items(Get_Parent_Ways_Predicate(extract_ids(input->nodes, input->attic_nodes), stmt->get_pos())) .swap(into.ways, into.attic_ways); @@ -937,7 +940,7 @@ void Recurse_Constraint::filter(Resource_Manager& rman, Set& into) .filter_items(Id_Predicate< Relation_Skeleton >( relation_relation_member_ids(input->relations, input->attic_relations))) .swap(into.relations, into.attic_relations); - else if (stmt->get_type() == RECURSE_NODE_RELATION) + else if (stmt->get_type() == RECURSE_NODE_RELATION || stmt->get_type() == RECURSE_NODE_WR) Timeless< Uint31_Index, Relation_Skeleton >{}.swap(into.relations, into.attic_relations) .filter_items(Get_Parent_Rels_Predicate( extract_ids(input->nodes, input->attic_nodes), Relation_Entry::NODE)) From b9ae8427a8b082d3a70d6e71dee8e819a313d817 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:40:03 +0000 Subject: [PATCH 69/80] tags: bound the ids collected from attic tags, as for current data 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 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/data/tags_global_reader.h | 63 +++++++++++++++++++--- 1 file changed, 55 insertions(+), 8 deletions(-) diff --git a/src/overpass_api/data/tags_global_reader.h b/src/overpass_api/data/tags_global_reader.h index ad1a1fe53..0e5571688 100644 --- a/src/overpass_api/data/tags_global_reader.h +++ b/src/overpass_api/data/tags_global_reader.h @@ -65,7 +65,7 @@ std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_kv( std::vector< std::pair< std::string, std::string > >::const_iterator kvit, uint64 timestamp, Block_Backend< Tag_Index_Global, Tag_Object_Global< Id_Type > >& tags_db, Block_Backend< Tag_Index_Global, Attic< Tag_Object_Global< Id_Type > > >& attic_tags_db, - std::vector< std::pair< Id_Type, Uint31_Index > >* relevant_ids = 0) + std::vector< std::pair< Id_Type, Uint31_Index > >* relevant_ids = 0, std::size_t limit = 0) { std::map< Id_Type, std::pair< uint64, Uint31_Index > > timestamp_per_id; Ranges< Tag_Index_Global > tag_req = get_kv_req(kvit->first, kvit->second); @@ -74,7 +74,11 @@ std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_kv( { if (!relevant_ids || std::binary_search( relevant_ids->begin(), relevant_ids->end(), std::make_pair(it2.object().id, Uint31_Index(0u)))) + { timestamp_per_id[it2.object().id] = std::make_pair(NOW, it2.object().idx); + if (limit && timestamp_per_id.size() >= limit) + return timestamp_per_id; + } } for (auto it2 = attic_tags_db.range_begin(tag_req); !(it2 == attic_tags_db.range_end()); ++it2) @@ -86,6 +90,8 @@ std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_kv( std::pair< uint64, Uint31_Index >& ref = timestamp_per_id[it2.object().id]; if (ref.first == 0 || it2.object().timestamp < ref.first) ref = std::make_pair(it2.object().timestamp, it2.object().idx); + if (limit && timestamp_per_id.size() >= limit) + return timestamp_per_id; } } @@ -113,21 +119,34 @@ template< class Id_Type > std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_k( std::vector< std::string >::const_iterator kit, uint64 timestamp, Block_Backend< Tag_Index_Global, Tag_Object_Global< Id_Type > >& tags_db, - Block_Backend< Tag_Index_Global, Attic< Tag_Object_Global< Id_Type > > >& attic_tags_db) + Block_Backend< Tag_Index_Global, Attic< Tag_Object_Global< Id_Type > > >& attic_tags_db, + std::vector< std::pair< Id_Type, Uint31_Index > >* relevant_ids = 0, std::size_t limit = 0) { std::map< Id_Type, std::pair< uint64, Uint31_Index > > timestamp_per_id; Ranges< Tag_Index_Global > ranges = get_k_req(*kit); for (auto it2 = tags_db.range_begin(ranges); !(it2 == tags_db.range_end()); ++it2) - timestamp_per_id[it2.object().id] = std::make_pair(NOW, it2.object().idx); + { + if (!relevant_ids || std::binary_search( + relevant_ids->begin(), relevant_ids->end(), std::make_pair(it2.object().id, Uint31_Index(0u)))) + { + timestamp_per_id[it2.object().id] = std::make_pair(NOW, it2.object().idx); + if (limit && timestamp_per_id.size() >= limit) + return timestamp_per_id; + } + } for (auto it2 = attic_tags_db.range_begin(ranges); !(it2 == attic_tags_db.range_end()); ++it2) { - if (it2.object().timestamp > timestamp && it2.index().value != void_tag_value()) + if (it2.object().timestamp > timestamp && it2.index().value != void_tag_value() + && (!relevant_ids || std::binary_search( + relevant_ids->begin(), relevant_ids->end(), std::make_pair(it2.object().id, Uint31_Index(0u))))) { std::pair< uint64, Uint31_Index >& ref = timestamp_per_id[it2.object().id]; if (ref.first == 0 || it2.object().timestamp < ref.first) ref = std::make_pair(it2.object().timestamp, it2.object().idx); + if (limit && timestamp_per_id.size() >= limit) + return timestamp_per_id; } } @@ -154,7 +173,7 @@ std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_kregv( std::vector< std::pair< std::string, Regular_Expression* > >::const_iterator krit, uint64 timestamp, Block_Backend< Tag_Index_Global, Tag_Object_Global< Id_Type > >& tags_db, Block_Backend< Tag_Index_Global, Attic< Tag_Object_Global< Id_Type > > >& attic_tags_db, - std::vector< std::pair< Id_Type, Uint31_Index > >* relevant_ids = 0) + std::vector< std::pair< Id_Type, Uint31_Index > >* relevant_ids = 0, std::size_t limit = 0) { std::map< Id_Type, std::pair< uint64, Uint31_Index > > timestamp_per_id; Ranges< Tag_Index_Global > ranges = get_k_req(krit->first); @@ -164,7 +183,11 @@ std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_kregv( if ((!relevant_ids || std::binary_search( relevant_ids->begin(), relevant_ids->end(), std::make_pair(it2.object().id, Uint31_Index(0u)))) && krit->second->matches(it2.index().value)) + { timestamp_per_id[it2.object().id] = std::make_pair(NOW, it2.object().idx); + if (limit && timestamp_per_id.size() >= limit) + return timestamp_per_id; + } } for (auto it2 = attic_tags_db.range_begin(ranges); !(it2 == attic_tags_db.range_end()); ++it2) @@ -177,6 +200,8 @@ std::map< Id_Type, std::pair< uint64, Uint31_Index > > collect_attic_kregv( std::pair< uint64, Uint31_Index >& ref = timestamp_per_id[it2.object().id]; if (ref.first == 0 || it2.object().timestamp < ref.first) ref = std::make_pair(it2.object().timestamp, it2.object().idx); + if (limit && timestamp_per_id.size() >= limit) + return timestamp_per_id; } } @@ -436,7 +461,15 @@ std::vector< std::pair< Id_Type, Uint31_Index > > collect_ids( return new_ids; } else - filter_id_list(new_ids, filtered, collect_attic_kv(kvit, timestamp, tags_db, *attic_tags_db.obj)); + { + std::size_t limit = !filtered && (check_keys_late == prefer_ranges || check_keys_late == ids_useful) + ? 1024*1024 : 0; + std::map< Id_Type, std::pair< uint64, Uint31_Index > > attic_ids = collect_attic_kv( + kvit, timestamp, tags_db, *attic_tags_db.obj, filtered ? &new_ids : 0, limit); + if (limit && attic_ids.size() >= limit) + return new_ids; + filter_id_list(new_ids, filtered, attic_ids); + } rman.health_check(stmt); } @@ -456,7 +489,14 @@ std::vector< std::pair< Id_Type, Uint31_Index > > collect_ids( return new_ids; } else - filter_id_list(new_ids, filtered, collect_attic_k(kit, timestamp, tags_db, *attic_tags_db.obj)); + { + std::size_t limit = !filtered && check_keys_late == ids_useful ? 1024*1024 : 0; + std::map< Id_Type, std::pair< uint64, Uint31_Index > > attic_ids = collect_attic_k( + kit, timestamp, tags_db, *attic_tags_db.obj, filtered ? &new_ids : 0, limit); + if (limit && attic_ids.size() >= limit) + return new_ids; + filter_id_list(new_ids, filtered, attic_ids); + } rman.health_check(stmt); } @@ -475,7 +515,14 @@ std::vector< std::pair< Id_Type, Uint31_Index > > collect_ids( return new_ids; } else - filter_id_list(new_ids, filtered, collect_attic_kregv(krit, timestamp, tags_db, *attic_tags_db.obj)); + { + std::size_t limit = !filtered && check_keys_late == ids_useful ? 1024*1024 : 0; + std::map< Id_Type, std::pair< uint64, Uint31_Index > > attic_ids = collect_attic_kregv( + krit, timestamp, tags_db, *attic_tags_db.obj, filtered ? &new_ids : 0, limit); + if (limit && attic_ids.size() >= limit) + return new_ids; + filter_id_list(new_ids, filtered, attic_ids); + } rman.health_check(stmt); } From f6fece34d381af413bb07ba179a895605517f6b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 15:06:20 +0000 Subject: [PATCH 70/80] changed: scan only the changelogs of element types in the set 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. --- src/overpass_api/statements/changed.cc | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/overpass_api/statements/changed.cc b/src/overpass_api/statements/changed.cc index b1bc4a0f4..7b73be65d 100644 --- a/src/overpass_api/statements/changed.cc +++ b/src/overpass_api/statements/changed.cc @@ -295,7 +295,9 @@ bool Changed_Constraint::get_relation_ids_within(Resource_Manager& rman, void Changed_Constraint::filter(Resource_Manager& rman, Set& into) { - if (!stmt->trivial()) + // Each type's changelog is scanned only if the set holds elements of that type: the scan can + // only keep elements that are already there. + if (!stmt->trivial() && !(into.nodes.empty() && into.attic_nodes.empty())) { std::vector< Node_Skeleton::Id_Type > ids = node_ids_within_valid ? node_ids_within : collect_changed_elements< Uint32_Index, Node_Skeleton > @@ -306,7 +308,7 @@ void Changed_Constraint::filter(Resource_Manager& rman, Set& into) filter_elems(ids, into.attic_nodes); } - if (!stmt->trivial()) + if (!stmt->trivial() && !(into.ways.empty() && into.attic_ways.empty())) { std::vector< Way_Skeleton::Id_Type > ids = way_ids_within_valid ? way_ids_within : collect_changed_elements< Uint31_Index, Way_Skeleton > @@ -317,7 +319,7 @@ void Changed_Constraint::filter(Resource_Manager& rman, Set& into) filter_elems(ids, into.attic_ways); } - if (!stmt->trivial()) + if (!stmt->trivial() && !(into.relations.empty() && into.attic_relations.empty())) { std::vector< Relation_Skeleton::Id_Type > ids = relation_ids_within_valid ? relation_ids_within : collect_changed_elements< Uint31_Index, Relation_Skeleton > From 910482d7f92e88b6e57c2f0a6811ab9d38370625 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 18:30:46 +0000 Subject: [PATCH 71/80] recurse: skip the scan for parent relations of no relations 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. --- src/overpass_api/statements/recurse.cc | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/overpass_api/statements/recurse.cc b/src/overpass_api/statements/recurse.cc index b937a49d8..b4fb369a7 100644 --- a/src/overpass_api/statements/recurse.cc +++ b/src/overpass_api/statements/recurse.cc @@ -374,6 +374,11 @@ Timeless< Uint31_Index, Relation_Skeleton > collect_relations current_ids.swap(children_ids); } + // Without input relations no relation can have one as a member: skip the scan of all relations + // (and at a past date, the reconstruction of all their old versions). + if (current_ids.empty()) + return result; + Request_Context context(&stmt, rman); if (!invert_ids) collect_items_flat(context, @@ -422,6 +427,10 @@ Timeless< Uint31_Index, Relation_Skeleton > collect_relations current_ids.swap(children_ids); } + // Without input relations no relation can have one as a member. + if (current_ids.empty()) + return result; + if (!invert_ids) collect_items_flat(context, And_Predicate< Relation_Skeleton, From 11cfa035988263bec1bc47f4f41271c51ca682b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 20:14:21 +0000 Subject: [PATCH 72/80] Write escaped strings in one pass, copying runs that need no escaping 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 Claude-Session: https://claude.ai/code/session_01736kJTiuJPoCWZs7RtFYjm --- src/expat/escape_json.cc | 87 ++++++++++++++---- src/expat/escape_json.h | 11 +++ src/expat/escape_xml.cc | 88 ++++++++++++++----- src/expat/escape_xml.h | 11 +++ .../output_formats/output_custom.cc | 2 +- .../output_formats/output_json.cc | 8 +- src/overpass_api/output_formats/output_xml.cc | 6 +- 7 files changed, 167 insertions(+), 46 deletions(-) diff --git a/src/expat/escape_json.cc b/src/expat/escape_json.cc index 27a183b71..948444202 100644 --- a/src/expat/escape_json.cc +++ b/src/expat/escape_json.cc @@ -16,31 +16,82 @@ * along with Overpass_API. If not, see . */ +#include #include #include "escape_json.h" -std::string escape_cstr(const std::string& s) +namespace { - std::string result; - result.reserve(s.length()*2); - for (std::string::size_type i(0); i < s.size(); ++i) + +struct Replacements +{ + Replacements() + { + for (int c = 0; c < 256; ++c) + replacement[c] = c < 32 ? "?" : 0; + replacement[(unsigned char)'\"'] = "\\\""; + replacement[(unsigned char)'\\'] = "\\\\"; + replacement[(unsigned char)'\n'] = "\\n"; + replacement[(unsigned char)'\t'] = "\\t"; + replacement[(unsigned char)'\r'] = "\\r"; + } + + // What each byte is written as, or 0 if it is written as it is. + const char* replacement[256]; +}; + + +const Replacements& replacements() +{ + static const Replacements result; + return result; +} + + +struct Stream_Sink +{ + std::ostream& out; + void append(const char* s, std::string::size_type n) { out.write(s, n); } + void append(const char* s) { out< +void write_escaped(const std::string& s, Sink& sink) +{ + const Replacements& table = replacements(); + const char* run = s.data(); + const char* end = s.data() + s.size(); + for (const char* pos = run; pos != end; ++pos) { - if (s[i] == '\"') - result += "\\\""; - else if (s[i] == '\\') - result += "\\\\"; - else if (s[i] == '\n') - result += "\\n"; - else if (s[i] == '\t') - result += "\\t"; - else if (s[i] == '\r') - result += "\\r"; - else if ((unsigned char)s[i] < 32) - result += '?'; - else - result += s[i]; + const char* replacement = table.replacement[(unsigned char)*pos]; + if (replacement) + { + sink.append(run, pos - run); + sink.append(replacement); + run = pos + 1; + } } + sink.append(run, end - run); +} + +} + + +std::string escape_cstr(const std::string& s) +{ + std::string result; + result.reserve(s.size()); + write_escaped(s, result); return result; } + + +std::ostream& operator<<(std::ostream& out, const Json_Escaped& e) +{ + Stream_Sink sink{out}; + write_escaped(e.s, sink); + return out; +} diff --git a/src/expat/escape_json.h b/src/expat/escape_json.h index 78c57b0d6..dfc1b0d18 100644 --- a/src/expat/escape_json.h +++ b/src/expat/escape_json.h @@ -19,10 +19,21 @@ #ifndef DE__OSM3S___EXPAT__ESCAPE_JSON_H #define DE__OSM3S___EXPAT__ESCAPE_JSON_H +#include #include std::string escape_cstr(const std::string& s); +// Writes escape_cstr(s) to a stream without building the escaped copy. s must outlive the expression. +struct Json_Escaped +{ + explicit Json_Escaped(const std::string& s_) : s(s_) {} + const std::string& s; +}; + +std::ostream& operator<<(std::ostream& out, const Json_Escaped& e); + + #endif diff --git a/src/expat/escape_xml.cc b/src/expat/escape_xml.cc index d80cf441b..77d2ac9ea 100644 --- a/src/expat/escape_xml.cc +++ b/src/expat/escape_xml.cc @@ -16,36 +16,84 @@ * along with Overpass_API. If not, see . */ +#include #include #include "escape_xml.h" -std::string escape_xml(const std::string& s) +namespace { - const char* digit = "0123456789abcdef"; - std::string result; - result.reserve(s.length()*2); - for (std::string::size_type i(0); i < s.size(); ++i) +struct Replacements +{ + Replacements() { - if (s[i] == '&') - result += "&"; - else if (s[i] == '\"') - result += """; - else if (s[i] == '<') - result += "<"; - else if (s[i] == '>') - result += ">"; - else if ((unsigned char)s[i] < 32) + for (int c = 0; c < 256; ++c) + replacement[c] = c < 32 ? "?" : 0; + replacement[(unsigned char)'&'] = "&"; + replacement[(unsigned char)'\"'] = """; + replacement[(unsigned char)'<'] = "<"; + replacement[(unsigned char)'>'] = ">"; + replacement[(unsigned char)'\t'] = " "; + replacement[(unsigned char)'\n'] = " "; + replacement[(unsigned char)'\r'] = " "; + } + + // What each byte is written as, or 0 if it is written as it is. + const char* replacement[256]; +}; + + +const Replacements& replacements() +{ + static const Replacements result; + return result; +} + + +struct Stream_Sink +{ + std::ostream& out; + void append(const char* s, std::string::size_type n) { out.write(s, n); } + void append(const char* s) { out< +void write_escaped(const std::string& s, Sink& sink) +{ + const Replacements& table = replacements(); + const char* run = s.data(); + const char* end = s.data() + s.size(); + for (const char* pos = run; pos != end; ++pos) + { + const char* replacement = table.replacement[(unsigned char)*pos]; + if (replacement) { - if ((s[i] == '\n') || (s[i] == '\t') || (s[i] == '\r')) - result += std::string("&#x") + digit[s[i] / 16] + digit[s[i] % 16] + ';'; - else - result += '?'; + sink.append(run, pos - run); + sink.append(replacement); + run = pos + 1; } - else - result += s[i]; } + sink.append(run, end - run); +} + +} + + +std::string escape_xml(const std::string& s) +{ + std::string result; + result.reserve(s.size()); + write_escaped(s, result); return result; } + + +std::ostream& operator<<(std::ostream& out, const Xml_Escaped& e) +{ + Stream_Sink sink{out}; + write_escaped(e.s, sink); + return out; +} diff --git a/src/expat/escape_xml.h b/src/expat/escape_xml.h index 36284682e..e6d2b5644 100644 --- a/src/expat/escape_xml.h +++ b/src/expat/escape_xml.h @@ -19,10 +19,21 @@ #ifndef DE__OSM3S___EXPAT__ESCAPE_XML_H #define DE__OSM3S___EXPAT__ESCAPE_XML_H +#include #include std::string escape_xml(const std::string& s); +// Writes escape_xml(s) to a stream without building the escaped copy. s must outlive the expression. +struct Xml_Escaped +{ + explicit Xml_Escaped(const std::string& s_) : s(s_) {} + const std::string& s; +}; + +std::ostream& operator<<(std::ostream& out, const Xml_Escaped& e); + + #endif diff --git a/src/overpass_api/output_formats/output_custom.cc b/src/overpass_api/output_formats/output_custom.cc index 7b56e1b40..8a5b9b42f 100644 --- a/src/overpass_api/output_formats/output_custom.cc +++ b/src/overpass_api/output_formats/output_custom.cc @@ -263,7 +263,7 @@ std::string process_members(const std::string& raw_template, uint32 id, const Re else if (raw_template.substr(new_pos, 10) == "{{{role}}}") { std::map< uint32, std::string >::const_iterator rit = roles.find(entry.role); - result<second : "???"); + result<second : "???"); } else if (raw_template.substr(new_pos, 8) == "{{first:") ; diff --git a/src/overpass_api/output_formats/output_json.cc b/src/overpass_api/output_formats/output_json.cc index 6d1d60504..e8aad512e 100644 --- a/src/overpass_api/output_formats/output_json.cc +++ b/src/overpass_api/output_formats/output_json.cc @@ -87,7 +87,7 @@ void print_meta_json(const OSM_Element_Metadata_Skeleton< Id_Type >& meta, ",\n \"changeset\": "<::const_iterator it = users.find(meta.user_id); if (it != users.end()) - std::cout<<",\n \"user\": \""<second)<<"\""; + std::cout<<",\n \"user\": \""<second)<<"\""; std::cout<<",\n \"uid\": "< >* tags { std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); std::cout<<",\n \"tags\": {" - "\n \""<first)<<"\": \""<second)<<"\""; + "\n \""<first)<<"\": \""<second)<<"\""; for (++it; it != tags->end(); ++it) - std::cout<<",\n \""<first)<<"\": \""<second)<<"\""; + std::cout<<",\n \""<first)<<"\": \""<second)<<"\""; std::cout<<"\n }"; } } @@ -241,7 +241,7 @@ void Output_JSON::print_item(const Relation_Skeleton& skel, std::cout <<"\n {" "\n \"type\": \""<end() ? rit->second : "???") << "\""; + ",\n \"role\": \""<end() ? rit->second : "???") << "\""; if (skel.members[i].type == Relation_Entry::NODE && geometry.has_faithful_relation_geometry() && geometry.relation_pos_is_valid(i)) diff --git a/src/overpass_api/output_formats/output_xml.cc b/src/overpass_api/output_formats/output_xml.cc index 4173cfff7..f7e6f73b3 100644 --- a/src/overpass_api/output_formats/output_xml.cc +++ b/src/overpass_api/output_formats/output_xml.cc @@ -82,7 +82,7 @@ void print_meta_xml(const OSM_Element_Metadata_Skeleton< Id_Type >& meta, <<"\" changeset=\""<::const_iterator it = users.find(meta.user_id); if (it != users.end()) - std::cout<<" user=\""<second)<<"\""; + std::cout<<" user=\""<second)<<"\""; } @@ -153,7 +153,7 @@ void print_tags(const std::vector< std::pair< std::string, std::string > >* tags } for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); it != tags->end(); ++it) - std::cout<<" first)<<"\" v=\""<second)<<"\"/>\n"; + std::cout<<" first)<<"\" v=\""<second)<<"\"/>\n"; } } @@ -323,7 +323,7 @@ void print_members(const Relation_Skeleton& skel, const Opaque_Geometry& geometr std::map< uint32, std::string >::const_iterator it = roles.find(skel.members[i].role); std::cout<<" second : "???")<<"\""; + <<"\" role=\""<second : "???")<<"\""; if (skel.members[i].type == Relation_Entry::NODE) { From 0de947f248f87dd17e08fc8990aeff4c7a3c5db8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 21:41:19 +0000 Subject: [PATCH 73/80] tag_store: build each element's tag list once, at its final size 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 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/overpass_api/data/tag_store.h | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/overpass_api/data/tag_store.h b/src/overpass_api/data/tag_store.h index 1d506648f..7dc358bdb 100644 --- a/src/overpass_api/data/tag_store.h +++ b/src/overpass_api/data/tag_store.h @@ -25,6 +25,7 @@ #include "../../template_db/block_backend.h" #include "../../template_db/transaction.h" +#include #include #include #include @@ -276,16 +277,35 @@ void collect_tags_framed while ((!(tag_it == items_db.range_end())) && ((tag_coarse_index(tag_it)) < coarse_index)) ++tag_it; + std::vector< std::pair< std::string, std::string > > key_values; + std::vector< std::pair< Id_Type, uint32 > > found; while ((!(tag_it == items_db.range_end())) && ((tag_coarse_index(tag_it)) == coarse_index)) { if (!(tag_it.object() < lower_id_bound) && (tag_it.object() < upper_id_bound) && contains_from_cursor(ids, cursor, tag_it.object())) - tags_by_id[tag_it.object()].push_back - (std::make_pair(tag_it.index().key, tag_it.index().value)); + { + const Tag_Index_Local& idx = tag_it.index(); + if (key_values.empty() || key_values.back().second != idx.value || key_values.back().first != idx.key) + key_values.push_back(std::make_pair(idx.key, idx.value)); + found.push_back(std::make_pair(tag_it.object(), uint32(key_values.size() - 1))); + } ++tag_it; } + + std::stable_sort(found.begin(), found.end(), + [](const std::pair< Id_Type, uint32 >& a, const std::pair< Id_Type, uint32 >& b) { return a.first < b.first; }); + for (typename std::vector< std::pair< Id_Type, uint32 > >::const_iterator it = found.begin(); it != found.end(); ) + { + typename std::vector< std::pair< Id_Type, uint32 > >::const_iterator end = it; + while (end != found.end() && end->first == it->first) + ++end; + std::vector< std::pair< std::string, std::string > >& tags = tags_by_id[it->first]; + tags.reserve(tags.size() + (end - it)); + for (; it != end; ++it) + tags.push_back(key_values[it->second]); + } } From a71b7e35c9cb7b437b2ec3b5c045a5e83cd47554 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 21:53:45 +0000 Subject: [PATCH 74/80] output: hand tags to output handlers by reference, without copying them 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 Claude-Session: https://claude.ai/code/session_01736kJUqyDw9zM3Bkh2W2QT --- src/Makefile.am | 1 + src/overpass_api/core/tag_list.h | 47 +++++++++++++ src/overpass_api/data/tag_store.h | 68 ++++++++++++++++--- src/overpass_api/dispatch/db_timestamp.cc | 14 ++-- src/overpass_api/frontend/output_handler.h | 65 ++++++++++++++++-- src/overpass_api/output_formats/output_csv.cc | 22 +++--- src/overpass_api/output_formats/output_csv.h | 14 ++-- .../output_formats/output_custom.cc | 18 ++--- .../output_formats/output_custom.h | 14 ++-- .../output_formats/output_json.cc | 18 ++--- src/overpass_api/output_formats/output_json.h | 14 ++-- .../output_formats/output_popup.cc | 40 +++++------ .../output_formats/output_popup.h | 22 +++--- src/overpass_api/output_formats/output_xml.cc | 24 +++---- src/overpass_api/output_formats/output_xml.h | 14 ++-- src/overpass_api/statements/print.cc | 24 +++---- 16 files changed, 285 insertions(+), 134 deletions(-) create mode 100644 src/overpass_api/core/tag_list.h diff --git a/src/Makefile.am b/src/Makefile.am index df1f7172d..7019e5b38 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -226,6 +226,7 @@ nobase_dist_HEADERS = \ overpass_api/core/index_computations.h\ overpass_api/core/parsed_query.h\ overpass_api/core/settings.h\ + overpass_api/core/tag_list.h\ overpass_api/core/type_area.h\ overpass_api/core/type_node.h\ overpass_api/core/type_relation.h\ diff --git a/src/overpass_api/core/tag_list.h b/src/overpass_api/core/tag_list.h new file mode 100644 index 000000000..102702f16 --- /dev/null +++ b/src/overpass_api/core/tag_list.h @@ -0,0 +1,47 @@ +/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al. + * + * This file is part of Overpass_API. + * + * Overpass_API is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * Overpass_API is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Overpass_API. If not, see . + */ + +#ifndef DE__OSM3S___OVERPASS_API__CORE__TAG_LIST_H +#define DE__OSM3S___OVERPASS_API__CORE__TAG_LIST_H + +#include +#include +#include + + +// A tag that refers to a key and value stored elsewhere. +struct Tag_Ref +{ + Tag_Ref(const std::string& first_, const std::string& second_) : first(first_), second(second_) {} + const std::string& first; + const std::string& second; +}; + +typedef std::vector< Tag_Ref > Tag_List; + + +inline void make_tag_list(const std::vector< std::pair< std::string, std::string > >& tags, Tag_List& result) +{ + result.clear(); + result.reserve(tags.size()); + for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) + result.push_back(Tag_Ref(it->first, it->second)); +} + + +#endif diff --git a/src/overpass_api/data/tag_store.h b/src/overpass_api/data/tag_store.h index 7dc358bdb..d9c3d81cd 100644 --- a/src/overpass_api/data/tag_store.h +++ b/src/overpass_api/data/tag_store.h @@ -24,13 +24,19 @@ #include "../core/datatypes.h" #include "../../template_db/block_backend.h" #include "../../template_db/transaction.h" +#include "../core/tag_list.h" #include +#include #include #include #include +template< typename Id_Type > +using Tag_Refs_By_Id = std::map< Id_Type, Tag_List >; + + template< typename Index, typename Object > class Tag_Store { @@ -46,9 +52,13 @@ class Tag_Store typename Object::Id_Type lower_id_bound, typename Object::Id_Type upper_id_bound); const std::vector< std::pair< std::string, std::string > >* get(const Index& index, const Object& elem); + const Tag_List* get_refs(const Index& index, const Object& elem); private: std::map< typename Object::Id_Type, std::vector< std::pair< std::string, std::string > > > tags_by_id; + std::deque< std::pair< std::string, std::string > > tag_pool; + Tag_Refs_By_Id< typename Object::Id_Type > refs_by_id; + Tag_List scratch; Transaction* transaction; bool use_index; Index stored_index; @@ -75,6 +85,15 @@ class Tag_Store< Uint31_Index, Derived_Structure > const std::vector< std::pair< std::string, std::string > >* get( const Uint31_Index& index, const Derived_Structure& elem) const { return &elem.tags; } + + const Tag_List* get_refs(const Uint31_Index& index, const Derived_Structure& elem) + { + make_tag_list(elem.tags, scratch); + return &scratch; + } + +private: + Tag_List scratch; }; @@ -265,7 +284,8 @@ void collect_tags template< class Id_Type > void collect_tags_framed - (std::map< Id_Type, std::vector< std::pair< std::string, std::string > > >& tags_by_id, + (Tag_Refs_By_Id< Id_Type >& refs_by_id, + std::deque< std::pair< std::string, std::string > >& tag_pool, const Block_Backend< Tag_Index_Local, Id_Type >& items_db, typename Block_Backend< Tag_Index_Local, Id_Type >::Range_Iterator& tag_it, std::map< uint32, std::vector< Id_Type > >& ids_by_coarse, @@ -277,7 +297,7 @@ void collect_tags_framed while ((!(tag_it == items_db.range_end())) && ((tag_coarse_index(tag_it)) < coarse_index)) ++tag_it; - std::vector< std::pair< std::string, std::string > > key_values; + std::vector< const std::pair< std::string, std::string >* > key_values; std::vector< std::pair< Id_Type, uint32 > > found; while ((!(tag_it == items_db.range_end())) && ((tag_coarse_index(tag_it)) == coarse_index)) @@ -287,8 +307,11 @@ void collect_tags_framed contains_from_cursor(ids, cursor, tag_it.object())) { const Tag_Index_Local& idx = tag_it.index(); - if (key_values.empty() || key_values.back().second != idx.value || key_values.back().first != idx.key) - key_values.push_back(std::make_pair(idx.key, idx.value)); + if (key_values.empty() || key_values.back()->second != idx.value || key_values.back()->first != idx.key) + { + tag_pool.push_back(std::make_pair(idx.key, idx.value)); + key_values.push_back(&tag_pool.back()); + } found.push_back(std::make_pair(tag_it.object(), uint32(key_values.size() - 1))); } ++tag_it; @@ -301,10 +324,10 @@ void collect_tags_framed typename std::vector< std::pair< Id_Type, uint32 > >::const_iterator end = it; while (end != found.end() && end->first == it->first) ++end; - std::vector< std::pair< std::string, std::string > >& tags = tags_by_id[it->first]; + Tag_List& tags = refs_by_id[it->first]; tags.reserve(tags.size() + (end - it)); for (; it != end; ++it) - tags.push_back(key_values[it->second]); + tags.push_back(Tag_Ref(key_values[it->second]->first, key_values[it->second]->second)); } } @@ -318,6 +341,8 @@ Tag_Store< Index, Object >::Tag_Store(Transaction& transaction_) template< typename Index, typename Object > void Tag_Store< Index, Object >::prefetch_all(const std::map< Index, std::vector< Object > >& elems) { + refs_by_id.clear(); + tag_pool.clear(); use_index = true; generate_ids_by_coarse(ids_by_coarse, elems); ranges = formulate_range_query(ids_by_coarse); @@ -345,6 +370,8 @@ void Tag_Store< Index, Object >::prefetch_chunk(const std::map< Index, std::vect typename Object::Id_Type lower_id_bound, typename Object::Id_Type upper_id_bound) { tags_by_id.clear(); + refs_by_id.clear(); + tag_pool.clear(); // The coarse indices and ids of this chunk's elements only: no other tags are collected. ids_by_coarse.clear(); @@ -357,7 +384,7 @@ void Tag_Store< Index, Object >::prefetch_chunk(const std::map< Index, std::vect auto tag_it = items_db.range_begin(ranges); for (typename std::map< uint32, std::vector< typename Object::Id_Type > >::const_iterator it = ids_by_coarse.begin(); it != ids_by_coarse.end(); ++it) - collect_tags_framed< typename Object::Id_Type >(tags_by_id, items_db, tag_it, ids_by_coarse, it->first, + collect_tags_framed< typename Object::Id_Type >(refs_by_id, tag_pool, items_db, tag_it, ids_by_coarse, it->first, lower_id_bound, upper_id_bound); } @@ -365,6 +392,8 @@ void Tag_Store< Index, Object >::prefetch_chunk(const std::map< Index, std::vect template< typename Index, typename Object > void Tag_Store< Index, Object >::prefetch_all(const std::map< Index, std::vector< Attic< Object > > >& attic_items) { + refs_by_id.clear(); + tag_pool.clear(); use_index = true; generate_ids_by_coarse(attic_ids_by_coarse, attic_items); ranges = formulate_range_query(attic_ids_by_coarse); @@ -399,6 +428,8 @@ void Tag_Store< Index, Object >::prefetch_chunk(const std::map< Index, std::vect { // As for current elements: only this chunk's tags and ids are needed. tags_by_id.clear(); + refs_by_id.clear(); + tag_pool.clear(); attic_ids_by_coarse.clear(); generate_ids_by_coarse(attic_ids_by_coarse, attic_items, lower_id_bound, upper_id_bound); @@ -459,8 +490,29 @@ const std::vector< std::pair< std::string, std::string > >* auto it = tags_by_id.find(elem.id); if (it != tags_by_id.end()) return &it->second; - else + auto rit = refs_by_id.find(elem.id); + if (rit == refs_by_id.end()) + return 0; + std::vector< std::pair< std::string, std::string > >& tags = tags_by_id[elem.id]; + for (Tag_List::const_iterator tit = rit->second.begin(); tit != rit->second.end(); ++tit) + tags.push_back(std::make_pair(tit->first, tit->second)); + return &tags; +} + + +template< typename Index, typename Object > +const Tag_List* Tag_Store< Index, Object >::get_refs(const Index& index, const Object& elem) +{ + if (!refs_by_id.empty()) + { + auto rit = refs_by_id.find(elem.id); + return rit == refs_by_id.end() ? 0 : &rit->second; + } + const std::vector< std::pair< std::string, std::string > >* tags = get(index, elem); + if (!tags) return 0; + make_tag_list(*tags, scratch); + return &scratch; } diff --git a/src/overpass_api/dispatch/db_timestamp.cc b/src/overpass_api/dispatch/db_timestamp.cc index c91f88151..cdba91fe3 100644 --- a/src/overpass_api/dispatch/db_timestamp.cc +++ b/src/overpass_api/dispatch/db_timestamp.cc @@ -41,31 +41,31 @@ class Output_Timestamp : public Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0) {} virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0) {} virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -73,12 +73,12 @@ class Output_Timestamp : public Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0) {} virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep) {} }; diff --git a/src/overpass_api/frontend/output_handler.h b/src/overpass_api/frontend/output_handler.h index 65204cb50..0cdf73e70 100644 --- a/src/overpass_api/frontend/output_handler.h +++ b/src/overpass_api/frontend/output_handler.h @@ -22,6 +22,7 @@ #include "../core/datatypes.h" #include "../core/geometry.h" +#include "../core/tag_list.h" struct Output_Mode @@ -50,6 +51,14 @@ const std::string& member_type_name(uint32 type); class Output_Handler { + static const Tag_List* as_tag_list(const std::vector< std::pair< std::string, std::string > >* tags, Tag_List& list) + { + if (!tags) + return 0; + make_tag_list(*tags, list); + return &list; + } + public: enum Feature_Action { keep, show_from, show_to, modify, push_away, pull_in, erase, create }; @@ -68,31 +77,31 @@ class Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0) = 0; virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0) = 0; virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -100,15 +109,57 @@ class Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0) = 0; virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep) = 0; + // For callers that hold their tags as pairs. + void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, + const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, + Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, + const Opaque_Geometry* new_geometry = 0, const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0) + { + Tag_List list, new_list; + print_item(skel, geometry, as_tag_list(tags, list), meta, users, mode, action, new_skel, new_geometry, + as_tag_list(new_tags, new_list), new_meta); + } + + void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, + const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, + Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, + const Opaque_Geometry* new_geometry = 0, const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0) + { + Tag_List list, new_list; + print_item(skel, geometry, as_tag_list(tags, list), meta, users, mode, action, new_skel, new_geometry, + as_tag_list(new_tags, new_list), new_meta); + } + + void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, + const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, + const std::map< uint32, std::string >* users, + Output_Mode mode, const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, + const Opaque_Geometry* new_geometry = 0, const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0) + { + Tag_List list, new_list; + print_item(skel, geometry, as_tag_list(tags, list), meta, roles, users, mode, action, new_skel, new_geometry, + as_tag_list(new_tags, new_list), new_meta); + } + + void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, + Output_Mode mode, const Feature_Action& action = keep) + { + Tag_List list; + print_item(skel, geometry, as_tag_list(tags, list), mode, action); + } + virtual std::string dump_config() const { return ""; } virtual ~Output_Handler() {} diff --git a/src/overpass_api/output_formats/output_csv.cc b/src/overpass_api/output_formats/output_csv.cc index 26aec3591..1dfc51c38 100644 --- a/src/overpass_api/output_formats/output_csv.cc +++ b/src/overpass_api/output_formats/output_csv.cc @@ -143,10 +143,10 @@ template< > void print_meta< int >(const std::string& keyfield, const int& meta, const std::map< uint32, std::string >* users) {} -std::string get_count_tag(const std::vector< std::pair< std::string, std::string> >* tags, std::string tag) +std::string get_count_tag(const Tag_List* tags, std::string tag) { if (tags) - for (std::vector< std::pair< std::string, std::string> >::const_iterator it_tags = tags->begin(); + for (Tag_List::const_iterator it_tags = tags->begin(); it_tags != tags->end(); ++it_tags) if (it_tags->first == tag) return it_tags->second; @@ -157,7 +157,7 @@ std::string get_count_tag(const std::vector< std::pair< std::string, std::string template< typename Id_Type, typename OSM_Element_Metadata_Skeleton > void process_csv_line(int otype, const std::string& type, Id_Type id, const Opaque_Geometry& geometry, const OSM_Element_Metadata_Skeleton* meta, - const std::vector< std::pair< std::string, std::string> >* tags, + const Tag_List* tags, const std::map< uint32, std::string >* users, const Csv_Settings& csv_settings, Output_Mode mode) @@ -169,7 +169,7 @@ void process_csv_line(int otype, const std::string& type, Id_Type id, const Opaq { if (tags) { - for (std::vector< std::pair< std::string, std::string> >::const_iterator it_tags = tags->begin(); + for (Tag_List::const_iterator it_tags = tags->begin(); it_tags != tags->end(); ++it_tags) { if (it_tags->first == it->first) @@ -231,14 +231,14 @@ void process_csv_line(int otype, const std::string& type, Id_Type id, const Opaq void Output_CSV::print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Node_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta) { process_csv_line(1, "node", skel.id, geometry, meta, tags, users, csv_settings, mode); @@ -247,14 +247,14 @@ void Output_CSV::print_item(const Node_Skeleton& skel, void Output_CSV::print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Way_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta) { process_csv_line(2, "way", skel.id, geometry, meta, tags, users, csv_settings, mode); @@ -263,7 +263,7 @@ void Output_CSV::print_item(const Way_Skeleton& skel, void Output_CSV::print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -271,7 +271,7 @@ void Output_CSV::print_item(const Relation_Skeleton& skel, const Feature_Action& action, const Relation_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta) { process_csv_line(3, "relation", skel.id, geometry, meta, tags, users, csv_settings, mode); @@ -280,7 +280,7 @@ void Output_CSV::print_item(const Relation_Skeleton& skel, void Output_CSV::print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action) { diff --git a/src/overpass_api/output_formats/output_csv.h b/src/overpass_api/output_formats/output_csv.h index aeb23e058..3b8f329f8 100644 --- a/src/overpass_api/output_formats/output_csv.h +++ b/src/overpass_api/output_formats/output_csv.h @@ -54,31 +54,31 @@ class Output_CSV : public Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0); virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0); virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -86,12 +86,12 @@ class Output_CSV : public Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0); virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep); diff --git a/src/overpass_api/output_formats/output_custom.cc b/src/overpass_api/output_formats/output_custom.cc index 8a5b9b42f..0dbf83e84 100644 --- a/src/overpass_api/output_formats/output_custom.cc +++ b/src/overpass_api/output_formats/output_custom.cc @@ -438,7 +438,7 @@ std::string antiprocess_coords(const std::string& raw_template) std::string process_template(const std::string& raw_template, unsigned long long id, std::string type, double south, double west, double north, double east, uint zoom, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const std::vector< Node::Id_Type >* nds, const std::vector< Relation_Entry >* members, const std::map< uint32, std::string >* roles) @@ -479,7 +479,7 @@ std::string process_template(const std::string& raw_template, unsigned long long { if (tags != 0 && !tags->empty()) { - std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); + Tag_List::const_iterator it = tags->begin(); std::string first = extract_first(raw_template.substr(new_pos + 7, old_pos - new_pos - 9)); if (first != "" && it != tags->end()) @@ -562,14 +562,14 @@ void Output_Custom::write_footer() void Output_Custom::print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Node_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta) { if (count == 0) @@ -640,14 +640,14 @@ unsigned int detect_zoom(const Opaque_Geometry& geometry) void Output_Custom::print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Way_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta) { if (count == 0) @@ -678,7 +678,7 @@ void Output_Custom::print_item(const Way_Skeleton& skel, void Output_Custom::print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -686,7 +686,7 @@ void Output_Custom::print_item(const Relation_Skeleton& skel, const Feature_Action& action, const Relation_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta) { if (count == 0) @@ -717,7 +717,7 @@ void Output_Custom::print_item(const Relation_Skeleton& skel, void Output_Custom::print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action) { diff --git a/src/overpass_api/output_formats/output_custom.h b/src/overpass_api/output_formats/output_custom.h index 512ae28cd..fa926a52a 100644 --- a/src/overpass_api/output_formats/output_custom.h +++ b/src/overpass_api/output_formats/output_custom.h @@ -45,31 +45,31 @@ class Output_Custom : public Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0); virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0); virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -77,12 +77,12 @@ class Output_Custom : public Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0); virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep); diff --git a/src/overpass_api/output_formats/output_json.cc b/src/overpass_api/output_formats/output_json.cc index e8aad512e..af15ef1ba 100644 --- a/src/overpass_api/output_formats/output_json.cc +++ b/src/overpass_api/output_formats/output_json.cc @@ -92,11 +92,11 @@ void print_meta_json(const OSM_Element_Metadata_Skeleton< Id_Type >& meta, } -void print_tags(const std::vector< std::pair< std::string, std::string > >* tags) +void print_tags(const Tag_List* tags) { if (tags != 0 && !tags->empty()) { - std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); + Tag_List::const_iterator it = tags->begin(); std::cout<<",\n \"tags\": {" "\n \""<first)<<"\": \""<second)<<"\""; for (++it; it != tags->end(); ++it) @@ -108,14 +108,14 @@ void print_tags(const std::vector< std::pair< std::string, std::string > >* tags void Output_JSON::print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Node_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta) { handle_first_elem(first_elem); @@ -154,14 +154,14 @@ void print_bounds(const Opaque_Geometry& geometry, Output_Mode mode) void Output_JSON::print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Way_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta) { handle_first_elem(first_elem); @@ -209,7 +209,7 @@ void Output_JSON::print_item(const Way_Skeleton& skel, void Output_JSON::print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -217,7 +217,7 @@ void Output_JSON::print_item(const Relation_Skeleton& skel, const Feature_Action& action, const Relation_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta) { handle_first_elem(first_elem); @@ -385,7 +385,7 @@ void print_geometry(const Opaque_Geometry& geometry, Output_Mode mode) void Output_JSON::print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action) { diff --git a/src/overpass_api/output_formats/output_json.h b/src/overpass_api/output_formats/output_json.h index 2b3b2e18b..3b46b0ec5 100644 --- a/src/overpass_api/output_formats/output_json.h +++ b/src/overpass_api/output_formats/output_json.h @@ -44,31 +44,31 @@ class Output_JSON : public Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0); virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0); virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -76,12 +76,12 @@ class Output_JSON : public Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0); virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep); diff --git a/src/overpass_api/output_formats/output_popup.cc b/src/overpass_api/output_formats/output_popup.cc index 9e918b631..a7eab9929 100644 --- a/src/overpass_api/output_formats/output_popup.cc +++ b/src/overpass_api/output_formats/output_popup.cc @@ -24,11 +24,11 @@ #include -bool Tag_Filter::matches(const std::vector< std::pair< std::string, std::string > >* tags) const +bool Tag_Filter::matches(const Tag_List* tags) const { if (!tags) return false; - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); it != tags->end(); ++it) + for (Tag_List::const_iterator it = tags->begin(); it != tags->end(); ++it) { if (it->first == key && condition.matches(it->second)) return straight; @@ -37,21 +37,21 @@ bool Tag_Filter::matches(const std::vector< std::pair< std::string, std::string } -std::string link_if_any(const std::vector< std::pair< std::string, std::string > >& tags) +std::string link_if_any(const Tag_List& tags) { std::string link; - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) + for (Tag_List::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->second.find("www.") != std::string::npos) link = "http://" + it->second; } - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) + for (Tag_List::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->second.find("http://") != std::string::npos) link = it->second; } - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) + for (Tag_List::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->second.find("https://") != std::string::npos) link = it->second; @@ -62,11 +62,11 @@ std::string link_if_any(const std::vector< std::pair< std::string, std::string > std::string title_if_any(const std::string& link, const std::string& title_key, - const std::vector< std::pair< std::string, std::string > >& tags) + const Tag_List& tags) { std::string title; - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) + for (Tag_List::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->first == title_key) { @@ -105,7 +105,7 @@ template< > std::string elem_type< Relation_Skeleton >() { return "Relation"; } template< typename TSkel > std::string print(const std::string& title_key, - const TSkel& skel, const std::vector< std::pair< std::string, std::string > >* tags) + const TSkel& skel, const Tag_List* tags) { std::string link = tags ? link_if_any(*tags) : ""; std::string result = "\n

" + (tags ? title_if_any(link, title_key, *tags) : ""); @@ -124,7 +124,7 @@ std::string print(const std::string& title_key, if (tags) { - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); + for (Tag_List::const_iterator it = tags->begin(); it != tags->end(); ++it) result += it->first + ": " + it->second + "
\n"; } @@ -133,7 +133,7 @@ std::string print(const std::string& title_key, bool Category_Filter::consider(const Node_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags) + const Tag_List* tags) { std::vector< std::vector< Tag_Filter* > >::const_iterator it_conj = filter_disjunction.begin(); for (; it_conj != filter_disjunction.end(); ++it_conj) @@ -156,7 +156,7 @@ bool Category_Filter::consider(const Node_Skeleton& skel, bool Category_Filter::consider(const Way_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags) + const Tag_List* tags) { std::vector< std::vector< Tag_Filter* > >::const_iterator it_conj = filter_disjunction.begin(); for (; it_conj != filter_disjunction.end(); ++it_conj) @@ -179,7 +179,7 @@ bool Category_Filter::consider(const Way_Skeleton& skel, bool Category_Filter::consider(const Relation_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags) + const Tag_List* tags) { std::vector< std::vector< Tag_Filter* > >::const_iterator it_conj = filter_disjunction.begin(); for (; it_conj != filter_disjunction.end(); ++it_conj) @@ -247,14 +247,14 @@ void Output_Popup::write_footer() void Output_Popup::print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Node_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta) { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) @@ -267,14 +267,14 @@ void Output_Popup::print_item(const Node_Skeleton& skel, void Output_Popup::print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Way_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta) { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) @@ -287,7 +287,7 @@ void Output_Popup::print_item(const Way_Skeleton& skel, void Output_Popup::print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -295,7 +295,7 @@ void Output_Popup::print_item(const Relation_Skeleton& skel, const Feature_Action& action, const Relation_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta) { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) @@ -308,7 +308,7 @@ void Output_Popup::print_item(const Relation_Skeleton& skel, void Output_Popup::print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action) { diff --git a/src/overpass_api/output_formats/output_popup.h b/src/overpass_api/output_formats/output_popup.h index 412ca3353..a402194f4 100644 --- a/src/overpass_api/output_formats/output_popup.h +++ b/src/overpass_api/output_formats/output_popup.h @@ -35,7 +35,7 @@ class Tag_Filter Tag_Filter(const std::string& key_, const std::string& value_, bool straight_) : key(key_), straight(straight_), condition(value_, true) {} - bool matches(const std::vector< std::pair< std::string, std::string > >* tags) const; + bool matches(const Tag_List* tags) const; private: std::string key; @@ -62,9 +62,9 @@ struct Category_Filter void set_title_key(const std::string& title_key); void add_filter(const std::vector< Tag_Filter* >& conjunction) { filter_disjunction.push_back(conjunction); } - bool consider(const Node_Skeleton& skel, const std::vector< std::pair< std::string, std::string > >* tags); - bool consider(const Way_Skeleton& skel, const std::vector< std::pair< std::string, std::string > >* tags); - bool consider(const Relation_Skeleton& skel, const std::vector< std::pair< std::string, std::string > >* tags); + bool consider(const Node_Skeleton& skel, const Tag_List* tags); + bool consider(const Way_Skeleton& skel, const Tag_List* tags); + bool consider(const Relation_Skeleton& skel, const Tag_List* tags); std::string result() const { return output; } @@ -100,31 +100,31 @@ class Output_Popup : public Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0); virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0); virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -132,12 +132,12 @@ class Output_Popup : public Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0); virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep); diff --git a/src/overpass_api/output_formats/output_xml.cc b/src/overpass_api/output_formats/output_xml.cc index f7e6f73b3..464a17429 100644 --- a/src/overpass_api/output_formats/output_xml.cc +++ b/src/overpass_api/output_formats/output_xml.cc @@ -141,7 +141,7 @@ void append_action(const Output_Handler::Feature_Action& action, bool is_new = f } -void print_tags(const std::vector< std::pair< std::string, std::string > >* tags, +void print_tags(const Tag_List* tags, Output_Mode mode, bool& inner_tags_printed) { if ((mode.mode & Output_Mode::TAGS) && tags && !tags->empty()) @@ -151,7 +151,7 @@ void print_tags(const std::vector< std::pair< std::string, std::string > >* tags std::cout<<">\n"; inner_tags_printed = true; } - for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); + for (Tag_List::const_iterator it = tags->begin(); it != tags->end(); ++it) std::cout<<" first)<<"\" v=\""<second)<<"\"/>\n"; } @@ -368,7 +368,7 @@ void print_members(const Relation_Skeleton& skel, const Opaque_Geometry& geometr void print_node(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode) @@ -394,7 +394,7 @@ void print_node(const Node_Skeleton& skel, void print_way(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode) @@ -418,7 +418,7 @@ void print_way(const Way_Skeleton& skel, void print_relation(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -464,14 +464,14 @@ void print_deleted(const std::string& type_name, const Id_Type& id, void Output_XML::print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Node_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta) { prepend_action(action); @@ -494,14 +494,14 @@ void Output_XML::print_item(const Node_Skeleton& skel, void Output_XML::print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Way_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta) { prepend_action(action); @@ -524,7 +524,7 @@ void Output_XML::print_item(const Way_Skeleton& skel, void Output_XML::print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -532,7 +532,7 @@ void Output_XML::print_item(const Relation_Skeleton& skel, const Feature_Action& action, const Relation_Skeleton* new_skel, const Opaque_Geometry* new_geometry, - const std::vector< std::pair< std::string, std::string > >* new_tags, + const Tag_List* new_tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta) { prepend_action(action); @@ -555,7 +555,7 @@ void Output_XML::print_item(const Relation_Skeleton& skel, void Output_XML::print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action) { diff --git a/src/overpass_api/output_formats/output_xml.h b/src/overpass_api/output_formats/output_xml.h index cf5eb4f6d..2173d0256 100644 --- a/src/overpass_api/output_formats/output_xml.h +++ b/src/overpass_api/output_formats/output_xml.h @@ -54,31 +54,31 @@ class Output_XML : public Output_Handler virtual void print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Node_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta = 0); virtual void print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action = keep, const Way_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta = 0); virtual void print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, @@ -86,12 +86,12 @@ class Output_XML : public Output_Handler const Feature_Action& action = keep, const Relation_Skeleton* new_skel = 0, const Opaque_Geometry* new_geometry = 0, - const std::vector< std::pair< std::string, std::string > >* new_tags = 0, + const Tag_List* new_tags = 0, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta = 0); virtual void print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, - const std::vector< std::pair< std::string, std::string > >* tags, + const Tag_List* tags, Output_Mode mode, const Feature_Action& action = keep); }; diff --git a/src/overpass_api/statements/print.cc b/src/overpass_api/statements/print.cc index f92f05c3e..75e1ef295 100644 --- a/src/overpass_api/statements/print.cc +++ b/src/overpass_api/statements/print.cc @@ -260,7 +260,7 @@ Extra_Data::~Extra_Data() void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Node_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Node_Skeleton::Id_Type >* meta = 0) { output.print_item(skel, Point_Geometry(::lat(ll_upper, skel.ll_lower), ::lon(ll_upper, skel.ll_lower)), @@ -269,7 +269,7 @@ void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Way_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Way_Skeleton::Id_Type >* meta = 0) { Geometry_From_Quad_Coords broker; @@ -280,7 +280,7 @@ void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Attic< Way_Skeleton >& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Way_Skeleton::Id_Type >* meta = 0) { Geometry_From_Quad_Coords broker; @@ -291,7 +291,7 @@ void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Relation_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Relation_Skeleton::Id_Type >* meta = 0) { Geometry_From_Quad_Coords broker; @@ -302,7 +302,7 @@ void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Attic< Relation_Skeleton >& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Relation_Skeleton::Id_Type >* meta = 0) { Geometry_From_Quad_Coords broker; @@ -313,7 +313,7 @@ void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Area_Skeleton& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Area_Skeleton::Id_Type >* meta = 0) { Derived_Skeleton derived("area", Uint64(skel.id.val())); @@ -322,7 +322,7 @@ void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, void print_item(Extra_Data& extra_data, Output_Handler& output, uint32 ll_upper, const Derived_Structure& skel, - const std::vector< std::pair< std::string, std::string > >* tags = 0, + const Tag_List* tags = 0, const OSM_Element_Metadata_Skeleton< Derived_Skeleton::Id_Type >* meta = 0) { if (skel.get_geometry()) @@ -377,7 +377,7 @@ void tags_quadtile_ { if (++element_count > limit) return; - print_item(extra_data, output, item_it->first.val(), *it2, tag_store.get(item_it->first, *it2), + print_item(extra_data, output, item_it->first.val(), *it2, tag_store.get_refs(item_it->first, *it2), meta_printer.get(item_it->first, it2->id)); } ++item_it; @@ -405,7 +405,7 @@ void tags_quadtile_attic_ { if (++element_count > limit) return; - print_item(extra_data, output, item_it->first.val(), *it2, tag_store.get(item_it->first, *it2), + print_item(extra_data, output, item_it->first.val(), *it2, tag_store.get_refs(item_it->first, *it2), meta_printer.get(item_it->first, it2->id, it2->timestamp)); } ++item_it; @@ -667,7 +667,7 @@ void tags_by_id = metadata.lower_bound(OSM_Element_Metadata_Skeleton< typename Object::Id_Type > (items_by_id.obj(i.val()).id)); print_item(extra_data, output, items_by_id.idx(i.val()).val(), items_by_id.obj(i.val()), - tag_store.get(items_by_id.idx(i.val()), items_by_id.obj(i.val())), + tag_store.get_refs(items_by_id.idx(i.val()), items_by_id.obj(i.val())), (meta_it != metadata.end() && meta_it->ref == items_by_id.obj(i.val()).id) ? &*meta_it : 0); } @@ -733,7 +733,7 @@ void tags_by_id_attic = only_current_metadata.lower_bound(OSM_Element_Metadata_Skeleton< typename Object::Id_Type > (items_by_id.obj(i.val()).id)); print_item(extra_data, output, items_by_id.idx(i.val()).val(), items_by_id.obj(i.val()), - current_tag_store.get(items_by_id.idx(i.val()), items_by_id.obj(i.val())), + current_tag_store.get_refs(items_by_id.idx(i.val()), items_by_id.obj(i.val())), (meta_it != only_current_metadata.end() && meta_it->ref == items_by_id.obj(i.val()).id) ? &*meta_it : 0); } @@ -744,7 +744,7 @@ void tags_by_id_attic items_by_id.obj(i.val()).id, items_by_id.timestamp(i.val())); print_item(extra_data, output, items_by_id.idx(i.val()).val(), Attic< Object >(items_by_id.obj(i.val()), items_by_id.timestamp(i.val())), - attic_tag_store.get(items_by_id.idx(i.val()), items_by_id.obj(i.val())), + attic_tag_store.get_refs(items_by_id.idx(i.val()), items_by_id.obj(i.val())), meta_it != attic_metadata.end() ? &*meta_it : 0); } } From 6f16ee2436d32506293a71f8e7de28f2fa07dfec Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:56:04 +0000 Subject: [PATCH 75/80] query: drop tag-index candidates outside the query's ranges during the 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 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit 77135cac7c69547b642b5e5f8f58cbdb460fc7e9) --- src/overpass_api/data/tags_global_reader.h | 150 ++++++++++++++++++++- src/overpass_api/statements/query.cc | 57 ++++---- src/template_db/block_backend.h | 10 ++ 3 files changed, 176 insertions(+), 41 deletions(-) diff --git a/src/overpass_api/data/tags_global_reader.h b/src/overpass_api/data/tags_global_reader.h index 0e5571688..2e051f5c1 100644 --- a/src/overpass_api/data/tags_global_reader.h +++ b/src/overpass_api/data/tags_global_reader.h @@ -423,7 +423,64 @@ void filter_id_list( class Statement; -template< typename Skeleton, typename Id_Type > +// Blocks a late tag check of these candidates reads: their cells' skeletons and local tags. +template< typename Skeleton, typename Id_Type, typename Index > +uint64 count_late_check_blocks(const std::vector< std::pair< Id_Type, Uint31_Index > >& ids, Resource_Manager& rman) +{ + std::vector< uint32 > cells; + cells.reserve(ids.size()); + for (auto it = ids.begin(); it != ids.end(); ++it) + cells.push_back(it->second.val() & 0x7fffff00); + std::sort(cells.begin(), cells.end()); + cells.erase(std::unique(cells.begin(), cells.end()), cells.end()); + + Ranges< Tag_Index_Local > tag_ranges; + Ranges< Index > skeleton_ranges; + for (auto it = cells.begin(); it != cells.end(); ++it) + { + tag_ranges.push_back({ *it, "", "" }, { *it + 0x100, "", "" }); + skeleton_ranges.push_back(Index(*it), Index(*it + 0x100)); + } + tag_ranges.sort(); + skeleton_ranges.sort(); + Block_Backend< Tag_Index_Local, Id_Type > local_tags_db + (rman.get_transaction()->data_index(current_local_tags_file_properties< Skeleton >())); + Block_Backend< Index, Skeleton > skeletons_db + (rman.get_transaction()->data_index(current_skeleton_file_properties< Skeleton >())); + return local_tags_db.count_blocks(tag_ranges) + skeletons_db.count_blocks(skeleton_ranges); +} + + +// The global tag index stores coarse indices (multiples of 0x100): keep ids whose cell overlaps ranges. +template< typename Id_Type, typename Index > +void keep_ids_inside(std::vector< std::pair< Id_Type, Uint31_Index > >& ids, const Ranges< Index >& ranges) +{ + std::vector< std::pair< Index, Index > > bounds; + for (auto it = ranges.begin(); it != ranges.end(); ++it) + bounds.push_back(std::make_pair(it.lower_bound(), it.upper_bound())); + std::sort(bounds.begin(), bounds.end()); + std::vector< std::pair< Index, Index > > merged; + for (auto it = bounds.begin(); it != bounds.end(); ++it) + { + if (!merged.empty() && !(merged.back().second < it->first)) + merged.back().second = std::max(merged.back().second, it->second); + else + merged.push_back(*it); + } + std::vector< std::pair< Id_Type, Uint31_Index > > kept; + for (auto it = ids.begin(); it != ids.end(); ++it) + { + Index idx(it->second.val()); + auto b = std::upper_bound(merged.begin(), merged.end(), idx, + [](const Index& x, const std::pair< Index, Index >& r) { return x < r.second; }); + if (b != merged.end() && b->first < Index(idx.val() + 0x100)) + kept.push_back(*it); + } + kept.swap(ids); +} + + +template< typename Skeleton, typename Id_Type, typename Index > std::vector< std::pair< Id_Type, Uint31_Index > > collect_ids( const std::vector< std::string >& keys, const std::vector< std::pair< std::string, std::string > >& key_values, @@ -431,8 +488,10 @@ std::vector< std::pair< Id_Type, Uint31_Index > > collect_ids( const std::vector< std::pair< Regular_Expression*, Regular_Expression* > >& regkey_regexes, const File_Properties& file_prop, const File_Properties& attic_file_prop, Resource_Manager& rman, const Statement& stmt, - uint64 timestamp, Query_Filter_Strategy check_keys_late, bool& result_valid) + uint64 timestamp, Query_Filter_Strategy check_keys_late, bool& result_valid, bool& check_rest_late, + const Ranges< Index >* spatial_ranges) { + check_rest_late = false; if (key_values.empty() && keys.empty() && key_regexes.empty() && regkey_regexes.empty()) return std::vector< std::pair< Id_Type, Uint31_Index > >(); @@ -443,11 +502,86 @@ std::vector< std::pair< Id_Type, Uint31_Index > > collect_ids( new Block_Backend< Tag_Index_Global, Attic< Tag_Object_Global< Id_Type > > > (rman.get_transaction()->data_index(&attic_file_prop))); - // Handle simple Key-Value pairs std::vector< std::pair< Id_Type, Uint31_Index > > new_ids; bool filtered = false; result_valid = false; + if (timestamp == NOW) + { + // Smallest lookups first; stop when checking the remaining tags late reads fewer blocks. + struct Lookup + { + Ranges< Tag_Index_Global > ranges; + Regular_Expression* value_regex; + bool limit_size; + uint64 blocks; + }; + std::vector< Lookup > lookups; + for (auto it = key_values.begin(); it != key_values.end(); ++it) + lookups.push_back(Lookup{ get_kv_req(it->first, it->second), 0, + check_keys_late == prefer_ranges || check_keys_late == ids_useful, 0 }); + if (check_keys_late != prefer_ranges) + { + for (auto it = keys.begin(); it != keys.end(); ++it) + lookups.push_back(Lookup{ get_k_req(*it), 0, check_keys_late == ids_useful, 0 }); + for (auto it = key_regexes.begin(); it != key_regexes.end(); ++it) + lookups.push_back(Lookup{ get_k_req(it->first), it->second, check_keys_late == ids_useful, 0 }); + } + uint64 remaining_blocks = 0; + for (auto it = lookups.begin(); it != lookups.end(); ++it) + { + it->blocks = tags_db.count_blocks(it->ranges); + remaining_blocks += it->blocks; + } + std::stable_sort(lookups.begin(), lookups.end(), + [](const Lookup& lhs, const Lookup& rhs) { return lhs.blocks < rhs.blocks; }); + + for (auto it = lookups.begin(); it != lookups.end(); ++it) + { + if (filtered && count_late_check_blocks< Skeleton, Id_Type, Index >(new_ids, rman) < remaining_blocks) + { + check_rest_late = true; + result_valid = true; + return new_ids; + } + if (it->value_regex) + filter_id_list(new_ids, filtered, tags_db.range_begin(it->ranges), tags_db.range_end(), + Trivial_Regex(), *it->value_regex, it->limit_size); + else + filter_id_list(new_ids, filtered, tags_db.range_begin(it->ranges), tags_db.range_end(), + Trivial_Regex(), Trivial_Regex(), it->limit_size); + if (!filtered) + return new_ids; + if (spatial_ranges) + keep_ids_inside(new_ids, *spatial_ranges); + if (new_ids.empty()) + { + result_valid = true; + return new_ids; + } + remaining_blocks -= it->blocks; + rman.health_check(stmt); + } + + if (check_keys_late != prefer_ranges) + { + for (auto it = regkey_regexes.begin(); it != regkey_regexes.end(); ++it) + { + Ranges< Tag_Index_Global > ranges = get_regk_req< Skeleton >(it->first, rman, stmt); + filter_id_list(new_ids, filtered, tags_db.range_begin(ranges), tags_db.range_end(), + *it->first, *it->second, check_keys_late == ids_useful); + if (!filtered) + return new_ids; + rman.health_check(stmt); + } + } + + result_valid = true; + return new_ids; + } + + // Handle simple Key-Value pairs + for (std::vector< std::pair< std::string, std::string > >::const_iterator kvit = key_values.begin(); kvit != key_values.end(); ++kvit) { @@ -855,7 +989,7 @@ void progress_1( const std::vector< std::pair< Regular_Expression*, Regular_Expression* > >& regkey_nregexes, Id_Constraint< Id_Type >& ids, std::vector< Index >& range_vec, uint64 timestamp, Query_Filter_Strategy& check_keys_late, - Resource_Manager& rman, const Statement& stmt) + Resource_Manager& rman, const Statement& stmt, const Ranges< Index >* spatial_ranges = 0) { File_Properties* file_prop = current_global_tags_file_properties< Skeleton >(); File_Properties* attic_file_prop = attic_global_tags_file_properties< Skeleton >(); @@ -867,11 +1001,13 @@ void progress_1( && (!keys.empty() || !key_regexes.empty() || !regkey_regexes.empty()))) { bool result_valid = true; + bool check_rest_late = false; std::vector< std::pair< Id_Type, Uint31_Index > > id_idxs = - collect_ids< Skeleton, Id_Type >( + collect_ids< Skeleton, Id_Type, Index >( keys, key_values, key_regexes, regkey_regexes, - *file_prop, *attic_file_prop, rman, stmt, timestamp, check_keys_late, result_valid); - if (check_keys_late == ids_useful && !result_valid) + *file_prop, *attic_file_prop, rman, stmt, timestamp, check_keys_late, result_valid, check_rest_late, + spatial_ranges); + if ((check_keys_late == ids_useful && !result_valid) || check_rest_late) check_keys_late = prefer_ranges; ids.invert = !result_valid; diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index 91dd74aae..326293706 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -1079,11 +1079,25 @@ void Query_Statement::execute(Resource_Manager& rman) std::vector< Uint31_Index > way_range_vec_31; std::vector< Uint31_Index > relation_range_vec_31; + // Known before the tag lookup, which drops candidates outside them. + Ranges< Uint32_Index > node_ranges = Ranges< Uint32_Index >::global(); + Ranges< Uint31_Index > way_ranges = Ranges< Uint31_Index >::global(); + Ranges< Uint31_Index > rel_ranges = Ranges< Uint31_Index >::global(); + for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); it != constraints.end(); ++it) + { + if (type & QUERY_NODE) + node_ranges.intersect((*it)->get_node_ranges(rman)).swap(node_ranges); + if (type & QUERY_WAY) + way_ranges.intersect((*it)->get_way_ranges(rman)).swap(way_ranges); + if (type & QUERY_RELATION) + rel_ranges.intersect((*it)->get_relation_ranges(rman)).swap(rel_ranges); + } + if (type & QUERY_NODE) { progress_1< Node_Skeleton, Node::Id_Type, Uint32_Index >( keys, key_values, key_regexes, regkey_regexes, key_nvalues, key_nregexes, regkey_nregexes, - node_ids, range_vec_32, timestamp, check_keys_late, rman, *this); + node_ids, range_vec_32, timestamp, check_keys_late, rman, *this, node_ranges.is_global() ? 0 : &node_ranges); if (node_ids.empty()) node_answer_state = data_collected; collect_nodes(node_ids, node_answer_state, into, rman); @@ -1092,7 +1106,7 @@ void Query_Statement::execute(Resource_Manager& rman) { progress_1< Way_Skeleton, Way::Id_Type, Uint31_Index >( keys, key_values, key_regexes, regkey_regexes, key_nvalues, key_nregexes, regkey_nregexes, - way_ids, way_range_vec_31, timestamp, check_keys_late, rman, *this); + way_ids, way_range_vec_31, timestamp, check_keys_late, rman, *this, way_ranges.is_global() ? 0 : &way_ranges); if (way_ids.empty()) way_answer_state = data_collected; collect_elems(QUERY_WAY, way_ids, way_answer_state, into, rman); @@ -1103,7 +1117,7 @@ void Query_Statement::execute(Resource_Manager& rman) { progress_1< Relation_Skeleton, Relation::Id_Type, Uint31_Index >( keys, key_values, key_regexes, regkey_regexes, key_nvalues, key_nregexes, regkey_nregexes, - relation_ids, relation_range_vec_31, timestamp, check_keys_late, rman, *this); + relation_ids, relation_range_vec_31, timestamp, check_keys_late, rman, *this, rel_ranges.is_global() ? 0 : &rel_ranges); if (relation_ids.empty()) relation_answer_state = data_collected; collect_elems(QUERY_RELATION, relation_ids, relation_answer_state, into, rman); @@ -1162,37 +1176,12 @@ void Query_Statement::execute(Resource_Manager& rman) } } - Ranges< Uint32_Index > node_ranges = Ranges< Uint32_Index >::global(); - Ranges< Uint31_Index > way_ranges = Ranges< Uint31_Index >::global(); - Ranges< Uint31_Index > rel_ranges = Ranges< Uint31_Index >::global(); - - if ((type & QUERY_NODE) && node_answer_state < data_collected) - { - for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); - it != constraints.end(); ++it) - node_ranges.intersect((*it)->get_node_ranges(rman)).swap(node_ranges); - - if (!range_vec_32.empty()) - intersect_ranges(node_ranges, range_vec_32).swap(node_ranges); - } - if ((type & QUERY_WAY) && way_answer_state < data_collected) - { - for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); - it != constraints.end(); ++it) - way_ranges.intersect((*it)->get_way_ranges(rman)).swap(way_ranges); - - if (!way_range_vec_31.empty()) - intersect_ranges(way_ranges, way_range_vec_31).swap(way_ranges); - } - if ((type & QUERY_RELATION) && relation_answer_state < data_collected) - { - for (std::vector< Query_Constraint* >::iterator it = constraints.begin(); - it != constraints.end(); ++it) - rel_ranges.intersect((*it)->get_relation_ranges(rman)).swap(rel_ranges); - - if (!relation_range_vec_31.empty()) - intersect_ranges(rel_ranges, relation_range_vec_31).swap(rel_ranges); - } + if ((type & QUERY_NODE) && node_answer_state < data_collected && !range_vec_32.empty()) + intersect_ranges(node_ranges, range_vec_32).swap(node_ranges); + if ((type & QUERY_WAY) && way_answer_state < data_collected && !way_range_vec_31.empty()) + intersect_ranges(way_ranges, way_range_vec_31).swap(way_ranges); + if ((type & QUERY_RELATION) && relation_answer_state < data_collected && !relation_range_vec_31.empty()) + intersect_ranges(rel_ranges, relation_range_vec_31).swap(rel_ranges); set_progress(3); rman.health_check(*this); diff --git a/src/template_db/block_backend.h b/src/template_db/block_backend.h index 4defdf0e0..0c982dafd 100644 --- a/src/template_db/block_backend.h +++ b/src/template_db/block_backend.h @@ -531,6 +531,16 @@ struct Block_Backend Range_Iterator range_begin(const Ranges< TIndex >& arg) { return Range_Iterator(file_blocks, arg.begin(), arg.end(), block_size); } + // From the block index alone: nothing is read or decompressed. + uint64 count_blocks(const Ranges< TIndex >& arg) + { + uint64 count = 0; + auto end = file_blocks.template range_end< typename Ranges< TIndex >::Iterator >(); + for (auto it = file_blocks.range_begin(arg.begin(), arg.end()); !(it == end); ++it) + ++count; + return count; + } + const Range_Iterator& range_end() const { return *range_end_it; } template< typename Container > From 835abb50836964a7cec23d76c671a0136047a250 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:50:54 +0000 Subject: [PATCH 76/80] query: collect few tag-index candidates by their exact indices 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 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit e0bbfaa2d585ce84549900c5f5b38f0a161bb44e) --- src/overpass_api/statements/query.cc | 50 ++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index 326293706..344d129ce 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -872,6 +872,42 @@ void Query_Statement::collect_elems(Answer_State& answer_state, Set& into, Resou } +// The id map holds a fixed number of ids per block and decompresses one block at a time, so +// looking ids up costs about one block per distinct block they fall in. +template< typename Index, typename Skeleton > +bool exact_indices_pay_off(const std::vector< typename Skeleton::Id_Type >& ids, + const Ranges< Index >& coarse_ranges, Resource_Manager& rman) +{ + if (ids.empty() || coarse_ranges.is_global()) + return false; + Random_File_Index* map = rman.get_transaction()->random_index(current_skeleton_file_properties< Skeleton >()); + uint64 ids_per_block = map->get_block_size() * map->get_compression_factor() / Index::max_size_of(); + uint64 map_blocks = 0; + uint64 last_block = ~uint64(0); + for (auto it = ids.begin(); it != ids.end(); ++it) + { + uint64 block = it->val() / ids_per_block; + if (block != last_block) + ++map_blocks; + last_block = block; + } + Block_Backend< Index, Skeleton > skeletons_db + (rman.get_transaction()->data_index(current_skeleton_file_properties< Skeleton >())); + return 2*map_blocks < skeletons_db.count_blocks(coarse_ranges); +} + + +template< typename Index > +Ranges< Index > exact_ranges(const std::vector< Index >& idxs) +{ + Ranges< Index > result; + for (auto it = idxs.begin(); it != idxs.end(); ++it) + result.push_back(*it, inc(*it)); + result.sort(); + return result; +} + + template< typename Index > Ranges< Index > intersect_ranges(const Ranges< Index >& range_a, std::vector< Index >& range_vec) { @@ -1176,12 +1212,26 @@ void Query_Statement::execute(Resource_Manager& rman) } } + // The global tag index gives only each candidate's coarse cell. Their exact indices from the + // id map narrow the blocks to read further, when the map blocks read are fewer than those saved. if ((type & QUERY_NODE) && node_answer_state < data_collected && !range_vec_32.empty()) + { intersect_ranges(node_ranges, range_vec_32).swap(node_ranges); + if (timestamp == NOW && !node_ids.invert && exact_indices_pay_off< Uint32_Index, Node_Skeleton >(node_ids.ids, node_ranges, rman)) + node_ranges.intersect(exact_ranges(get_indexes_< Uint32_Index, Node_Skeleton >(node_ids.ids, rman))).swap(node_ranges); + } if ((type & QUERY_WAY) && way_answer_state < data_collected && !way_range_vec_31.empty()) + { intersect_ranges(way_ranges, way_range_vec_31).swap(way_ranges); + if (timestamp == NOW && !way_ids.invert && exact_indices_pay_off< Uint31_Index, Way_Skeleton >(way_ids.ids, way_ranges, rman)) + way_ranges.intersect(exact_ranges(get_indexes_< Uint31_Index, Way_Skeleton >(way_ids.ids, rman))).swap(way_ranges); + } if ((type & QUERY_RELATION) && relation_answer_state < data_collected && !relation_range_vec_31.empty()) + { intersect_ranges(rel_ranges, relation_range_vec_31).swap(rel_ranges); + if (timestamp == NOW && !relation_ids.invert && exact_indices_pay_off< Uint31_Index, Relation_Skeleton >(relation_ids.ids, rel_ranges, rman)) + rel_ranges.intersect(exact_ranges(get_indexes_< Uint31_Index, Relation_Skeleton >(relation_ids.ids, rman))).swap(rel_ranges); + } set_progress(3); rman.health_check(*this); From 13f99e4cbec53820731191cc7c46e5e54d3a00cf Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:50:54 +0000 Subject: [PATCH 77/80] tags: reject entries of later keys with a bit filter before the binary 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 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit 284a1099aa1f0b65169c6248820f04ab4e5f7389) --- src/overpass_api/data/tags_global_reader.h | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/overpass_api/data/tags_global_reader.h b/src/overpass_api/data/tags_global_reader.h index 2e051f5c1..5e894704c 100644 --- a/src/overpass_api/data/tags_global_reader.h +++ b/src/overpass_api/data/tags_global_reader.h @@ -31,6 +31,7 @@ #include "../core/settings.h" #include "../statements/statement.h" #include "../dispatch/resource_manager.h" +#include "abstract_processing.h" #include "filenames.h" #include "filter_by_tags.h" #include "regular_expression.h" @@ -354,9 +355,20 @@ void filter_id_list( std::vector< std::pair< Id_Type, Uint31_Index > > old_ids; old_ids.swap(new_ids); Tag_Entry_Matcher< Key_Regex, Val_Regex > matcher(key_regex, val_regex); + // Most entries of a later key belong to none of the candidates: reject those with one bit test. + std::vector< Id_Type > old_id_list; + if (filtered) + { + old_id_list.reserve(old_ids.size()); + for (auto it = old_ids.begin(); it != old_ids.end(); ++it) + old_id_list.push_back(it->first); + } + Id_Bit_Filter old_id_filter(old_id_list); for (Iterator it = begin; !(it == end); ++it) { + if (filtered && !old_id_filter.maybe_contains(it.object().id.val())) + continue; if (matcher.matches(it.index()) && (!filtered || std::binary_search(old_ids.begin(), old_ids.end(), std::make_pair(it.object().id, Uint31_Index(0u))))) new_ids.push_back(std::make_pair(it.object().id, it.object().idx)); From 3b6e5baeffb491330610819d0de578455f058e67 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:50:54 +0000 Subject: [PATCH 78/80] tag_store: reject other elements' tag entries with a bit filter 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 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit edf6f1e0e63e4af3a7695bed8f35936b477476e8) --- src/overpass_api/data/tag_store.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/overpass_api/data/tag_store.h b/src/overpass_api/data/tag_store.h index d9c3d81cd..a6a0bb0c3 100644 --- a/src/overpass_api/data/tag_store.h +++ b/src/overpass_api/data/tag_store.h @@ -20,6 +20,7 @@ #define DE__OSM3S___OVERPASS_API__DATA__TAG_STORE_H +#include "abstract_processing.h" #include "filenames.h" #include "../core/datatypes.h" #include "../../template_db/block_backend.h" @@ -294,6 +295,8 @@ void collect_tags_framed { const std::vector< Id_Type >& ids = ids_by_coarse[coarse_index]; typename std::vector< Id_Type >::const_iterator cursor = ids.begin(); + // Most of a cell's tag entries belong to other elements: reject those with one bit test. + Id_Bit_Filter id_filter(ids); while ((!(tag_it == items_db.range_end())) && ((tag_coarse_index(tag_it)) < coarse_index)) ++tag_it; @@ -302,7 +305,8 @@ void collect_tags_framed while ((!(tag_it == items_db.range_end())) && ((tag_coarse_index(tag_it)) == coarse_index)) { - if (!(tag_it.object() < lower_id_bound) && + if (id_filter.maybe_contains(tag_it.object().val()) && + !(tag_it.object() < lower_id_bound) && (tag_it.object() < upper_id_bound) && contains_from_cursor(ids, cursor, tag_it.object())) { From af72b3c0ac028cf95ab8d84d0828830ffca337be Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 00:28:22 +0000 Subject: [PATCH 79/80] block cache: don't keep global tag index blocks 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 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit 6fde65ad0c96f446c4abc25f88bb0aa5e705d692) --- src/template_db/transaction.h | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/template_db/transaction.h b/src/template_db/transaction.h index 101092362..01c5b280a 100644 --- a/src/template_db/transaction.h +++ b/src/template_db/transaction.h @@ -97,6 +97,12 @@ inline void Nonsynced_Transaction::flush() } +inline bool ends_with(const std::string& s, const std::string& suffix) +{ + return s.size() >= suffix.size() && s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0; +} + + inline File_Blocks_Index_Base* Nonsynced_Transaction::data_index (const File_Properties* fp) { @@ -108,7 +114,9 @@ inline File_Blocks_Index_Base* Nonsynced_Transaction::data_index File_Blocks_Index_Base* data_index = fp->new_data_index(access_mode, use_shadow, db_dir, file_name_extension); if (data_index != 0) { - if (access_mode == Access_Mode::readonly) + // Statements of a union read the same skeleton and local tag blocks, but look up different + // tags in the global tag index, so its blocks are rarely read again: don't cache them. + if (access_mode == Access_Mode::readonly && !ends_with(fp->get_file_name_trunk(), "_tags_global")) data_index->block_cache = &block_cache_; data_files[fp] = data_index; } From 02ea3966c505f39ebc305d0bd20bda3fca7200f1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 01:44:35 +0000 Subject: [PATCH 80/80] query: collect only the elements the local tag index says match 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 Claude-Session: https://claude.ai/code/session_01736kJWpJaGbt8ML6jz9N35 (cherry picked from commit d053c621f2751bd4e482119d870b3a5310755340) --- src/overpass_api/statements/query.cc | 120 +++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) diff --git a/src/overpass_api/statements/query.cc b/src/overpass_api/statements/query.cc index 344d129ce..7fab61512 100644 --- a/src/overpass_api/statements/query.cc +++ b/src/overpass_api/statements/query.cc @@ -1083,6 +1083,93 @@ void restrict_to_constraint_ids( } +// Ids of current elements in the coarse cells of ranges that carry every positive tag filter +// (keys, key-values, key-regexes), read from the local tag index alone: the late tag check can +// then collect just these instead of every element in the ranges. Returns false where it doesn't +// apply: no positive filter, or ranges spanning too many cells. +template< typename Index, typename Id_Type > +bool ids_from_local_tags( + const std::vector< std::string >& keys, + const std::vector< std::pair< std::string, std::string > >& key_values, + const std::vector< std::pair< std::string, Regular_Expression* > >& key_regexes, + const Ranges< Index >& ranges, const File_Properties& local_tags_file, + Resource_Manager& rman, std::vector< Id_Type >& result) +{ + if (keys.empty() && key_values.empty() && key_regexes.empty()) + return false; + + std::vector< uint32 > cells; + for (auto it = ranges.begin(); it != ranges.end(); ++it) + { + // Uint31_Index orders by the low 31 bits first, so its ranges are spans of those bits; the + // local tag index files elements under (index & 0x7fffff00) for both kinds of index. + uint32 lower = it.lower_bound().val(); + uint32 upper = it.upper_bound().val() - 1; + if (std::is_same< Index, Uint31_Index >::value) + { + lower &= 0x7fffffff; + upper = it.upper_bound().val() & 0x7fffffff; + } + else if ((lower ^ upper) & 0x80000000) + return false; + if (upper < lower) + return false; + for (uint64 cell = lower & 0x7fffff00; cell <= (upper & 0x7fffff00); cell += 0x100) + { + cells.push_back(cell); + if (cells.size() > 64*1024) + return false; + } + } + std::sort(cells.begin(), cells.end()); + cells.erase(std::unique(cells.begin(), cells.end()), cells.end()); + + Block_Backend< Tag_Index_Local, Id_Type > tags_db(rman.get_transaction()->data_index(&local_tags_file)); + std::vector< std::vector< Id_Type > > per_filter; + auto collect = [&](const std::string& key, const std::string* value, Regular_Expression* value_regex) + { + Ranges< Tag_Index_Local > tag_ranges; + for (auto cell = cells.begin(); cell != cells.end(); ++cell) + { + if (value) + tag_ranges.push_back({ *cell, key, *value }, { *cell, key, *value + std::string(1, '\0') }); + else + tag_ranges.push_back({ *cell, key, "" }, { *cell, key + std::string(1, '\0'), "" }); + } + tag_ranges.sort(); + std::vector< Id_Type > ids; + for (auto it = tags_db.range_begin(tag_ranges); !(it == tags_db.range_end()); ++it) + { + if (it.index().value == void_tag_value()) + continue; + if (value_regex && !value_regex->matches(it.index().value)) + continue; + ids.push_back(it.object()); + } + std::sort(ids.begin(), ids.end()); + ids.erase(std::unique(ids.begin(), ids.end()), ids.end()); + per_filter.push_back(std::move(ids)); + }; + for (auto it = key_values.begin(); it != key_values.end(); ++it) + collect(it->first, &it->second, 0); + for (auto it = keys.begin(); it != keys.end(); ++it) + collect(*it, 0, 0); + for (auto it = key_regexes.begin(); it != key_regexes.end(); ++it) + collect(it->first, 0, it->second); + + std::sort(per_filter.begin(), per_filter.end(), + [](const std::vector< Id_Type >& lhs, const std::vector< Id_Type >& rhs) { return lhs.size() < rhs.size(); }); + result.swap(per_filter.front()); + for (auto it = per_filter.begin() + 1; it != per_filter.end() && !result.empty(); ++it) + { + std::vector< Id_Type > both; + std::set_intersection(result.begin(), result.end(), it->begin(), it->end(), std::back_inserter(both)); + result.swap(both); + } + return true; +} + + void Query_Statement::execute(Resource_Manager& rman) { Cpu_Timer cpu(rman, 1); @@ -1233,6 +1320,39 @@ void Query_Statement::execute(Resource_Manager& rman) rel_ranges.intersect(exact_ranges(get_indexes_< Uint31_Index, Relation_Skeleton >(relation_ids.ids, rman))).swap(rel_ranges); } + // Tags checked late over ranges: find the matching ids from the local tag index first, so that + // collection skips the other elements without decoding them. + if (check_keys_late == prefer_ranges && timestamp == NOW) + { + if ((type & QUERY_NODE) && node_answer_state < data_collected && node_ids.invert && node_ids.ids.empty() + && !node_ranges.is_global() + && ids_from_local_tags(keys, key_values, key_regexes, node_ranges, + *osm_base_settings().NODE_TAGS_LOCAL, rman, node_ids.ids)) + { + node_ids.invert = false; + if (node_ids.ids.empty()) + node_answer_state = data_collected; + } + if ((type & QUERY_WAY) && way_answer_state < data_collected && way_ids.invert && way_ids.ids.empty() + && !way_ranges.is_global() + && ids_from_local_tags(keys, key_values, key_regexes, way_ranges, + *osm_base_settings().WAY_TAGS_LOCAL, rman, way_ids.ids)) + { + way_ids.invert = false; + if (way_ids.ids.empty()) + way_answer_state = data_collected; + } + if ((type & QUERY_RELATION) && relation_answer_state < data_collected && relation_ids.invert + && relation_ids.ids.empty() && !rel_ranges.is_global() + && ids_from_local_tags(keys, key_values, key_regexes, rel_ranges, + *osm_base_settings().RELATION_TAGS_LOCAL, rman, relation_ids.ids)) + { + relation_ids.invert = false; + if (relation_ids.ids.empty()) + relation_answer_state = data_collected; + } + } + set_progress(3); rman.health_check(*this);