Repository navigation
fix(indexer): a reindex keeps the ledger's spatial index - #2274
Conversation
The rebuild collected and remapped spatial entries, then published a root with no spatial arenas, so every reindex dropped the ledger's spatial index (and an incremental build that fell back to a rebuild did too). It now builds and uploads them with the builder the rebuild had left unused.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is the right fix, and no pushback at a design level: wiring the builder the rebuild already had, and writing through ContentStore the way fulltext does, is what I'd have done. Two notes worth lifting up. (1) After this the incremental build still keeps its own ~250-line copy of the spatial builder (incremental.rs:1720-1973), so there are two live implementations that already differ on caching and error handling; details below. (2) This is the third time a full rebuild has quietly diverged from the incremental build:
8ac57d75afully retracted partitions;282c21458rebuild stats; this PR, spatial arenas
I'm not arguing that this PR should take that brittleness on, the point fix is right here, but the class fix would be a test that indexes the same commits both ways and compares the roots arena by arena and stat by stat, which would have caught all three. Good to merge once it's ready.
Full review below:
✅ Approve.
Nice: this closes the one GraphArenaRefs field the rebuild left empty, and it does it with the builder that was already there rather than a new one. Claude read the rest of the rebuild's arena assembly to answer "what else does a reindex drop this way", and the answer is nothing today: numbig and vector arenas come from the uploaded dictionaries and fulltext from build_and_upload_fulltext_arenas, so spatial was the only gap. The test fails at the first check with the fix reverted, the GC side already enumerates spatial CIDs (index_root.rs:1243-1248), and the next conflict is the one the body names, where keeping this side is right because ContentStore makes next's namespace parameter unnecessary. The notes below are optional: pin the remapped subject identity in the test (that remap runs for the first time here), make a remap miss fail like fulltext's, consider routing the incremental path through the same builder, and the reindex cost Claude measured for the record.
Adherence to repo commitments:
- Patterns/abstractions: ✔ revives the existing
build_and_upload_spatial_indexesand moves it ontoContentStorelike fulltext;⚠️ the incremental path still has its own copy of the builder (optional note). - Performance (speed first, memory second): ✔ rebuild-time only, proportional to non-point geometries: about 40 µs per polygon measured (20,000 polygons: ~140 ms → ~950 ms per reindex); no query-path change, no performance-degradation risk.
- Deployment targets: ✔ the rebuild runs in the same process shape on the server and embedded; the cost is linear and far from any execution ceiling at realistic polygon counts. The eager spatial load on index open is pre-existing and now also applies to reindexed ledgers; spatial stays off on wasm32 (
#[cfg(not(target_arch = "wasm32"))]). - Testing: ✔
grp_querytest across reindex then incremental-without-fallback, red under mutation;⚠️ it pins counts rather than subject identities. - Conventions: ✔ descriptive commit body; the PR title is self-describing; CI fmt/clippy green on the head.
Verified at branch HEAD (aec94c939): Claude ran a_rebuild_keeps_the_spatial_index and the it_query_geo tests on a box (pass), reverted rebuild.rs and spatial.rs to the merge base (the test fails, left: [], right: [1]), timed reindexes with and without the fix, and checked the next merge with git merge-tree (only spatial.rs conflicts); CI test, clippy and wasm32 are green on this SHA.
Approving so you can merge when ready, but maybe worth considering a few of these first.
| .reindex(id, fluree_db_api::ReindexOptions::default()) | ||
| .await | ||
| .unwrap(); | ||
| assert_eq!(spatial_geometry_counts(&fluree, id).await, vec![1]); |
There was a problem hiding this comment.
Optional (test). I may be wrong about how much this matters, but the count reads geometry_count, which is the arena's distinct-WKT count (fluree-db-spatial/src/builder.rs:390, self.arena.len()), so it says nothing about which subject each geometry was indexed under. The subject remap at rebuild.rs:483-491 runs for the first time with this PR, and a wrong remap would still give [1] and then [2].
Minimally, one assertion that the cell entries' subject_id for the park is the id the index's subject dictionary gives ex:park would pin it (a retraction wouldn't show up in this count, since the builder adds retracted WKT to the arena too). Minor and non-blocking, but since this is the first time that remap is exercised, I'd rather see it pinned now.
There was a problem hiding this comment.
Addressed in ed7d235. Pinning the subject turned up a second bug: the incremental resolver never remapped the spatial hook's subject ids, so geometries written since the base index were indexed under their chunk-local id. Fixed in the same commit, next to the fulltext remap; the test checks both subjects.
| // The spatial hook accumulated entries with chunk-local s_id values; | ||
| // spatial_chunk_ranges[ci] = (start, end) into entries for chunk ci. | ||
| let _spatial_entries: Vec<crate::spatial_hook::SpatialEntry> = { | ||
| let spatial_entries: Vec<crate::spatial_hook::SpatialEntry> = { |
There was a problem hiding this comment.
Optional. A miss in this remap is silent: if let Some(&global_s) = s_remap.get(local_s) leaves the chunk-local id in place on a miss (:487-489), which would index that geometry under whatever subject happens to have that global id. The fulltext remap right below it handles the same miss by warning and neutralizing the entry (:512-525). A miss shouldn't happen, so this is cheap insurance rather than a bug, but now that these entries reach the index, we may want the two remaps to fail the same way, e.g. warn and drop the entry. Fold it in now if you agree.
There was a problem hiding this comment.
Addressed in ed7d235. The incremental build's new subject remap fails the same way.
| // Use when: rebuild.rs is extended to upload spatial indexes after Phase C remap. | ||
| #[expect(dead_code)] | ||
| pub(crate) async fn build_and_upload_spatial_indexes<S: Storage>( | ||
| pub(crate) async fn build_and_upload_spatial_indexes<C: ContentStore + ?Sized>( |
There was a problem hiding this comment.
Optional (altitude). With this function live again there are two implementations of "build a (g, p) spatial index and upload it": this one, and the inline block in build/incremental.rs:1720-1973 (about 250 lines). They already drift a little: the incremental one caches each blob and root to the local index cache (cache_artifact_bytes) and ignores per-geometry errors (let _ = builder.add_geometry(…)), while this one warns on them and caches nothing.
The incremental block could build its prior entries as SpatialEntrys from the snapshot (it already has subject, WKT, t and op for each), append novelty, and call this function, keeping only its replace-and-GC bookkeeping. That's the same "two paths that should agree" shape this PR fixes a symptom of, so if you agree it's PR-sized I'd rather see it folded in here than have the two drift further; if it turns out bigger than it looks, say so and we can leave it.
There was a problem hiding this comment.
Addressed in ed7d235. Folding it in turned up a bug in the incremental copy: it re-added each prior geometry once per cell entry, so every incremental build multiplied the index by up to the covering size (8); five polygons reached 37,448 cell entries after four builds. The shared path reloads one entry per distinct geometry. The incremental build keeps its local cache seeding through an on_put hook, and per-geometry errors now warn on both paths.
| let spatial_by_graph: std::collections::BTreeMap< | ||
| fluree_db_core::GraphId, | ||
| Vec<fluree_db_binary_index::SpatialArenaRef>, | ||
| > = super::spatial::build_and_upload_spatial_indexes( |
There was a problem hiding this comment.
Optional (performance, for the record). Not a blocker, just the measurement #2152 item 5 asked for. Claude timed a reindex of a file-backed ledger holding 20,000 12-sided polygons (--profile dev-fast, three reindexes per build, on a c7i.8xlarge): 286 / 132 / 146 ms with this PR's two indexer files reverted, 1,078 / 961 / 957 ms with them (and 1,084 / 948 / 938 ms on a second build). So about 40 µs per polygon, in the single-threaded per-(g, p) loop, and none for point-only ledgers. That's the same work the incremental build already does, so I think it's right, but a sentence in the body would help the release notes.
The other cost is pre-existing, not introduced here: every index load from a v6 root fetches every spatial blob into memory (fluree-db-binary-index/src/read/binary_index_store.rs:4021-4054) for a provider nothing queries yet, and reindexed ledgers now pay that too. Commenting here because binary_index_store.rs is not in this diff.
There was a problem hiding this comment.
Added to the PR body. The eager spatial load on index open is noted on #2152.
…ry, under its subject The incremental build reloaded a spatial index by re-adding each geometry once per cell entry, and the builder emits one cell entry per covering cell, so every build that touched a spatial predicate multiplied the prior entries by up to the covering size (8): five polygons reached 37,448 cell entries after four builds. It now reads one entry per distinct (subject, geometry, t, op) and builds through the same builder the full rebuild uses, which removes its own copy. A cell scan error falls back to a full rebuild rather than dropping the prior geometries. The incremental resolver also never remapped the spatial hook's chunk-local subject ids, so geometries written since the base index were indexed under the wrong subject. They are now remapped after reconciliation, as fulltext string ids are. A remap miss in either build warns and drops the entry.
|
Filed the rebuild-vs-incremental comparison as #2335. It would have caught both incremental bugs this PR now fixes as well. |
Brings #2271 (reasoning batched lanes) and #2274 (spatial index rebuild). - The object lane's overlay ops: main caches the IRI_REF subset as the merge plan; next's object lane also batches triple-term keys, so a term-handle flush reconciles against its own o_type subset (object_probe_ops) instead of the plan's ref ops. - The left-key loop keeps next's per-key o_type and main's deferred, memoized key resolution; the per-row path keeps next's independent scan replay ahead of main's open_per_row_scan. - Overlay providers carry both new methods (next's overlay_graph_ids, main's overlay_range_flake_count). - Lane admission takes main's LaneOutput and keeps next's pooled-graph gate. - Main's tests: async genesis ledgers, content_store by namespace, ContentBytes, 64-bit list place. The named-graph reasoning lane test pins its graph dedicated, since the batched lanes don't read a pooled graph under reasoning.
Partially addresses #2152: this fixes item 5 (a full rebuild drops the spatial index), plus two incremental-build bugs in the same index found while testing it. The issue stays open for the S2 query surface: no parser builds an
idx:spatialsearch (1), the syntax decision (2), the operator and provider map keying providers differently (3), novelty geometries (4) and the cell key (6).Follow-up: #2335 (a test that a full rebuild and incremental builds produce the same index).
What was wrong
A full rebuild dropped the spatial index. It collected and remapped the spatial hook's entries into an unused
_spatial_entries, then published a root whose graph arenas hadspatial: Vec::new().build_and_upload_spatial_indexessat unused under#[expect(dead_code)]. So a reindex, the first build of a clone or restore, and any incremental build that fell back to a rebuild each published a root with no spatial index.An incremental build multiplied the spatial index. To rebuild a predicate's spatial index, it reloaded the prior index by re-adding each geometry once per cell entry. The cell index holds one entry per covering cell (up to 8), so every incremental build that touched a spatial predicate multiplied the prior entries by up to 8: one reindex and four incremental builds over five polygons produced 37,448 cell entries, where 40 is right.
An incremental build indexed new geometries under the wrong subject. The incremental resolver remaps the fulltext hook's chunk-local string ids after reconciliation, but never remapped the spatial hook's chunk-local subject ids. Every geometry written since the base index was indexed under whichever subject has its chunk-local id.
The change
fluree-db-indexer/src/build/rebuild.rs: builds and uploads the spatial indexes from the remapped entries and lists them in each graph's arenas. A subject remap miss warns and drops the entry, as the fulltext remap does.fluree-db-indexer/src/build/spatial.rs: the builder writes through the build'sContentStore(put, using the CID it returns) instead ofStorage::content_write_bytes, and passes each upload to anon_puthook.fluree-db-indexer/src/build/incremental.rs: reloads oneSpatialEntryper distinct (subject, geometry, t, op) and builds throughbuild_and_upload_spatial_indexes, replacing its own ~250-line copy of the builder. It seeds the local artifact cache throughon_put. A failed cell scan falls back to a full rebuild instead of dropping the prior geometries.fluree-db-indexer/src/run_index/build/incremental_resolve.rs: remaps the spatial hook's subject ids after reconciliation, next to the fulltext remap. A miss warns and drops the entry.No format change: the root's per-graph
spatialrefs already exist, and incremental builds already write them.Cost
A reindex now computes an S2 covering for each non-point geometry, as an incremental build already did: about 40 µs per polygon, in the single-threaded per-(graph, predicate) loop. A reindex of 20,000 polygons went from about 140 ms to about 950 ms. Point-only ledgers are unaffected. Incremental builds on a ledger whose spatial index had grown get cheaper.
Existing ledgers
Nothing queries the spatial index yet (#2152 items 1 and 3), so no query result changes today. A spatial index written before this fix can be wrong three ways:
Reindexing on this version rebuilds all three.
Test
it_query_geo::a_rebuild_keeps_the_spatial_indexreindexes a ledger holding one polygon and checks that every cell entry in the spatial index belongs toex:park, by the id the index's subject dictionary gives it. It then adds a second polygon and builds incrementally with no rebuild fallback, and checks that the park's cell entries carry over once and the rest belong toex:lake. It fails with each fix taken out: the rebuild's (no spatial index), the per-geometry reload's (64 park cell entries, not 8), and the subject remap's (no entry belongs toex:lake).Merging into
nextIn the next main→next merge,
fluree-db-indexer/src/build/spatial.rsandfluree-db-indexer/src/build/incremental.rsconflict. Keep this side of both.ContentStoremakesnext's namespace parameter unnecessary inspatial.rs. Inincremental.rs,next'scache_artifact_bytesandfetch_cached_index_bytestake nocache_dir, so drop that argument from the spatial block's calls and fromload_prior_spatial_entries.