Skip to content

MOD-15893 - Nrange new command - #2052

Merged
TalBarYakar merged 17 commits into
masterfrom
tal.ba/feat/RANGEX
Jun 11, 2026
Merged

TalBarYakar merged 17 commits into
masterfrom
tal.ba/feat/RANGEX

Conversation

@TalBarYakar

@TalBarYakar TalBarYakar commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Note

Medium Risk
New public read commands on the hot range/aggregation path with multi-key merge semantics and cluster slot rules; behavior is heavily tested but aggregator parsing and NaN gap semantics are easy to get wrong for clients.

Overview
Adds TS.NRANGE and TS.NREVRANGE (since 8.10.0): multi-key range queries that return rows [timestamp, [value per key…]], with NaN where a key has no sample at that timestamp. They reuse TS.RANGE/TS.REVRANGE options (filters, COUNT, LATEST, aggregation, etc.) but take numkeys plus an explicit key list instead of label filters.

Implementation wires TSDB_generic_nrange: validates numkeys (including overflow-safe arity checks), optionally rewrites space-separated per-key aggregators into the comma form parseRangeArguments expects, opens one iterator per key, and ReplySeriesNRange k-way merges sample streams. parseRangeArguments now scans options only from fromTimestamp onward so key names cannot be mistaken for option tokens. Cluster routing uses a keynum key-spec on both commands (cross-slot keys rejected).

Metadata is updated in commands.json and ts_info.c; flow tests cross-check results against per-key TS.RANGE/TS.REVRANGE merges and cover cluster CROSSSLOT.

Reviewed by Cursor Bugbot for commit 81b75bb. Bugbot is set up for automated code reviews on this repo. Configure here.

@TalBarYakar
TalBarYakar requested a review from gabsow June 4, 2026 07:06
@TalBarYakar TalBarYakar self-assigned this Jun 4, 2026

@gabsow gabsow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review — TS.RANGEX / TS.REVRANGEX

Technically: approve. The streaming k-way merge, resource handling (keys / iterators / aggregation classes), count semantics, and test coverage (incl. the per-key TS.RANGE cross-check + fuzz suites) all hold up — details inline.

Process: please hold for confirmation. The linked ticket MOD-15893 is a research task and its parent epic MOD-15727 ("Group multiple series by timestamp") is still To Do, yet this PR adds a permanent public command with cluster routing deferred. I'd get explicit team sign-off on scope + the deferred cluster key-spec before merging to public master. See the note on the command registration.

Comment thread src/module.c Outdated
// (after numkeys), so they are not declared as a fixed key range here. Per-key
// ACLs are enforced at runtime by GetSeries(GetSeriesFlags_CheckForAcls); a
// proper keynum key-spec for cluster routing is a follow-up.
if (RedisModule_CreateCommand(ctx, "ts.rangex", TSDB_rangex, "readonly", 0, 0, -1) ==

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Scope / process — please confirm before merging. This registers a new public command, but the linked ticket MOD-15893 is a research ("reserch") task and the parent epic MOD-15727 is still To Do. A new public command is a permanent API commitment (command names, the pivoted RESP shape, NaN semantics, the numkeys grammar) that should be locked at the epic/design level first.

Also, cluster routing is deferred: registered with key-spec 0, 0, -1 (no declared keys), so it won't route in cluster and cross-slot keys aren't rejected by Redis (runtime per-key ACL via GetSeries(CheckForAcls) still applies). For a multi-key command this is significant.

Suggestion: land behind the epic with an explicit experimental / standalone-only note + a follow-up story for a numkeys-based key-spec, or hold on a branch until MOD-15727 is greenlit.

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.

done , setRangexKeySpec added

Comment thread src/module.c

long long numKeys;
if (RedisModule_StringToLongLong(argv[1], &numKeys) != REDISMODULE_OK || numKeys <= 0) {
RTS_ReplyGeneralError(ctx, "TSDB: numkeys must be a positive integer");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Validation looks good (numKeys > 0, plus the arity check argc < 2 + numKeys + 2 just below). Minor / defense-in-depth: numKeys has no upper bound beyond argc, so it's already bounded by request size — a sanity cap would be optional hardening, not required.

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.

Agree — numKeys is bounded by argc via the arity check, so it can't exceed request size. A hard cap (e.g. reject numkeys > N) would be optional hardening / nicer error messaging only, not a correctness or safety fix. Fine to leave as-is.

Comment thread src/module.c
int rv = REDISMODULE_ERR;
size_t opened = 0;

for (; opened < (size_t)numKeys; opened++) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Verified clean: on every GetSeries failure path the key is either never opened (ACL failure returns before OpenKey) or CloseKeyd internally (empty / WRONGTYPE), and *key is never set. Combined with the calloc'd keys[] and the 0..opened-1 cleanup loop, there's no key leak and no double-close. 👍

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.

No leak, no double-close, no NULL-deref.

Comment thread src/module.c

iters = malloc(numKeys * sizeof(AbstractSampleIterator *));
for (size_t i = 0; i < (size_t)numKeys; i++) {
RangeArgs perKey = rangeArgs; // shares filters; classes is read-only here

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Aggregation wiring is correct: broadcast (numClasses == 1) selects &classes[0] for every key, per-key (== numKeys) selects &classes[i], and each per-key iterator sees exactly one class. rangeArgs.aggregationArgs.classes is freed once in cleanup, after ReplySeriesRangeX returns — and since the iterators pointing into it are closed inside the reply first, there's no use-after-free. 👍

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.

none needed

Comment thread src/reply.c
size_t num_keys,
long long count,
bool reverse) {
const long long limit = (count < 0) ? LLONG_MAX : count;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

count semantics are consistent with the existing ReplySeriesRange (which uses if (args->count != -1)): default -1 → LLONG_MAX (unlimited), COUNT 0 → empty. 👍

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.

no action needed

Comment thread src/reply.c
const long long limit = (count < 0) ? LLONG_MAX : count;

// Streaming k-way merge: hold only one "front" sample per key at a time.
Sample *front = malloc(num_keys * sizeof(*front));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

These bare mallocs route through rmutil/alloc.h to RedisModule_Alloc (abort-on-OOM), so the absence of NULL checks is consistent with the codebase convention. Same for iters[i] not being NULL-checked later — SeriesCreateSampleIterator is treated as non-NULL elsewhere (tsdb.c). No change required; noting for completeness.

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.

no action needed

Comment thread src/reply.c
long long emitted = 0;
while (active_count > 0 && emitted < limit) {
// Next output timestamp: smallest front (largest when reverse).
// Linear over the fronts; a heap could replace it if num_keys grows large.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The merge is O(rows × num_keys) due to the linear front scan — fine for typical key counts, and the comment already flags a heap as the alternative if num_keys grows large. No action needed.

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.

no action needed

Comment thread src/reply.c
RedisModule_ReplySetArrayLength(ctx, emitted);

for (size_t i = 0; i < num_keys; i++) {
iters[i]->Close(iters[i]);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Good — all iterators are Closed here and front / active / row are freed; the caller only frees the iters array (not the iterators themselves), so ownership is clean with no double-free.

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.

no action needed

@gabsow

gabsow commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

move to XRange

@gabsow

gabsow commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

unheppy flow (negative flow tests ) , make sure we are not leaking

@gabsow gabsow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Code review for the TS.RANGEX / TS.REVRANGEX work. Core algorithm and memory handling look sound, and the cross-check + fuzz tests are strong (they pass cleanly under valgrind — the valgrind CI red is in Redis-core replication.c, unrelated to this PR).

Main items, detailed inline:

  • 🔴 Spec decisions needed: command naming (RANGEX vs ticket's XRANGE) and aggregator syntax (comma- vs space-separated).
  • 🔴 No cluster test coverage despite shipping the keynum key-spec; commands.json/COMMAND DOCS metadata missing.
  • 🟠 numkeys overflow → NULL-deref crash (reachable DoS).
  • 🟠 CI reds: clang-format (make format) and 29 SonarCloud security hotspots to triage.
  • 🟡 NaN present-vs-missing ambiguity (document); LATEST untested.

Comment thread src/module.c Outdated
}

// cmd + numkeys + numKeys keys + fromTimestamp + toTimestamp
if ((long long)argc < 2 + numKeys + 2) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Integer overflow → NULL-deref crash (reachable DoS).

numKeys is user-controlled. For values near LLONG_MAX, 2 + numKeys + 2 is signed overflow (UB); in practice it wraps negative, this guard passes, then calloc(numKeys, …) below returns NULL and the open loop dereferences it. e.g. TS.RANGEX 9223372036854775807 {tag}:k - + against an existing key crashes the shard.

Compare against the known argc bound instead (can't overflow, and keeps the WrongArity behavior test_rangex_errors already expects):

Suggested change
if ((long long)argc < 2 + numKeys + 2) {
if (numKeys > (long long)argc - 4) {

(cmd + numkeys + from + to = 4 non-key args). This also makes numKeys <= argc, so the subsequent allocations can't realistically fail.

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.

done

Comment thread src/module.c Outdated

const size_t numClasses = rangeArgs.aggregationArgs.numClasses;
if (numClasses != 0 && numClasses != 1 && numClasses != (size_t)numKeys) {
RTS_ReplyGeneralError(ctx,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

clang-format violation here (module.c:627:35) is failing the linter / spellcheck CI job. Please run make format.

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.

done

Comment thread src/module.c Outdated
// Like TS.RANGE but over an explicit list of same-slot keys, returning results
// pivoted by timestamp: one row [timestamp, [value-per-key...]] in key order,
// NaN where a key has no sample at that timestamp. With AGGREGATION, the number
// of (comma-separated) aggregators must be 1 (broadcast) or equal to numkeys

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Aggregation syntax deviates from the ticket — needs product sign-off.

RED-149232 specifies space-separated aggregators (AGGREGATION start max min end sum 10000), but this reuses the RED-132360 parser, so the actual syntax is a single comma-separated token (AGGREGATION start,max,min,end,sum 10000). The comma form is internally consistent with the existing multi-aggregator feature, but it differs from the approved spec — please confirm which is intended before this ships (public API).

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 wrong , the comma is for multi agg only
@LiorKogan do you really think multi agg is needed ?

Comment thread src/module.c Outdated
// TS.RANGEX / TS.REVRANGEX: keys are explicit but at variable positions (after
// numkeys), so they can't use the fixed first/last/step args; a keynum key-spec
// is attached below via setRangexKeySpec for cluster routing.
if (RedisModule_CreateCommand(ctx, "ts.rangex", TSDB_rangex, "readonly", 0, 0, -1) ==

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Command naming deviates from the ticket — needs product/docs sign-off.

RED-149232 and issue #1677 specify TS.XRANGE / TS.XREVRANGE; this ships TS.RANGEX / TS.REVRANGEX. RANGEX arguably avoids confusion with Redis Streams' XRANGE, so it may be the better choice — but it's permanent public API and diverges from the approved spec, so it needs an explicit decision.

Also: these two commands aren't added to commands.json (all 18 existing commands are there), and setRangexKeySpec sets only arity + key-specs — no summary/since/complexity/args — so COMMAND DOCS TS.RANGEX returns nothing. Please add the catalog entries + doc metadata.

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.

rename to NRANGE , the command added to command.json and ts_info

Comment thread src/reply.c Outdated
if (!active[i]) {
continue;
}
if (!found || (reverse ? (front[i].timestamp > target) : (front[i].timestamp < target))) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

clang-format violation here (reply.c:283:26) is failing the linter / spellcheck CI job (line exceeds the column limit). Please run make format.

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.

done

Comment thread src/reply.c
active_count--;
}
} else {
row[i] = NAN;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

NaN ambiguity worth documenting. A key that legitimately has a sample with value NaN at target produces the same NaN cell as a key with no sample at target — the two are indistinguishable to the client. Fine for OHLCV, but should be called out as a known limitation in the command docs. (The fuzzer injects real NaN values and still passes only because the comparison normalizes both sides to NAN, so it doesn't surface the ambiguity.)

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.

Applied — comment added documenting the intentional missing-vs-real-NaN conflation

Comment thread tests/flow/test_ts_rangex.py Outdated
# must produce exactly that pivot.
#
# All keys share a hash tag so they live in the same slot (TS.RANGEX requires it).
# Cluster is skipped until the keynum key-spec lands.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This comment is now stale and the cluster path is untested. The keynum key-spec lands in this PR (setRangexKeySpec), yet every test still skipOnCluster()s — so the new cluster routing / cross-slot rejection ships with zero coverage. Since all tests already use a shared hash tag, dropping skipOnCluster() should route to a single shard and just work. At minimum, please add a test asserting cross-slot keys return CROSSSLOT.

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.

Updated the stale comment and added test_nrange_crossslot (cluster-only) asserting cross-slot keys return CROSSSLOT for both NRANGE/NREVRANGE — that's the only genuinely cluster-specific behavior since the commands are single-shard (no LibMR fan-out; once routed, execution == standalone). Kept the single-shard logic tests on skipOnCluster() rather than re-running standalone-equivalent code under cluster.



def _single_args(name, key, lo, hi, *, aggs=None, idx=0, bucket=None,
fbt=None, fbv=None, align=None, bts=None, empty=False, latest=False):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

latest is plumbed through all three helpers but no test ever passes latest=True (nor does the fuzzer set it). LATEST interacts with compaction source series, so please add at least one case exercising it.

Comment thread src/module.c Resolved
Comment thread src/module.c Outdated

const size_t numClasses = rangeArgs.aggregationArgs.numClasses;
if (numClasses != 0 && numClasses != 1 && numClasses != (size_t)numKeys) {
RTS_ReplyGeneralError(ctx, "TSDB: the number of aggregators must be 1 or equal to numkeys");

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.

Why? The number of aggregator/aggregators arguments should always match numkeys.

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.

0 means that no aggregators were requested. If aggregators are used, their count must match the number of specified keys.

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.

Why is 1 always valid as well?

# Same hash tag => same slot (TS.NRANGE requires it). Cluster skipped until the
# keynum key-spec lands.

AGGS = ['min', 'max', 'sum', 'avg', 'count', 'first', 'last', 'range',

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.

countNaN/countAll are missing. Is this intentional?

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 right , added

Comment thread commands.json Outdated
@@ -663,6 +663,238 @@
"since": "1.0.0",
"group": "timeseries"
},
"TS.NRANGE": {
"summary": "Query a range across multiple time series in forward direction, returning the results pivoted by timestamp (one value column per key)",
"complexity": "O(numkeys*(n/m+k)) where n = Number of data points, m = Chunk size (data points per chunk), k = Number of data points that are in the requested range",

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.

data points --> samples ?

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.

done

Comment thread commands.json Outdated
"name": "LATEST",
"type": "string",
"optional": true,
"since": "1.8.0"

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.

Should be removed?
(+ other places)

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.

done

Comment thread commands.json
"optional": true
},
{
"type": "string",

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.

Shouldn't it be multiple?

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.

done

@gabsow gabsow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-reviewed after today's updates — nice progress, most of my earlier comments are addressed:

  • ✅ Overflow/crash guard fixed (numKeys > (long long)argc - 4).
  • ✅ Renamed to TS.NRANGE / TS.NREVRANGE (off RANGEX; still a product call on the final name).
  • ✅ clang-format fixed; commands.json added; full COMMAND DOCS metadata added via ts_info.c.
  • ✅ setRangexKeySpec cleanly replaced by the centralized RegisterTSCommandInfos path (key-spec now part of TS_NRANGE_INFO/TS_NREVRANGE_INFO, with a null-check on GetCommand) — no duplicate registration.
  • ✅ Good new edge-case tests for all-NaN buckets (trailing / interior / no-early-truncation).

The ts_info.c command-info definitions look correct and thorough (key-spec, arity -5, nested arg blocks matching the option grammar, aggregators as a single comma-separated string consistent with the implementation).

One blocker remains: the new test_nrange_crossslot asserts the wrong exception type, which is what's reddening all the build jobs — fix inline below should turn them green. Plus the since version to confirm, and SonarCloud's hotspots still need a triage pass.

Comment thread tests/flow/test_ts_nrange.py Outdated
r.execute_command('TS.CREATE', 'cs{a}')
r.execute_command('TS.CREATE', 'cs{b}')
for cmd in ('TS.NRANGE', 'TS.NREVRANGE'):
with pytest.raises(redis.ResponseError, match='CROSSSLOT'):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is what's failing CI (make flow_tests Error 1, ~26 build/macOS jobs).

When keys span slots, redis-py's cluster client rejects the command client-side in determine_slot() and raises RedisClusterException: TS.NRANGE - all keys must map to the same key slot — it never reaches the server, so no CROSSSLOT ResponseError is ever produced. pytest.raises(redis.ResponseError) doesn't catch RedisClusterException → unhandled exception → fail.

(Good news: this actually proves the keynum key-spec works — the client correctly identified args 2 & 3 as keys and computed their slots.)

Accept either the client-side or a server-side rejection:

Suggested change
with pytest.raises(redis.ResponseError, match='CROSSSLOT'):
with pytest.raises((redis.ResponseError, redis.exceptions.RedisClusterException), match='CROSSSLOT|same key slot'):

(RedisClusterException's message contains "same key slot", the server's contains "CROSSSLOT", so the combined match covers both client versions.)

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.

done

Comment thread src/cmd_info/ts_info.c
"results pivoted by timestamp (one value column per key)",
.complexity = "O(numkeys*(n/m+k)) where n = Number of data points, m = Chunk size (data "
"points per chunk), k = Number of data points that are in the requested range",
.since = "8.10.0",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Confirm since = "8.10.0" matches the actual target release for these commands (both TS.NREVRANGE here and TS.NRANGE below use it). Everything else in this file is 1.0.0/1.4.0, so this is the one version string to double-check against the milestone.

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

@gabsow

gabsow commented Jun 9, 2026

Copy link
Copy Markdown
Collaborator

Did you created command info for this command ?

Comment thread tests/flow/test_ts_nrange.py Resolved

@gabsow gabsow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Status re-check on 1f67cd8: the cross-slot test fix landed (nrange suite is now 375/0) — nice. CI is still red, but it's narrowed to one stale test plus a behavior change to confirm (both inline). SonarCloud hotspots and the rebase (behind master) are still outstanding.

Comment thread tests/flow/test_ts_nrange.py Outdated
Comment on lines +208 to +209
res = r.execute_command('TS.NRANGE', len(keys), *keys, 0, 30,
'AGGREGATION', 'last', 10, 'EMPTY')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is what's now failing CI (4 failures × run-mode → flow_tests Error 1 across ~26 build/macOS jobs).

apply the changes tightened the aggregator rule to exactly numkeys aggregators (broadcast removed — see module.c), and the broadcast tests were renamed accordingly — but this one was missed: it still passes a single 'last' for 5 keys, so the server now (correctly) rejects it with TSDB: the number of aggregators must be equal to numkeys.

Pass one aggregator per key (the _pivot_ref_empty(..., 'last', ...) reference already applies last to every key, so it still matches):

Suggested change
res = r.execute_command('TS.NRANGE', len(keys), *keys, 0, 30,
'AGGREGATION', 'last', 10, 'EMPTY')
res = r.execute_command('TS.NRANGE', len(keys), *keys, 0, 30,
'AGGREGATION', ','.join(['last'] * len(keys)), 10, 'EMPTY')

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.

done

Comment thread src/module.c
}

const size_t numClasses = rangeArgs.aggregationArgs.numClasses;
if (numClasses != 0 && numClasses != (size_t)numKeys) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Heads-up that this commit removed single-aggregator broadcast — it's now exactly numkeys aggregators (was 1 || numkeys). That's a deliberate-looking API change (the broadcast tests were renamed to ..._rejected / ..._same_aggregator_per_key), but please confirm it's intended: the ticket's primary case is one-agg-per-key, yet "one aggregator for all keys" was a reasonable convenience. If it stays removed, make sure commands.json / COMMAND DOCS say "exactly numkeys aggregators" so the docs match the behavior.

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.

yes intended

@gabsow

gabsow commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator

Review status (head 2daa01d)

Thanks for the quick turnaround — the test_nrange_empty_matches fix is in (one aggregator per key), and the full CI matrix is re-running now. The previous run was down to just that one stale test, so the build/test jobs should come back green.

A few non-CI items still worth resolving before merge:

  • Broadcast aggregator removed — apply the changes made it exactly numkeys aggregators (was 1 || numkeys). That looks intentional (the broadcast tests were renamed to ..._rejected / ..._same_aggregator_per_key), but please confirm it's the desired API. If it stays, make sure commands.json / COMMAND DOCS state "exactly numkeys aggregators" so the docs match the behavior.
  • SonarCloud quality gate — still flagging security hotspots (largely the fuzzer's random usage); needs a triage/won't-fix pass to clear the gate.
  • Branch is behind master — will need a rebase/merge before it can land.
  • Final command name (TS.NRANGE / TS.NREVRANGE) — still a product call vs. the ticket's TS.XRANGE; just flagging it's permanent public API.

Will re-check once the matrix finishes.

@gabsow gabsow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

One remaining review nit — the NaN-column semantics are undocumented. Details + suggested wording inline. This is the last open code-side item; everything else we raised is addressed.

Comment thread src/reply.c
active_count--;
}
} else {
row[i] = NAN;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

NaN semantics should be documented (last open item from the review).

This NaN is the sentinel for "this key has no sample/bucket at target". But a key that legitimately holds a sample whose value is NaN produces the exact same cell, so from the client's side "missing" and "present-but-NaN" are indistinguishable. That's an acceptable trade-off (especially for OHLCV, where values aren't NaN), but it's currently undocumented — nothing in commands.json or the ts_info.c summary says what a NaN column means.

Please add a line to the command's reply/description, e.g.:

Each row is [timestamp, [value-per-key in input order]]. A value of NaN means the corresponding key has no sample (raw) or no data in the bucket (aggregation) at that timestamp; it is not distinguished from a stored NaN value.

(The since = "8.10.0" version in ts_info.c is also still worth confirming against the target release while you're in there.)

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

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 677764ae4024f018ae174ab800ff5d8fca977f23. Configure here.

Comment thread src/module.c
ctx, rangeStart, rewrittenArgv ? rewrittenArgv : argv, rangeArgc, &rangeArgs) !=
REDISMODULE_OK) {
goto cleanup;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Extra keys shift from/to

Medium Severity

TS.NRANGE only checks that numkeys is not greater than argc - 4, so a call can list more keys than numkeys while still passing arity. fromTimestamp and toTimestamp are then taken from the wrong argv slots (a spare key name instead of the real bounds), so the query runs against the wrong window without a clear arity error.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 677764ae4024f018ae174ab800ff5d8fca977f23. Configure here.

Comment thread tests/flow/test_ts_nrange_compare.py Resolved
@TalBarYakar TalBarYakar changed the title MOD-15893 - rangex new command MOD-15893 - Nangex new command Jun 10, 2026
@TalBarYakar TalBarYakar changed the title MOD-15893 - Nangex new command MOD-15893 - Nrange new command Jun 10, 2026
@TalBarYakar
TalBarYakar force-pushed the tal.ba/feat/RANGEX branch 2 times, most recently from 0812cc0 to 5f5660a Compare June 11, 2026 09:30

@gabsow gabsow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Two remaining code findings from a deeper pass on the space-separated-aggregator rewrite (inline). The new splice/rewrite itself checks out — index arithmetic and alloc/free pairing verified, no leaks/double-frees. I'm intentionally not flagging the unchecked malloc/calloc sites: those map to the aborting RedisModule_Alloc (no NULL to deref) and are all O(input size), so they're consistent with the rest of the module and not a real DoS — not worth churn unless you're moving everything to rts_try_alloc.

Comment thread src/module.c
goto cleanup;
}

if (parseRangeArguments(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Option keywords collide with user key names (medium).

parseRangeArguments and its helpers (parseLatestArg, parseCountArgument, parseFilterByValueArgument, parseFilterByTimestamp, parseAlignmentArgs) locate their options with RMUtil_ArgIndex scanning the entire argv from index 0. NRANGE puts user-controlled keys at argv[2 .. 1+numkeys], so a series key named exactly like an option (LATEST, COUNT, FILTER_BY_TS, FILTER_BY_VALUE, ALIGN, EMPTY, BUCKETTIMESTAMP) is matched as that option → silently wrong results or a confusing parse error. e.g.:

TS.NRANGE 2 LATEST somekey 0 100 AGGREGATION min 5000   # the "LATEST" *key* turns on LATEST mode
TS.NRANGE 2 COUNT k2 0 100 COUNT 10 AGGREGATION min 5000     # COUNT picks up the key, not the 10

You already guard against this for AGGREGATION (line 610 scopes the search to argv + rangeStart); the other options need the same treatment. Cleanest fix is to give parseRangeArguments an explicit options-start index and scope the sub-parsers to it; cheaper options are to reject keys whose name is an option token, or to document the limitation. It's pre-existing for single-key TS.RANGE, but NRANGE widens the exposure (many user-supplied key names).

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.

done

Comment thread src/reply.c
Comment on lines +291 to +294
// reported as NaN -- indistinguishable from a key that has a real sample
// whose value is NaN. This conflation is intentional (documented in the
// TS.NRANGE/TS.NREVRANGE command summary); disambiguating would require a
// separate null cell.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This comment references docs that don't exist yet (low). It says the NaN conflation is "documented in the TS.NRANGE/TS.NREVRANGE command summary", but the summaries in ts_info.c / commands.json only describe the pivot — they don't mention NaN or that "missing" is indistinguishable from a stored NaN. Either add that line to the summary or soften the comment (e.g. "intended behavior; see command docs"). The user-facing doc is being tracked separately on the initiative, but the in-code claim should be accurate.

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.

done

Option keywords were found by scanning all of argv, so a series key
named like an option (LATEST, COUNT, FILTER_BY_TS, ...) was parsed as
that option. Pre-existing for single-key TS.RANGE; TS.NRANGE widened it
with many user-named keys. Fixed by passing argv + start_index to the
option sub-parsers so keys before from/to are no longer scanned.
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
29 Security Hotspots
8.8% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@gabsow gabsow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approving — code LGTM.

Reviewed the implementation (multi-key pivot read, the space-separated→comma aggregator splice/rewrite, the streaming k-way merge, cluster key-spec, and command-info), plus an adversarial pass over the new parsing/memory code. All review findings I raised are addressed and I verified the fixes:

  • Aggregator-arity overflow guard, clang-format, commands.json + COMMAND DOCS metadata, cluster cross-slot test, the empty_matches syntax fix, and LATEST coverage.
  • The option-keyword/key-name collision is now fixed cleanly by scoping all option parsers to argv + start_index (a nice unified fix across the whole TS.RANGE family; verified no regression — existing RANGE/MRANGE tests pass).
  • NaN-conflation comment corrected.
  • The unchecked malloc/calloc sites are fine as-is (aborting allocator, input-proportional sizes — consistent with the module).

This is a code approval; it's still gated by branch protection on the remaining non-code items, which are not mine to clear:

  • SonarCloud security-hotspots gate (needs a triage/won't-fix pass).
  • In-flight linux-valgrind / macOS jobs should be green before merge.
  • Product/API sign-off on the permanent choices: command name TS.NRANGE/TS.NREVRANGE (vs the ticket's TS.XRANGE), space-separated one-aggregator-per-key (broadcast removed), and since = "8.10.0". (NaN semantics for the website are tracked on the initiative.)

@gabsow

gabsow commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator

Approved on my side, and the serious code items are resolved in 93bf090c (numKeys overflow guard, clang-format, aggregator-count validation, option parsing scoped past the key block). Flagging what's still blocking merge so nothing slips:

CI

  • 10 jobs still pending (6× macOS, valgrind, focal, alma9, azurelinux3) — let those go green.
  • SonarCloud Code Analysis is failing. Non-required, so it won't block the button, but please confirm it's just the new-code coverage gate and not a real finding.

Sign-offs needed before merge (decisions, not code)

  • Command naming: RED-149232 / Best way to store OHLCV data #1677 specify TS.XRANGE / TS.XREVRANGE; this ships TS.NRANGE / TS.NREVRANGE. Needs product/docs sign-off.
  • Scope: MOD-15893 is a research ticket, but this registers new public commands. Confirm that's intended.
  • since version: both commands declare 8.10.0 — confirm that matches the target release.
  • NaN semantics: a key with a real NaN sample is indistinguishable from a missing sample in the output. Worth documenting in commands.json for clients.

Nothing here is a code-quality objection — once CI is green and the naming/scope/version calls are confirmed, this is good to merge.

@TalBarYakar
TalBarYakar merged commit 0bb7e19 into master Jun 11, 2026
49 of 55 checks passed
@TalBarYakar
TalBarYakar deleted the tal.ba/feat/RANGEX branch June 11, 2026 13:48
YaacovHazan pushed a commit to redis/redis that referenced this pull request Jun 14, 2026
## Summary

Bumps the pinned `MODULE_VERSION` for **RedisTimeSeries** from `v8.8.0`
to `v8.9.80`. RedisBloom and RedisJSON are unchanged.

| Module          | From    | To       |
|-----------------|---------|----------|
| RedisTimeSeries | v8.8.0  | v8.9.80  |

> **Note:** `v8.9.80` is the **8.10 LTS branch cut** (targets Redis
8.10) and has diverged from `v8.8.0`. The `v8.8.0...v8.9.80` ancestry
diff contains 37 commits, but **7 are backports already shipped in
`v8.8.0`** (verified with `git cherry`, see below); the **30 genuinely
new** changes are listed here.

## Module changes ([v8.8.0 →
v8.9.80](RedisTimeSeries/RedisTimeSeries@v8.8.0...v8.9.80))

- MOD-14124 — m commands acl
([#1913](RedisTimeSeries/RedisTimeSeries#1913))
- MOD-14250 — missing artifacts logs fix
([#1932](RedisTimeSeries/RedisTimeSeries#1932))
- MOD-14289 — Increase LibMR execution timeout for Valgrind builds
([#1933](RedisTimeSeries/RedisTimeSeries#1933))
- MOD-12726 — unique snapshot name + new output params for nighly event
([#1937](RedisTimeSeries/RedisTimeSeries#1937))
- MOD-14674 — oss refresh list
([#1935](RedisTimeSeries/RedisTimeSeries#1935))
- nightly build, upload snapshot artifact
([#1954](RedisTimeSeries/RedisTimeSeries#1954))
- MOD-14902 — existence check to prevent Timeseries crash when Redis is
not aligned with new redis-core changes
([#1940](RedisTimeSeries/RedisTimeSeries#1940))
- MOD-14850 — Bump libmr
([#1962](RedisTimeSeries/RedisTimeSeries#1962))
- MOD-14715 — add apt retries/timeouts to Debian/Ubuntu Dockerfiles
([#1965](RedisTimeSeries/RedisTimeSeries#1965))
- MOD-15262 — Align TimeSeries with the RedisModule_GetUserUserName API
changes
([#1975](RedisTimeSeries/RedisTimeSeries#1975))
- RED-180951 RED-180027 — fixing bugs and improving the code
([#2004](RedisTimeSeries/RedisTimeSeries#2004))
- MOD-14239 — Ignore known init-rdbchannel migration timeout under
sanitizer
([#1979](RedisTimeSeries/RedisTimeSeries#1979))
- MOD-15105 — make one generic getUser function
([#1981](RedisTimeSeries/RedisTimeSeries#1981))
- MOD-15741 MOD-14091 — add dont-cache command tip to non-cacheable read
commands
([#2031](RedisTimeSeries/RedisTimeSeries#2031))
- MOD-15731 — modules modernization alignment
([#2027](RedisTimeSeries/RedisTimeSeries#2027))
- MOD-15728 — Tal.ba/feat/blocking get
([#2028](RedisTimeSeries/RedisTimeSeries#2028))
- MOD-8187 — fix the aggregation bugs (fix reverse iterator)
([#2036](RedisTimeSeries/RedisTimeSeries#2036))
- MOD-15749 — Link to new version of LibMR with short-form CLUSTERSET
and add tests
([#2034](RedisTimeSeries/RedisTimeSeries#2034))
- Fix REDISMODULE_MAIN typo + drop common.h forward-decl workarounds
([#2044](RedisTimeSeries/RedisTimeSeries#2044))
- CI: switch flow-linux arm64 runner to standard ubuntu-24.04-arm
([#2048](RedisTimeSeries/RedisTimeSeries#2048))
- MOD-15999 — Centralize Redis ref into a single source-of-truth file
for CI
([#2045](RedisTimeSeries/RedisTimeSeries#2045))
- CI: trigger OSS cluster (multi-shard) benchmarks on demand
([#2050](RedisTimeSeries/RedisTimeSeries#2050))
- MOD-15899 — oom try calloc
([#2051](RedisTimeSeries/RedisTimeSeries#2051))
- MOD-8187 — fix non twa aggregation
([#2053](RedisTimeSeries/RedisTimeSeries#2053))
- MOD-16224 — Fix filter-blind neighbor lookups in EMPTY aggregation
([#2056](RedisTimeSeries/RedisTimeSeries#2056))
- MOD-15893 — Nrange new command
([#2052](RedisTimeSeries/RedisTimeSeries#2052))
- MOD-16160 — update blocking get syntax
([#2054](RedisTimeSeries/RedisTimeSeries#2054))
- MOD-16160 — Fix client-side cache tips for TS.BGET and
TS.NRANGE/TS.NREVRANGE
([#2057](RedisTimeSeries/RedisTimeSeries#2057))
- Cut 8.10 LTS branch: bump version to 8.9.80, target Redis 8.10
([27484f7](RedisTimeSeries/RedisTimeSeries@27484f7))
- Fix event-nightly CI on 8.10: read Redis ref from dedicated redis_ref
field
([#2058](RedisTimeSeries/RedisTimeSeries#2058))

<details>
<summary>7 commits excluded — already shipped in v8.8.0 as
backports</summary>

These show up in the `v8.8.0...v8.9.80` ancestry diff with different
SHAs, but `git cherry` confirms their patch content is already in
`v8.8.0`: they were backported to the 8.8 release branch (the "in 8.8
via" PR below), so they are **not** new in this bump.

- MOD-9320 — Multiple aggregators single command
([#1916](RedisTimeSeries/RedisTimeSeries#1916))
→ in 8.8 via
[#1921](RedisTimeSeries/RedisTimeSeries#1921)
- MOD-9320 — rename AGGREGATION token in m commands
([#1926](RedisTimeSeries/RedisTimeSeries#1926))
→ in 8.8 via
[#1927](RedisTimeSeries/RedisTimeSeries#1927)
- MOD-13142 — Allow changing number of threads while pool hasn't started
([#1928](RedisTimeSeries/RedisTimeSeries#1928))
→ in 8.8 via
[#1934](RedisTimeSeries/RedisTimeSeries#1934)
- MOD-14439 — Detect cluster topology changes during a multi-shard
command
([#1930](RedisTimeSeries/RedisTimeSeries#1930))
→ in 8.8 under the same PR
- ci: skip Event CI when PR only changes src/version.h
([#1984](RedisTimeSeries/RedisTimeSeries#1984))
→ in 8.8 via
[#1986](RedisTimeSeries/RedisTimeSeries#1986)
- MOD-15020 — remove bionic os support
([#1983](RedisTimeSeries/RedisTimeSeries#1983))
→ in 8.8 via
[#1996](RedisTimeSeries/RedisTimeSeries#1996)
- MOD-14420 — fix count reducers return wrong NaN
([#2013](RedisTimeSeries/RedisTimeSeries#2013))
→ in 8.8 via
[#2016](RedisTimeSeries/RedisTimeSeries#2016)

</details>

## Test plan
- [ ] CI passes for RedisTimeSeries at the new pinned version
- [ ] `make all` builds RedisTimeSeries cleanly against `unstable`
- [ ] Module tests run under `make test`

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
@gabsow gabsow added the bug Something isn't working label Jun 16, 2026
gabsow added a commit that referenced this pull request Jun 17, 2026
…ption

A series key whose name equals an option keyword (ALIGN, COUNT, LATEST,
AGGREGATION, FILTER_BY_VALUE, FILTER_BY_TS) used to be matched as that option
in single-key TS.RANGE/TS.REVRANGE, with the next token consumed as the
option's value -- e.g. a key named 'align' matched ALIGN and ate the
fromTimestamp as the alignment value. PR #2052 (MOD-15893) scoped option
parsing past the key to fix it.

This test asserts a series keyed by an option keyword returns exactly what an
identically populated control series returns, across TS.RANGE/TS.REVRANGE and
the affected options, plus explicit post-fix values for the 'align'-named key
(the scenario the Jedis #align test hit).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
gabsow added a commit that referenced this pull request Nov 2, 2026
…ption (#2069)

A series key whose name equals an option keyword (ALIGN, COUNT, LATEST,
AGGREGATION, FILTER_BY_VALUE, FILTER_BY_TS) used to be matched as that option
in single-key TS.RANGE/TS.REVRANGE, with the next token consumed as the
option's value -- e.g. a key named 'align' matched ALIGN and ate the
fromTimestamp as the alignment value. PR #2052 (MOD-15893) scoped option
parsing past the key to fix it.

This test asserts a series keyed by an option keyword returns exactly what an
identically populated control series returns, across TS.RANGE/TS.REVRANGE and
the affected options, plus explicit post-fix values for the 'align'-named key
(the scenario the Jedis #align test hit).

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants