Skip to content

COUNT(DISTINCT ?s) / COUNT(DISTINCT ?o) fast paths undercount when retracted history sits at a leaflet seam #2394

Open

Description

@bplatz

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_inner and count_lead_groups_for_predicate (fluree-db-query/src/fast_count.rs) add up each leaflet's lead_group_count. They subtract one where a leaflet's first lead equals the previous leaflet's last lead (:1727 and :1756, :1895 and :1924 on main).
  • lead_group_count counts live rows only (compute_lead_group_count, fluree-db-binary-index/src/format/leaflet.rs:137).
  • Since 25e0721, a leaflet's first_key and last_key are widened over its retracted history (flush_leaflet in fluree-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 its first_key to 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_key the 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 in compute_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_len can'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

  1. added
    bug
    P1
    area:query
    on Nov 14, 2026
  2. bplatz commented on Nov 14, 2026

    @bplatz
    ContributorAuthor

    Plan (decided 2026-11-14, revised the same day after review)

    This is fixed in v5 first. A separate fix for main follows.

    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.

    • The capability is declared by the format (a capability flag or a version), so a reader can tell "absent, legacy file" apart from "empty".
    • Every writer upholds it, including maintenance writers.

    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.

      Order Group Two edges
      SPOT subject 16 B
      OPST object 20 B
      PSOT predicate + subject 24 B
      POST predicate + object 28 B

      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 on next an 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_count differently. The boundary rule lives in the shared walk once: add the counts, and subtract one when left.last_live == right.first_live.

      • Declines have to propagate. Today count_distinct_lead_groups turns None into 0 (fast_count.rs:1224), so a decline must reach the caller as a decline, not as 0.
    • Related fixes:

    • 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:

      • At boundaries where the routing leads match, read the live lead from the lead column.
      • Skipping that read for a leaflet with an empty history segment is sound only because main's writers never remove history (main has no history_drop).
      • The skip means not decoding the leaflet's edges. Its live rows are still counted.
    • Tests:

      • each stored summary matches its own decoded live rows;
      • combining summaries matches an independent row-level answer;
      • full and incremental builds give equivalent answers. Their physical summaries can differ, because their leaflet boundaries differ.
      • splits, history removal, erasure and empty leaflets preserve all of this;
      • a group that genuinely spans a boundary whose next leaflet is also stretched;
      • chunk seams forced with FLUREE_PARALLEL_DIR_WALK_MIN_LEAVES=1;
      • MustFire stamps and JSON-LD twins;
      • the patch above, kept as regression tests.
    • 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.

      • A query restricted to one predicate sums whole leaves only where the leaf's entire live contribution belongs to that predicate. Boundary leaves that hold several predicates descend into their leaflet summaries.
      • Leaf summaries need the predicate scope in their boundary groups.
      • Measure root growth first.

    main, after v5. A query-time fix:

    • At a boundary where the routing leads match, read the live lead of each side before subtracting.
    • Skip that read for leaflets with an empty history segment. That is sound on main, which never removes history.
    • Measure the cold cost before merging.
    • Caching live edges is optional. Its case is repeated-query latency weighed against memory, since it doesn't help a truly cold query.

    Other shapes that go through the same walks, not reproduced: SUM(STRLEN(GROUP_CONCAT(...))) (separators), Cypher whole-graph count(*) with a property, and the histogram's null group.

  3. added this to the 5.0.0 milestone on Nov 14, 2026
  4. bplatz commented on Nov 20, 2026

    @bplatz
    ContributorAuthor

    The v5 half landed on next in #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 fixture tests/fixtures/leaflet-edges-4.2.6 covers that. The issue's repro is in it_leaflet_live_edges.

    Open for the main fix in the plan above.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1area:querybug

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions