Skip to content

perf: sustained writes on large ledgers — staging, indexing, publish stalls - #2230

Merged
bplatz merged 16 commits into
mainfrom
perf/large-update-write-path
Nov 3, 2026
Merged

bplatz merged 16 commits into
mainfrom
perf/large-update-write-path

Conversation

@bplatz

@bplatz bplatz commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Sustained, scattered writes on a large ledger ran at about 10K flakes/s, slowed as unindexed data grew, and eventually ran the server out of memory. The workload: 236.5M flakes on 37.3M hash-named subjects; 500-subject values … where {?s ?p ?o} delete {?s ?p ?o} retractions alternating with 5K-flake upserts of new subjects; half of all flakes retractions.

This branch removes the per-transaction costs that grew with novelty, a rebuild cliff in the incremental indexer, a serial tail in every index build, and the stalls an index publish put in front of commits.

Results

Measured on m7a.4xlarge (16 vCPU, 64 GB, gp3 at 1,000 MB/s) with an 8 GB cache, one transaction in flight, mimalloc as the global allocator (now the default; see the last change below). These numbers come from that run only: the repo's benches cover the upsert of new subjects (transact_upsert_replace), not the planner-stats or publish changes.

main this branch
Throughput, reindex 10 KB min / 50 MB max 10.1K flakes/s; out of memory after ~12 min 23.3K flakes/s; RSS flat at 16–19 GB
Throughput, reindex 200 MB min / 1 GB max 3.6K flakes/s; first large build falls back to a full rebuild 41.2K flakes/s
VALUES delete, 500 subjects 111 µs/flake, 400 at 1.6M flakes of novelty 15–28 µs/flake, flat in novelty
Upsert of new subjects 13 µs/flake, 57 at 1.6M flakes of novelty 2.1–2.4 µs/flake, flat in novelty

Commit latency at 200 MB / 1 GB, steady state, before and after the two publish changes: p99.9 289 → 74 ms, max 545 → 136 ms.

Changes

  • perf(transact): decide upsert subject absence without walking novelty.
    • An upsert subject missing from the persisted dictionary sent generate_upsert_deletions, and the reifier pre-check, through a walk of the graph's whole novelty once per transaction.
    • Dictionary novelty now records the novelty t it covers (DictNovelty::covers / mark_covered_through). That mark is set wherever a state is populated from all of novelty: load, LedgerState::new, index install, binary-store attach. A commit extends it only if it held before.
    • A miss in a covering dictionary proves the subject absent. Anything else falls back to a seek bounded to the subject, so a missing mark costs speed, never a retraction.
    • LedgerState::new now populates its dictionary from the novelty it is given.
  • perf(novelty): sum planner stats from per-segment deltas, together with fix(novelty): keep planner stats sums with their segment, as hashes.
    • Every write invalidated the planner stats view, and rebuilding it walked all of novelty. That cost about 190 ms of a 500-subject delete at ~250K flakes of novelty, and every query after a write paid it too.
    • The planner merge is a blind ±1 sum, and segments are immutable. Each segment's sums are computed once and kept in the segment, so they are freed with it. Distinct-value counts key on a hash of the term, not a copy of it.
    • Counts clamp at zero once, on the total, instead of per flake. The two differ only where a running count would dip below zero.
  • perf(indexer): run class-stat base lookups in parallel slices. Phase 3b's four base-index lookups ran as one serial chunk loop: about 2.7 s of a 9 s build on this ledger, on one thread.
  • perf(indexer): scale the re-type rebuild gate with the index.
    • A fixed cap of 100K existing subjects whose rdf:type set changes sent any batch deleting more entities than that to a full rebuild. On this ledger the rebuild took minutes and about 60 GB of RAM.
    • The cap is now the larger of the configured value and an eighth of the distinct typed subjects, taken from rdf:type's ndv_subjects.
  • perf(novelty): trim the fact state at index publish without rebuilding it.
    • Installing an index rebuilt the dedup fact state from all surviving novelty under the ledger write lock, which took 75–830 ms per publish.
    • It now records a cutoff, and entries at or below the cutoff read as absent. Every later op has a higher t and supersedes them under the existing rule.
    • Commits sweep the stale entries out in bounded steps, and a graph the trim fully drains drops its map at once.
    • A trim that leaves few flakes, at most 1,024 across graphs, rebuilds those graphs' maps from them instead, so a ledger that goes idle after a publish keeps none of the trimmed window resident. The budget bounds what this adds to the publish lock.
  • perf(ledger): free trimmed novelty off the ledger lock. Dropping the old novelty freed every trimmed flake inside the lock, up to 775 ms per publish. It now happens on a short-lived thread that each index install spawns, and that only frees memory; on wasm32 the drop stays in place.
  • perf(indexer): upload a branch's rewritten leaves concurrently. The per-order uploader awaited each leaf put, then its sidecar put, before taking the next blob. It now buffers puts under the existing upload budget. No measurable change on local disk; aimed at remote storage, which I have not benchmarked.
  • perf(indexer): hand prefetched leaves to the rewrite instead of copying them. Each prefetched leaf and sidecar is moved into the copy-on-write on its last read instead of cloned.
  • perf(novelty): merge tier-compacted segments instead of re-sorting them. Tier compaction re-sorted all four orders from scratch while holding the write lock; it now k-way merges them.
  • perf(api): compact novelty before staging under the write lock.
    • A query snapshot tier-compacts novelty. The lock-held write path staged on the cached state as it was. That path serves policy-gated requests, pre-built transactions, Cypher sequences, the consensus build and restages.
    • A writer that never queries there stages against one novelty segment per commit since the last index. Every read it stages, such as a DELETE's WHERE or an upsert's prior values, binary-searches each segment, and hash-named subjects defeat the per-segment key-range skip.
    • On a replace workload held about 110 segments deep, those searches took half the writer's CPU, and a retracted flake cost 33–37 µs against 10–11 µs when queries interleaved. Each commit was a DELETE … WHERE over a chunk's entities followed by its INSERT DATA, about 10K retractions.
    • LedgerWriteGuard::clone_state_for_staging runs the snapshot's bounded merge before cloning. The lock-held transaction path, push and incremental commit import use it; branch merge and rebase, which run rarely, still clone the state as it is. A tier width of 0 still turns compaction off.
  • build: make mimalloc the default allocator for the CLI, server and Python package.
    • Under sustained writes with frequent index builds, glibc keeps freed memory. A malloc_trim(0) took a running server from 42 GB to 12 GB RSS, and without mimalloc this branch runs a 64 GB host out of memory within minutes at these write rates; with it, RSS stays at 16–32 GB.
    • The mimalloc feature is now on by default for fluree-db-cli and fluree-db-server, and maturin builds the Python extension with it.
    • The extension is a dlopen'd library, so it uses mimalloc's local-dynamic TLS model. Its allocator covers the extension's own allocations, not Python's.
    • Libraries still leave the choice to the binary that links them. docs/operations/configuration.md shows embedders the one line that opts in.

Tests

Each of these fails with its fix reverted:

  • it_transact_upsert::upsert_on_a_rebuilt_state_retracts_the_value_novelty_holds
  • it_transact_upsert::dictionary_novelty_covers_novelty_across_commits
  • it_upsert_skip_fires::indexed_ledger_load_keeps_dictionary_coverage
  • it_upsert_skip_fires::new_subjects_over_heavy_novelty_read_no_novelty (the upsert pre-check's ruled_out_by_dictionary)
  • runtime_stats::tests::segment_sums_match_the_walk (segment sums against the walk)
  • it_indexing_stats::retype_gate_scales_with_typed_subjects
  • it_indexing_stats::retype_gate_counts_subjects_not_class_memberships
  • tests::trimmed_fact_state_answers_as_a_rebuild_from_survivors
  • tests::a_trim_leaving_few_survivors_rebuilds_the_fact_state
  • tests::segment_merge_matches_building_from_all_flakes
  • it_staging_compacts_novelty::policy_gated_updates_stage_on_compacted_novelty
  • it_staging_compacts_novelty::pushes_to_a_ledger_nothing_queries_stage_on_compacted_novelty
  • ledger_manager::tests::staging_on_the_locked_state_compacts_novelty

transact_upsert_replace gains new_subjects_novelty_heavy, the upsert of new subjects over 4×N flakes of unrelated novelty.

Unit tests for the new helpers:

  • par_batched_lookup_tests
  • prefetched_tests
  • fact_state::tests::sweep_removes_only_stale_entries_in_bounded_steps

Not in this PR

  • History sidecars. FHS1 sidecars are rewritten whole for every touched leaf and never pruned. After 20 minutes of this workload they outweigh the leaves (1.35 MB against 0.96 MB on average), and builds slowed about 70%. They compress about 4× with zstd. A compressed or append-only history format would be a next change.
  • Leaf rewrite floor. At this change density every build rewrites nearly every leaf, about 5–6 s per build. Larger reindex thresholds amortize it.
  • Replacement upserts. New values on existing subjects still read slot by slot, at about 30–100 µs/flake.

Partially addresses #1731. Planning at the current state no longer walks novelty. Planning at a t below a segment's newest flake still walks, and predicates without indexed ndv still merge their segments' distinct-value maps on each planning pass.

Follow-up: #2258 (tests that a write's cost follows its transaction, not the novelty a ledger holds).

bplatz added 10 commits October 31, 2026 17:30
The per-order uploader awaited each leaf and sidecar put before taking
the next blob off the channel, so an incremental build issued one put at
a time per order while the shared upload budget allowed far more. Drain
the channel through buffer_unordered under the same budget; the branch
records each leaf's CID from the copy-on-write, so put order is free.
A subject missing from the persisted dictionary sent generate_upsert_deletions
(and the reifier pre-check) through an unbounded walk of the graph's whole
novelty, once per transaction, so upserts of new subjects slowed in
proportion to unindexed data.

Dictionary novelty holds every subject of a novelty flake that the persisted
dictionary does not, when it was populated from every commit novelty holds.
Make that a recorded property rather than an assumption: the dictionary
carries the novelty t it covers, set where a state populates it from all of
novelty (load, LedgerState::new, index install) and extended by a commit
only when it held before. A miss in a covering dictionary proves absence; a
hit, or a dictionary that cannot vouch (a state paired with novelty it was
not populated from), is settled by a seek bounded to the subject.
Phase 3b reads the base index four ways for the subjects a build touches:
their rdf:type classes, the live properties of re-typed subjects, inbound
refs to re-typed objects, and the classes of stable ref endpoints. Each ran
as one serial chunk loop. With scattered subject ids those loops sweep most
of the type partition or the subjects' SPOT range on every build, on one
thread, after the parallel leaf rewrite has finished.

Each lookup answers per requested id, so contiguous slices of the sorted
ids scan disjoint ranges and their answers union without overlap; run the
slices on the rayon pool.
Every commit moves the planner stats view's cache key, and rebuilding the
view walked every novelty flake through the K-way merge. So each transaction
WHERE, and each query after a commit, paid O(novelty) before it planned: on a
large ledger with a few hundred thousand unindexed flakes that was about half
of a 500-subject VALUES delete's staging time.

The planner merge is the blind +/-1 delta log, a sum, and novelty segments
are immutable. Compute each segment's sums once, keyed by its process-unique
id and the index's ndv scope, and sum K of them per view. Counts are clamped
at zero once, on the total, where the walk clamped per flake; the two differ
only where a running count would dip below zero. A segment holding flakes
past the requested t still takes the walk.
An incremental batch that changes the rdf:type set of more than 100,000
existing subjects aborts to a full rebuild, on the premise that recomputing
class stats from scratch is cheaper than re-scanning those subjects. That
holds for a small index, not a large one: deleting entities retracts their
types, so a batch deleting 200K entities from a 236M-flake ledger went to a
rebuild that re-reads every commit, taking minutes and most of the host's
memory, where the re-scan takes seconds.

Keep the configured count as a floor and raise it to an eighth of the base
index's typed subjects.
…ng them

Phase 2 prefetches every touched leaf and sidecar of an order, then the
copy-on-write cloned each one out of the prefetch map, so every touched
leaf and sidecar was copied once more in memory and the map kept all of
them until the order finished. Hand each blob over on its last read, so a
blob read once is moved and its memory goes as its leaf is rewritten. A
read past the expected count is an error rather than an absent sidecar,
which would drop that leaf's history.
Tier compaction concatenated the flakes of tier_width segments and sorted
all four index orders from scratch, under the ledger write lock, though
each input's orders are already sorted. K-way merge the inputs' orders
instead: O(n log k) comparisons rather than O(n log n), the four orders
merged in parallel.
…g it

Installing an index trims novelty through the index t under the ledger
write lock, and that rebuilt the dedup fact state from every surviving
flake: a k-way merge of novelty plus an ordered-map insert per flake. On a
ledger with a few hundred thousand flakes left in novelty that held the
lock for 75-830 ms at each publish, stalling every commit queued behind it.

The fact state keeps each identity's winning op, and every op recorded
after the trim has a higher t, so an entry at or below the trim names an
op the index now holds and can simply read as absent. Record the cutoff
instead of rebuilding, and let commits sweep the stale entries out a
bounded number at a time. A graph the trim leaves with no novelty drops its
map at once, so an idle ledger whose novelty is all indexed keeps none of it.
Installing an index replaces the ledger's novelty with its trimmed copy
under the ledger write lock. When nothing else held the old novelty, that
replacement freed every flake the trim dropped, often most of novelty,
inside the lock: up to 775 ms of an install on a ledger indexing about a
million flakes per build, against well under a millisecond once the old
novelty is handed to a short-lived thread to drop.
The per-segment planner sums sat in a process-global cache bounded by
entry count, so for predicates without indexed ndv they could keep whole
copies of strings, JSON and vectors alive, and keep them after the ledgers
that made them were gone. Keep each segment's sums in the segment, so they
are freed with it, and key distinct-value counts on a hash of the term
rather than a copy of it; subjects already share the segment's Sids.
@bplatz bplatz added the performance Performance improvement (release notes: Performance) label Nov 1, 2026
@bplatz
bplatz requested a review from a team November 1, 2026 02:19
…thon package

mimalloc was an opt-in feature pending a soak. Sustained writes with index
builds are that soak, and they make the case: glibc keeps most of the memory
the process frees, so resident memory climbs until the host runs out (42-63
GB on a 64 GB host serving a 236M-flake ledger, about 30 GB of it returned by
a malloc_trim), where mimalloc stays at 16-32 GB on the same workload.

Turn the feature on by default for fluree-db-cli and fluree-db-server, and
add it to the Python extension module, which maturin builds with it. The
extension is a dlopen'd library, so it uses mimalloc's local-dynamic TLS
model; its global allocator covers the extension's own allocations, not
Python's. Libraries still leave the choice to the binary that links them;
the configuration docs show embedders the one line that opts in.
A query snapshot tier-compacts novelty; the lock-held write path staged
on the cached state as it was. That path serves policy-gated requests,
pre-built transactions, Cypher sequences, the consensus build and
restages. A writer that never queries there stages against one novelty
segment per commit since the last index, and every read it stages, such
as a DELETE's WHERE or an upsert's prior values, binary-searches each
segment. Hash-named subjects defeat the per-segment key-range skip.

On a replace workload (DELETE ... WHERE over a chunk's entities, then
its INSERT DATA; ~10K retractions a commit) held ~110 segments deep,
those searches took half the writer's CPU, and a retracted flake cost
33-37 us against 10-11 us when queries interleaved.

LedgerWriteGuard::clone_state_for_staging runs the snapshot's bounded
merge before cloning, and every lock-held staging site uses it. A tier
width of 0 still turns compaction off.

@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.

@bplatz these are really nice finds, and I appreciate that each stall comes with its mechanism named and actually removed rather than moved somewhere else. At a design level no pushback from me (the per-segment sums and the cutoff-instead-of-rebuild for the fact state are both really nice). One headline note: this falls into a class we keep hitting one instance at a time, namely "work on a per-write path that's proportional to the unindexed window, and so is only cheap while indexing keeps up":

#1549's per-graph upsert walk (8ae18197b, which this PR removes); the reifier invariant walking novelty per annotation (6160a9542); filtered-DELETE list-meta hydration (acc5db560); the planner stats walk (#1731, partially closed here); overlay translation (#1722, still open)

To be clear, I think the point fixes are right for this PR. But nothing in the repo would catch one of them coming back: Claude restored a whole-graph novelty walk in novelty_holds_subject and all 64 upsert/staging tests still passed, and transact_upsert_replace's new_subjects scenario runs over empty novelty. So I'd like at least the upsert path to get a novelty-heavy bench scenario in this PR (details below). Maybe a "flat in novelty" guard, e.g. a counting overlay asserting a write visits O(txn) novelty rather than O(novelty), is the class-level fix worth its own effort. Approving, and good to merge once you've had a look at the notes below.

Full review below:


✅ Approve.

This is a really satisfying one to review, @bplatz. Every stall in the body traces to a named mechanism on main, and the diff removes each one rather than moving it: the upsert absence walk, the planner-stats walk after every write, the fact-state rebuild and the free under the install lock, the re-sort in tier compaction, the retype rebuild cliff and the serial Phase 3b tail. The derived state lands in the right places too: sums that live and die with their segment, a cutoff whose answers match a rebuild (Claude checked that both fact-state tests go red without it), and a coverage flag that fails safe. Nothing I found is blocking. The notes above are a bench scenario so the upsert win can't quietly revert, a memory case in the fact-state trim, a one-line nit in the sweep, and the push and import sites.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ extends the existing structures (segments, DictNovelty, NoveltyFactState, LedgerWriteGuard, the tier-compaction policy) rather than adding parallel ones, and compact_novelty now serves both the snapshot and the staging trigger.
  • Performance (speed first, memory second): ✔ a clear improvement on the write, publish and post-write planning paths, with no hot-path slowdown found. The new commit-path work is bounded: compaction the optimistic path already paid, the sweep, and a thread spawn per install. On memory, the fact-state trim can keep the previous window resident on an idle ledger under a large reindex_min_bytes (inline), and per-segment planner sums are now resident for predicates the index has no ndv for.
  • Deployment targets: ✔ shared code, so every host runs it. The evidence is Linux test, wasm32/wasm-smoke, and the python job building the wheel with the new mimalloc feature on Linux, macOS and Windows. The one new thing that outlives its call is drop_off_thread's short-lived thread, and it only frees memory. An embedder that freezes the process after a response (e.g. AWS Lambda) just frees later, nothing coordinates across processes, and on wasm32 it drops in place. It's worth one line in the body that index installs now spawn that thread. The allocator change reaches the binaries and the Python extension only; library embedders keep their own.
  • Testing: ⚠️ the correctness half is well pinned. The new tests in grp_transact, grp_index, it_upsert_skip_fires and the unit tests are all present in CI's nextest log, and mutations confirm the coverage and cutoff tests. But no test or bench fails when the performance fixes are reverted (inline on stage.rs).
  • Conventions: ✔ thorough multi-line commit bodies, a self-describing title, clippy and fmt green, and configuration.md updated for the allocator default.

Verified locally at branch HEAD (0d0cea2d7): fluree-db-novelty 106/106, and the upsert and staging-compaction integration tests 17/17. Three mutation checks: removing the cutoff turns 2 tests red, removing the LedgerState::new populate turns the rebuilt-state upsert red, and restoring the whole-graph walk leaves 64/64 still green. Also a fact-state retention probe, and a clean git merge-tree against current main.

Approving so you can merge when ready, but I'd like to see the upsert bench scenario folded in first, and maybe worth considering the other notes too.

Comment thread fluree-db-transact/src/stage.rs Outdated
/// read. Otherwise, and for a hit (the dictionary novelty spans every graph,
/// and names ref objects too), a seek bounded to the subject decides, never a
/// walk of the graph's novelty.
fn novelty_holds_subject(ledger: &LedgerState, g_id: GraphId, subject: &Sid) -> bool {

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, but I'd like it in this PR.

Nothing in the repo would catch this walk coming back.

The tests added here pin correctness (the rebuilt-state upsert still retracts, and the coverage flag survives load and commits) but not cost. The one bench with a new_subjects scenario runs it over an indexed base with empty novelty (fluree-db-api/benches/transact_upsert_replace.rs:130, asserted at :277), where main's walk was free too. novelty_heavy does carry 4×N novelty, but its upsert names base-dictionary subjects, so it never reaches the slow side of this function.

Claude checked this by mutation. With novelty_holds_subject ignoring covers and walking the whole graph's novelty per subject (worse than main's once-per-graph walk), cargo nextest run -p fluree-db-api --test grp_transact --test it_upsert_skip_fires -E 'test(/upsert/) | test(/it_staging_compacts_novelty::/)' is still 64/64 green.

A cheap guard would be a new_subjects_novelty_heavy scenario in that bench: the novelty_heavy fixture plus an upsert of N subjects the ledger has never seen. The bench already has its regression-budget.json entry, so it's just a new Scenario arm. The planner-stats-after-write and install-stall wins don't have a bench either. Those are harder to shape and I don't think they need one here, but it'd be good for the body to say the numbers come from the external run only.

This is minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.

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 ef75e6f. Besides the bench arm, the pre-check now reports ruled_out_by_dictionary and it_upsert_skip_fires asserts it, so the walk coming back fails CI; the body says the numbers come from the EC2 run only, and the class-level guard is #2258.

Comment thread fluree-db-novelty/src/fact_state.rs Outdated
/// novelty drops its whole map now, so a ledger whose novelty has all been
/// indexed holds none of it while idle; the rest move the cutoff and are
/// swept by later commits (see [`NoveltyFactState`]).
pub(crate) fn trim_through(&mut self, cutoff_t: i64, drained: impl Fn(GraphId) -> bool) {

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 (memory).

A trim that leaves a few survivors keeps the whole previous window's fact state resident.

trim_through drops a graph's map only when the trim drains it. Otherwise every entry stays until commits sweep it, and each entry is a cloned FactKey, so string, JSON and lang values are copied. The sweep only runs from apply_commit, at least 4,096 entries per commit.

Claude's probe (a scratch test, not part of the PR) made 50 commits of 1,000 string-valued flakes plus one more 1-flake commit, then ran clear_up_to(50). The graph's map still held 50,001 entries for 1 survivor, where main rebuilds it to 1. One later 1-flake commit swept 4,093, and a draining trim dropped the rest. Under the default reindex_min_bytes (100 bytes) the next build drains it right away, so it's transient. With a large minimum, though, like the 200 MB / 1 GB row in the body's table, a ledger that goes idle after a burst whose last commit landed during the final build holds the previous window's fact state until writes resume.

I think there's a way to keep both wins. The rebuild's cost is proportional to the survivors, so it is cheap exactly when this case applies. Per graph, then: few survivors → rebuild that graph's map from them, as main did; many → move the cutoff. Roughly:

// in Novelty::clear_up_to, per graph after the segment trim
match surviving_flakes(g) {
    0 => drop the map,                                  // as now
    n if n <= FACT_REBUILD_MAX => rebuild g's map from its survivors,
    _ => keep it under the cutoff and let commits sweep it, // as now
}

Minor and non-blocking, but if you agree, I'd rather see it in this PR than lost in the backlog.

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 19081f9. The rebuild budget is 1,024 survivors shared across graphs rather than per graph, since it runs under the publish lock queries wait on.

Comment thread fluree-db-novelty/src/fact_state.rs Outdated
if t <= self.cutoff {
stale.push(key.clone());
}
last = Some(key.clone());

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 (nit, commit path).

So minor, but only the last examined key needs cloning. last = Some(key.clone()) runs for every examined entry: three Arc bumps, a heap copy for string, JSON and lang values, and a drop of the previous one. That happens at least 4,096 times per commit while a sweep is pending, under the write lock. Holding a reference and cloning once after the loop does the same job. Claude applied this and the crate's 106 tests pass:

let mut last: Option<&FactKey> = None;
// … in the loop:
    last = Some(key);
}
let last = last.cloned();
for key in &stale {

Cheap enough that I'd fold it in.

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 19081f9

/// novelty — a DELETE's WHERE, an upsert's prior values — and each read
/// searches every segment, so a writer that never queries would stage
/// against one segment per commit since the last index.
pub fn clone_state_for_staging(&mut self) -> LedgerState {

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. (Real location: fluree-db-api/src/commit_transfer.rs:346.)

Push and import still stage on the uncompacted state.

The commit message says every lock-held staging site uses this, but push_commits (commit_transfer.rs:346) and import_commits_incremental (:2441) still take guard.clone_state(). Push reads novelty for every pushed retraction (assert_retractions_exist, :517) and stages each commit on that state. So a peer that only receives pushes and isn't queried sees the same one-segment-per-commit fan-out this commit fixes for transactions. The fix is let mut guard plus clone_state_for_staging() at each. The branch operations (tx_builder.rs:1246, :2080) are occasional enough that I don't mind either way.

Commenting here because commit_transfer.rs:346 is not 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.

Addressed in bdba0a7

/// `novelty_t` ([`Self::mark_covered_through`]). A dictionary that cannot
/// vouch reads as not covering, never the reverse, so a reader that skips
/// work on a miss here must treat `false` as "may be present".
pub fn covers(&self, novelty_t: i64) -> bool {

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.

I really like that this fails safe by construction. Any path that advances novelty.t without vouching just loses coverage and falls back to the bounded seek, so only an explicit mark_covered_through can make the skip unsound. Claude traced every non-test site that populates a LedgerState's dictionary novelty. Each one marks only after populating from all of novelty, or extends coverage only when it held before. And upsert_on_a_rebuilt_state_retracts_the_value_novelty_holds is the right guard for the unsafe direction: Claude dropped the populate from LedgerState::new while keeping the mark, and the test goes red on the missed retraction.

…te-path

main's c30ad2b moved the planner stats pass's maps to FxHash, including
the `graph_index` and `novelty_ndv` maps that `get_or_insert_graph_entry`
and `finalize_properties` now take. This branch moved that pass into
per-segment sums (runtime_stats/segment_sums.rs), which still built std
maps, so the merge didn't compile. segment_sums.rs now uses FxHash for the
same maps, and for the per-segment sums built from the same keys. The class
deltas stay std, as `counts_only_classes` takes them.
`push_commits` and `import_commits_incremental` took `clone_state()` under
the write lock, so they staged on novelty as it stood: one segment per
commit since the last index on a ledger nothing queries. A push reads
novelty for every retraction it carries and stages each commit on that
state, so a peer that only receives pushes paid the fan-out the
transaction path stopped paying. Both now take `clone_state_for_staging()`.

The new test pushes 40 single-commit pushes to a ledger with tier width 4
and nothing querying it; on the uncompacted clone it holds 40 segments.
Moving the fact state's cutoff at a trim leaves every entry of the trimmed
window in place until commits sweep it, and commits only sweep while they
arrive. A ledger that went idle after a burst whose last commit landed
during the final index build kept the previous window's fact state
resident (50,001 entries for 1 survivor in a probe), where main rebuilt it
to the survivors. Under a large `reindex_min_bytes` that lasts until
writes resume.

The rebuild costs what the survivors cost, so it is cheap exactly where
the cutoff's leftovers are worst. `clear_up_to` now rebuilds each graph's
map from its surviving flakes while they fit a shared budget of 1,024
across graphs, and moves the cutoff for the rest. The budget bounds what
the trim adds to the index-publish write lock, which query snapshots wait
on; a drained graph still just drops its map.

The sweep also clones only the last key it examined, instead of every
key, under the write lock.
…uch there is

Nothing failed when the upsert absence check stopped using the dictionary
novelty: with `novelty_holds_subject` walking the graph's whole novelty
per subject, the upsert and staging suites stayed green, and the one bench
with new subjects ran over empty novelty, where any check is free.

The pre-check now reports `ruled_out_by_dictionary`, the subjects it
skipped with no read of novelty, beside `skipped_subjects`. For that it
calls the two halves of `novelty_holds_subject` itself:
`dictionary_rules_out`, then `novelty_seek_finds_subject` when the
dictionary does not settle it. `subjects_with_prior_rows` keeps the
combined check.

`it_upsert_skip_fires` upserts ten subjects the ledger has never seen over
20 commits of unindexed novelty and asserts the dictionary settled all
ten. With the dictionary never ruling a subject out it reads 0 of 10, and
only this test fails.

`transact_upsert_replace` gains `new_subjects_novelty_heavy`:
`new_subjects` over the 4×N unrelated novelty of `novelty_heavy`.
@bplatz

bplatz commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Updated the PR body: index installs now spawn a short-lived thread that only frees memory (dropped in place on wasm32), and the throughput numbers come from the EC2 run only.

Merging main in (de7e172) needed one fix: main's c30ad2b moved the planner-stats helpers to FxHash, and this branch had moved that pass into runtime_stats/segment_sums.rs, so segment_sums.rs uses FxHash for the same maps now (the class deltas stay std, as counts_only_classes takes them).

@bplatz
bplatz merged commit 43215a3 into main Nov 3, 2026
19 checks passed
@bplatz
bplatz deleted the perf/large-update-write-path branch November 3, 2026 22:34
@aaj3f aaj3f mentioned this pull request Nov 4, 2026
bplatz added a commit that referenced this pull request Nov 4, 2026
Brings #2247, #2232, #2246, #2248, #2245, #2230, #2205, #2231, #2255,
#2219, #2209, #2207, #2190, #2216, #2186, #2215, #2213, #2184, #2210,
#2206, #2198, #2187, #2183, #2200, #2193, #2199, #2196 and #2145 into next.

Resolutions:
- Novelty: main's fact-state trim (a cutoff plus a bounded sweep) and the
  dictionary's coverage watermark sit on next's graph slots and per-graph
  OrdMaps. A commit's reification links count toward coverage. Planner
  stats from segment sums decline under annotations, whose link deltas
  only the walk counts, and otherwise carry the indexed link counts.
- Stats-view identity: the index root's id reaches the snapshot through
  next's root decoder (`decode` takes the id, as `take_snapshot_metadata`
  does). `LedgerState::load_record` has a decoding-root form beside
  `load_decoding_root`.
- Transact: #2184's parallel-relationship check runs in next's link
  cascade, counting the `rdf:reifies` links on the retracted edge that the
  transaction does not retract itself. Main's bundle `edge_reifiers` is
  dropped, and `subjects_with_prior_rows` and
  `enforce_single_target_reifiers` stay deleted. The upsert pre-check
  takes main's dictionary probe and bounded seek.
- Query: geo search resolves the graph's POST tree once at open (pooled
  graphs keep their filter), an empty manifest when there is none.
  `branch_or_none` reads the dedicated branch, and the batched joins keep
  next's pooled lanes. The stats-view key hashes the root id.
- Indexer: `apply_dict_novelty` and `compact_forward_streams` take the
  cycle's compaction budget, so the term dictionary keeps its reserved
  share. `Prefetched` holds `ContentBytes`. `relocalize_sorted_commit`
  rewrites next's 20-byte types records.
- Disk cache: main's in-flight write registration, with an empty entry
  still read as crash debris that a write replaces. The process-wide
  eviction walk stays removed.
- Graph import (#2232): fenced CAS and publishes, the seed carries the
  record's namespace and fence, 32-bit graph ids and next's loaders. An
  import into a graph of an existing ledger refuses triple terms and edge
  annotations: the splice merges no triple-term dictionary yet.
- Iceberg: `create_iceberg_graph_source` goes with main (a source needs a
  mapping); the R2RML path keeps next's `model_instance`.
- CLI: main's shared import flags without the leaflet flags; `graph
  import` routes through next's process-wide server routing, and
  `upload_source_import` serves next's `Destination`. Doc sources read a
  ledger through the command's open instance.
- Tests: sibling ledger ids become distinct names, `genesis_ledger` is
  awaited, Cypher state dumps include each relationship's `rdf:reifies`
  link, and the graph-import arena test checks the refusal instead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Performance improvement (release notes: Performance)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants