Repository navigation
Description
Problem
On an indexed ledger that holds retractions, the metadata-only fast paths for COUNT(DISTINCT ?s) and COUNT(DISTINCT ?o) undercount. The general pipeline on the same index gives the right answer.
Repro on main at f42ea37, with tiny leaflets (leaflet_rows = 4, two live rows per group, so every leaflet seam falls at a group boundary):
| Data | Build | Query | Fast path | General pipeline, same index | Unindexed |
|---|---|---|---|---|---|
40 subjects with ex:v 1, 2, 9, then ex:v 9 deleted |
full | COUNT(DISTINCT ?s) over ?s ?p ?o |
21 | 40 | 40 |
| same | incremental | same | 30 | 40 | 40 |
| 40 integer objects, each held by three subjects, then the third subject's fact deleted | full | COUNT(DISTINCT ?o) over ?s ?p ?o |
21 | 40 | 40 |
| same | incremental | same | 30 | 40 | 40 |
| same | full | COUNT(DISTINCT ?o) over ?s ex:p ?o |
21 | 40 | 40 |
| same | incremental | same | 30 | 40 | 40 |
The fast and general answers come from the same indexed view, with fluree_db_api::set_fast_paths_disabled toggled between them. In the full builds, 20 leaflets give 19 seams, and 40 − 19 = 21.
Cause
count_distinct_lead_groups_innerandcount_lead_groups_for_predicate(fluree-db-query/src/fast_count.rs) add up each leaflet'slead_group_count. They subtract one where a leaflet's first lead equals the previous leaflet's last lead (:1727and:1756,:1895and:1924onmain).lead_group_countcounts live rows only (compute_lead_group_count,fluree-db-binary-index/src/format/leaflet.rs:137).- Since 25e0721, a leaflet's
first_keyandlast_keyare widened over its retracted history (flush_leafletinfluree-db-binary-index/src/format/leaf.rs). They are routing bounds, not the keys of the first and last live rows. - The build buffers a retracted fact's history and files it into the leaflet that the next record goes to (
push_record→commit_all_pending; SPOT has no segments to split it off). Suppose a leaflet fills right after group G's last live row, and G's next fact in sort order is retracted. That history lands in the next leaflet and lowers itsfirst_keyto G. The walk then counts G as spanning the seam and subtracts one, but the next leaflet never counted G. - An incremental build can widen a leaflet's
last_keythe same way. This happens when it retracts a group's last rows in that leaflet.
The existing tests (indexed_number_of_subjects_and_objects_matches_general, indexed_parallel_number_of_subjects_objects_matches_general) only insert data, so they never produce widened keys.
Affected
Any ledger whose index holds retractions. The error is one per seam where this happens. Paths that use these walks:
count_distinct_position_operator(subjects and objects);- the subject universe in
fast_whole_graph_agg(compute_clean, and the base count incompute_overlay); count_distinct_objects_for_predicate;count_distinct_subjects_for_predicate. It gave the right answer in this repro, and I didn't work out whether this query took the directory walk.
next has the same walk and the same writer.
Fix directions
main, where the index format is frozen: the walk can't trust the keys at a seam whose leads match. Before subtracting, it has to read the lead of the next leaflet's first live row and the previous leaflet's last live row. That adds a column read at each matching seam, which raises the cold cost of these queries, so measure it.history_lencan't serve as a cheap skip, because a full build records every fact's assert in history, so almost every leaflet has some.- v5: record each leaflet's live first and last lead, or a "keys widened" flag with a fallback, so the walk stays directory-only. perf(index): per-leaf lead-group counts in the branch manifest for instant global COUNT(DISTINCT ?s) / COUNT(DISTINCT ?o) #1322's per-leaf counts in the manifest need the same information.
Repro test
The temporary tests below were appended to fluree-db-api/tests/it_query_sparql_indexed.rs. They run one at a time (-- --test-threads=1), because the fast-path switch is process-global. They should become the regression test for the fix.
Patch
diff --git a/fluree-db-api/tests/it_query_sparql_indexed.rs b/fluree-db-api/tests/it_query_sparql_indexed.rs
index 3923b9812..a56949bea 100644
--- a/fluree-db-api/tests/it_query_sparql_indexed.rs
+++ b/fluree-db-api/tests/it_query_sparql_indexed.rs
@@ -9913,3 +9913,201 @@ async fn indexed_values_seeded_star_replays_fully_retracted_predicate() {
"the predicate is gone at head, so the same plan must return nothing"
);
}
+
+async fn seam_retraction_counts(
+ label: &'static str,
+ seed: serde_json::Value,
+ del: serde_json::Value,
+ index_between: bool,
+) {
+ let queries = [
+ (
+ "number-of-subjects",
+ "SELECT (COUNT(DISTINCT ?s) AS ?count) WHERE { ?s ?p ?o }",
+ ),
+ (
+ "number-of-objects",
+ "SELECT (COUNT(DISTINCT ?o) AS ?count) WHERE { ?s ?p ?o }",
+ ),
+ (
+ "distinct-subjects-of-v",
+ "PREFIX ex: <http://example.org/ns/> SELECT (COUNT(DISTINCT ?s) AS ?count) WHERE { ?s ex:v ?o }",
+ ),
+ (
+ "distinct-objects-of-p",
+ "PREFIX ex: <http://example.org/ns/> SELECT (COUNT(DISTINCT ?o) AS ?count) WHERE { ?s ex:p ?o }",
+ ),
+ ];
+ let index_cfg = IndexConfig {
+ reindex_min_bytes: 0,
+ reindex_max_bytes: 80_000_000,
+ };
+
+ let mem = FlureeBuilder::memory().build_memory();
+ let mem_id = "it/seam-mem:main";
+ let mem_ledger = mem
+ .insert_with_opts(
+ genesis_ledger_for_fluree(&mem, mem_id),
+ &seed,
+ TxnOpts::default(),
+ CommitOpts::default(),
+ &index_cfg,
+ )
+ .await
+ .expect("mem seed")
+ .ledger;
+ let mem_ledger = mem
+ .update_with_opts(
+ mem_ledger,
+ &del,
+ TxnOpts::default(),
+ CommitOpts::default(),
+ &index_cfg,
+ )
+ .await
+ .expect("mem delete")
+ .ledger;
+ let mem_view = mem.db_at_t(mem_id, mem_ledger.t()).await.expect("mem view");
+ let mut mem_rows = Vec::new();
+ for (_, q) in &queries {
+ mem_rows.push(normalize_rows(
+ &mem.query(&mem_view, QueryInput::Sparql(q))
+ .await
+ .expect("mem query")
+ .to_jsonld(&mem_view.snapshot)
+ .expect("to_jsonld"),
+ ));
+ }
+
+ let fluree = FlureeBuilder::memory()
+ .with_ledger_cache_config(LedgerManagerConfig::default())
+ .build_memory();
+ let ledger_id = "it/seam-idx:main";
+ let mut idx_config = fluree_db_indexer::IndexerConfig::small();
+ idx_config.leaflet_rows = 4;
+ idx_config.leaf_target_bytes = 2_000;
+ idx_config.leaf_max_bytes = 4_000;
+ let (local, handle) = start_background_indexer_local(
+ fluree.backend().clone(),
+ fluree
+ .nameservice_mode()
+ .as_arc_indexing_nameservice()
+ .expect("test fluree has writable nameservice"),
+ idx_config,
+ );
+ local
+ .run_until(async move {
+ let ledger1 = fluree
+ .insert_with_opts(
+ genesis_ledger_for_fluree(&fluree, ledger_id),
+ &seed,
+ TxnOpts::default(),
+ CommitOpts::default(),
+ &index_cfg,
+ )
+ .await
+ .expect("indexed seed")
+ .ledger;
+ if index_between {
+ let _ = trigger_index_and_wait_outcome(&handle, ledger_id, ledger1.t()).await;
+ }
+ let ledger1 = fluree.ledger(ledger_id).await.expect("reload");
+ let ledger2 = fluree
+ .update_with_opts(
+ ledger1,
+ &del,
+ TxnOpts::default(),
+ CommitOpts::default(),
+ &index_cfg,
+ )
+ .await
+ .expect("indexed delete")
+ .ledger;
+ let outcome = trigger_index_and_wait_outcome(&handle, ledger_id, ledger2.t()).await;
+ eprintln!("{label}: index outcome {outcome:?}");
+ let view = fluree
+ .db_at_t(ledger_id, ledger2.t())
+ .await
+ .expect("indexed view");
+ let mut failures = Vec::new();
+ for ((name, q), mem) in queries.iter().zip(&mem_rows) {
+ let run = || async {
+ normalize_rows(
+ &fluree
+ .query(&view, QueryInput::Sparql(q))
+ .await
+ .expect("indexed query")
+ .to_jsonld(&view.snapshot)
+ .expect("to_jsonld"),
+ )
+ };
+ let fast = run().await;
+ fluree_db_api::set_fast_paths_disabled(true);
+ let generic = run().await;
+ fluree_db_api::set_fast_paths_disabled(false);
+ eprintln!(
+ "{label} {name}: indexed fast={fast:?} indexed generic={generic:?} unindexed={mem:?}"
+ );
+ if &fast != mem || &generic != mem {
+ failures.push(*name);
+ }
+ }
+ assert!(failures.is_empty(), "{label}: mismatch in {failures:?}");
+ })
+ .await;
+}
+
+fn subject_seam_data() -> (serde_json::Value, serde_json::Value) {
+ let nodes: Vec<serde_json::Value> = (0..40)
+ .map(|i| json!({"@id": format!("ex:s{i:03}"), "ex:v": [1, 2, 9]}))
+ .collect();
+ let seed = json!({"@context": {"ex": "http://example.org/ns/"}, "@graph": nodes});
+ let del = json!({
+ "@context": {"ex": "http://example.org/ns/"},
+ "where": [{"@id": "?s", "ex:v": 9}],
+ "delete": [{"@id": "?s", "ex:v": 9}]
+ });
+ (seed, del)
+}
+
+fn object_seam_data() -> (serde_json::Value, serde_json::Value) {
+ let mut nodes = Vec::new();
+ for k in 0..40i64 {
+ for suffix in ["a", "b", "z"] {
+ nodes.push(json!({"@id": format!("ex:o{k:03}{suffix}"), "ex:p": 1000 + k}));
+ }
+ }
+ let seed = json!({"@context": {"ex": "http://example.org/ns/"}, "@graph": nodes});
+ let deletes: Vec<serde_json::Value> = (0..40i64)
+ .map(|k| json!({"@id": format!("ex:o{k:03}z"), "ex:p": 1000 + k}))
+ .collect();
+ let del = json!({
+ "@context": {"ex": "http://example.org/ns/"},
+ "delete": deletes
+ });
+ (seed, del)
+}
+
+#[tokio::test]
+async fn seam_repro_subjects_full_build() {
+ let (seed, del) = subject_seam_data();
+ seam_retraction_counts("subjects/full", seed, del, false).await;
+}
+
+#[tokio::test]
+async fn seam_repro_subjects_incremental() {
+ let (seed, del) = subject_seam_data();
+ seam_retraction_counts("subjects/incremental", seed, del, true).await;
+}
+
+#[tokio::test]
+async fn seam_repro_objects_full_build() {
+ let (seed, del) = object_seam_data();
+ seam_retraction_counts("objects/full", seed, del, false).await;
+}
+
+#[tokio::test]
+async fn seam_repro_objects_incremental() {
+ let (seed, del) = object_seam_data();
+ seam_retraction_counts("objects/incremental", seed, del, true).await;
+}
Activity
bplatz commentedon Nov 14, 2026
Plan (decided 2026-11-14, revised the same day after review)
This is fixed in v5 first. A separate fix for
mainfollows.The invariant. In the v5 format, every non-empty leaflet has an exact live group count and exact live first and last groups. These are independent of its routing bounds and of any history it retains.
v5 (
next)Persist live boundaries. Each leaflet directory entry stores its live first and last group as self-contained prefixes of the order's key. Routing keys stay as they are.
The group has to be defined for every order. That includes GSPO, which is counted as graph + subject (
leaflet.rs:362), and the graph-suffixed pooled orders. Pooled orders keep their current fast-path exclusions, because a pooled summary can't answer a query restricted to one member graph.Writers recompute whenever live rows change. That covers the incremental merge, leaflet splits, and erasure of current rows. A history-only rewrite (
rewrite_leaf_history) keeps the rows, so it can keep their summary. It also keeps the stretched routing keys while dropping their history, which is why onnextan empty history segment doesn't prove the keys are exact.One shared walk for distinct-group counts. Today the boundary dedup is written three times, and the copies treat a leaflet with rows but no
lead_group_countdifferently. The boundary rule lives in the shared walk once: add the counts, and subtract one whenleft.last_live == right.first_live.count_distinct_lead_groupsturnsNoneinto 0 (fast_count.rs:1224), so a decline must reach the caller as a decline, not as 0.Related fixes:
MIN/MAXreads the persisted live edge (Numeric MIN/MAX fast path can return a retracted value: it reads leaflet routing keys as the extremes #2398).post_o_key_bounds, and needs no live-edge reads (Range semijoin prunes POST leaflets by o_key without checking the key's o_type #2399).fast_count.rs:544). It declines there, which costs performance but not correctness.v4 roots are a fully supported path, not a transition. A v5 binary serves a v4 root until the ledger's first v5 build, and a read-only ledger may never build. On those roots:
main's writers never remove history (mainhas nohistory_drop).Tests:
FLUREE_PARALLEL_DIR_WALK_MIN_LEAVES=1;MustFirestamps and JSON-LD twins;After that: per-leaf summaries in the branch manifest (perf(index): per-leaf lead-group counts in the branch manifest for instant global COUNT(DISTINCT ?s) / COUNT(DISTINCT ?o) #1322) build on this field.
main, after v5. A query-time fix:main, which never removes history.Other shapes that go through the same walks, not reproduced:
SUM(STRLEN(GROUP_CONCAT(...)))(separators), Cypher whole-graphcount(*)with a property, and the histogram's null group.bplatz commentedon Nov 20, 2026
The v5 half landed on
nextin #2402 (merged 2026-11-19, c63b329). Each v5 leaflet stores the groups of its first and last live rows, and one shared walk (fast_lead_walk) counts from those, not from routing keys. A v5 binary serving a v4 index reads the lead column at a boundary only where a leaflet holds history and the routing groups meet. The fixturetests/fixtures/leaflet-edges-4.2.6covers that. The issue's repro is init_leaflet_live_edges.Open for the
mainfix in the plan above.