Skip to content

Overlay translation materializes all novelty before applying bound-subject filter — scans and queries cost O(accumulated novelty) under sustained writes #1722

Closed

Description

@aaj3f

While profiling a sustained continuous-write workload (many small transactions into one ledger, background indexer running behind) I went looking for the source of a very fat latency tail and found something I think matters well beyond the write path: every scan that consults the novelty overlay materializes the entire graph's novelty before it applies the bound-subject filter, so under sustained writes both transactions and ordinary queries carry a cost that grows linearly with accumulated novelty.

The part that makes this worth fixing rather than documenting: novelty is already fully seekable, the correctly-bounded walk is already written in the same file, and it is wired to exactly one path — just not the hot one.

What I measured

A 10-minute unthrottled run (batch-100 JSON-LD transactions, mixed insert/delete/update, reindex_min_bytes at its default so the indexer is in continuous cycle):

  • The p99 transaction tail is not the commit path. txn_commit p99 was 100 ms; where_exec p99 was 3.92 s, and txn_stage accounted for 74% of wall time.
  • where_exec p90 scales linearly with accumulated novelty — about 5 ms per MB: 27.9 ms at 4–6 MB, 45.4 at 8–10, 68.8 at 12–14, 86.0 at 16–18, 107.5 at 20–22, 118.7 at 24–26, 153.8 at 28–30, 161.3 at 32–34 MB. Monotone across the whole range.
  • The distribution is sharply bimodal — 51% of executions finish under 10 ms, while the slowest 5% consume 77% of all staging time.
  • Effective throughput collapsed 48× within the ten minutes (1,246 transactions in the first decile of wall time, 26 in the seventh) while medians stayed sub-millisecond.

The mechanism

Claude traced this end to end; pasting its findings, which I've spot-checked against the code:

The cost is in BinaryScanOperator::open() (fluree-db-query/src/binary_scan.rs). At :2270 it unconditionally materializes the whole graph's novelty — translated to OverlayOp, sorted into the cursor's index order, lifecycle-resolved — and only afterwards, at :2354-2362, narrows to the bound subject via overlay_window_for_range, which is just two partition_point calls over the product it has already paid to build. The pruning is applied exactly one step too late.

Roughly four passes over all N novelty ops happen per execution: the per-segment copy at :2828 into an un-with_capacity'd vec (:2802), sort_overlay_ops_stable (:2850), resolve_overlay_ops (:2324), and the Arc<[OverlayOp]> copy (:2330). At 40 bytes per op, 33 MB of novelty is roughly 250–500k flakes, and ~0.5 µs/flake lands squarely on the measured 161 ms — the arithmetic and the measurement agree independently.

The caches don't rescue this under writes, which is the crux of why it has stayed invisible. The per-execution cache is cold by construction (new transaction, new ExecutionContext). The process-wide global_translation_cache() is keyed on overlay_epoch and to_t (:2287-2296) — and Novelty::apply_commit bumps the epoch on every commit (fluree-db-novelty/src/lib.rs:861), with to_t advancing too — so with any write traffic, every execution is a guaranteed miss. The tier-2 per-segment translation cache does work and does save the per-flake dictionary translation; it just doesn't save the assembly, which is the O(N) part.

The bimodality has a clean explanation too: a subject that isn't in the persisted dictionary (freshly inserted, novelty-only) diverts to open_overlay_only_fallback (:2054), which is the cheap bounded path. Only operations touching already-indexed subjects pay the toll — which is exactly the shape of a delete or update against real data.

Why I think this is a missed optimization rather than a design limit

Novelty is already seekable. Each Segment carries four sorted index orders (spot/psot/post/opst, fluree-db-novelty/src/lib.rs:162-173), Segment::range binary-searches both ends (:238-269), may_overlap is a zone map that skips whole segments (:279-307), and for_each_overlay_flake honors first/rhs/leftmost all the way down (:1451-1486). A bound-subject SPOT read is O(log novelty + matched) — if you ask for it. Both translation callers pass None, None, true (binary_scan.rs:2650, :2739), i.e. they ask for everything.

And the bounded version is already written, in the same file: BinaryScanOperator::overlay_walk_bounds (:1548-1620), whose own doc comment states the thesis better than I can —

"Segment::range seeks with partition_point on both ends, so supplying bounds turns the overlay walk from O(novelty) into O(log novelty + matched) and lets may_overlap skip whole segments. With first/rhs left None the walk covers the entire graph's novelty on every probe."

It is called in exactly one place: open_overlay_only_fallback (:1655-1665). The main indexed path never calls it. There's also repo precedent for the identical fix on the predicate-leading orders — predicate_walk_bounds in fast_path_common.rs:2077-2135.

Worth noting the code already anticipated this conversation: the comment at binary_scan.rs:2845-2849 defers the remaining O(n) copy "until profiling shows the (now integer-only) merge dominates the already-cached per-segment dict translation." I think the numbers above are that profiling.

This is not just a write-path problem

The bit that moved this up my list: ordinary queries pay it too. execute_pattern (fluree-db-query/src/lib.rs:206) and dataset_operator.rs:164 route to the same BinaryScanOperator::open(). In a read-only steady state the epoch and to_t are stable, the global cache serves, and the cost is invisible — which is precisely why no existing read benchmark has caught it. Under concurrent writes, every query against head misses both caches and pays one full O(novelty) build per (graph, index order) per execution, so a user's bound-subject point lookup carries the same ~5 ms/MB floor, and a query touching two index orders pays it twice.

So the user-visible statement is roughly: any deployment that reads and writes at the same time sees query latency grow with how far the indexer has fallen behind.

Suggested fix

The smallest credible version: in open() at :2270, when the subject (or a predicate on a p-leading order) is bound, skip both translated-product caches and build a windowed op vec using the existing overlay_walk_bounds + for_each_overlay_flake(first, rhs, leftmost=false, …) — the exact call shape already sitting at :1655-1665 — then sort and resolve over that window only, memoized per (epoch, g_id, index, s_id) in the per-execution cache so a VALUES probe over K subjects costs K × O(log n + matched) instead of one O(novelty). Leave the unbounded path untouched for genuine wildcard scans.

Correctness rests on the same property predicate_walk_bounds already relies on: SPOT sorts subject first, so a subject-bracketed window contains every op for that subject, and resolve_overlay_ops still sees a complete lifecycle with no assertion separated from its retraction. Ephemeral predicate ids stay per-cursor, which cached_overlay_ops already documents and depends on.

Two follow-ons I'd keep separate: the general wildcard case (have collect_segment_merged_ops return per-segment runs and teach the cursor a K-way merge — this is the "incremental/persistent merge" :2845 defers), and the near-free Vec::with_capacity at :2802.

Regardless of the fix: there are no tracing spans anywhere in binary_scan.rs, which is why this hid inside where_exec with no sub-attribution for as long as it did. A debug_span!("overlay_translate", ops_len, segments, cache_hit) around :2270-2345 costs nothing disabled and would have made this a five-minute diagnosis.

Gates that would hold it

Three harnesses already exist and two want small extensions:

  • fluree-db-api/examples/delete_where_probe.rs is nearly a purpose-built reproducer — its WHERE is literally {"@id": subject, "?p": "?o"} and it reindexes first, so subjects are in the persisted dictionary and it takes the expensive path. It just runs at one fixed novelty level; parameterizing the novelty-building loop makes it emit the slope directly. (Its PROBE_NOMATCH mode uses non-existent subjects, which likely diverts to the cheap fallback and would understate the cost — the matching mode is the one to use.)
  • fluree-db-api/tests/it_transact_growth_slope.rs is exactly the right gate shape — least-squares slope of per-commit µs against novelty flakes with an opt-in ceiling, built for a previous O(novelty)-per-commit bug. It drives insert() only, so it doesn't cover this path; adding a bound-subject DELETE lane turns it into the direct regression gate, and the slope should collapse toward the intercept after the fix.
  • fluree-db-api/benches/query_overlay_matrix.rs already has an overlay lane aimed at "overlay→binary translation and cursor-merge", which would catch the query-side half; it wants a point-lookup shape and a novelty sweep to become a slope gate rather than a single point.

Caveats, honestly

The novelty-size correlation comes from a workload where novelty and elapsed time both grow, and later transactions also hit more matching deletes — so the correlation alone is evidence rather than proof. What convinces me is that the mechanism is O(novelty) by construction independent of match count, and the byte arithmetic independently predicts the measured slope. Two controls are running now (a large-reindex_min_bytes arm that holds big novelty early, and an insert-only arm with no WHERE at all); I'll post the numbers when they land, and I'm happy to be told the mechanism reading is wrong before anyone spends effort on the fix.

Activity

  1. aaj3f commented on Aug 27, 2026

    @aaj3f
    ContributorAuthor

    Correction to my own issue, before anyone spends time on it: the mechanism I described above is real, but it is not the dominant cost, and the headline framing here overclaims. I built the fix, measured it in isolation, and the numbers say so plainly.

    The fix does what the issue predicted. Bounding the walk turns the translation into a seek — overlay_translate mean 11.9 µs, p50 0.6 µs (a warm bounded call traces at 1.75 µs busy against 239 µs cold), and scan-open cost drops ~39% mean / 32% p50 / 49% max on a read-only probe with novelty held between 13k and 22k flakes. So the O(novelty) translation described above is genuine and is now gone for bound-subject and bound-predicate scans.

    But end-to-end it doesn't move: 594.3 → 554.1 µs per 1k novelty flakes, about 7%, which is inside run-to-run noise on my box. I'm reporting that as not a demonstrated win rather than dressing it up.

    Where the time actually goes. Span attribution at ~20k novelty flakes puts query_run at 3,360 µs of which query_prepare is 3,310 µs — the scan is a minority of the query, and query_prepare:plan alone runs 1.34–2.58 ms. The cause is the planner's stats view: cached_stats_view_for_db (fluree-db-query/src/stats_cache.rs:41) → assemble_fast_stats → assemble_fast_stats_inner (fluree-db-novelty/src/runtime_stats.rs), whose body is for flake in novelty.iter_flakes(IndexType::Post) — an unbounded full walk of all novelty, per query, to rebuild the stats view. And its cache is keyed on the overlay epoch (stats_cache.rs:99-104), which increments on every overlay mutation, so under sustained writes it misses on every commit.

    That is the same structural bug one layer up, and it is the larger of the two. So the honest statement is: the ~5 ms/MB reported in this issue has at least two contributors with identical shape — an epoch-keyed cache in front of an unbounded novelty walk — and this issue only identified the smaller one. I've filed the planner-stats term separately rather than growing this issue, since it needs its own correctness discussion (the planner tolerates approximate stats in a way the scan emphatically does not, which probably makes it the easier of the two to fix — incremental per-predicate counters maintained on apply_commit, or an explicitly stale-tolerant stats view).

    I'd still like to land the scan fix, but framed for what it is rather than for a latency number it can't currently support: it removes one of two O(novelty) terms on scan open, halves scan-open cost, and — the part I'd argue matters most right now — it adds the first tracing spans binary_scan.rs has ever had, which is the only reason the larger term became visible at all. That file being uninstrumented is why this cost hid inside where_exec for as long as it did.

    Two process notes worth recording, since both nearly produced wrong conclusions (Claude did the build and measurement; these are its findings, and I think they generalise):

    • The end-to-end DELETE-lane slope test I started with was useless for attribution — a whole transaction also pays commit-write, fsync, novelty apply and dedup, each with its own novelty-linear term, so it can't isolate the scan. One of its runs also landed on a box at load 72 and produced a 0.8× ratio, i.e. the last delete faster than the first, which is nonsense for an O(novelty) path. The isolating read-only probe is what produced usable numbers.
    • The original mechanism trace was done by code reading alone, with no span data. It was mechanically correct and materially incomplete — exactly the failure mode that measurement exists to catch.
  2. aaj3f commented on Aug 28, 2026

    @aaj3f
    ContributorAuthor

    The controls I promised have landed, and they close the confound. Posting the numbers because I said I would, and because they change this from "a correlation I believe" to something I think is actually settled.

    Test 1 — the sawtooth. The earlier evidence had novelty and elapsed time rising together, so it couldn't separate "cost scales with accumulated novelty" from "cost scales with how long the workload has been running." The fix is to make novelty go down as well as up: set reindex_min_bytes low enough that the indexer trims repeatedly mid-run (42 index cycles in 300 s), then ask whether latency follows novelty in both directions. Elapsed time and ledger size only ever increase, so neither can produce a downward movement.

    Over 30 ten-second buckets on a clean, uncontended run (3,502 commits, novelty oscillating 0.1–38.9 MB):

    Pearson r vs p90 latency
    accumulated novelty +0.529
    elapsed time −0.086

    Novelty decreased across 15 bucket transitions, and p90 latency fell in 14 of them (93%). And comparing matched novelty levels early versus late in the run — which holds novelty constant and varies everything the confound proposed — latency does not rise with time: at 12–17 MB it was 166.5 ms early and 125.2 ms late; at 17–24 MB, 157.9 ms early and 152.6 ms late.

    So the cost tracks novelty up, tracks it back down, and shows essentially no independent time trend. The "later transactions just hit more matching deletes" explanation predicts the opposite on all three counts.

    Test 2 — the insert-only control. Same batch size, same fsync mode, same reindex_min_bytes, differing only in whether transactions carry a WHERE clause:

    mixed workload insert-only
    novelty accumulated 65 MB 146 MB
    events/s 321 2,063
    commit p99 1,540 ms (p90) / 4,198 ms 74.7 ms
    where_exec in the span table p99 3.92 s absent

    With 2.2× more accumulated novelty, the insert-only workload is 6.4× faster with a tail two orders of magnitude smaller. Large novelty is simply not expensive for transactions that don't read — which rules out "anything gets slower when novelty is large" and isolates the cost to the read path.

    Two caveats so the numbers aren't over-read. Cross-run throughput comparisons on my box have roughly a 20% noise floor (I have several cases where a contended run measured faster than its clean re-run), so I'd only lean on effects much larger than that — which these are. And the sawtooth run's correlation is computed within a single run, which is the comparison the noise floor doesn't touch.

    Net: the O(novelty) shape described in this issue and in #1731 is real and is driven by novelty specifically. Since #1731 carries the dominant term (the planner's per-query stats walk, ~1.3–2.6 ms versus this issue's ~0.6 µs once bounded), that remains the one to fix for an end-to-end win — but the mechanism underneath both is now established rather than inferred.

  3. bplatz commented on Nov 14, 2026

    @bplatz
    Contributor

    Fixed by #1732 (663ece8): when the subject (or a predicate on a predicate-leading order) is bound, BinaryScanOperator::open() now brackets the overlay walk (bounded_overlay_walk), so translation is a seek rather than an O(novelty) build, and binary_scan.rs emits overlay_translate spans. As scoped here, the unbound (wildcard) merge is a separate follow-on; the remaining novelty-linear costs are tracked in #1731 and #1758.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions