Skip to content

perf: eliminate per-flake staging cost in bulk upserts - #1549

Merged
bplatz merged 4 commits into
mainfrom
fix/upsert-staging-new-subject-scan
Jul 30, 2026
Merged

bplatz merged 4 commits into
mainfrom
fix/upsert-staging-new-subject-scan

Conversation

@bplatz

@bplatz bplatz commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

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() and retractions ≈ 0).

Root cause

generate_upsert_deletions issues 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 — BinaryScanOperator cannot resolve an s_id, sets unresolved_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 for rdf:type and the multi-valued blockingKey alone; 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:

  • persisted presence via the subject reverse dictionary (find_subject_id_by_parts + full-IRI find_subject_id), authoritative under the canonical namespace-encoding invariants;
  • novelty presence via one Sid-space overlay walk per referenced graph (no dictionary translation, works even when dict-novelty is uninitialized).

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 → Sid table on BinaryIndexStore: every scan open() rebuilt the full predicate table (one dict resolve + namespace encode per predicate in the ledger), and the binary_range materialization 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 behind Arc) 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)

scenario deletion phase staging total
new subjects, before 13,270 ms 13,292 ms
new subjects, after 0.9 ms 3.5 ms
existing subjects (values changed) ~40 ms ~43 ms

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_subjects debug field added for prod diagnosis).

Tests

New it_transact_upsert_indexed.rs pins 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.

bplatz added 2 commits July 28, 2026 21:48
… 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 aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_transact and 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 -- --check clean and cargo clippy --all-targets silent on all three changed crates.

Recommend merge. Note that PR #1553 is stacked on this branch, so this one must land first.

Comment thread fluree-db-transact/src/stage.rs Outdated
})
.collect();

// Novelty presence: one overlay walk per referenced graph, collecting which

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

bplatz added 2 commits July 29, 2026 22:36
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.
@bplatz

bplatz commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f Thanks for the careful review — all three optional items are handled:

  • Lazy novelty walk: addressed in bb2a042. The skip now checks the base dictionary point-probe 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. The "bounded by reindex backpressure" comment is reworded to name reindex_max_bytes as the actual ceiling.
  • Named-graph × indexed coverage: addressed in b4b4020. upsert_indexed_named_graphs_replace_independently upserts the same subject IRI into two named graphs post-index (replaced independently, no cross-graph leakage), alongside a brand-new subject and a never-registered graph in the same transaction — asserted from novelty and again after the next index build.
  • Upsert bench: agreed, deferring to a follow-up PR (new-subject and persisted-subject variants beside transact_commit, plus a regression-budget entry) so stacked perf: batched read lanes for Cypher relationship-property queries and large UNWINDs #1553 isn't held up. The two variants will guard both sides of the now-lazy pre-check.

@bplatz
bplatz merged commit f73e4ee into main Jul 30, 2026
14 checks passed
@bplatz
bplatz deleted the fix/upsert-staging-new-subject-scan branch July 30, 2026 02:40
q-qp-p pushed a commit to q-qp-p/fluree-db that referenced this pull request Oct 19, 2026
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.
q-qp-p pushed a commit to q-qp-p/fluree-db that referenced this pull request Oct 19, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants