Skip to content

perf(query): seek a bound-term overlay window instead of translating all novelty - #1732

Merged
aaj3f merged 14 commits into
mainfrom
perf/bounded-overlay-translation
Sep 2, 2026
Merged

aaj3f merged 14 commits into
mainfrom
perf/bounded-overlay-translation

Conversation

@aaj3f

@aaj3f aaj3f commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

What this delivers

1. Removes one of two O(novelty) terms on scan open.

BinaryScanOperator::open() translated the WHOLE graph's novelty to OverlayOp, sorted it, and lifecycle-resolved it — and only then applied the pattern's bound term via overlay_window_for_range, a binary search over an array that cost O(novelty) to build. The bound term was used, one step too late.

Both memo layers miss under sustained writes: Novelty::apply_commit bumps epoch on every commit and to_t advances with it, and both appear in the per-execution key and in GlobalTranslationKey. So every staging WHERE and every query against head paid a full O(accumulated-novelty) build.

A bound subject (or, failing that, a bound predicate) now brackets the walk itself. bounded_overlay_walk builds the leading-term range and translate_overlay_flakes_in_range seeks it via Segment::range's two partition_point probes plus the may_overlap zone-map skip — O(log novelty + matched) instead of O(novelty).

On the read-only probe added in this series (bound-subject query, ~13k–22k novelty flakes), the translation itself is now a sub-microsecond seek: overlay_translate at 0.6 µs p50, 1.75 µs warm against 239 µs cold, with bounded=true confirmed by trace. That is the figure this section rests on — a span that small cannot be a contention artifact, and it is the signature of a seek rather than a walk.

Scan-open wall-clock moved too, but that measurement's before/after split was unevenly contended and the absolute figures are not a claim. They are recorded inside the box below rather than as a headline, so they cannot be cited without the conditions that produced them.

⚠️ Measurement conditions — read before quoting these numbers

3. End-to-end is ~7% and inside noise. This is NOT a demonstrated latency win.

Same probe, end-to-end query latency: 594.3 → 554.1 µs per 1k novelty flakes. I am explicitly not claiming that as a result — and per the measurement-conditions box above, the before run of that pair was the contended one, so even this small gap is likely flattered.

The reason is that a second, larger O(novelty) term dominates, filed as #1731: query_prepare:plan is 1.3–2.6 ms/query because cached_stats_view_for_db → assemble_fast_stats_inner does an unbounded for flake in novelty.iter_flakes(IndexType::Post) behind a cache keyed on the overlay epoch — the identical structural defeat, one layer up, and the bigger half. Span attribution at ~20k flakes: query_run 3360 µs, of which query_prepare is 3310 µs.

This PR should be read as "removes one of two O(novelty) terms on scan open, halves scan-open cost, and adds the instrumentation that found the other one" — not as a latency win. It is worth landing ahead of #1731 because the spans are what make #1731 diagnosable.

Design: leading-term-only, and why

bounded_overlay_walk brackets on the index's leading term only — subject (SPOT walk) or predicate (PSOT walk) — and lets every other component span its full range.

A bound object is deliberately not used to narrow, even on OPST. Object identity in the bracket is FlakeValue equality, which is not the cross-type numeric equality the scan filter applies (Long(5) and Double(5.0) are distinct values that can both satisfy one pattern). An object-narrowed window could therefore omit a novelty retraction for a base row the cursor still emits — a stale row.

The pre-existing overlay_walk_bounds does fold the object in, and that is safe there because open_overlay_only_fallback only ever returns overlay matches. The main path merges the product against base rows, so it needs the stricter rule. Hence a sibling rather than reuse.

Correctness, as verified

The window is built before resolve_overlay_ops runs, so the hazard is a window that is too narrow.

  • Leading-term completeness. Every op sharing a FactKeyV3 shares both its subject and its predicate, and cmp_spot / cmp_psot lead with those terms (fluree-db-core/src/comparator.rs:161-180). A leading-term bracket therefore cannot split an assertion from the retraction that cancels it.
  • Property test over randomized real Novelty, 24 seeds × 4 to_t values (including mid-history), asserting the bounded walk yields exactly the whole walk filtered to the bracketed term — no misses, no strays.
  • Resolve subset-stability proven independently for subject and predicate partitions.
  • Per-cursor ephemeral ids. p_sids_ephemeral is per-cursor and OperatorState::can_open() is matches!(Created) — an operator opens exactly once, so cross-window id bleed is unreachable. Ids also start at store.predicate_count() and so can never collide with base p_ids.
  • Namespace normalization. The bracket compares against extract_bound_terms_snapshot's normalized Sids, which that function documents as re-encoded "to the compressed form matching novelty flakes".
  • to_t / time travel and multi-graph are pass-through (ctx.to_t, self.g_id), each with a dedicated integration test.

Tests, and the mutations that prove they bite

8 unit tests (bounded_overlay_walk_tests) + 7 integration tests (it_bounded_overlay_translation.rs, wired into grp_query) covering novelty-only subjects, indexed-only subjects, assert/retract lifecycles spanning the index↔novelty boundary, bound-predicate scans, named graphs, time travel, and scattered retractions read back across every subject.

Four mutations, each reverted afterwards:

mutation result
M1 — predicate bracket walked in SPOT order instead of PSOT window property test FAILED ✅
M2 — subject bracket rhs narrowed (Sid::max → Sid::min) 2 tests FAILED ✅
M3 — OverlayOp::fact_key drops p_id fact-key premise test FAILED ✅
M4 — bounded window drops retractions (the stale-row hazard) 6 of 7 integration tests FAILED ✅

M4 is the one that matters: it is exactly the failure mode a too-narrow window would produce, and the suite reddens on it. (The 7th test correctly still passes — it exercises the novelty-only fallback lane, which does not use the bounded path.)

Worth recording: my first attempt at M3 silently patched the wrong one of two identically-named fact_key methods in types.rs and scored a false green. A mutation that fails to apply is indistinguishable from a test that passes.

Also in this series

  • fix(query): demote the partitioned GROUP BY hint for history plans — a correctness fix that predates this branch and affects main. detect_partitioned_group_by assumes the scan emits rows grouped by the GROUP BY key, which current-mode scans honor but BinaryHistoryScanOperator does not: it emits events in collection order (persisted sidecar + base per leaflet, then novelty appended), so once any part of a history range is served from a published index, one subject's events are not adjacent and the adjacency-based partitioned aggregate emits one group per key run — GROUP BY ?person COUNT(*) returned [(alice,1),(alice,1),(bob,1),(bob,1)] instead of [(alice,2),(bob,2)]. The fix demotes the hint for history plans (partitioned && !planning.is_history()), mirroring the existing enable_fused_fast_paths gate, so history grouping takes the representation-normalizing hash lane; current-mode plans and the bounded overlay walk are untouched. This surfaced as a red CI test job here only because the FlureeBuilder::file background indexer (reindex every commit) won the race against the query on the merged head and not on earlier runs — with a deterministically published index the same split reproduces on main and the pre-merge head. New pins cover both deterministic index states on the SPARQL surface plus a JSON-LD twin; all three fail without the demotion.
  • fix(query): match untranslated overlay flakes on normalized Sids — split into its own commit. The untranslated (@vector) post-filter re-derived raw s_sid/p_sid off self.pattern, so an uncompressed term compared unequal against every novelty flake and silently dropped the whole lane, while a Ref::Iri skipped the filter and made it over-inclusive. Latent and independent of the perf work; reviewable and revertable on its own.
  • collect_segment_merged_ops sizes merged_ops in one allocation rather than growing through ~log2(N) realloc-and-memcpy rounds.
  • A read-only probe (examples/bounded_overlay_probe.rs) that isolates scan cost from write-path cost.
  • A delete_where_growth_slope lane in it_transact_growth_slope.rs. This is an end-to-end gate, not an attribution tool, and the PR's numbers deliberately do not come from it: a whole DELETE transaction also pays commit-write, fsync, novelty-apply and dedup, each with its own novelty-linear term, so it cannot attribute a change to the scan. That is why the read-only probe exists.

Gates

  • cargo check --workspace --all-targets (excluding the two search crates, which fail on this box from an unrelated local C++/usearch toolchain issue)
  • cargo clippy --all-targets --no-deps -D warnings on fluree-db-query and fluree-db-api
  • cargo test -p fluree-db-query — 1431 + 60 across 8 binaries, 0 failed
  • cargo test -p fluree-db-api --features native — 2253 passed, 0 failed, 40 binaries
  • cargo fmt --all --check clean, run last

Re-measured clean (2026-08-31) — replacing the contaminated table above

The original numbers were taken on a box concurrently running a write benchmark, with a bias that ran one way (every "before" run inside a contended window, every "after" in a gap). Re-run on a dedicated c7i.4xlarge (AL2023), interleaved 5+5 end-to-end and 3+3 span runs, load 0.5–1.0 throughout, baseline = this PR's merge-base plus only the probe example cherry-picked, so both arms run a byte-identical probe against different engine code.

The mean/p50 improvement did not reproduce, and the sign is wrong. The body previously claimed −39% mean / −32% p50; clean measurement gives +1.4% and +2.8%, and the p50 run-ranges don't overlap (base 4970–5090 µs vs 5160–5220 µs), so that small regression is real rather than noise. End-to-end is flat: 594.6 → 600.0 µs per 1k novelty flakes, ranges overlapping. A methodology check worth stating: the baseline slope reproduces the original run's 594.3 to within 0.05%, so the harness matches — only the "after" side had been flattered.

What is real is the tail, and it behaves exactly like an O(novelty) term being removed. Per-round operator_open max, base→PR, as novelty grows:

novelty (flakes) 14.4k 15.7k 16.9k 18.1k 19.3k 20.5k 21.7k
Δ max +4.0% +6.9% +4.5% −8.1% −17.3% −22.1% −25.7%

There is a small fixed cost and a growing benefit, crossing over around 17–18k flakes — and the probe's whole sweep (13k–21.7k) sits at the very bottom of that curve. Sustained-write deployments, which is what #1722 is about, run orders of magnitude past it. The post-reindex cold open goes 1570 µs → 93.6 µs (−94%). And overlay_translate measures 0.906 µs p50 against the ~0.6 µs originally claimed — same order, claim stands.

One flag for reviewers, since it explains the flat middle: operator_open grows ~340 µs per 1k novelty flakes on both arms (3372 µs at 14.4k → 5862 µs at 21.7k, essentially identical). A novelty-linear term of that size survives inside operator_open and is not the translation this PR removes — consistent with #1731's planner-stats walk, though I couldn't attribute it further without more spans. That is why the typical case barely moves while only the tail improves.

Honest summary of what this PR buys, then: it removes an unbounded worst case (measurably, and increasingly with novelty), it makes cold opens ~15× cheaper, it kills an unbounded per-execution memo, and it adds the first spans binary_scan.rs has ever had — which is what made #1731 findable. It does not improve typical-case latency at small novelty, and costs ~2.8% p50 there.

Raw data: 5+5 end-to-end runs, 3+3 span traces, and computed aggregates archived locally; happy to attach any of it.


Round 2 (2026-09-02): the refinement, and the measurement that settles it

Rather than defer the warm-cache-first idea from the review discussion, it's implemented — along with what attribution revealed while building it. Head f6edf08ca; this round also merges current main (135 commits, one trivial test-file conflict) and incorporates the t-pin test extension pushed to this branch directly.

Attribution first: the +2.8% p50 from round 1 was never this PR's code. Splitting the span logs by population: only 529 of 1,600 opens took the binary-scan path at all — and the PR makes those dramatically better (mean 173 → 18 µs; the baseline's 12.4 ms worst open is the once-per-epoch whole-novelty build, the PR's worst is 0.35 ms). The entire p50 delta lived in the other 1,071 opens, which ran against unindexed db_t=0 views — fluree.db() serves index-less views for ~1 s after each commit while re-adoption completes — taking a pre-existing O(novelty) range fallback that executes zero lines this PR touches. (That adoption lag is its own production-relevant finding, filed separately.)

What landed: (1) warm-cache-first — a bounded open probes the per-execution memo and global_translation_cache for a warm whole product before seeking; hit → the historical windowed path; miss → seek; the probe never builds. Key construction is single-sourced so probe and build can't diverge. (2) A guard floor (BOUNDED_WALK_GUARD_MIN_MATCHED = 256): the selectivity guard and its O(segments) denominator run only after a walk already matched ≥256 ops — under churn the novelty reached 328 segments, so this prevents a per-open O(328) sum on every one of 4,800 opens. (3) A churn mode for the probe. All mutation-verified (wrong-product-on-warm-hit and inverted-floor mutants redden their tests; two vacuity traps found and fixed with positive ran-markers).

Read-burst arm — p50 parity achieved, and the mean flipped to a large win. On a dedicated c7i.4xlarge, all arms interleaved, baseline = merge-base + probe only:

novelty base e2e mean PR e2e mean Δ
14.4k 53.2 µs 39.7 µs −25.5%
16.9k 73.6 µs 45.3 µs −38.5%
19.3k 94.3 µs 51.4 µs −45.5%
21.7k 124.7 µs 67.0 µs −46.3%

Bands disjoint in every row; the win grows with novelty; no crossover remains. e2e p50: 10.0 vs 10.0 µs — exact parity at every novelty level, and the range-path population is byte-identical across arms. Why round 1 looked flat: main's recently-merged stats work collapsed the probe's absolute scale ~80× (base last-round e2e 10,080 → 125 µs), unmasking the scan term this PR removes.

Neuter discriminator (same binary, bounded walk env-gated): gate-off ≡ PR within ±0.7%, gate-on ≡ base within ±1.0%, at every round — the delta is 100% behavioral, 0% layout. Consistency check: the gate-on arm's overlay_translate shows cache_hit=false exactly 8 epochs × 3 runs = 24 times — one whole build per epoch, as theory demands.

Churn arm — the #1722 target case, first clean measurement (a write every 5 queries; epoch churns under the read stream; segments up to 328):

metric base PR Δ
operator_open mean 47.0 µs 20.0 µs −57%
operator_open p90 173 µs 34 µs −80%
operator_open max 1,780 µs 152 µs −91%
e2e mean @12.5k novelty 748.4 µs 696.3 µs −7.0% (bands disjoint)

The base's shape is exactly the pathology: four of five queries hit the epoch cache, every fifth pays an O(novelty) whole rebuild. The PR is flat ~17 µs per open with no tail. Honest trade: the churn median is +2–5 µs absolute (every query seeks where the base's median query was a cache hit) — bought back many times over at p90/max. The novelty-linear tail that remains (~260–290 µs per 1k flakes) is identical on both arms and sits in fresh-epoch stats assembly outside the scan — evidence posted to #1731.

Raw data (44 files, three arms) and the analyzer are archived; happy to attach.

Refs #1722, #1731

aaj3f added 5 commits August 27, 2026 17:42
…all novelty

Opening any scan with an overlay present translated the WHOLE graph's
novelty to `OverlayOp`, sorted it and lifecycle-resolved it, and only then
applied the pattern's bound term via `overlay_window_for_range` — a binary
search over an array that cost O(novelty) to build.

Both memo layers miss under sustained writes: `Novelty::apply_commit` bumps
`epoch` on every commit and `to_t` advances with it, and both appear in the
per-execution key and in `GlobalTranslationKey`. So every staging WHERE and
every query against head paid one full O(accumulated-novelty) build.

A bound subject (or, failing that, a bound predicate) now brackets the walk
itself: `bounded_overlay_walk` builds the leading-term range and
`translate_overlay_flakes_in_range` seeks it through `Segment::range`'s two
`partition_point` probes plus the `may_overlap` zone-map skip —
O(log novelty + matched) rather than O(novelty). The product is memoized per
`(epoch, graph, index, OverlayWalkScope)` so a VALUES probe over K subjects
pays K seeks, not one whole-overlay build.

Correctness rests on the window holding COMPLETE fact-key groups, since it is
built before `resolve_overlay_ops` runs. Every op sharing a `FactKeyV3` shares
both its subject and its predicate, and `cmp_spot`/`cmp_psot` lead with those
terms, so a leading-term bracket can never split an assertion from the
retraction that cancels it. Only one term is pinned; everything trailing spans
its full range, keeping the window a superset of the pattern's matches with the
cursor's own filters as the backstop.

A bound OBJECT is deliberately NOT used to narrow. Object identity in the
bracket is `FlakeValue` equality, which is not the cross-type numeric equality
the scan filter applies, so an object-narrowed window could omit a novelty
retraction for a base row the cursor still emits. The wildcard path is
untouched and still builds the whole-overlay product.

Measured on the read-only probe added later in this series: `operator_open`
mean 1902us -> 1153us, and `overlay_translate` itself falls to a ~0.6us p50
seek. End-to-end query latency is NOT materially improved — a second,
larger O(novelty) term dominates (see #1731).

Also here:
- `collect_segment_merged_ops` sizes `merged_ops` in one allocation instead of
  growing through ~log2(N) realloc-and-memcpy rounds.
- An `overlay_translate` debug span records bounded/cache_hit/segments/ops_len.
  `binary_scan.rs` had no tracing spans at all, which is why this cost stayed
  invisible inside `where_exec` — and the span is what made #1731 findable.

Refs #1722, #1731
The `untranslated` post-filter — the lane that carries overlay flakes V3
cannot represent, notably `@vector` — re-derived its own `s_sid`/`p_sid`
straight off `self.pattern`:

    let s_sid = match &self.pattern.s { Ref::Sid(s) => Some(s.clone()), _ => None };

Novelty flakes carry Sids in the snapshot's COMPRESSED form. A pattern term
can arrive uncompressed (`Sid(EMPTY, "http://example.org/s")`), and a
`Ref::Iri` produced `None` outright. In the uncompressed case every
comparison against a novelty flake was unequal, so the filter silently
dropped the entire untranslated lane and the query returned no `@vector`
rows; in the `Ref::Iri` case the filter was skipped and the lane was
over-inclusive instead.

`open()` already computes correctly normalized `s_sid`/`p_sid` a few hundred
lines above, via `extract_bound_terms_snapshot`, whose own comment says it
re-encodes "so that uncompressed Sids ... are normalized to the compressed
form matching novelty flakes". Use those, and drop the shadowing locals.

Latent and independent of the bounded-overlay change it was found next to;
split out so it can be reviewed and reverted on its own.

Refs #1722
…s off

`overlay_segments` allocates a Vec sized by segment count, and the span
recorded it on every cache miss — including the bounded path, which is now a
seek that touches a handful of flakes. Instrumentation must not be a
meaningful share of the thing it measures, so gate the call on
`Span::is_disabled()`.

Also satisfies clippy 1.97 (`manual_is_multiple_of`,
`semicolon_if_nothing_returned`) in the new unit tests.

Refs #1722
…cost

`delete_where_growth_slope` times a whole DELETE transaction, so commit write,
fsync, novelty apply and dedup — each with its own novelty-linear term — sit on
top of the scan and mask any change to it. This probe issues read-only queries
against a ledger whose novelty grows between rounds, so the scan is the only
thing varying, and it prints the `overlay_translate` / `operator_open` spans
that attribute the cost.

It is also what showed the bounded-overlay fix is real but currently masked:
`operator_open` mean drops 1902us -> 1153us and `overlay_translate` falls to a
~0.6us p50 seek, while end-to-end latency barely moves because
`query_prepare:plan` rebuilds the planner stats view through
`assemble_fast_stats`'s full `iter_flakes(Post)` novelty walk, behind an
epoch-keyed cache that misses on every commit.

Refs #1722

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

Approving. Three inline items to look at before merge — the first is the one I'd want resolved, the other two may turn out to be non-issues.

Verified the premise structurally on main rather than from the description: open() really does build the whole-graph product (translate_overlay_flakes_with_untranslated / collect_segment_merged_ops), sort, and resolve_overlay_ops before overlay_window_for_range narrows it — the bound term is used one step too late. And both memo layers really do miss under writes: GlobalTranslationKey carries overlay_epoch + to_t, and Novelty::apply_commit does self.epoch += 1 (fluree-db-novelty/src/lib.rs:861, "Bump epoch once per commit").

Also checked, since they're the places this kind of change goes wrong:

  • sort_overlay_ops(&mut ops, order) runs after the range walk, so seeking in SPOT/PSOT while the cursor wants POST/OPST is handled.
  • No .await inside the translate_span.enter() scope. Worth stating explicitly — this is the file's first-ever span and open() is async, and CLAUDE.md calls a guard held across .await the root cause of a past trace-corruption bug.
  • Adding OverlayWalkScope to the memo key is necessary rather than cosmetic: without it a narrow bounded product could be served to a whole-overlay consumer, which is a stale-row bug.

On the measurement box: no argument from me, and the overlay_translate p50 is the right thing to rest on. Only ask is to finish the clean re-measure or drop the headline table before merge, so the contaminated figures don't get quoted later from the merged description.

u64,
GraphId,
IndexType,
crate::binary_scan::OverlayWalkScope,

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.

Adding scope to the key is necessary, but it changes the memo's growth from O(1) to O(distinct probed subjects) per execution, with no eviction.

OverlayWalkScope::Subject(Sid) is per-subject, this is a plain FxHashMap built per ExecutionContext and shared across same-overlay derivations, and nested-loop joins reopen the inner scan per outer row. So a join probing 100k subjects accumulates 100k entries — an owned Sid plus an Arc<TranslatedOverlayOps> each — held for the whole execution. Previously the key was bounded by a handful of entries no matter how many rows probed.

The PR's own instrumentation is the argument against caching the bounded scopes at all: the quoted trace line is overlay_translate{bounded=true cache_hit=false …} at 0.6 µs p50. The bounded path is sub-microsecond on a miss, so the memo buys roughly a microsecond on a duplicate probe and costs unbounded memory to do it. Either skip the memo for Subject/Predicate scopes and keep it for Whole, or cap the map.

This is the item I'd want settled before merge, since it's introduced here.

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.

Removed entirely for the bounded scopes (31a25a403) — Whole keeps both memo layers, Subject/Predicate are no longer cached at all, and the now-dead scope field came out of BoundedOverlayWalk with it. Your argument was the decisive one and it was our own instrumentation making it: the bounded path is sub-microsecond on a miss, so a memo buys ~a microsecond and pays unbounded memory for it. Confirmed the growth was reachable rather than theoretical, too — join.rs:1494/1516 builds a fresh right scan and re-opens per outer row against the same ExecutionContext, so a 100k-subject probe really would have accumulated 100k owned Sid + Arc entries with no eviction. That one's squarely on us: we added an unbounded map to a hot execution structure without thinking about join cardinality, in a PR whose whole premise is bounding unbounded work.

The clean re-measure (details in the body) puts a number on the remaining cost: overlay_translate is 0.906 µs p50 on a dedicated box, so there was nothing worth caching.

Comment thread fluree-db-query/src/binary_scan.rs Outdated
///
/// A bound OBJECT is deliberately NOT used to narrow, even on OPST. Object
/// identity here is `FlakeValue` equality, which is not the cross-type
/// numeric equality the scan filter applies (`Long(5)` and `Double(5.0)` are

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 rationale doesn't hold on the facts. Long(5) and Double(5.0) are not distinct under FlakeValue:

// value.rs:757 — PartialEq
if self.is_numeric() && other.is_numeric() {
    return self.numeric_cmp(other) == Some(Ordering::Equal);
}

and Ord::cmp routes both-numeric through numeric_cmp too, with an explicit comment — "'number is a number': equal values are equal regardless of numeric type."

The decision to leave the object out is still safe (a wider window is never unsound), so nothing here is broken. But this comment is what the next person attempting an object-narrowed window will read, and it points them away from the real question. If there is a genuine obstacle it's the dt tie-breaker inside an equal-value run, which is a different and more tractable problem than cross-type numeric equality.

Worth either correcting the reason or, if the object bracket turns out to be constructible, revisiting whether it's worth taking.

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.

You're right, and the comment was actively misleading. Verified first-hand: value.rs PartialEq routes both-numeric through numeric_cmp, and Ord::cmp does too with the "a number is a number" comment — so Long(5) and Double(5.0) are not distinct, and our stated reason for excluding the object was false. Comment rewritten (31a25a403) to name the real obstacle.

Since you asked whether it's constructible: I think yes in principle, no at the standard this code should meet. The genuine blocker is cmp_object's tie-break (comparator.rs:139 — value first, then dt), so a correct object bracket has to pin the value and span the whole dt range, which does capture every numeric representation provided equal values form one contiguous comparator run. That premise breaks on NaN: numeric_cmp returns None and the comparator falls back to a discriminant ordering, so the run-contiguity guarantee the bracket rests on isn't unconditional. There's a second unproven step too — that filter-match is a subset of comparator-equal-run — which the leading-term brackets get for free from cmp_spot/cmp_psot leading with s/p. Neither is obviously unfixable; both would need the same property-test treatment the subject/predicate brackets got before I'd trust an object-narrowed window against base rows. Left as a documented obstacle rather than a hand-wave.

Comment thread fluree-db-query/src/binary_scan.rs Outdated
}
let entry = if let Some(walk) = bounded.as_ref() {
// Bounded path. The cross-query `global_translation_cache`
// is deliberately skipped: its key has no scope dimension,

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.

Skipping the cross-query cache reads as clearly right for a bound subject. Less obviously so for a bound predicate, which is the fallback when no subject is bound and is not necessarily selective.

?s <hot_predicate> ?o against a large novelty window takes the bounded path, matches a large fraction of novelty, and now pays an uncached translate per execution — where the old path hit global_translation_cache. Under sustained writes the epoch churns and that cache missed anyway, so nothing is lost there. But a read-heavy window between commits — stable epoch — is exactly the case the old cache was earning its keep in.

May well be a non-issue if the predicate bracket rarely matches much. Worth a measurement, or a selectivity guard that falls back to the whole-graph cached path when the matched set is a large share of the window.

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.

Verified and acted on — this was the sharpest of the three, because the regression you predicted is exactly what the clean re-measure found, though not only for the reason you gave.

The guard is in (31a25a403): after a bounded walk, if the matched set exceeds BOUNDED_WALK_MAX_MATCH_PERCENT (25%) of the graph's novelty window, the bounded product is discarded and we take the whole-graph cached path — restoring global_translation_cache amortization precisely where it was earning its keep, and costing nothing under epoch churn where that cache missed anyway. The denominator comes from a new OverlayProvider::overlay_flake_count (O(segments), None by default so a provider that can't count cheaply just disables the guard). It's observable as overlay_translate{fallback=true}, and two integration tests pin it: an unselective predicate falls back, a selective predicate and a bound subject stay bounded, with results asserted identical either way.

What the clean measurement then showed is that the stable-epoch cost is broader than the unselective-predicate case: on a read-burst workload the baseline builds the whole-graph product once per epoch and serves ~200 queries from cache, while we seek per query — so operator_open p50 comes out +2.8% (non-overlapping ranges). The tail moves the other way and increasingly so with novelty (−25.7% at 21.7k flakes, crossover ~17–18k), which is the shape you'd want, but the median cost at small novelty is real.

That suggests a refinement neither of us has proposed yet: consult global_translation_cache before choosing to bound, and if a whole-graph product for this (epoch, g_id, index) is already warm, just use it — a hit is cheaper than a seek, and a warm cache is by definition the case where bounding has nothing to win. Cold or churning epochs keep the seek. That's strictly dominant over either path alone and it should erase the p50 regression while keeping the tail win. Happy to fold it in here rather than defer it — say the word and it goes in this PR.

aaj3f added 2 commits August 28, 2026 16:18
… brackets

Review remediation for the two open items on the bounded-translation PR.

1. Bounded (subject-/predicate-bracketed) products no longer enter the
   per-execution TranslatedOverlayCache. The memo key's OverlayWalkScope made
   its growth O(distinct probed subjects) per execution with no eviction:
   nested-loop joins open a fresh right scan per left row against the same
   ExecutionContext, each binding a different subject and thus a new
   Subject(Sid) key. The PR's own instrumentation shows the bounded walk at
   ~0.6us p50 ON A MISS, so the memo bought ~a microsecond per duplicate
   probe and paid unbounded memory for it. Whole-graph products stay memoized
   (their build is O(novelty) and reuse is real); the scope stays in the key
   as a type-level guard against a future bounded insert aliasing the whole
   product, and the dead scope field comes off BoundedOverlayWalk.

2. Selectivity guard (BOUNDED_WALK_MAX_MATCH_PERCENT = 25): a bracketed walk
   matching more than a quarter of the graph's novelty window discards the
   bounded product and takes the whole-graph cached path. An unselective hot
   predicate paid an uncached O(novelty) translate per execution where the
   old path amortized it across executions via global_translation_cache in
   read-heavy windows at a stable epoch; the fallback restores exactly that
   amortization, and under epoch churn the cross-query cache missed anyway.
   The denominator is a new O(segments) OverlayProvider::overlay_flake_count
   (None disables the guard; delegating overlays forward it). The guard is
   observable as overlay_translate{fallback=true} and covered by two
   integration tests (unselective predicate falls back / selective predicate
   and subject stay bounded, identical results either way).

3. The bound-object bracket comment claimed FlakeValue equality diverges from
   the scan filter's cross-type numeric equality; that is wrong (both Ord and
   PartialEq route both-numeric comparisons through numeric_cmp - 'a number
   is a number'). Rewritten to the real obstacles: the dt tie-break inside an
   equal-value run (solvable by pinning the value across the full dt range)
   and the total-order corners (NaN) plus filter/comparator equivalence a
   safety proof would still owe.
The tracing guide's new-instrumentation checklist requires every added span
to appear in the telemetry span hierarchy and carry acceptance coverage in
it_tracing_spans.rs. overlay_translate (added earlier in this series) now:

- sits in docs/operations/telemetry.md's query span tree under
  operator_open, with its fields (bounded / fallback / cache_hit / segments
  / ops_len) documented, and in the Tier-1 span list
- has two acceptance tests: emits at DEBUG with the bounded field plus the
  deferred cache_hit/ops_len fields on a novelty-backed binary scan, and is
  zero-noise at INFO
@aaj3f

aaj3f commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @bplatz — all three landed, and the first one was the right thing to block on.

The memo (context.rs:209). You're right, and your reading of the instrumentation is the argument that settles it: the bounded walk is ~0.6 µs p50 on a miss, so memoizing it bought about a microsecond per duplicate probe and paid unbounded memory for it. Bounded products no longer enter the per-execution cache at all — a nested-loop join reopening the inner scan per outer row binds a fresh Subject(Sid) every time, which is exactly the O(distinct probed subjects) growth you described. Whole-graph products stay memoized, since their build really is O(novelty) and the reuse is real. The scope stays in the key even though bounded entries never land there — as a type-level guard against a future bounded insert aliasing the whole product, which was the stale-row hazard you flagged as the reason the key needed it in the first place. The now-dead scope field came off BoundedOverlayWalk.

The bound-object comment (binary_scan.rs:1648). You're right and the comment was wrong: both Ord and PartialEq route both-numeric comparisons through numeric_cmp — "a number is a number" — so Long(5) and Double(5.0) are not distinct under FlakeValue. (For what it's worth that relation has now been verified independently a couple of times in adjacent work, including the NaN corner, so it's well established.) Rewritten to the obstacles that actually stand: the dt tie-break inside an equal-value run — which looks solvable by pinning the value across the full dt range — plus the total-order corners around NaN and the filter/comparator equivalence a safety proof would still owe. Your instinct that the object bracket is more tractable than the old comment implied looks right; the rewrite says so rather than steering the next person away from it.

The bound-predicate cache (binary_scan.rs:2427). Not a non-issue — your read of it was correct. There's now a selectivity guard: a bracketed walk matching more than BOUNDED_WALK_MAX_MATCH_PERCENT = 25 of the graph's novelty window discards the bounded product and takes the whole-graph cached path, restoring exactly the amortization you were worried about losing in a read-heavy window at a stable epoch (and under epoch churn the cross-query cache was missing anyway, as you noted). The denominator is a new O(segments) OverlayProvider::overlay_flake_count — None disables the guard, and delegating overlays forward it. It's observable as overlay_translate{fallback=true}, with integration tests both directions: an unselective predicate falls back, a selective predicate and a bound subject stay bounded, identical results either way.

On the headline table — I've done something between your two options and I'd rather flag it than have you find it. Rather than dropping the numbers or re-measuring on a box I don't trust yet, the operator_open rows now live inside the measurement-conditions box rather than as a standalone table, so they can't be lifted out of the merged description without the paragraph explaining why they aren't a claim. What §1 rests on is now just the load-independent part — the 0.6 µs p50 / 1.75 µs warm seek, which is what you said was the right thing to rest on. The clean re-measure is still pending and still tied to the #1731 stats fix, since measuring the scan term alone doesn't settle anything while the larger term dominates. If you'd rather the rows were simply gone, say so and I'll cut them — I kept them only because the contamination analysis is itself worth preserving.

@aaj3f

aaj3f commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

Three items addressed, plus a clean re-measure that I'd rather lead with because it contradicts this PR's own headline numbers.

The measurement first. You asked for clean numbers or no table. Re-ran on a dedicated c7i.4xlarge, interleaved arms, load 0.5–1.0, baseline = merge-base + only the probe cherry-picked. The mean/p50 win did not reproduce and the sign is wrong — the body claimed −39%/−32%, the truth is +1.4%/+2.8%, with non-overlapping p50 ranges so the small regression is real. End-to-end is flat. The baseline slope reproduces the original run's to within 0.05%, so the harness was fine; only the "after" side had been flattered by the contended window. The body now carries the corrected table and the full story.

What survives is the tail, and it behaves exactly like an O(novelty) term coming out: Δmax goes +4.0% → −25.7% as novelty grows 14.4k → 21.7k flakes, crossing over around 17–18k — and the probe's entire sweep sits at the bottom of that curve, whereas the sustained-write case #1722 is about runs orders of magnitude past it. Cold opens go 1570 µs → 93.6 µs. overlay_translate measures 0.906 µs p50 against the ~0.6 µs claimed.

One finding for you, since it explains the flat middle: operator_open grows ~340 µs per 1k novelty flakes on both arms, essentially identically. A novelty-linear term that size survives inside operator_open and is not the translation this PR removes — consistent with #1731's planner-stats walk. Worth knowing before anyone reads the flat median as "bounding doesn't help."

On your three inline items: the bounded-scope memo is gone entirely (your instrumentation argument was unanswerable, and the growth was reachable via nested-loop reopens — that one was a genuine own-goal in a PR about bounding unbounded work); the FlakeValue comment was factually wrong as you said and now names the real obstacle, with an assessment of whether an object bracket is constructible; and the selectivity guard is in. The last thread also carries a refinement your predicate concern pointed at — checking whether a whole-graph product is already warm before choosing to bound — which should erase the p50 regression while keeping the tail win. I'd rather fold that in here than defer it; tell me if you agree and it lands in this PR.

…translation

# Conflicts:
#	fluree-db-api/tests/it_tracing_spans.rs
A bounded open now probes the per-execution memo and the cross-query
global_translation_cache for a warm WHOLE-graph product at
(epoch, g_id, index) before seeking. On a hit it takes the historical
windowed-cached-product path — a warm cache is by definition the case
where bounding has nothing left to win — and on a miss it seeks; the
probe never builds a whole product. This restores cross-query
amortization on read-heavy stable-epoch windows while keeping the seek
under sustained writes. The cross-query key is now built by a single
closure shared by the probe and the build path, so the two cannot
disagree on a key dimension.

The selectivity guard gains an absolute floor
(BOUNDED_WALK_GUARD_MIN_MATCHED = 256): below it a bounded product is
trivially cheap to rebuild regardless of window share, so the guard —
and its O(segments) overlay_flake_count denominator — is skipped
entirely, keeping the denominator amortized against matched work
instead of being a fixed per-open tax on selective seeks.

Tests: a warm-first differential (cold-seek rows == warm-served rows,
byte-identical), positive span ran-markers on every step (an unindexed
post-commit view diverts to the range fallback and would otherwise pass
vacuously), epoch-discipline coverage, and a below-floor unselective
bracket pinned to stay bounded. Mutations: a wrong product served on a
warm hit reddens the differential; an inverted floor reddens both guard
tests.
PROBE_WRITE_EVERY=K commits one untimed write every K queries INSIDE a
round, so the overlay epoch and to_t move under the read stream and
every translation-cache layer misses — the sustained-write shape
#1722 targets, which the read-only rounds never exercised.

Churn mode reads through views built directly off the transacting
ledger lineage (re-seeded from the cached handle once it has adopted
the reindexed store): the cached handle re-adopts a persisted index
asynchronously after each commit, so under per-few-queries commits
fluree.db() would return unindexed views almost always, divert every
scan to the range fallback, and measure nothing. Verified by span
capture: every churn-mode query emits overlay_translate{bounded=true}
against an indexed (db_t > 0) view. The default (0) keeps rounds
byte-for-byte identical to the historical read-only probe.
The cached handle re-adopts a persisted index asynchronously after a
commit; under parallel-test load fluree.db() can return an unindexed
(snapshot.t == 0) view that diverts to the range fallback, emits no
overlay_translate span, and fails the guard/selectivity span pins
spuriously (observed once in a full-suite run). Route the three
span-pinned tests through the indexed_view poller; results-only tests
are path-agnostic and stay as they were.
detect_partitioned_group_by assumes the single scan emits rows grouped by
the GROUP BY key (comparator-adjacent). Current-mode scans honor that, but
BinaryHistoryScanOperator::collect_history_flakes emits the event stream in
collection order — persisted sidecar + base rows per leaflet, then novelty
appended — so one subject's events are not adjacent once any part of the
range is served from a published index. The adjacency-based partitioned
streaming-aggregate lane then emits one group per key run:
GROUP BY ?person COUNT(*) returned [(alice,1),(alice,1),(bob,1),(bob,1)]
instead of [(alice,2),(bob,2)].

The stock rdf_star_history_group_by_count test only caught this when the
FlureeBuilder::file background indexer (reindex_min_bytes = 100, i.e. every
commit) won the race against the query — which it did on the merged-head CI
run and not before. The defect itself predates this branch: with a
deterministically published index the same split reproduces on main and on
the pre-merge head.

Demote the hint inside apply_solution_modifiers, next to its consumer, so
no caller can reintroduce the unsound combination; history grouping takes
the hash-based lane. Current-mode plans keep the partitioned fast path
unchanged.

New coverage pins the two deterministic index states (range fully
index-served; published index plus trailing novelty — the bounded-overlay
translation shape) on the SPARQL surface, plus a JSON-LD twin, asserting
both the pre-aggregation event rows and the grouped counts. All three fail
without the one-line demotion.
@aaj3f

aaj3f commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Round 2 is in — the PR body carries the full write-up, but the short version belongs on this thread since it resolves the two things left open here.

The warm-cache-first refinement from the selectivity-guard discussion is implemented rather than deferred (plus a guard floor that keeps the O(segments) denominator off the per-open path until a walk has matched ≥256 ops — under churn novelty hit 328 segments, so that floor is load-bearing). And re-measured on a dedicated box, three arms interleaved, with a same-binary env-gated "neuter" arm as the layout-vs-behavior discriminator:

Branch head f6edf08ca also merges current main (135 commits, one trivial test conflict) and includes the t-pin quantification extension pushed to the branch directly. Full suites, clippy -D warnings, workspace check, fmt all green; CI running on the merged head.

@aaj3f
aaj3f merged commit 663ece8 into main Sep 2, 2026
14 checks passed
@aaj3f
aaj3f deleted the perf/bounded-overlay-translation branch September 2, 2026 14:22
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