Repository navigation
perf: eliminate per-flake staging cost in bulk upserts - #1549
Conversation
… novelty generate_upsert_deletions issued one bound-subject point query per (subject, predicate) tuple. For subjects not yet in the persisted subject dictionary (bulk upserts of new entities), BinaryScanOperator cannot resolve an s_id and falls back to a full PSOT predicate-partition walk with per-row subject-IRI decoding — ~2-8 ms per flake, turning a 6,600 flake upsert into 13-70 s of staging that produces zero retractions. Group predicates by subject and resolve existence once per subject: - persisted presence via the subject reverse dictionary (authoritative under canonical namespace encoding), - novelty presence via one Sid-space overlay walk per referenced graph. Subjects absent from both are skipped outright; everything else keeps the existing per-predicate query path (which is fast once s_id resolves). Repro ledger (451k flakes, 600 new subjects / 6,600 flakes): deletion phase 13.3 s -> 0.9 ms; staging total 13.3 s -> 3.5 ms.
Every BinaryScanOperator::open rebuilt the full predicate table — one dictionary resolve + namespace encode per predicate in the ledger — and the binary_range materialization loops re-resolved the predicate per emitted row. Both are O(predicate count) fixed costs on point lookups that scale badly for ledgers with wide schemas. Build the table once per store instance (OnceLock; stores are immutable once shared behind Arc) and share it as Arc<[Sid]>. Novelty-only predicates keep their ephemeral p_ids in a per-operator overlay map instead of resizing the shared table.
aaj3f
left a comment
There was a problem hiding this comment.
This is really nice to have! And nice to remove wasted work rather than needing a new fast path.
The remaining items are optional: the novelty walk is eager where it could be lazy, named-graph-plus-indexed has no test despite being the most-restructured branch, and no bench covers upsert staging at all.
Adherence to repo commitments:
- Patterns/abstractions: ✔ Generalizes an existing per-open computation to a per-store one and honors the engine's fail-open convention on lookup errors; no parallel mechanism introduced.
- Performance (speed first, memory second): ✔ with one noted window. Large net win on the target shape plus an O(predicate-count) fixed cost removed from every scan
open(); the one regression window is a small upsert against large novelty, non-blocking under shipped defaults, cheap to close by making the walk lazy. No bench covers this path either way. - Testing: ✔ New integration test is wired into
grp_transactand runs, and it goes red under mutation of both halves of the pre-check — not merely present. Gap: no named-graph × indexed case. - Conventions: ✔ Two focused
perf(...)-style commits with substantive multi-line bodies carrying the measurements; no AI-attribution trailers;cargo fmt --all -- --checkclean andcargo clippy --all-targetssilent on all three changed crates.
Recommend merge. Note that PR #1553 is stacked on this branch, so this one must land first.
| }) | ||
| .collect(); | ||
|
|
||
| // Novelty presence: one overlay walk per referenced graph, collecting which |
There was a problem hiding this comment.
Optional (performance). The novelty-presence walk is unconditional and eager, so an upsert whose subjects all resolve in the persisted dictionary now pays a full novelty walk it previously did not.
Mechanism: the walk is built before the subject loop for every upsert with a binary store, and the skip test at :2743-2748 consults the novelty set first (!novelty_present…is_some_and(…) && !subject_in_base(subject)). So the O(novelty-in-graph) cost is paid even when the dictionary would have answered every subject on its own.
Concrete window: a single-subject upsert against an already-persisted subject on a ledger whose novelty has grown. Before this PR that was one ~13 µs point probe; after, it is that probe plus a walk of every novelty flake in the graph, each hashed into a HashSet<&Sid> probe. Under the shipped defaults this is free — DEFAULT_REINDEX_MIN_BYTES = 100 (server_defaults.rs:31) means novelty is trimmed after essentially every commit — but the bound the comment appeals to is reindex_max_bytes, which is 20% of system RAM floored at 64 MB (server_defaults.rs:48-62). That is the ceiling that applies when indexing lags or is manual, and at that scale the walk is tens of milliseconds to seconds.
Suggested fix: make the set lazy rather than eager — check subject_in_base first (a point lookup) and build the per-graph novelty set only on the first subject that misses the dictionary. Bulk-new-subject upserts still do exactly one walk per graph, so the headline win is untouched, while all-persisted upserts do none. Worth also softening the comment at :2662-2664: "bounded by reindex backpressure" is accurate about the mechanism but reads as "small," and the actual bound is 20% of RAM.
There was a problem hiding this comment.
Addressed in bb2a042 — the skip now consults the base dictionary first and builds the per-graph novelty set only on the first subject that misses it, so all-persisted upserts pay no walk while bulk new-subject upserts keep exactly one walk per graph. Comment reworded to name reindex_max_bytes as the real ceiling.
|
|
||
| /// One upsert touching a persisted subject, a novelty-only subject, and a | ||
| /// brand-new subject must replace values for the first two and plainly insert | ||
| /// the third — before and after the next index build. |
There was a problem hiding this comment.
Optional (coverage). The new test covers only the default graph, but named-graph handling is the part of generate_upsert_deletions the diff restructured most: the graph-id translation was hoisted out of the loop into ledger_g_for_txn_g (stage.rs:2636-2656), a new early continue was added for a named graph absent from the ledger registry (:2737-2740), and effective_g_id is now derived before the skip rather than after it. The skip keys the novelty set per ledger graph while subject_in_base is graph-agnostic.
The existing named-graph upsert test does not cover this: it_named_graph_isolation.rs:370 pre_index_upsert_isolates_named_graphs is explicitly a genesis-time test ("This runs at genesis (no binary index)", :416), so binary_store.is_some() is false and the new skip never engages. I could not find any post-index named-graph upsert test.
Suggested: add a second case to this file that indexes, then upserts the same subject IRI into two named graphs, asserting that each graph's values are replaced independently and neither leaks into the other. The graph-agnostic subject_in_base makes the skip conservative here rather than wrong, so I expect this to pass — which is exactly why it is cheap to pin.
There was a problem hiding this comment.
Addressed in b4b4020 — added upsert_indexed_named_graphs_replace_independently: post-index upsert of the same subject IRI into two named graphs (replaced independently, no leakage), plus a brand-new subject and a never-registered graph in the same transaction, asserted both from novelty and after the next index build.
| ledger: &LedgerState, | ||
| txn: &Txn, | ||
| new_t: i64, | ||
| graph_sids: &std::collections::HashMap<u16, Sid>, |
There was a problem hiding this comment.
Optional (perf evidence). A hot-path change with no bench coverage. No bench in fluree-db-api/benches or fluree-db-query/benches exercises upsert at all — transact_commit.rs benches insert_turtle_with_opts, and regression-budget.json has no staging entry — so the nightly regression gate cannot catch a future regression in this function, and the PR's own 13.3 s → 0.9 ms number has no standing home. An upsert-shaped variant alongside transact_commit (new subjects and persisted subjects as separate inputs, since they exercise different paths) would give the win a durable guard. Commenting here because fluree-db-api/benches/ has no file in this diff.
There was a problem hiding this comment.
Agreed but deferring to a follow-up PR — an upsert-shaped bench beside transact_commit with new-subject and persisted-subject variants plus a regression-budget entry is a bigger lift, and #1553 is stacked on this branch. The two variants will also guard both sides of the now-lazy pre-check.
| self.dicts.predicates.resolve(p_id) | ||
| } | ||
|
|
||
| /// Shared persisted `p_id → Sid` table, built once per store on first use. |
There was a problem hiding this comment.
Praise. The OnceLock staleness argument in the doc comment is correct and I verified it rather than taking it: the store has exactly two &mut self methods (set_ns_split_mode, augment_namespace_codes) and both are reachable only from load-time sites holding the store by owned &mut before Arc::new; the post-commit refresh_index path deliberately does not re-sync (ledger/loading.rs:31-38). Stating the invariant in the comment where a future reader will need it is the right call for a cache whose failure mode would be silent.
| // Retraction flakes carry the graph Sid (flake.g), looked up by the | ||
| // txn-local g_id. Resolved before any skip so broken graph delta/sid | ||
| // wiring still surfaces as an error. | ||
| let graph_sid: Option<Sid> = match graph_id { |
There was a problem hiding this comment.
Praise. Resolving graph_sid before the skip, with a comment saying why, keeps broken graph delta/sid wiring loud instead of letting a new fast path swallow it. That is the easy thing to get wrong when hoisting work out of a loop.
The upsert-deletion subject pre-check walked novelty eagerly, once per referenced graph, before the subject loop — so an upsert whose subjects all resolve in the persisted subject dictionary paid a full per-graph novelty walk it never needed. Under shipped defaults novelty is trimmed after nearly every commit, but when indexing lags the walk is bounded by reindex_max_bytes (up to 20% of system RAM), turning a ~13us point probe into tens of milliseconds or worse for a small upsert. Reorder the skip to consult the base dictionary first and build the per-graph novelty set only on the first subject that misses it. Bulk new-subject upserts still do exactly one walk per graph (unchanged headline cost); all-persisted upserts now do none. Also reword the comment that described novelty as small — the actual ceiling is reindex_max_bytes, not the reindex trigger threshold.
Named-graph handling is the most-restructured part of the pre-check diff (txn-graph -> ledger-graph translation hoisted out of the subject loop, early continue for graphs absent from the registry, effective g_id derived before the skip), but the only named-graph upsert test runs at genesis where no binary store exists and the skip never engages. Add a post-index case: the same subject IRI upserted into two named graphs in one transaction is replaced independently with no cross-graph leakage, alongside a brand-new subject (skip path) and a graph the ledger registry has never seen (nothing-to-retract path) — asserted both from novelty and again after the next index build. The graph-agnostic subject_in_base makes the skip conservative here, and this pins that it stays correct.
|
@aaj3f Thanks for the careful review — all three optional items are handled:
|
Nothing in the suite measured the upsert wave that retracts the current values of every (graph, subject, predicate) an upsert names: insert_formats upserts only new subjects and transact_commit measures inserts. Eight scenarios: default and named graph, each unindexed and indexed; language tags plus @list; 16 predicates per subject; an indexed base under 4x unrelated novelty; and new subjects as the fluree#1549 control. Each scenario asserts its lane in setup and its retract/assert counts after every measured upsert, so a drifting fixture fails instead of timing the wrong path.
The upsert wave queried each (graph, subject, predicate) with execute_pattern and rebuilt every retraction from the ?o binding with m: None. A language-tagged value was retracted without its tag and a list entry without its position, so neither retraction matched anything: the old values stayed, and an identical refresh of such values committed two flakes every time (fluree#1976). A named graph without a range provider also walked the graph's whole novelty once per slot. The wave now asks CurrentFacts for each slot's current facts and retracts them as stored. The fluree#1549 absence pre-check and its counters are unchanged; pattern_queries now counts slot reads. binding_to_flake_object, query_novelty_for_graph and the per-group materializer are gone. The replacement unit is one function, upsert_replacement_slots: every current value of each (graph, subject, predicate) the payload names, all languages and list positions together. Blank subjects join the wave when the skolem scope is deterministic (the upsert payload scope), so an identical re-upsert of a document with blank nodes is now a no-op too.
Problem
Bulk JSON-LD upserts staged at ~8 ms/flake (STAGING-PERF-BUG report: 35–70 s per ~6k-flake transaction against a 5 MB / 451k-flake ledger, with essentially all time inside
stage()andretractions ≈ 0).Root cause
generate_upsert_deletionsissues one bound-subject point query per (subject, predicate) tuple to find existing values to retract. For subjects not yet in the persisted subject dictionary — the dominant case when bulk-upserting new entities —BinaryScanOperatorcannot resolve ans_id, setsunresolved_bound_subject_iri, and degrades to a full PSOT predicate-partition scan with per-row subject-IRI decoding. On the repro ledger that's ~56k row-decodes per subject forrdf:typeand the multi-valuedblockingKeyalone; a 600-subject upsert spent 13.27 s of 13.29 s staging in this loop, producing zero retractions.Resolved subjects were never the problem: the same 3,000-tuple loop over existing subjects runs in ~40 ms (~13 µs per point probe).
Fix
Commit 1 — subject-existence pre-check in
generate_upsert_deletions: group predicates by subject and resolve existence once per subject:find_subject_id_by_parts+ full-IRIfind_subject_id), authoritative under the canonical namespace-encoding invariants;Subjects present in neither cannot have values to retract and skip their per-predicate queries entirely. Everything else keeps the existing query path.
Commit 2 — cache the persisted
p_id → Sidtable onBinaryIndexStore: every scanopen()rebuilt the full predicate table (one dict resolve + namespace encode per predicate in the ledger), and thebinary_rangematerialization loops re-resolved the predicate per emitted row. The table is now built once per store instance (OnceLock<Arc<[Sid]>>; stores are immutable once shared behindArc) and shared; novelty-only predicates keep their ephemeral p_ids in a per-operator overlay map. Removes an O(predicate-count) fixed cost per scan open that becomes significant for wide-schema ledgers.Results (repro clone, 600 subjects / 6,600 flakes)
Verified on the repro ledger that all three subject classes retract correctly: persisted subjects (values replaced, no duplicates), novelty-only subjects, and new subjects (skipped,
skipped_subjectsdebug field added for prod diagnosis).Tests
New
it_transact_upsert_indexed.rspins replace-semantics across persisted + novelty-only + new subjects in a single upsert against a file-backed indexed ledger, re-checked after the next index build. Existing transact/query/index/history integration groups and unit tests pass.