Skip to content

MOD-19332 perf(numeric): go through the child query only once per batch - #11561

Closed
ThierryBerger wants to merge 10 commits into
thierry-14948-child-drivenfrom
thierry-14948-child_advance_once
Closed

ThierryBerger wants to merge 10 commits into
thierry-14948-child-drivenfrom
thierry-14948-child_advance_once

Conversation

@ThierryBerger

@ThierryBerger ThierryBerger commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Go through child only once per batch rather than intersecting it after storing it in a Vec.

Benchmark parent (µs) single pass (µs) Δ
filtered n10k k10 12.3 12.0 −2.6%
filtered n10k k100 29.2 27.9 −4.6%
filtered n100k k10 29.7 28.8 −3.1%
filtered n100k k100 35.1 35.2 +0.3%
unfiltered n10k k10 11.0 11.0 −0.1%
unfiltered n10k k100 19.6 19.4 −0.7%
unfiltered n100k k10 24.5 23.7 −3.2%¹
unfiltered n100k k100 36.4 34.0 −6.6%¹
selectivity 1% 168.4 152.7 −9.3%
selectivity 10% 36.1 34.9 −3.4%
selectivity 50% 54.0 48.1 −10.9%
expensive child 1% 240.6 175.2 −27.2%
expensive child 10% 91.8 81.5 −11.2%
expensive child 50% 166.5 131.1 −21.3%
bounded unfiltered k10 51.9 51.7 −0.3%
bounded unfiltered k1000 151.1 160.5 +6.2%²
bounded filtered k100 66.7 64.8 −2.8%
bounded single-value excluded 668.1 666.2 −0.3%

¹ This revision doesn't change the unfiltered path. The parent's run drifted +3–7% on these rows, so the "gain" is that run's noise.
² This is noise, not a regression. A targeted re-run gave 151.0 / 154.1 µs for single pass against 151.7 / 151.1 µs for the parent.

Mark if applicable

  • This PR introduces API changes
  • This PR introduces serialization changes

Release Notes

  • This PR requires release notes
  • This PR does not require release notes

If a release note is required (bug fix / new feature / enhancement), describe the user impact of this PR in the title.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 076c026153

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +334 to +338
Some(score) => {
if keep(child_doc, score) {
child.accept(child_doc, score);
}
child.next()?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Deduplicate repeated child IDs before accepting a match

When the filter child can yield duplicate IDs (the GeoShape iterator explicitly permits this in src/redisearch_rs/rqe_iterators/src/geo_shape.rs:92-94), this advances only the child while leaving the range cursor on the same document, so every duplicate is accepted into the heap. For example, with descending scores {1: 10, 2: 9}, k=2, and a GEOSHAPE child [1, 1, 2], the two copies of doc 1 fill the heap and doc 2 is rejected, producing a duplicate result and omitting a matching document; the previous batch intersection advanced the numeric batch after a match and did not do this. Skip duplicate child IDs or advance/mark the matched range record before accepting another occurrence.

Useful? React with 👍 / 👎.

@ThierryBerger ThierryBerger mentioned this pull request Sep 25, 2026
1 of 4 tasks
@codecov

codecov Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.98214% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.54%. Comparing base (0db2d72) to head (8b306ba).

Files with missing lines Patch % Lines
...arch_rs/numeric_score_source/src/range_iterator.rs 96.98% 0 Missing and 5 partials ⚠️
...c/redisearch_rs/numeric_score_source/src/source.rs 92.85% 1 Missing and 1 partial ⚠️
src/redisearch_rs/top_k/src/iterator.rs 92.85% 2 Missing ⚠️
Additional details and impacted files
@@                      Coverage Diff                       @@
##           thierry-14948-child-driven   #11561      +/-   ##
==============================================================
+ Coverage                       83.52%   83.54%   +0.02%     
==============================================================
  Files                             668      668              
  Lines                           86374    86519     +145     
  Branches                        40566    40711     +145     
==============================================================
+ Hits                            72141    72284     +143     
- Misses                          13849    13853       +4     
+ Partials                          384      382       -2     
Flag Coverage Δ
flow 84.58% <ø> (-0.01%) ⬇️
unit 58.94% <95.98%> (+0.06%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ThierryBerger
ThierryBerger force-pushed the thierry-14948-child-driven branch from 2013887 to c61fbb9 Compare September 28, 2026 08:00
@ThierryBerger
ThierryBerger force-pushed the thierry-14948-child_advance_once branch from 076c026 to efbbe18 Compare September 28, 2026 08:00
@ThierryBerger
ThierryBerger force-pushed the thierry-14948-child-driven branch from c61fbb9 to bd64749 Compare September 28, 2026 08:16
@ThierryBerger
ThierryBerger force-pushed the thierry-14948-child_advance_once branch from efbbe18 to c39a0c6 Compare September 28, 2026 08:16
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child_advance_once branch from c39a0c6 to fbca9bf Compare September 28, 2026 12:32
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child-driven branch 2 times, most recently from 0dfca4d to e8a0917 Compare September 29, 2026 07:37
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child_advance_once branch from fbca9bf to 0bbb21c Compare September 29, 2026 07:37
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child_advance_once branch from 0bbb21c to 92bbaaf Compare September 30, 2026 08:02
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child-driven branch 2 times, most recently from 0301ff4 to 9cee5c5 Compare October 1, 2026 07:26
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child_advance_once branch from 92bbaaf to 3542f35 Compare October 1, 2026 07:26
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child-driven branch from 9cee5c5 to 7f5d0fc Compare October 5, 2026 09:38
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child_advance_once branch from 3542f35 to 3eb3350 Compare October 5, 2026 09:38
@sonarqubecloud

sonarqubecloud Bot commented Oct 5, 2026

Copy link
Copy Markdown

@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child-driven branch from 7f5d0fc to d2ab63d Compare October 5, 2026 11:06
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child_advance_once branch from 3eb3350 to 99adf41 Compare October 5, 2026 11:06
@JonasKruckenberg JonasKruckenberg changed the title perf(numeric): go through the child query only once per batch MOD-19332 perf(numeric): go through the child query only once per batch Oct 5, 2026
GuyAv46 and others added 3 commits October 5, 2026 14:27
…ailures" (#11776)

Revert "[CI] Do not block PRs and the merge queue on Codecov upload failures …"

This reverts commit 9962c27.
)

* query: borrow a parser-owned token node for rewriting

Add QueryNodeMut::token_node_mut, which admits exactly the QN_TOKEN nodes
token_mut declines, and extend QueryNodeMut::new with the invariant covering
the tokens tag evaluation rewrites in place. The query evaluation entry points
now pass that invariant on to their callers.

The tag evaluation tests now build every token with the Redis module
allocator, as the parser does, rather than only the one whose lowercased form
outgrows its buffer: on a case-insensitive field the new invariant requires
it, since lowercasing may free and replace the buffer. The separate
RedisToken child variant is therefore gone.

* rs_token: normalize a tag token in place

Add RSTokenMut::normalize_tag, wrapping tag_strtolower to remove query
escapes and optionally lowercase a tag token.

* rs_token: normalize a tag token in Rust

Normalizing a tag token takes two steps, now each in string_utils:
tag::unescape removes the query escapes, and unicode::tolower_bytes
lowercases the result exactly as the C unicode_tolower does, malformed
UTF-8 included, so query tag values keep matching what indexing
lowercased. tolower_bytes builds on new libnu::nu_utf8_decode and
nu_utf8_encode models of the lax C codec. Property tests compare the
codec, tolower_bytes, and the two steps together against the C
functions on arbitrary input, through new strconv.h test wrappers for
nu_utf8_read and nu_utf8_write.

The one deliberate difference: C removes escapes only up to an interior
NUL yet shortens the length by the escapes it removed, garbling the bytes
after it; unescape keeps them verbatim.

RSTokenMut::normalize_tag now runs the two steps instead of the C
tag_strtolower, writing the result back in place when it fits the
token's buffer and replacing the buffer only when lowercasing makes it
longer.

tag::strtolower, which had no callers outside its tests, is gone; its
tests now cover the two steps.
…ffi and tag_index (#11618)

* trie_rs: share the pattern-filtered lending iterator

Move the runtime-selected prefix/contains/suffix/wildcard lending iterator
out of triemap_ffi into trie_rs as PatternLendingIter, built through
TrieMap::pattern_lending_iter, so Rust callers can walk a trie by pattern
without going through the TrieMapIterator C ABI.

The suffix filter now carries its pattern instead of a boxed closure.

* tag_index: walk tag values with the shared pattern iterator

Replace the crate's own copy of the mode-dispatching lending iterator with
trie_rs's PatternLendingIter, and re-export PatternMode as IterMode so the
crate's API is unchanged.
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child-driven branch from d2ab63d to af1eafa Compare October 5, 2026 11:47
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child_advance_once branch 2 times, most recently from 58b05fe to 8b306ba Compare October 5, 2026 12:02
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child-driven branch from af1eafa to 0db2d72 Compare October 5, 2026 12:02
eyalrund and others added 7 commits October 5, 2026 12:05
…unexpected key (#11636)

* Add tests for loading legacy byte offsets from an RDB

Build a legacy (encver 16) index spec RDB file in the test and start the
server from it. One test checks that byte offsets which exactly fill
their blob load and upgrade. The other gives the offsets a length prefix
larger than the blob, which must fail the load with a diagnostic rather
than crash the server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fail legacy RDB loads with truncated byte offsets

LoadByteOffsets trusted the counts and lengths in the serialized blob,
so a blob shorter than its own length prefix made it read past the end
of the buffer, after allocating as much as the prefix claimed. Check
each read against the bytes remaining and return NULL when the blob is
short. DocTable_LegacyRdbLoad, its only caller, now logs and fails the
load in that case.

Failing the load also needs the legacy spec's cleanup to be safe:
IndexSpec_LegacyRdbLoad never initialized the spec's IndexError, so
freeing the spec on any load error hit an assertion (debug) or a NULL
dereference (release). Initialize it when the spec is created, and
clear it before the legacy upgrade reinitializes the stats.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add test for loading a deleted legacy doc flagged with a payload

Build a legacy (encver 16) index spec RDB file in the test and start the
server from it. Its only document is deleted and flagged as having a
payload; the load must drop it and upgrade the index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fix crash loading a deleted legacy doc flagged with a payload

DocTable_LegacyRdbLoad does not load the payload of a deleted document,
but it left Document_HasPayload set on it. Freeing the dropped document
then dereferenced its NULL payload in DMD_Free and crashed the server
during the RDB load. Clear the flag when the payload is not loaded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Test loading a deleted legacy doc flagged with a payload at encver 13

Encver 13 is the only encoding that saved the payload of a deleted doc,
so its load has to skip that string as well as clear the payload flag.
Parameterize the legacy spec fixture by encoding version and cover it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add test for loading a legacy index whose fields have no path

Encodings older than 8 store a field's name but no path. Build an
encver 7 index spec RDB file with one TEXT field, start the server from
it, and check that the upgraded index reports and serves the field, also
after saving it in the current format and reloading.

Store the fixture's legacy spec under idx:<name>, the key the upgrade
deletes, instead of a plain name the upgrade left behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fix crash loading a legacy index whose fields have no path

FieldSpec_RdbLoadCompat8, the loader for encodings older than 8, set a
field's name but left its path NULL. Everywhere else a field without a
separate path uses its name as the path, and IndexSpec_BuildSpecCache
relies on that: it duplicates the path whenever it is not the name,
so a NULL path crashed the server during the RDB load. Set the path to
the name when loading these fields.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Add test for a legacy index spec stored under an unexpected key

Store an encver 16 index spec under a key other than idx:<name> in the
RDB file the server starts from. The load must fail with a diagnostic
rather than leave the key behind for a later save to crash on. The
fixture writer takes the key to store the spec under.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Refuse a legacy index spec that is not stored under its index key

The legacy upgrade deletes each spec's key by the name it was saved
under, idx:<name> in db 0. A spec loaded from any other key, or from
another db, was upgraded but its key stayed in the keyspace, holding the
legacy load result rather than an IndexSpec. Saving that key, on the
next SAVE, BGSAVE or DUMP, handed it to IndexSpec_RdbSave_Wrapper and
crashed the server. Fail such a load instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Fix leak of field names loaded from legacy encodings

FieldSpec_RdbLoadCompat8 read each field name into an allocated buffer
and passed it to NewHiddenString with takeOwnership set, which copies
the buffer rather than adopting it, so the loaded buffer leaked.
FieldSpec_RdbLoad hands the buffer over instead (takeOwnership false),
and FieldSpec_Cleanup frees it; do the same. The leak became reachable
once loading these fields stopped crashing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…11760)

* Add regression test for unrepresentable date-function timestamps

Covers timefmt and the eight date extraction/rounding functions with
timestamps that fit in time_t but overflow struct tm's year, and with
values outside time_t (2^63, inf, nan), both shard-side and
coordinator-side.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Check timestamp range and gmtime_r result in date functions

hour, day, dayofmonth, dayofweek, dayofyear, year, month and monthofyear
ignored gmtime_r failure and returned values built from the partially
written struct tm. All nine date functions, timefmt included, also cast
the double argument to time_t without a range check, which is undefined
behavior for NaN, infinity and values >= 2^63.

Convert through a helper that rejects values outside time_t before the
cast and fails when gmtime_r fails. Such inputs now yield null, the
existing result for invalid input.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
* Expose the RSValue number conversion as Value::to_number

`RSValue_ToNumber` and the comparison code each carried a copy of the
conversion (follow references and trios, parse strings with `str_to_float`).
It is now `Value::to_number`, which both use, so Rust callers can convert
without going through the C ABI.

`to_number` is `#[inline]`: `RSValue_ToNumber` converts every arithmetic
operand of `APPLY`/`FILTER`, and without the hint the extracted call made an
APPLY-heavy aggregation about 4% slower in a release build.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Port the COUNT, SUM, AVG, MIN and MAX reducers to Rust

The per-group logic of the five numeric reducers moves from `count.c`,
`sum.c` and `minmax.c` to the `reducers` crate. As with COLLECT, C keeps
the argument parsing (`RDCR*_New`) and calls a Rust constructor, and the
per-group states live in a `bumpalo` arena owned by the reducer instead
of the C block allocator.

The three reducers share one shape, a per-group state folded row by row,
which is the new `Accumulator` trait. `AccumulatorReducer` runs one, and
`reducers_ffi` wires a single set of generic vtable callbacks for all of
them, so the unsafe glue exists once. The states must not need dropping,
which `AccumulatorReducer::new` checks at compile time, so the vtable sets no
`FreeInstance`. A test drives the vtable with interleaved groups, so Miri
covers the glue.

Behavior is unchanged: numbers are converted as `RSValue_ToNumber` does,
empty groups give NaN for SUM/AVG and infinities for MIN/MAX, and MIN/MAX keep
the comparisons of C's `MIN`/`MAX` macros, including how they treat NaN.
`reducerId` is now 0 for all five (MIN and MAX used to set their own ids), and
`Reducer.srckey` is left unset; nothing reads either.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Use an enum for the SUM and AVG reducer mode

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…ys (#11641)

c_wrapper: wrap C fat arrays in owned and borrowed types

Add the fat_array crate with FatArray, which owns a C fat array, and
FatArrayRef, which borrows one for a lifetime, both exposing the
elements as a slice.

Dropping a FatArray drops each element, then frees the storage with
array_free, even if an element's destructor panics. Debug builds check
that the array's element size and alignment match T, which requires
binding array_hdr_t.
…lue field against C

Every group queried the whole field, so no range ever passed the filter
only in part. The bounded group queries the middle of the field and a
single-value range the filter excludes; the C shim now takes the filter
bounds so both sides run the same query.

No group indexed a multivalue field either, so the full read that keeps a
document on its best value went unmeasured. The multivalue group gives
every document two values in different ranges.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
TopKIterator now hands its child to the source through a narrow
ChildCursor view before each filtered batch. The default
next_batch_with_child ignores it, so behavior is unchanged; sources that
can seek their own reader build on it to skip records the intersection
would discard. NumericScoreSource's stale-entry filtering moves into
drop_stale so such an override can share it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…itself

The filtered source walks the child against the batch's ranges in merged
doc-id order and hands each match straight to the top-k heap, instead of
leapfrogging every range separately into a batch that TopKIterator then
intersects with the child again. The child is rewound and walked once per
batch, and nothing is materialized. A multivalue field keeps the full
read, the only one that can coalesce a doc onto its best value.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@JonasKruckenberg
JonasKruckenberg force-pushed the thierry-14948-child_advance_once branch from 8b306ba to 8f635e1 Compare October 6, 2026 10:54
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-06T11:01:43.239909Z 8f635e1 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@sonarqubecloud

sonarqubecloud Bot commented Oct 6, 2026

Copy link
Copy Markdown

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants