Skip to content

fix(query): top-k sorts size their buffers from what they hold - #2098

Merged
aaj3f merged 2 commits into
mainfrom
fix/topk-buffer-capacity
Oct 14, 2026
Merged

aaj3f merged 2 commits into
mainfrom
fix/topk-buffer-capacity

Conversation

@aaj3f

@aaj3f aaj3f commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

ORDER BY with a LIMIT keeps the best LIMIT + OFFSET rows in a bounded buffer, on the generic plan, on several fast paths, and in the Iceberg scan's top-k. Each buffer now reserves at most 4,096 entries up front and grows as rows arrive, so a large LIMIT or OFFSET only costs the rows there actually are. One function, fluree_db_core::topk::initial_capacity, sizes all of them.

The grouped-count top-k fast path (?s <p> ?o, grouped by ?o, ordered by the count descending, with a LIMIT) now applies OFFSET too: it keeps the best LIMIT + OFFSET groups and skips OFFSET of them, as the generic plan does. It used to return the first LIMIT groups whatever the OFFSET was.

And in SPARQL, a LIMIT or OFFSET above 9223372036854775807 is now reported as "LIMIT is too large: the largest supported value is 9223372036854775807" rather than "expected integer after LIMIT". Values up to that parse exactly as before.

Changes

  • fluree-db-core: topk::initial_capacity(k): k + 1, at most 4,096. It lives in core so that fluree-db-query and fluree-db-iceberg share it. It is used by:
    • the ORDER BY sort's top-k heap;
    • the POST-order DESC scan's result buffers (both lanes);
    • the grouped-count top-k heap;
    • the vector top-k (replacing its own cap, same value);
    • BM25's top-k heap;
    • the Iceberg scan's top-k bound (TopKBound), whose k is the query's LIMIT + OFFSET handed down through set_topk.
  • fluree-db-query:
    • The grouped-count top-k is planned with LIMIT + OFFSET under an OffsetOperator.
    • The POST-order scan's planning estimate adds OFFSET and LIMIT saturating.
  • fluree-db-sparql: the LIMIT / OFFSET message for an integer beyond i64::MAX.

Tests

  • it_topk_large_limit_offset (own test binary; it toggles the fast-path kill switch).
    • Cases: SPARQL and JSON-LD SELECT, plus SPARQL CONSTRUCT, with LIMIT or OFFSET of 9223372036854775807 and of 2^62. Also a grouped count with a small and a large OFFSET on both surfaces, and a LIMIT 2 OFFSET 1 control.
    • Coverage: each case runs with fast paths on and off, on an indexed ledger and on one with novelty over its index.
    • Routing: the POST-order scan and the grouped-count top-k are stamped as proceeding, so a case can't pass on the generic plan alone.
  • it_iceberg_local_fs::order_by_with_a_limit_beyond_the_table_answers_its_rows: ORDER BY DESC(?score) LIMIT 9223372036854775807, with and without OFFSET 1, on SPARQL and JSON-LD, against the committed local Iceberg fixture.
  • scan::topk::tests::large_k_starts_at_the_capped_capacity (fluree-db-iceberg) and topk::tests (fluree-db-core).
  • test_limit_offset_beyond_the_largest_value (fluree-db-sparql parser).

Reverting any one of the five sites (the three buffers, the grouped-count OFFSET, the message) fails its test. Putting the Iceberg bound back to k.saturating_add(1) fails both Iceberg tests.

Performance

For LIMIT + OFFSET below 4,096, every buffer reserves exactly what it did. Above that, a buffer starts at 4,096 and grows by doubling, so it reallocates about log2(k / 4096) times, and only if that many rows arrive. The Iceberg bound never holds more than k values, and in practice no more than the non-null sort values it reads. Not benchmarked.

Gates

At the head, 657aec5:

  • cargo fmt --all --check is clean.
  • clippy -D warnings --all-targets --no-deps over fluree-db-core, fluree-db-query, fluree-db-iceberg and fluree-db-api with --all-features: clean. With default features, fluree-db-core, fluree-db-query and fluree-db-api are clean; fluree-db-iceberg alone has one dead_code warning on env_switch_enabled, which is on main and only used under its aws feature.
  • CI's two wasm32 clippy lints (engine and parse) are clean.
  • Tests, all passing:
    • lib tests: fluree-db-core 807, fluree-db-query 1,667, fluree-db-iceberg 291 (332 with aws);
    • fluree-db-api: it_topk_large_limit_offset, it_iceberg_local_fs (9) and it_iceberg_policy's top-k test.

At c966669, before the Iceberg change, these also passed: fluree-db-sparql (689), fluree-db-api's query, SPARQL-query, misc and graph-source groups plus the fast-path binaries (1,614 in all), fluree-db-server (704), and the W3C SPARQL suite (36 of 36 groups).

Not run: the other fluree-db-api groups, the CLI suite, the workspace --all-features test run (CI's) and benchmarks.

Persisted data

None. Query planning and execution only.

A buffer that keeps the best `LIMIT + OFFSET` rows now reserves at most
4096 entries up front and grows as rows arrive, so a `LIMIT` or `OFFSET`
beyond the rows there are costs only the rows there are. One function,
`sort::topk_initial_capacity`, sizes each of them: the `ORDER BY` sort,
the POST-order `DESC` scan, the grouped-count top-k, the vector top-k and
BM25's top-k.

The grouped-count top-k (`GROUP BY ?o ... ORDER BY DESC(COUNT) LIMIT`)
applies `OFFSET`: it keeps the best `LIMIT + OFFSET` groups and skips
`OFFSET` of them, as the generic plan does.

The POST-order scan's planning estimate adds `OFFSET` and `LIMIT`
saturating.

SPARQL: a `LIMIT` or `OFFSET` above 9223372036854775807 is reported as
too large rather than as a missing integer.
@aaj3f aaj3f added bug Something isn't working as expected area:query Query execution, planning, fast paths, overlay, result formatting labels Oct 12, 2026
@aaj3f
aaj3f requested a review from bplatz October 12, 2026 13:44

@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, but please review the inline comment before merging: the Iceberg top-k heap is one more buffer this doesn't reach yet.

What I checked locally: reverting the grouped-count OFFSET change fails exactly the fast-lane grouped-count cases that use an OFFSET, on both ledgers, and CI's log shows both new tests ran. Elsewhere, no unchecked LIMIT + OFFSET sums remain, and the Bolt, R2RML aggregate and SQL-lane buffers are bounded by the rows they hold or by batch size.

Comment thread fluree-db-query/src/sort.rs Outdated
Comment on lines +31 to +37
/// Initial capacity for a buffer that keeps the best `k` rows, plus the one a
/// full buffer takes in before it evicts. `k` comes from a query's `LIMIT`
/// and `OFFSET`, which may far exceed the rows there are, so the buffer
/// starts at most [`TOPK_INITIAL_CAPACITY`] and grows as rows arrive.
pub(crate) fn topk_initial_capacity(k: usize) -> usize {
k.saturating_add(1).min(TOPK_INITIAL_CAPACITY)
}

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.

One more top-k buffer doesn't go through this yet: the Iceberg scan's TopKBound::new still reserves k.saturating_add(1) with no cap (topk.rs#L113). Its k is the query's LIMIT + OFFSET: operator.set_topk(ordering, k) (operator_tree.rs#L3989) pushes it into the R2RML operator, which passes it to TopKBound::new(tk.k, tk.ascending) (r2rml.rs#L4159). So ORDER BY DESC(?x) LIMIT 9223372036854775807 on an Iceberg-backed graph source still reaches it. In a scratch test, TopKBound::new(i64::MAX as usize, false) panics with capacity overflow. I traced the query path in code but didn't run it end to end.

fluree-db-iceberg doesn't depend on fluree-db-query, so this needs the helper moved somewhere both can reach, such as fluree-db-core, or a matching cap in the Iceberg crate. Until then, the description's "one function sizes all of them" isn't quite true.

@aaj3f aaj3f Oct 14, 2026 •

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.

Good catch, I missed that the Iceberg scan keeps its own heap. In 657aec5 the function moved to fluree_db_core::topk::initial_capacity, since fluree-db-core is the crate both fluree-db-query and fluree-db-iceberg already depend on, and TopKBound::new now sizes its heap with it like the other five. sort::topk_initial_capacity is gone rather than kept as a second name, so there's one definition. There's a unit test that TopKBound::new(i64::MAX as usize, false) starts at the cap, and an end-to-end one in it_iceberg_local_fs that runs ORDER BY DESC(?score) LIMIT 9223372036854775807 (with and without OFFSET 1, SPARQL and JSON-LD) against the committed fixture, so the path through set_topk → the R2RML operator → TopKBound is now run, not just traced. Putting k.saturating_add(1) back fails both.

I also grepped the workspace for other with_capacity / reserve sized from a LIMIT, OFFSET or k, and didn't find any others. The commit export's page is capped at 500, Bolt's PULL takes at most the rows it holds, a Cypher bounded path is capped at 16 hops, the SQL lane's output buffers are sized by batch, and nothing in fluree-db-r2rml or fluree-db-sql reserves from a limit.

The scan-side top-k bound on an Iceberg graph source keeps the best
`LIMIT + OFFSET` sort values, and reserved that many entries up front.
It now starts at the same capped capacity as the other top-k buffers and
grows as values arrive.

The sizing function moves to `fluree_db_core::topk::initial_capacity`,
which both `fluree-db-query` and `fluree-db-iceberg` reach, so one
function sizes all six buffers: the `ORDER BY` sort, the POST-order
`DESC` scan, the grouped-count top-k, the vector top-k, BM25's top-k and
the Iceberg scan's bound.
@aaj3f

aaj3f commented Oct 14, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for tracing the R2RML path, I'd only looked inside fluree-db-query. The Iceberg heap now goes through the same function, which lives in fluree-db-core, so "one function sizes all of them" holds now, and the description lists it as the sixth buffer.

@aaj3f
aaj3f merged commit c57793a into main Oct 14, 2026
26 of 27 checks passed
@aaj3f
aaj3f deleted the fix/topk-buffer-capacity branch October 14, 2026 13:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:query Query execution, planning, fast paths, overlay, result formatting bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants