Skip to content

MOD-15728 - Tal.ba/feat/blocking get - #2028

Merged
TalBarYakar merged 15 commits into
masterfrom
tal.ba/feat/blocking_get
May 26, 2026
Merged

TalBarYakar merged 15 commits into
masterfrom
tal.ba/feat/blocking_get

Conversation

@TalBarYakar

@TalBarYakar TalBarYakar commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Note

Medium Risk
New blocking command path and SignalKeyAsReady on every append/compaction destination write add server-side client lifecycle surface area; behavior is well-tested but touches hot write paths.

Overview
Adds TS.BGET, a blocking read for cursor-style tailing: up to count samples with timestamp >= cursor, oldest-first, optionally waiting up to timeout ms for a full batch.

Behavior: With timeout > 0, the client blocks on the key until enough qualifying samples exist or the deadline hits (then partial/empty flush). With timeout == 0, it never blocks. Cursor supports literals, - (from start), and + (snapshotted lastTimestamp + 1 at command time). Replies mirror a limited ascending range read; strict mode pre-counts before replying.

Infrastructure: New RTS_BlockClientOnKey wraps BlockClientOnKeys and blocked-client timing. Waiters wake via RedisModule_SignalKeyAsReady after sample appends in internalAdd and after compaction writes to destination keys in tsdb.c. Command is registered readonly (not fast); documented in commands.json (8.10.0).

Tests: Broad flow coverage in tests/flow/test_ts_bget.py (immediate reply, blocking until count, paging, timeout, sentinels, multi-client broadcast, compaction destination, MULTI/EVAL refusal, validation).

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

Comment thread src/module.c Resolved
Comment thread src/module.c Resolved
Comment thread src/utils/blocked_client.c 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.

Review for TS.BGET — RED-132421

Reviewed against the Jira initiative spec (RED-132421) and the repo's existing conventions. Overall the implementation is well-structured (clear separation between try_reply / reply_cb / timeout_cb, decent doc comments, a meaningful test suite). The findings below split into spec compliance, correctness, conventions, and test gaps.


🔴 Critical

1. The - / + timestamp sentinels are part of the initiative spec but are not implemented.
The Jira ticket explicitly requires:

  • - → earliest sample (or 0 when empty)
  • + → latest at command-receive time; intended for the first call to TS.BGET so a tailing client can subscribe to "only new samples"

The PR rejects them at parse time (src/module.c parse_bget_args, line ~1268) with "'-' / '+' timestamp sentinels are not yet supported" and only carries a @todo. Without + in particular, the natural tailing flow described in the initiative cannot be expressed — every client must either re-fetch history or guess a starting timestamp. This is the headline UX of the feature and should not ship as a follow-up.

2. Cursor inclusive vs. exclusive — spec deviation that needs to be reconciled.
The Jira spec says: "retrieve up to count samples, each with timestamp >= timestamp" and "on subsequent calls … set timestamp to the timestamp of last retrieved sample" — those two sentences contradict each other (you'd re-receive the last sample every call). The implementation picks the sensible interpretation (> cursor, exclusive) in TSDB_bget_try_reply (startTimestamp = args->cursor + 1, line ~1349), which is what makes the "advance cursor" pagination usable. This is almost certainly the right call, but:

  • The Jira ticket text should be corrected, or
  • The command's own help/docs should document that the cursor is exclusive (> timestamp), not >=, otherwise users will write code that drops a sample.

3. BlockedClientMeasureTime is half-paired — telemetry will be wrong.
RTS_BlockClientOnKey (src/utils/blocked_client.c:36) calls RedisModule_BlockedClientMeasureTimeStart(bc), but with RedisModule_BlockClientOnKeys the client is unblocked by the reply / timeout callback returning REDISMODULE_OK — not via RTS_UnblockClient. There is no path that calls BlockedClientMeasureTimeEnd for TS.BGET, so the metric is open-ended on every blocked client. Either:

  • Call RedisModule_BlockedClientMeasureTimeEnd(bc) at the start of TSDB_bget_reply_callback / TSDB_bget_timeout_callback before returning OK, or
  • Don't start the timer for BlockClientOnKeys clients at all.

This is the same kind of pairing that the existing RTS_BlockClient / RTS_UnblockClient got right; the new helper introduced the asymmetry.

4. commands.json not updated.
commands.json at the repo root is the canonical spec used to publish command metadata for redis.io / redis-cli, and TS.GET lives there but TS.BGET is missing entirely. New commands must be registered here, with the right blocking/cluster routing hints — otherwise clients (redis-cli, ACL category resolution, redis-stack docs, etc.) won't know it exists. This is required before merge.


🟠 Major

5. MULTI / Lua / deny-blocking refusal is reactive, error message is broken.
The PR currently relies on RedisModule_BlockClientOnKeys returning NULL and then replies:

"TSDB: blocking TS.BGET is not allowed  or in a deny-blocking context"

(src/module.c in TSDB_bget, line ~1426). Two problems:

  • Double space and grammar ("is not allowed or in a deny-blocking context") — clearly a leftover edit.
  • Reactive: the codebase already has the canonical preemptive pattern in TSDB_mget (src/module.c:1227):
    int ctxFlags = RedisModule_GetContextFlags(ctx);
    if (ctxFlags & (REDISMODULE_CTX_FLAGS_LUA | REDISMODULE_CTX_FLAGS_MULTI |
                    REDISMODULE_CTX_FLAGS_DENY_BLOCKING)) {
        RedisModule_ReplyWithError(ctx, "<clear error>");
        return REDISMODULE_OK;
    }
    TS.BGET should mirror it (and also reject when timeout_ms > 0, since timeout_ms == 0 is fine in MULTI / Lua — the command resolves synchronously in flush mode). The existing @todo Refuse blocking in MULTI / Lua / replica contexts should be addressed here, not later.

6. Double SignalKeyAsReady on compaction destination keys.
Two new signal sites get wired into the compaction-rule path that fire on the same destination key for one bucket commit:

  • src/tsdb.c RuleSeriesUpsertSample (line ~605) signals rule->destKey.
  • src/module.c internalAdd (line ~697) signals series->keyName — and internalAdd is also called for compaction at module.c:602 (internalAdd(ctx, destSeries, …, false)), so the destSeries' keyName gets signaled there too.

Both paths feed the same wakeup. It's not incorrect (the reply_cb re-checks and stays parked if there's nothing new), but it doubles the per-commit wakeup work for every blocked TS.BGET, and it's the kind of thing that bit-rots into a bug. Pick one site (recommendation: keep the one in internalAdd since it's the chokepoint, drop the one in RuleSeriesUpsertSample).

7. Wasted wakeups on in-place updates to older samples.
internalAdd signals unconditionally after either SeriesUpsertSample (in-place, same or earlier ts) or SeriesAddSample (append). An upsert that doesn't extend series->lastTimestamp can never satisfy any blocked TS.BGET (the strict-mode shortcut at line ~1326 explicitly returns false when lastTimestamp <= cursor). The signal still fires, the reply_cb still runs, and every blocked client across the keyspace pays for it. Easy gate:

if (timestamp > lastTimestampBeforeAdd) {
    RedisModule_SignalKeyAsReady(ctx, series->keyName);
}

(or pass a "did we advance lastTimestamp?" bool out of SeriesAddSample / SeriesUpsertSample). Important if anyone runs a high-cardinality keyspace with even a few blocked tailers.


🟡 Minor / nits

8. The "no abort reply" comment is misleading. In TSDB_bget_try_reply (src/module.c line ~1294):

"Never starts writing samples until it knows they will all go out (the Module API has no 'abort reply')."

That's not actually true for BlockClientOnKeys reply callbacks — returning REDISMODULE_ERR from the reply_cb discards any partial reply written so far (which is exactly what enables the postponed-array-length pattern in ReplySeriesRange). The pre-walk via TSDB_count_samples_up_to is really a performance optimization (don't materialize a partial reply you'll throw away), not a correctness requirement. Recommend fixing the comment so the next reader doesn't preserve the pattern under the wrong rationale.

9. Double iteration on the happy path. When strict mode succeeds, the series is walked once by TSDB_count_samples_up_to and then again by ReplySeriesRange. For a typical "count=1000 samples just landed" wake-up that's two passes over the qualifying chunks. Given (8), this could fold into a single pass — speculatively write via REDISMODULE_POSTPONED_ARRAY_LEN, abort with REDISMODULE_ERR if we don't reach count. Not blocking, but worth a follow-up if BGET sees real traffic.

10. RedisModule_AutoMemory(ctx) + manual RetainString mix. TSDB_bget enables AutoMemory; TSDB_bget_block then RedisModule_RetainString(ctx, priv->key) and TSDB_bget_free_privdata calls RedisModule_FreeString(ctx, priv->key) (where ctx is the blocked-client ctx). This works in practice — RetainString makes the string independent of the original ctx — but it's worth a one-line comment so reviewers don't second-guess whether AutoMemory will double-free the key.

11. Risk-summary in the PR description is too generous about SignalKeyAsReady. The PR description says "cheap no-op when no client is blocked" — that's directionally true (it's an O(1) hashtable check in the server), but combined with (7) above and the fact that it fires on every internalAdd invocation (including in-place updates), there's still a small per-write constant we should be honest about in the perf notes.


🧪 Test gaps

The existing four tests cover the right golden paths (immediate / blocks-then-unblocks / paging / timeout flush). The following spec-level behaviors are not exercised:

  • Compaction-driven wake-up. The PR explicitly adds SignalKeyAsReady on the compaction destination (src/tsdb.c) but no test exercises it. Add a TS.BGET on the destination key, drive samples into the source, let the rule fire, verify wake-up.
  • Multiple parallel blocked clients on the same key, both receive the samples. The Jira spec calls this out explicitly: "samples are not distributed between blocked clients but retrieved by each waiting client" — needs a dedicated test, since this is the contract that distinguishes TS.BGET from BLPOP-style queue semantics.
  • timeout_ms == 0 non-blocking flush with (a) no qualifying samples → empty array, (b) fewer than count qualifying → partial.
  • WRONGTYPE path (TS.BGET on a string key) — currently untested.
  • Deny-blocking refusal (inside MULTI or EVAL) — currently untested and, see (5), the implementation of this is itself incomplete.
  • Parse-error paths (negative count, negative timeout, non-integer timestamp, wrong arity) — currently untested.
  • Cursor at lastTimestamp exactly — with strict semantics this should block; worth pinning down.

Summary

Solid scaffolding, correct callback wiring, and the strict/flush split is a clean design choice. Blocking-merge items in my view:

  1. Implement - and + sentinels (spec deliverable for the initiative).
  2. Add commands.json entry.
  3. Fix the BlockedClientMeasureTime pairing (broken telemetry).
  4. Reconcile the cursor >= vs > semantics with the Jira text (likely fix the spec).
  5. Preemptive MULTI/Lua/deny-blocking refusal + fix the typo in the error string.
  6. Pick a single SignalKeyAsReady site for compaction rules; gate the internalAdd signal on lastTimestamp actually advancing.
  7. Add the test-gap items, especially the multi-client and compaction wake-up cases.

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

Inline anchors for the top items from my main review (see the parent comment for full context).

Comment thread src/module.c
// Wake any TS.BGET waiters parked on this key. Cheap no-op when no client
// is blocked; harmless extra try_reply when the upsert was an in-place
// update (the reply_cb will re-check and stay parked if nothing changed).
RedisModule_SignalKeyAsReady(ctx, series->keyName);

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.

[#7 from main review] Wasted signal on in-place updates.

This fires after every internalAdd, including the upsert branch where timestamp <= series->lastTimestamp. Those updates can never satisfy a blocked TS.BGET — the strict-mode shortcut in TSDB_bget_try_reply (series->lastTimestamp <= cursor) returns false immediately. So every such write costs all blocked tailers a wake-up + reply_cb that does nothing useful.

Suggest gating the signal on lastTimestamp actually advancing:

const api_timestamp_t lastBefore = series->lastTimestamp;
// ... existing add / upsert ...
if (series->lastTimestamp > lastBefore) {
    RedisModule_SignalKeyAsReady(ctx, series->keyName);
}

Keeps the signal where it belongs (the append chokepoint) without the per-write tax in workloads with high out-of-order or upsert traffic.

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.

I don't think the gate is safe. The lastTimestamp <= cursor shortcut is only the O(1) trivial early-out; the real qualification check is TSDB_count_samples_up_to over [cursor, +inf]. An out-of-order insert at e.g. ts=x+3 when lastTimestamp=x+10 doesn't advance lastTimestamp but does drop a new sample inside the range and may push a parked client over its count threshold. Gating on lastTimestamp > lastTS_before_add would silently swallow those wake-ups. Leaving the unconditional signal; happy to revisit with a tighter predicate if perf becomes a real issue.

Comment thread src/module.c Outdated
const char *ts_str = RedisModule_StringPtrLen(argv[2], &ts_len);
if (ts_len == 1 && (ts_str[0] == '-' || ts_str[0] == '+')) {
RedisModule_ReplyWithError(
ctx, "TSDB: '-' / '+' timestamp sentinels are not yet supported");

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.

[#1 from main review] - / + sentinels are part of the Jira initiative spec.

The initiative (RED-132421) defines these explicitly:

  • - → timestamp of earliest sample (or 0 if empty)
  • + → timestamp of latest sample at command-receive time; the natural way for a client to subscribe to "only new samples from now on"

Without + in particular, the tailing UX described in the spec can't be expressed — every client has to either re-fetch history or guess a starting timestamp. This is the headline UX of the feature, not a follow-up. Resolving them is cheap: open the key once, read series->firstTimestamp / series->lastTimestamp, write back into out->cursor.

IMO this is blocking for the initiative deliverable.

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.

parse_bget_args now resolves both at parse time: '-' → cursor = 0 (every sample qualifies under ts >= cursor); '+' → opens the key once and snapshots series->lastTimestamp + 1 (or 0 for empty/missing key, WRONGTYPE for non-series). Resolved exactly once here so the cursor stays stable across wake-ups — re-resolving on every signal would let lastTimestamp chase forward and the client would never unblock.

Comment thread src/module.c Outdated
// error so the client doesn't hang on an empty pipeline.
RedisModule_ReplyWithError(
ctx,
"TSDB: blocking TS.BGET is not allowed "

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.

[#5 from main review] Typo + reactive refusal.

Two issues on this branch:

  1. Error string has a double space and broken grammar: "blocking TS.BGET is not allowed or in a deny-blocking context".
  2. The refusal is reactive (relies on BlockClientOnKeys returning NULL). The repo already has a preemptive pattern — see TSDB_mget at module.c:1227:
    int ctxFlags = RedisModule_GetContextFlags(ctx);
    if (ctxFlags & (REDISMODULE_CTX_FLAGS_LUA | REDISMODULE_CTX_FLAGS_MULTI |
                    REDISMODULE_CTX_FLAGS_DENY_BLOCKING)) {
        RedisModule_ReplyWithError(ctx, "...");
        return REDISMODULE_OK;
    }
    TS.BGET should mirror it. Note: a timeout_ms == 0 request resolves synchronously even inside MULTI/Lua, so the preemptive check should only fire when timeout_ms > 0.

This is also the @todo Refuse blocking in MULTI / Lua / replica contexts — let's land it 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.

Good call — mirrored the TSDB_mget pattern (LUA | MULTI | DENY_BLOCKING) and scoped it to timeout_ms > 0 so timeout_ms == 0 still resolves synchronously inside MULTI/Lua.
done.

Comment thread src/module.c
@@ -1848,6 +2212,8 @@ int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)

RegisterCommandWithModesAndAcls(ctx, "ts.info", TSDB_info, "readonly", "read fast");
RegisterCommandWithModesAndAcls(ctx, "ts.get", TSDB_get, "readonly", "read fast");
// TS.BGET may block on the key; intentionally NOT flagged "fast".
RegisterCommandWithModesAndAcls(ctx, "ts.bget", TSDB_bget, "readonly", "read");

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.

[#4 from main review] commands.json not updated.

The repo-root commands.json is the canonical command spec — it has TS.GET etc. but no TS.BGET. Without an entry there, clients (redis-cli completion, redis.io docs publishing, ACL category resolution) won't see the new command. Required before merge.

Also worth confirming the command flag string here ("readonly" + acl "read") is the right combination for a blocking-on-keys command — there's no "blocking" flag in the Module API, so "readonly" looks correct, but please make sure the matching entry in commands.json declares the blocking semantics correctly for clients that care (e.g., redis-cli's -3 behavior, cluster routing libraries).

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.

Added. Used readonly + blocking for command_flags and read for acl_categories, matching the TS.GET shape for the parts that overlap. Please double-check the since value (1.14.0) is the right target release.

Comment thread src/tsdb.c
// Wake any TS.BGET waiters parked on the destination key, so a
// compaction-rule bucket landing here triggers them just like a direct
// write would.
RedisModule_SignalKeyAsReady(ctx, rule->destKey);

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.

[#6 from main review] Duplicate signal on compaction destination.

internalAdd is also invoked for compaction-rule destinations (module.c:602: internalAdd(ctx, destSeries, ..., false)), and the new signal at module.c:697 fires on destSeries->keyName. So this signal here and the one in internalAdd both fire on the same destination key for one bucket commit — double wakeup, double reply_cb run, every time a rule lands.

Not incorrect (reply_cb is idempotent) but it's the kind of redundancy that bit-rots into a bug. Recommend deleting this site and relying on the internalAdd chokepoint.

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.

RuleSeriesUpsertSample is the out-of-order compaction path and isn't reached via internalAdd, so removing the signal here would actually drop wake-ups, not deduplicate them. Even within internalAdd's own compaction call, an out-of-order bucket landing inside a parked client's [cursor, +inf] range can satisfy its count without advancing lastTimestamp — so I want the signal to fire on every successful compaction write. Happy to revisit if benchmarks show the double-signal is measurable.

Comment thread src/module.c Resolved
Comment thread src/module.c
// Wake any TS.BGET waiters parked on this key. Cheap no-op when no client
// is blocked; harmless extra try_reply when the upsert was an in-place
// update (the reply_cb will re-check and stay parked if nothing changed).
RedisModule_SignalKeyAsReady(ctx, series->keyName);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unconditional signal causes wasted wake-ups on upserts

Medium Severity

RedisModule_SignalKeyAsReady fires after every internalAdd, including the upsert branch where timestamp <= series->lastTimestamp. These in-place updates never advance lastTimestamp, so TSDB_bget_try_reply's O(1) shortcut (series->lastTimestamp < cursor) will always reject them. Every upsert needlessly wakes all blocked TS.BGET clients parked on that key, each running a full reply callback cycle that does nothing. Gating the signal on lastTimestamp actually advancing would eliminate this overhead.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 19cd7f8f1fb73dfed0b1fa892cfe0d4e19fef75a. Configure 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.

Considered but unsafe (same answer to both reviewers). The lastTimestamp < cursor shortcut is only the O(1) trivial early-out; the real qualification check is TSDB_count_samples_up_to over [cursor, +inf]. An in-place upsert / out-of-order insert at e.g. ts = x+3 when lastTimestamp = x+10 doesn't advance lastTimestamp but does drop a new sample inside a parked client's range and may push it over its count threshold — that's the exact case the feature exists to handle (count=5, 3 qualifying samples present, gets unblocked when out-of-order samples 4 and 5 land). Gating on lastTimestamp > lastTS_before_add would silently swallow those. Happy to revisit with a tighter predicate if benchmarks show the per-write cost is measurable.

@gabsow

gabsow commented May 19, 2026 •

Copy link
Copy Markdown
Collaborator

Follow-up on test coverage gaps

Thanks for the fixes on the four critical items — sentinels, cursor inclusivity, MeasureTime pairing, and commands.json are all in good shape, and the new - / + tests are a clean addition.

Before merging, I'd like to see the test surface extended to cover the remaining spec contracts and error paths. Listed in rough priority order:

🎯 High priority — spec contracts not yet pinned

1. Multiple blocked clients on the same key all receive the samples.
The Jira initiative (RED-132421) explicitly calls this out:

"Similar to other blocking commands, however, when multiple clients are blocked — samples are not distributed between blocked clients but retrieved by each waiting client."

This is the load-bearing semantic that distinguishes TS.BGET from BLPOP-style queue dequeueing. Without a test, a future refactor that introduces one-shot or first-waiter-wins behavior would slip through. Suggested shape:

def test_bget_broadcasts_to_all_blocked_clients():
    # Park N clients on the same key with cursor='+'/strict mode.
    # Producer issues ONE TS.ADD.
    # Assert: every client unblocks with the same sample, none times out.

2. Compaction-driven wake-up.
The PR adds SignalKeyAsReady in RuleSeriesUpsertSample specifically so a TS.BGET parked on a compaction destination wakes up when a bucket lands. No test exercises that path today; the signal could silently regress and the existing tests would still pass. Suggested shape:

def test_bget_on_compaction_destination_wakes_on_bucket_commit():
    # TS.CREATE src; TS.CREATE dst; TS.CREATERULE src dst AGGREGATION avg <bucket>
    # TS.BGET dst '+' 1 <timeout>  on a worker thread
    # TS.ADDs into src that close a bucket
    # Assert: BGET on dst unblocks with the compacted sample.

🔒 Medium priority — error paths

3. WRONGTYPE on the literal-cursor path.
The new + sentinel branch already tests WRONGTYPE via the parse step, but TSDB_bget_try_reply has its own WRONGTYPE path that's still uncovered. One line:

def test_bget_wrongtype():
    r.set("not_a_ts", "hello")
    with pytest.raises(ResponseError, match="WRONGTYPE"):
        r.execute_command("TS.BGET", "not_a_ts", 0, 1, 0)

4. Refusal inside MULTI / EVAL / deny-blocking.
The error string was fixed in the last round but no test verifies the refusal fires correctly when timeout > 0. Worth pinning since this is the one place we deliberately chose the reactive path over the preemptive TSDB_mget pattern — if BlockClientOnKeys's NULL semantics ever change, we'd want CI to catch it.

def test_bget_inside_multi_refuses_with_clear_error():
    pipe = r.pipeline(transaction=True)
    pipe.execute_command("TS.BGET", "ts", 0, 1, 1000)
    # assert the response is the explanatory error, not a hang or empty reply.

(And the same with EVAL "redis.call('TS.BGET', ...)".)

🧪 Lower priority — parse / arity validation

5. Parse-error paths. All currently untested:

  • Wrong arity (3 args, 6 args).
  • count <= 0 (zero and negative).
  • timeout < 0.
  • Non-integer count / timeout (e.g. "abc", "1.5").
  • Non-integer, non-sentinel timestamp (e.g. "abc").
  • Negative literal timestamp.

A single parametrized test would cover all of these in ~15 lines.

6. Explicit timeout_ms == 0 non-blocking flush. There's implicit coverage via the existing tests, but no test that directly asserts: "with timeout=0 and partial data available, return the partial set immediately without blocking." Worth a one-liner with a time.time() bound to prove it doesn't sleep.


None of these block the design — they pin behavior so we don't regress. #1 (multi-client broadcast) is the one I'd most want to land before merge since it's a direct Jira spec deliverable and is the test most likely to catch real-world breakage in a future refactor.

Comment thread commands.json Resolved
@TalBarYakar

Copy link
Copy Markdown
Contributor Author

Duplicate TS.BGET key in commands.json overwrites correct entry

High Severity

There are two "TS.BGET" keys in the same JSON object. Most JSON parsers silently use the last occurrence, so the second entry (line 1267) wins. This second entry is missing command_flags (losing "readonly" and "blocking") and acl_categories (losing "read"), and has an incorrect since value of "8.10.0" instead of "1.14.0". Clients relying on this spec (redis-cli completion, ACL category resolution, documentation publishing) will see an incomplete and incorrectly versioned command definition.

tests were added

@gabsow
gabsow requested a review from AvivDavid23 May 24, 2026 08:27
@gabsow

gabsow commented May 25, 2026

Copy link
Copy Markdown
Collaborator

linter

Comment thread commands.json Outdated
"acl_categories": [
"read"
],
"since": "1.14.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.

8.10.0

@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-review against PR HEAD cfd2ffd6e0 ✅

Walked through every item from my original review against the four new commits (add - + support, cleaning the blocking key, fix remarks, add tests). Status:

✅ Critical — all addressed

# Finding Fix
1 - / + sentinels missing parse_bget_args (module.c:1320-1338) — - → cursor=0; + → opens key, snapshots lastTimestamp+1, handles empty + WRONGTYPE
2 Cursor >= vs > ambiguity Settled on inclusive >= (range .startTimestamp = cursor, shortcut lastTimestamp < cursor). Matches Jira spec literally
3 BlockedClientMeasureTime never paired New TSDB_bget_account_blocked_time helper called from both reply (line 1521) and timeout (line 1544) callbacks before returning OK
4 commands.json missing entry Added with command_flags: [readonly, blocking], full argument schema

✅ Major — all addressed

# Finding Fix
5 Reactive MULTI/Lua refusal + typo'd error Preemptive GetContextFlags check at module.c:1642-1652 (mirrors TSDB_mget), gated on timeout_ms > 0. Error string clean. Defensive fallback retained for unknown deny-blocking flags
8 "Module API has no abort reply" comment Rewritten correctly — now describes the pre-walk as a perf optimization, not a correctness requirement

✅ Test coverage — every gap closed

The test file grew from 4 → 16 tests. All items from my test-gaps follow-up are addressed:

  • test_bget_broadcasts_to_all_blocked_clients (the Jira-mandated "not distributed" semantic)
  • test_bget_on_compaction_destination_wakes_on_bucket_commit
  • test_bget_wrongtype_literal_cursor
  • test_bget_inside_multi_refuses_with_clear_error + test_bget_inside_eval_refuses_with_clear_error
  • test_bget_parse_errors
  • test_bget_timeout_zero_returns_partial_without_blocking
  • Plus 4 sentinel-specific tests (- populated/empty, + empty/with-new/no-new-samples)

⚠️ Minor follow-ups — non-blocking

Three items from the original review remain open. Inline comments below for each. None of them block merge in my view — they're perf/cleanup items that can be addressed in-place or as a follow-up PR.

Also one new observation I didn't flag before — see the inline comment on + sentinel resolution about out-of-order arrival semantics.

Bottom line: nothing critical remains, the PR is mergeable from a code-quality and spec-compliance standpoint. Nice turnaround on the iteration.

Comment thread src/module.c
// Wake any TS.BGET waiters parked on this key. Cheap no-op when no client
// is blocked; harmless extra try_reply when the upsert was an in-place
// update (the reply_cb will re-check and stay parked if nothing changed).
RedisModule_SignalKeyAsReady(ctx, series->keyName);

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-review — original finding #7] Wasted signal on in-place updates is still here.

Not blocking, just flagging that this still fires unconditionally after every internalAdd, including upserts that don't extend lastTimestamp. The reply_cb shortcut at module.c:1446 (series->lastTimestamp < args->cursor) absorbs the cost, so it's correct — just an avoidable per-write tax for keyspaces with blocked tailers.

If you want to land it as a small follow-up:

const api_timestamp_t lastBefore = series->lastTimestamp;
// ... add / upsert ...
if (series->lastTimestamp > lastBefore) {
    RedisModule_SignalKeyAsReady(ctx, series->keyName);
}

Comment thread src/module.c
Series *series = RedisModule_ModuleTypeGetValue(key);
cursor = (SeriesGetNumSamples(series) == 0)
? 0
: (api_timestamp_t)(series->lastTimestamp + 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.

[Re-review — new observation] + sentinel and out-of-order arrival semantics.

The Jira spec for + says: "Retrieve samples reported after this command was received by the server." The chosen implementation snapshots lastTimestamp + 1 once at parse time, which uses logical timestamp comparison.

Consequence: a sample physically TS.ADD-ed after the command but with logical ts ≤ lastTimestamp (out-of-order arrival) won't be returned to a +-cursor BGET, even though the spec arguably means physical arrival order.

Not a bug — just an interpretation worth pinning down. Two options:

  1. Document the chosen semantics in the command help ("+ snapshots the logical lastTimestamp; out-of-order samples with earlier ts are not delivered"). This is what the current code does and is the simpler contract.
  2. Track physical arrival via a per-series sequence number and have + resolve to that — closer to the spec's literal wording, but a bigger change.

Worth a one-line clarification in commands.json summary either way.

Comment thread src/tsdb.c
// Wake any TS.BGET waiters parked on the destination key, so a
// compaction-rule bucket landing here triggers them just like a direct
// write would.
RedisModule_SignalKeyAsReady(ctx, rule->destKey);

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-review — original finding #6] Compaction-destination signal duplication still present.

Both this site and module.c:697 (via handleCompaction → internalAdd) signal the same destination key. On closer inspection these may be distinct code paths — RuleSeriesUpsertSample is called from tsdb.c:655/894/939 for rule-driven re-computation flows that may not all route through handleCompaction → internalAdd.

Not blocking, but worth a quick audit: for each RuleSeriesUpsertSample call site, is the destination also going through internalAdd for the same write? If yes anywhere, the signal here is redundant and can be removed; if no, this site is needed and the duplicate is path-dependent. Either way a one-line comment explaining the intent would help the next reader.

Comment thread src/module.c Outdated
// Strict mode: refuse to commit a reply until we know it will be
// complete. The pre-count walk reads only chunk metadata.
if (require_full_batch &&
TSDB_count_samples_up_to(series, &range, args->count) < args->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.

[Re-review — original finding #9, non-blocking] Strict-mode still does two passes.

On the happy path (qualifying ≥ count), TSDB_count_samples_up_to walks once via SeriesQuery, then ReplySeriesRange walks again. For high-rate wake-ups this is the dominant cost.

Since the comment block above now correctly notes that REDISMODULE_ERR discards a postponed-array reply, the natural optimization is to fold both passes: write samples speculatively into the postponed array, return REDISMODULE_ERR if we didn't reach count. Not blocking — file as a follow-up if the perf matters.

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

my comments

Comment thread src/module.c
@@ -1848,6 +2273,8 @@ int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)

RegisterCommandWithModesAndAcls(ctx, "ts.info", TSDB_info, "readonly", "read fast");
RegisterCommandWithModesAndAcls(ctx, "ts.get", TSDB_get, "readonly", "read fast");
// TS.BGET may block on the key; intentionally NOT flagged "fast".
RegisterCommandWithModesAndAcls(ctx, "ts.bget", TSDB_bget, "readonly", "read");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Missing "blocking" flag in command registration

High Severity

TS.BGET is registered with mode "readonly" but omits the "blocking" flag. The commands.json correctly declares both "readonly" and "blocking" in command_flags, but the actual RegisterCommandWithModesAndAcls call only passes "readonly". Without the "blocking" flag, Redis does not recognize this command as one that may block, which can break cluster proxy routing, CLIENT LIST reporting, and may prevent REDISMODULE_CTX_FLAGS_DENY_BLOCKING from being set correctly in some contexts.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 735a96d95986f164417fe1c5ca5b630ee84ff362. Configure here.

Comment thread src/module.c Resolved
gabsow
gabsow previously approved these changes May 25, 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.

Code Review — TS.BGET (MOD-15728)

Great implementation overall — clean lifecycle, correct memory management, solid test coverage. Almost ready, one thing to fix before merging.


SHOULD-FIX

lastTimestamp + 1 overflow for + sentinel (src/module.c)

cursor = (api_timestamp_t)(series->lastTimestamp + 1);

If lastTimestamp == UINT64_MAX, cursor wraps to 0 and matches all samples — the opposite of the intended "only new samples" behavior. Add a guard:

cursor = (series->lastTimestamp < UINT64_MAX) ? series->lastTimestamp + 1 : UINT64_MAX;

NITS

Cluster behavior undocumented — all tests skip on cluster but the command registration has no cluster guard. A call on a non-local key would silently block or return empty. Either restrict to non-cluster or document the behavior explicitly.

Double scan per wake-up — TSDB_count_samples_up_to + ReplySeriesRange each walk the series on every signal. The comment explains it's intentional (avoid partial reply materialization), which is a reasonable tradeoff — just worth a note in the PR description for future readers.


What looks good ✓

  • Memory management is correct — RetainString in TSDB_bget_block, FreeString in TSDB_bget_free_privdata, null-safe throughout
  • Reply/timeout/free callback lifecycle is clean and correct
  • + sentinel snapshotted once at parse time — right design, prevents cursor chasing
  • MULTI/EVAL/deny-blocking refusal handled properly with a defensive fallback
  • Test coverage is excellent — 15 cases covering immediate reply, blocking, paging, timeout flush, sentinels, multi-client broadcast, compaction destination, WRONGTYPE, MULTI/EVAL, and parse errors

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

Overflow fix looks correct — saturates at instead of wrapping to 0. LGTM, good to merge.

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

Overflow fix looks correct — saturates at UINT64_MAX instead of wrapping to 0. LGTM, good to merge.

@TalBarYakar
TalBarYakar force-pushed the tal.ba/feat/blocking_get branch from 5a50b3b to 0a3790b Compare May 26, 2026 06:01
@sonarqubecloud

Copy link
Copy Markdown

1 similar comment
@sonarqubecloud

Copy link
Copy Markdown

@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 1 potential issue.

There are 3 total unresolved issues (including 2 from previous reviews).

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 0a3790b. Configure here.

Comment thread src/module.c
// equivalent to TS.RANGE [cursor, +inf] LIMIT count.
const RangeArgs range = {
.startTimestamp = args->cursor,
.endTimestamp = LLONG_MAX,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Wrong max constant truncates valid timestamp range

Medium Severity

endTimestamp is set to LLONG_MAX but the field type is api_timestamp_t (uint64_t). Every other open-ended range in the codebase uses UINT64_MAX (e.g., filter_iterator.c, libmr_commands.c). LLONG_MAX is 0x7FFFFFFFFFFFFFFF, which excludes timestamps in (LLONG_MAX, UINT64_MAX]. This also breaks the + sentinel saturation path: when cursor is UINT64_MAX, the range [UINT64_MAX, LLONG_MAX] is empty (start > end as unsigned), so a qualifying sample would never be found.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 0a3790b. Configure here.

@TalBarYakar
TalBarYakar merged commit 42155db into master May 26, 2026
62 of 64 checks passed
@TalBarYakar
TalBarYakar deleted the tal.ba/feat/blocking_get branch May 26, 2026 06:44
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]>
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