Repository navigation
perf(query): seek bound decimals in TI3 object joins - #1826
Conversation
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is a good catch and good fix. After looking at it for a second, I think there are maybe 2 items worth addressing and highlighting here: (1) the proof over (store, g_id, p_id) seems recomputed on every open() when it could be hoisted to an operator OnceLock the way we do with FLUREE_DISABLE_QUERY_FAST_PATHS etc and (2) we tend to have a pattern where a fast path attempt failure declines to the correct slow path, but in this PR a failure in predicate_is_decimal_only returns QueryError::Internal. Full review below
Nice find — the one-token index fix and the arena-handle seek together turn a per-binding predicate walk into a point lookup, and the proof for the untyped case (arena has no bigint, every leaf for the predicate is NUM_BIG_OVERFLOW, no novelty, current state) is conservative in all the places I tried to get around it: scale aliases, negative zero, novelty-only values, a retract-then-reindex, mixed inline types, as_of. I reproduced the direction and magnitude locally (0.58 ms vs 81.5 ms, and 1.79 ms vs 6.78 s with 500 rejected bindings, same binary, FLUREE_DISABLE_DECIMAL_SEEKS as the control).
The one thing that has to change before merge is mechanical: 100000 at it_query_ti3.rs:30 trips the workspace-denied unreadable_literal lint under --all-targets, so the clippy job goes red the moment this is retargeted to main (the libraries are clean, which is what the body checked; the test target isn't).
Everything else is hoisting/degradation hygiene rather than correctness: the proof and both env reads run once per driving row and could be memoized, a leaf-dir read error should decline the proof rather than fail the query, and the current-state guard on the point lookup has no test behind it. Also worth saying in the commit body that the POST-for-bound-predicate change applies to every ?s <p> <const> pattern, not only decimals.
Adherence to repo commitments:
- Patterns/abstractions: ✔ extends the existing
open()encode path andvalue_to_otype_okeyfamily; store accessors added onBinaryIndexStore; correctness-preserving fallback honoured (NotFound→ overlay-only,Unsupported→ un-narrowed).⚠️ oneInternalerror where a decline is the pattern. - Performance (speed first, memory second): ✔ hot path, 70×–3,800× on the target shape;
⚠️ per-row proof + env reads could be hoisted (noise-level on measured shapes). No performance-degradation risk. - Testing: ✔ three integration tests + two unit tests + arena reload test, all wired and seen by name; the novelty gate mutation goes red.
⚠️ the current-state gate on the point lookup has no teeth. - Conventions: ✖ clippy
-D warnings --all-targetsfails onit_query_ti3.rs:30(unreadable_literal, a workspace-denied lint) —100_000fixes it;cargo fmt --checkclean.⚠️ subject-only commit body. No CI ran on this PR (stacked two deep) — it needs a retarget once #1825 lands.
Verified locally at branch HEAD 6bf720eb9: cargo fmt --all -- --check clean; clippy --all-targets -D warnings on fluree-db-query/fluree-db-api/fluree-db-binary-index fails (one unreadable_literal in the new test); grp_query_sparql it_query_ti3 3 passed; fluree-db-binary-index --lib numbig 12 passed; fluree-db-query --lib binary_scan 19 passed; gate mutations: novelty veto caught, current-state guard not; adversarial novelty/zero/scale probe identical with seeks on and off; dev-fast A/B as above; merge-tree onto origin/main clean.
Requesting changes only for the lint — add the underscore and I'll flip this to approve; maybe worth considering the hoist and the decline-not-error in the same push. It'll also need a base retarget after #1825 (it applies cleanly to main on its own if you'd rather reorder).
Notes with no line in this diff to anchor to:
Commit 6bf720eb9 — ⚪ nit. Subject-only commit message; the PR body has the mechanism, admission rules, and the measurement table, and none of it made it into the commit. The repo's habit is multi-line bodies (these feed archaeology, not just release notes) — a paste of the body's first three paragraphs would do.
| for i in 0..probe { | ||
| graph.push( | ||
| // Keep p3's average fanout above p2's, matching TI3's join order. | ||
| json!({"@id":format!("ex:u{i}"), "ex:p3":decimal(if i < 2 {230+i} else {100000+i % (probe / 20).max(1)})}), |
There was a problem hiding this comment.
fluree-db-api/tests/it_query_ti3.rs:30 — 🔴 blocking (CI gate). 100000 trips the workspace-denied clippy::unreadable_literal, so the repo's clippy gate fails on this branch. CI's clippy job is cargo clippy --all --all-features --all-targets -- -D warnings on top of the 23 [workspace.lints.clippy] denials, and --all-targets compiles this test file. Locally: cargo clippy -p fluree-db-query -p fluree-db-api -p fluree-db-binary-index --all-targets --no-deps -- -D warnings → error: long literal lacking separators … it_query_ti3.rs:30:85 … help: consider: 100_000 → could not compile fluree-db-api (test "grp_query_sparql"). The body's "Clippy for the three affected libraries with -D warnings" is why it was missed — the libraries are clean; the test target isn't, and no CI ran on this PR to say so. Fix is 100_000 (the 1_000 two lines up already has the underscore). Just be sure to get this in before it merges, since the first CI run after a retarget to main will be red on it.
| && !self.mode.is_history() | ||
| && ctx.to_t >= store_ref.max_t() | ||
| && !crate::fast_path_common::overlay_has_novelty(ctx) | ||
| && std::env::var_os("FLUREE_DISABLE_DECIMAL_SEEKS").is_none() |
There was a problem hiding this comment.
fluree-db-query/src/binary_scan.rs:2138 — 🔵 optional. Two std::env::var_os("FLUREE_DISABLE_DECIMAL_SEEKS") reads (:2138, :2208) and the whole predicate_is_decimal_only walk (:2141) sit inside open(), which a nested-loop join calls once per driving row — so on the TI3 shape that's 508 env-lock-and-allocate pairs and 508 leaf walks for a fact that is constant per (store, g_id, p_id). The sibling switch is hoisted (operator_tree.rs:2268, OnceLock). I don't think it's measurable on the shapes here (the proof exits at the first leaf when it fails, and when it succeeds the seek it enables dwarfs it — my quiet first_join A/B was 1.847/1.865 ms with seeks vs 1.859/1.832 ms without — parity), but it's per-row work the rest of the file goes out of its way to avoid. Minimally a static ENV: OnceLock<bool>; more fully, memoize the proof on the operator (Option<bool> keyed by nothing, since g_id/p_id don't change across opens) or on the store per (g_id, p_id). Minor and non-blocking — but if you agree it's right, I'd rather see it in this PR than lost in the backlog.
There was a problem hiding this comment.
Addressed in b2cdbc5
Memoized on the store rather than the operator: the nested-loop join builds a fresh scan per driving row (make_right_scan), so an operator field would reset every time. Conclusive proofs are cached per (g_id, p_id); an inconclusive one isn't. The env read is now a OnceLock.
| } | ||
| let dir = store | ||
| .open_leaf_dir(&leaf.leaf_cid) | ||
| .map_err(|e| QueryError::Internal(format!("leaf dir open: {e}")))?; |
There was a problem hiding this comment.
fluree-db-query/src/binary_scan.rs:3923 — 🔵 optional. A boundary-leaf directory read failure becomes QueryError::Internal("leaf dir open: …") and fails the query, whereas everything else in this proof declines (Ok(false)) and lets the general matcher run — and that's the fallback contract the fast paths in this file follow (a translation that can't be established makes the fast path unavailable, never the query wrong or dead). A remote CAS hiccup on one leaf dir shouldn't turn a slow-but-correct join into a 500. map_err(..)? → else { return Ok(false) } is the whole change. Fold-in-now if you agree.
There was a problem hiding this comment.
Addressed in b2cdbc5
The failed read declines and is not memoized, so it is retried on a later open.
| if let FlakeValue::Decimal(value) = bound_o { | ||
| if *dt_sid == Sid::new(namespaces::XSD, xsd_names::DECIMAL) | ||
| && !self.mode.is_history() | ||
| && ctx.to_t >= store_ref.max_t() |
There was a problem hiding this comment.
fluree-db-query/src/binary_scan.rs:2207 — 🔵 optional / testing. The current-state guard on the point lookup (ctx.to_t >= store_ref.max_t()) has no test teeth: I removed it and every test passed, including the as_of(original_t) section of decimal_seeks_preserve_scales_mixed_types_and_novelty, because the arena keeps obsolete handles so a historical value is never reported absent today. If arena entries are ever retired at an index publish (I looked — #1821 retires dictionary entries, not arenas, so this is latent, not live), that guard is the only thing between an as_of read and a false empty. A probe that reads at a t older than a reindex that dropped the value would pin it; short of that, a comment on the gate saying why it's there would do.
There was a problem hiding this comment.
Addressed in b2cdbc5
Tried to give it teeth first: with both max_t guards removed, a decimal asserted, retracted, reindexed, then read as_of the assert time still returns the row (typed and untyped), since the arena keeps retracted values. Any test would pass without the guard, so it's a comment on the gate instead.
| if index_hint.is_none() | ||
| && object_bounds.is_none() | ||
| && !s_bound | ||
| && !p_bound |
There was a problem hiding this comment.
fluree-db-query/src/binary_scan.rs:705 — ⚪ info. Worth being explicit in the commit body that && !p_bound changes the default index for every ?s <p> <const> pattern (including ?s a <Type>) from OPST to POST, not just decimals. Both are a point range once the object encodes, and my type-scan-heavy Q4 A/B against #1825's head was 81.9/79.1 ms vs 78.4/77.8 ms at identical fuel (+1.6–4.5%, two rounds — can't be separated from noise), but no bench pins it and the nightly bench.yml is the only thing that would notice.
| // novelty and historical reads retain the general numeric matcher. | ||
| if dt_sid.is_none() | ||
| && inferred_dt_sid.is_none() | ||
| && lang.is_none() |
There was a problem hiding this comment.
fluree-db-query/src/binary_scan.rs:2132 — praise. The novelty veto on the untyped proof is load-bearing and tested: removing it makes decimal_seeks_preserve_scales_mixed_types_and_novelty fail (a novelty integer 22 would be filtered out by an o_type seek). That's the one gate in this PR I expected to be decorative; it isn't.
| Ok(true) | ||
| } | ||
|
|
||
| fn decimal_object_key( |
There was a problem hiding this comment.
fluree-db-query/src/binary_scan.rs:3936 — praise. Distinguishing "zero handles → NotFound → overlay-only" from "several handles → Unsupported → un-narrowed" is exactly right for legacy scale-alias arenas; my probe with a novelty-only 999.0 under the untyped path and -0.0 against a stored 0.0 returns the same rows with seeks on and off.
Joins build a scan per driving row, so the untyped decimal-only proof ran once per row for a fact fixed per (store, graph, predicate). Memoize conclusive proofs on the store; an unreadable leaf directory now declines the proof (general matcher) instead of failing the query, and is not cached. FLUREE_DISABLE_DECIMAL_SEEKS is read once per process and is listed with the other kill switches. Context for the TI3 change this completes: a bound predicate with a bound object now keeps the predicate-leading POST index instead of switching to OPST. This applies to every `?s <p> <const>` pattern, including `?s a <Type>`, not only decimals. Both are point ranges once the object encodes; POST additionally stays narrow when it cannot (a decimal without a unique arena handle). The current-state guard on the decimal point lookup is documented rather than tested: the arena keeps retracted values, so an as_of read cannot observe its removal today.
TI3-style joins bind a decimal object while leaving the subject unbound. The scan could override its predicate-leading POST index with OPST, then fail to encode the decimal arena handle and scan broadly for every incoming binding. Keep the predicate bound and resolve eligible decimal bindings to point lookups in the graph/predicate numeric arena; a proven absent value skips persisted rows and checks novelty.
Stacked on #1825, targeting
fix/bi-q4-projected-ratioso the diff contains only the TI3 work and the branch retains the Q4 improvement for combined testing.The untyped arena proof requires current indexed data without novelty and verifies both the stored object types and decimal-only arena contents. It uses branch extrema and at most two boundary-directory reads. Mixed numeric representations, historical reads, and ambiguous legacy scale aliases retain the general matcher. Explicit decimal constraints can still check novelty. Subject-bound lookups avoid the extra metadata proof. The existing join plan and cost thresholds are preserved.
Local synthetic measurements (optimized
dev-fastbuild, warmup plus five measured executions; eight result rows preserved):The disabled/enabled comparison isolates decimal seeks: both sides already retain the predicate-leading scan bound. These fixtures do not establish that the original full Wikidata timeout is resolved; a matched run on the retained database remains necessary. The ignored
it_query_ti3::ti3_local_scalingtest reproduces the measurements withTI3_PROBE,TI3_NOISE,TI3_MISSES, andFLUREE_DISABLE_DECIMAL_SEEKS.Validation: 2,981 passing tests across query/binary-index unit suites and API query, SPARQL, history, reasoning, numeric identity, VALUES, and scan-narrowing suites; final focused tests and the larger scaling probe also passed. Regression coverage checks multiplicity, graph/dataset execution, scale normalization, mixed integer/double/overflow-integer values, novelty, retractions, historical reads, arena reloads, and a fuel bound against repeated predicate scans. Clippy for the three affected libraries with
-D warnings, formatting, and whitespace checks passed.Partially addresses #1328: decimal scan lookups are covered; overflow-integer and other batched prefilter callers remain outside this change.
Follow-up: #1321 — preserve precise NumBig datatype statistics, with indexing-throughput and memory benchmarks. That product change is separate from this PR.