Repository navigation
perf: make filtered-DELETE list-meta hydration O(novelty), not O(retractions × novelty) - #1675
Conversation
…not O(retractions × novelty) A WHERE/DELETE update over a predicate carried by ~40k subjects never committed on a novelty-heavy ledger: staging called `range_with_overlay` once per retracted (subject, predicate) and every call paid for the graph's entire overlay. Commit itself took 0.2 s; all the time was in `hydrate_list_index_meta_for_retractions`. - Track whether any indexed row carries an RDF-list position. `IndexRoot.has_list_meta: Option<bool>` lives in two FIR6 extended-flags bits (TRACKED + HAS); a legacy zero byte decodes to `None` so old roots are never mistaken for "no lists". Full rebuilds record it exactly from the resolver; incremental passes flip it to `Some(true)` on the first list row; bulk import leaves it untracked. `Novelty.has_list_meta` is the sticky in-memory counterpart. When both say no lists, hydration is skipped. - Otherwise hydrate from ONE SPOT overlay walk per graph bucketed by the wanted (s,p) pairs plus a `NoOverlay` base seek per group, merged with the same lifecycle rule `range_with_overlay` applies (`fluree_db_core::range::resolve_current_flakes`). - `BinaryCursor::emit_overlay_only` now stops at `overlay_end` instead of walking to the end of the whole overlay after the computed window. - `set_overlay_ops_window`'s duplicate-key debug_assert checks only the window, so debug-build profiles stop being dominated by it. 40.5k-retraction delete, ~243k flakes in novelty: >20 min → 0.9 s (no lists) / 3.1 s (lists present); half in novelty: 8.9 s → 1.3 s.
… by tag
A language-tagged WHERE binding produces a retraction with
`m = { lang, i: None }`, which the list-meta hydration treated as "already
has metadata" and skipped — so `DELETE { ?s p "b"@fr }` on a @list entry
never matched the stored positional fact and silently retracted nothing.
Candidate selection also ignored the tag, so "b"@en and "b"@fr at different
positions could swap.
- Only skip retractions that already carry a list index.
- Match candidates on datatype AND language tag; the copied meta keeps the
tag with the position.
- Test: tagged list across an indexed base and novelty; deleting "b"@fr
removes position 1 and leaves "b"@en.
- The base+novelty test now really performs the retract-then-reassert
lifecycle its description promised, and `resolve_current_flakes` gets
direct unit coverage (newest op wins, retracts drop, list positions are
distinct fact keys).
aaj3f
left a comment
There was a problem hiding this comment.
This is really nicely done, @bplatz, and great outcome performance wins too.
The two notes I wanted to make are are both test-only: the !ledger.novelty.has_list_meta half of the skip guard is pinned by nothing today (dropping it leaves all three new tests green, and the shape it protects — indexed no-list root, @list in novelty — silently keeps the entry), and the lifecycle case re-asserts the identical key so resolve_current_flakes isn't load-bearing there (a stale-base-candidate shape is; both probes are written up in the inline notes).
Separately, the probes surfaced a pre-existing bug your code didn't introduce — a @list retraction on a novelty-only predicate over an indexed ledger commits but never takes effect, reproducible at the merge base — which deserves its own issue.
Adherence to repo commitments:
- Patterns/abstractions: ✔ reuses the extended-flags sticky-bit precedent (
FLAG_EXT_HAD_ANNOTATION_ARENA),for_each_overlay_flake,NoOverlay, and factors the merge rule intofluree-db-core::rangerather than a transact-local copy. - Performance (speed first, memory second): ✔ hot path (filtered-DELETE staging) goes from
groups × noveltyto one overlay walk per graph plus one base seek per group;emit_overlay_onlyand the window assert are strictly less work engine-wide; new per-flake cost inNoveltyis a bool OR. No performance-degradation risk. No bench covers the path (see nit). - Testing:
⚠️ new integration target is real and runs in CI ([[test]]withnative, the default feature); flag round-trip and merge-rule units are good; but two load-bearing behaviors (novelty half of the skip, stale-candidate resolution) survive mutation with every test green — both are cheap to add. - Conventions: ✔ two multi-line commits, self-describing
perf:title,docs/design/index-format.mddocuments the flag bytes, fmt/clippy clean at package scope.
Verified locally at branch HEAD afcaf2bd7: cargo fmt --all -- --check clean; cargo clippy on the six touched crates --all-targets -- -D warnings clean; cargo nextest run on binary-index/core/novelty/transact 1598/1598; the new api target 3/3; grp_transact + grp_misc list/overlay cases 24/24; six mutations and four probes as detailed inline. (The red bench-compare check is setup-mold failing to download mold 2.42.0 — twenty HTTP 504s — not this PR, and that job is advisory.)
Approving so you can merge when ready, but I'd genuinely like the two test additions in before it lands — they're the difference between "the guard is correct" and "the guard stays correct."
| // Nothing to copy when neither the indexed base nor novelty holds a | ||
| // single `@list` position. `Some(false)` is an exact observation by the | ||
| // indexer; `None` (legacy root, bulk import) must fall through. | ||
| if ledger.snapshot.has_list_meta == Some(false) && !ledger.novelty.has_list_meta { |
There was a problem hiding this comment.
optional, but I'd really rather it land here. The && !ledger.novelty.has_list_meta half of the skip is not pinned by any test. I deleted that clause and all three new tests in it_filtered_delete_list_meta.rs stay green — every list-bearing case also has a @list in the indexed base, so the root is Some(true) and the novelty bit never gets to decide. The shape that fails is the ordinary one: an indexed no-list ledger (Some(false)) that then gets a @list in novelty, followed by WHERE { ?s ex:items "b" } DELETE { ?s ex:items "b" }. With the clause gone the retraction leaves hydration with m = None, commits (flake count 1), and the entry is still there afterwards. A probe with exactly that shape (ex:items also present on the base subjects as a plain value, indexed via the background indexer, then ex:nov1 @list ["a","b","c"], then delete "b", expect ["a","c"]) is green at HEAD and red under the mutation — and a reload variant (fresh FlureeBuilder::file on the same directory) confirms the replayed novelty carries the bit, which is the other half of what that test would pin. This is a test-only ask and it's the guard's entire reason for existing, so if you agree it's right I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Addressed in 8e6a885 — novelty_list_over_indexed_no_list_root_still_hydrates.
Built it to your shape: indexed base carrying ex:items as plain values only so the root reads Some(false), then ex:nov1 @list ["a","b","c"] in novelty, then WHERE { ?s ex:items "b" } DELETE { ?s ex:items "b" }. Dropping the clause fails it with exactly the symptom you described — commits, entry survives:
assertion `left == right` failed: novelty list entry retracted at its hydrated position
left: ["a", "b", "c"] right: ["a", "c"]
The reload leg is folded into the same test rather than split out: drop(fluree), fresh FlureeBuilder::file on the same directory, assert the replayed novelty still carries the bit, then run a second delete through the reloaded handle so the bit is load-bearing after a restart and not just present.
| let _ = fluree | ||
| .insert_with_opts( | ||
| ledger, | ||
| &json!({"@context": ctx(), "@id": "ex:base2", "ex:items": {"@list": ["b", "b", "d"]}}), |
There was a problem hiding this comment.
optional. I may be reading the intent wrong, but I don't think the lifecycle case here actually exercises resolve_current_flakes: it retracts d@2 and then re-asserts the identical d@2 key, so whether the stale base row is dropped or not, the first candidate for every deleted value is the same. Replacing stage.rs:1698 with the raw unresolved union leaves all three tests green. The scenario where the rule is load-bearing is a stale base candidate that sorts first: base ["b"] (b@0) indexed → delete "b" → insert @list ["x","b"] (x@0, b@1) → delete "b" again. Without resolution metas["b"] is [b@0 (stale, from base), b@1], the retraction is hydrated to position 0, and b@1 survives — I have that as a probe: green at HEAD, red under the mutation (["x","b"] vs ["x"]). Swapping the lifecycle step in this test to that shape (or adding it as a fourth case) would make the integration test say what the commit message says it says. Minor and non-blocking — but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Addressed in 8e6a885 — stale_base_list_candidate_resolves_before_hydration.
You read the intent right; the existing case does not exercise the rule. Added your shape as a fourth case rather than swapping the lifecycle step, since base-retract-then-reassert is still worth keeping on its own: base ["b"] (b@0) indexed, delete "b", re-assert as ["x","b"] (x@0, b@1), delete "b" again. Replacing resolve_current_flakes with the raw union fails it with your predicted values verbatim — ["x","b"] vs ["x"].
| @@ -1617,17 +1617,20 @@ async fn hydrate_list_index_meta_for_retractions( | |||
| ) -> Result<()> { | |||
There was a problem hiding this comment.
fluree-db-transact/src/stage.rs:1613 — pre-existing, not introduced here — flagging so it isn't lost. While building the first probe I hit a @list retraction that commits but doesn't take effect: receipt.flake_count = 1, the retraction leaves hydration correctly with m = { i: 1 } (I instrumented it), and the list is unchanged afterwards. The trigger is the list's predicate existing only in novelty (no persisted p_id) on an indexed ledger — the same probe with the predicate present in the base passes, and list position doesn't matter (fails at 0, 1, and last). I reproduced it at the merge base a65eb1958 with an equivalent probe, so your code didn't introduce this and hydration isn't the faulty component; it looks like the query/overlay side and ephemeral predicate ids. This is one of the two cases where I think a separate issue is the right home — it's a different mechanism from what this PR touches — so I'll leave it to you whether to file it or hand me the repro to file.
There was a problem hiding this comment.
Opened #1683 for this. Wrote up everything from your note — reproduced at the merge base a65eb1958, trigger is the predicate existing only in novelty on an indexed ledger, position-independent, and hydration ruled out as the faulty component via your instrumented m = { i: 1 } — and pointed the starting points at predicate-id assignment for novelty-only predicates rather than the write path.
If your probe is easy to hand over, please drop it on the issue; I described the shape but yours is the one that actually reproduces.
| let mut out_t: Vec<u32> = Vec::new(); | ||
|
|
||
| while self.overlay_pos < self.overlay_ops.len() { | ||
| while self.overlay_pos < self.overlay_end { |
There was a problem hiding this comment.
praise + a small nit. I looked hard for the way this engine-wide change could drop novelty rows and I don't think it can: set_overlay_ops still passes (0, len), both window callers (binary_range.rs:663, binary_scan.rs:2364) go through overlay_window_for_range, and the merge path already trusted exactly that window via slice_overlay_for_leaf / has_any_overlay before this PR — so the old "scan to the end" tail was a correctness no-op (reverting it to .len() leaves every test green). The nit: overlay_end.saturating_sub(1) here fails all four api tests but leaves fluree-db-binary-index's 378 unit tests green, so the overlay-only window path has no unit-level pin. A tiny cursor test (window narrower than the ops slice, no leaves, assert the emitted count) would be cheap insurance. Minor and non-blocking — but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Addressed in 8e6a885 — overlay_only_emits_exactly_the_window in binary_cursor's own test module.
Empty branch so next_batch goes straight to the overlay-only path, five ops, window [1,3); asserts the row count and that the emitted s_ids are [2,3] — the window, not a prefix of the shared slice. Reverting the bound to .len() fails it (left: 4, right: 2).
Getting the store fixture across from the sibling module made binary_index_store's test mod and its empty_store / temp_cache_dir helpers pub(crate) — three visibility keywords, nothing moved.
Also took your correctness finding into the test's doc comment: my first draft claimed running past the window emits another cursor's rows, which overclaims given you verified the merge path already trusted the window. Rewritten to say what is actually true — it was cost, O(overlay) per novelty-only point lookup, not wrong rows.
| //! before the accumulator dedups. That lookup used to cost a full overlay | ||
| //! walk per retracted (subject, predicate) — quadratic in retractions × | ||
| //! novelty (a 40k-retraction delete over a novelty-heavy ledger never | ||
| //! finished). Now: |
There was a problem hiding this comment.
fluree-db-api/benches/transact_commit.rs — optional. This is more of a question than a suggestion. Nothing benches the filtered-DELETE staging path (transact_commit doesn't exercise WHERE/DELETE), which is how a retractions × novelty shape sat unnoticed until a 40k-subject delete hit it. A transact_filtered_delete bench with a novelty-heavy ledger (plus its regression-budget.json entry so workspace_reconcile stays happy) would guard the win this PR just bought. Happy to talk through whether that belongs here or with the SHACL sibling you mention in the follow-ups.
Commenting here because fluree-db-api/benches/transact_commit.rs is not in this diff.
There was a problem hiding this comment.
Opened #1684. Agreed on the premise — this is exactly why the shape went unnoticed.
Kept it out of this PR because the fixture is real work rather than a bench stub: the regression it needs to catch is superlinear, so it has to be large enough for the two curves to separate, and it wants both branches of the skip guard since their cost profiles differ (0.9 s clean vs 3.1 s with a @list on the same 40.5k-retraction delete). Noted the regression-budget.json entry, and left the question of whether one fixture covers the SHACL validate_staged_nodes sibling open on the issue rather than deciding it here.
| // Bulk import does not observe list positions at root | ||
| // assembly; leave the flag untracked so the write path keeps | ||
| // hydrating until the first full rebuild records it exactly. | ||
| has_list_meta: None, |
There was a problem hiding this comment.
question, not a suggestion. Bulk-imported roots stay None until a full rebuild, which means the skip never applies on exactly the ledgers big enough to care. import_sink.rs:467 already has the list index in hand at that point — is a sticky bit there cheap, or does the parallel chunking make the aggregation more than a one-liner? If the latter, leaving it named in the follow-ups is fine by me.
There was a problem hiding this comment.
Opened #1685. Your instinct is right that this matters — the skip missing exactly the ledgers big enough to care is the wrong way round.
To answer the question: not a one-liner, but not far off. write_record is per chunk, so a bool there has to ride both SpoolResult and BufferedSpoolResult and get OR-folded at root assembly. The cleaner version, written up on the issue, puts it on the shared SpoolConfig alongside numbig_pool — plain bool on SpoolContext, OR'd only on the i != LIST_INDEX_NONE branch, one relaxed store at finish, read at root assembly. That parallels how has_annotations is derived at the same site from a merged global structure.
Keeping it out of this PR mainly because it lands in the parallel import path with none of this PR's tests covering it, and a wrongly-false root there would silently drop list retractions — so it wants its own tests, which the issue names.
…green Review found three load-bearing behaviors in this branch that no test constrained. Each addition below fails under the corresponding mutation and passes at HEAD. `novelty_list_over_indexed_no_list_root_still_hydrates` pins the `!ledger.novelty.has_list_meta` half of the hydration skip. Every existing list case puts a `@list` in the indexed base, so the root reads `Some(true)` and the novelty bit never decides anything. The shape that needs it is the ordinary one: an indexed no-list root (`Some(false)`) that then takes a `@list` in novelty. Dropping the clause skips hydration, the retraction commits with `m = None`, and the entry survives. The reload leg covers the other half — novelty replayed from the commit chain must carry the bit, and a second delete through the reloaded handle makes it load-bearing rather than merely present. `stale_base_list_candidate_resolves_before_hydration` pins `resolve_current_flakes`. The existing lifecycle case retracts `d@2` and re-asserts the identical key, so the first candidate is the same whether or not the stale base row is dropped. The rule only bites when the stale candidate sorts first: base `["b"]` (b@0) indexed, delete `"b"`, re-assert as `["x", "b"]` (x@0, b@1), delete `"b"` again. Unresolved, hydration copies b@0, the retraction lands on position 0, and b@1 survives as `["x", "b"]`. `overlay_only_emits_exactly_the_window` pins the `overlay_end` bound in `emit_overlay_only`. The change is engine-wide but was constrained only by api-level tests — narrowing the bound by one left all 378 binary-index unit tests green. Empty branch so `next_batch` takes the overlay-only path; asserts the emitted `s_id`s are the window, not a prefix of the shared slice. Reaching the store fixture from the sibling module makes `binary_index_store`'s test mod and two helpers `pub(crate)`.
Problem
A
WHERE { ?s p ?o } DELETE { ?s p ?o }update over a predicate carried by ~40k subjects never committed on a novelty-heavy ledger. Staging calledrange_with_overlayonce per retracted (subject, predicate) to copy@listpositions onto retractions, and every call paid for the graph's entire overlay:retractions × novelty. Commit itself took 0.2 s; all the time was inhydrate_list_index_meta_for_retractions. Stack-sampled three distinct per-call taxes:collect_overlay_onlyfull walk + sort +remove_stale_flakesBinaryCursor::emit_overlay_onlylooped tooverlay_ops.len()instead of the computedoverlay_endset_overlay_ops_window's duplicate-keydebug_assert!scanned the whole ops sliceChanges
IndexRoot.has_list_meta: Option<bool>— two bits in the FIR6 extended-flags byte (LIST_META_TRACKED+HAS_LIST_META), no format bump. A legacy zero byte decodes toNone(untracked), never "no lists". Full rebuilds record it exactly from the resolver; incremental passes flip toSome(true)on the first list row; bulk import leaves itNone.Novelty.has_list_metais the sticky in-memory twin. When both say no lists, hydration is skipped entirely.NoOverlaybase seek per group, merged with the same lifecycle rulerange_with_overlayapplies (newfluree_db_core::range::resolve_current_flakes).emit_overlay_onlystops atoverlay_end(engine-wide: every overlay-only point lookup on a novelty-only subject was scanning to the end of the overlay).m = { lang, i: None }, which was treated as "already has meta" and skipped —DELETE { ?s p "b"@fr }on a list entry silently retracted nothing. Candidates now require a matching tag as well as datatype.Numbers
40.5k-retraction delete, ~243k flakes (unoptimized test build, debug assertions off):
@listvalue present (O(N) path)Tests
fluree-db-api/tests/it_filtered_delete_list_meta.rs: flag states through a real index build; one-entry-per-binding list retraction across base-indexed, novelty-only, and retract-then-reassert lists; tagged-list deletion by language (fails onmain).resolve_current_flakesunit tests.--all-features --all-targets -D warningsclean.Docs:
docs/design/index-format.mddocuments the header flag bytes.Follow-ups (not in this PR)
spawn_blockingso a caller'stokio::time::timeoutcan actually fire on a slow staging.validate_staged_nodeshas the same per-subject-range shape (and theStagedLedgeroverlay has nocontent_version, so no translation LRU).mthrough from the WHERE match so hydration disappears as a concept.