Repository navigation
[MOD-14327] [AGG/SEARCH/HYBRID] Use BlockClient reply_callback to reply - #8609
Conversation
🛡️ Jit Security Scan Results✅ No security findings were detected in this PR
Security scan by Jit
|
There was a problem hiding this comment.
Pull request overview
This PR refactors FAIL-timeout handling to use RedisModule reply_callback (reply-on-unblock) instead of replying directly from background threads, aiming to prevent double-reply races and simplify timeout behavior across coordinator (FT.HYBRID) and worker-executed queries.
Changes:
- Split blocked-client callbacks into
reply_callbackandtimeout_callback, and wire them through concurrent execution andBlockQueryClientWithTimeout. - Add “store results then reply in callback” paths for AREQ and HybridRequest under FAIL policy (including new stored reply state).
- Update timeout/reply handling logic in distributed hybrid coordinator flow and adjust a related pytest.
Reviewed changes
Copilot reviewed 17 out of 17 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/pytests/test_blocked_client_timeout.py | Adjusts FT.HYBRID test parameters/comments for FAIL-policy no-timeout flow. |
| src/module.c | Switches coordinator blocked-client handling to reply/timeout callbacks for DistHybrid FAIL policy. |
| src/info/info_redis/block_client.h | Extends BlockQueryClientWithTimeout to accept a reply callback in addition to timeout callback. |
| src/info/info_redis/block_client.c | Passes reply/timeout callbacks into RedisModule_BlockClient. |
| src/hybrid/hybrid_request.h | Adds coordinator flag + stored reply state to HybridRequest. |
| src/hybrid/hybrid_request.c | Removes old reply-state helpers; retains timeout helpers and HybridRequest init/free logic. |
| src/hybrid/hybrid_exec.h | Declares helpers to store results and serialize stored results for reply-callback flow. |
| src/hybrid/hybrid_exec.c | Implements storing results for reply_callback, refactors serialization helpers, and adds reply-callback serialization path. |
| src/coord/hybrid/dist_hybrid.h | Declares new coordinator reply callback for DistHybrid. |
| src/coord/hybrid/dist_hybrid.c | Implements DistHybrid reply callback and simplifies timeout callback; updates cleanup flow. |
| src/coord/coord_request_ctx.h | Updates coordinator request context API/docs for reply_callback model; adds GetRequest. |
| src/coord/coord_request_ctx.c | Implements GetRequest and removes reply-state claiming APIs. |
| src/concurrent_ctx.h | Renames blocked-client context fields to reply_callback / timeout_callback. |
| src/concurrent_ctx.c | Uses the new callback fields when blocking clients. |
| src/aggregate/aggregate_request.c | Adds teardown for stored reply state (results + stored error). |
| src/aggregate/aggregate_exec.c | Refactors chunk serialization, adds reply_callback for FAIL policy, stores results/error for main-thread reply. |
| src/aggregate/aggregate.h | Introduces ChunkReplyState stored reply state and embeds it in AREQ; updates sync-context docs. |
Comments suppressed due to low confidence (1)
src/aggregate/aggregate_exec.c:1122
blockedClientReqCtx_destroy()no longer decrements the transferred AREQ reference, butAREQ_Execute_Callbackonly releases that ref viaAREQ_Execute()on the success path. On early error returns (e.g., index dropped / prepareExecutionPlan failure), the request is never decref’d, so it will leak (BlockedQueryNode only releases its own incremented ref). Ensure the background worker always releases its owned AREQ reference on all non-cursor paths, including error paths.
static void blockedClientReqCtx_destroy(blockedClientReqCtx *BCRctx) {
RedisModule_BlockedClientMeasureTimeEnd(BCRctx->blockedClient);
void *privdata = RedisModule_BlockClientGetPrivateData(BCRctx->blockedClient);
RedisModule_UnblockClient(BCRctx->blockedClient, privdata);
// Note: We don't call AREQ_DecrRef here despite owning the transferred reference.
// The reference is released by AREQ_Execute (shared code path also used by the main thread).
WeakRef_Release(BCRctx->spec_ref);
rm_free(BCRctx);
}
// Helper for error handling in AREQ_Execute_Callback.
// For FAIL policy (useReplyCallback=true): stores error for QueryReplyCallback to handle.
// For RETURN policy: replies with error directly.
static void ReplyOrStoreError(bool useReplyCallback, AREQ *req, RedisModuleCtx *ctx, QueryError *status) {
if (useReplyCallback) {
// Deep copy since QueryError contains heap-allocated strings.
// QueryReplyCallback will clear the stored error after replying.
QueryError_CloneFrom(status, &req->storedReplyState.err);
} else {
QueryError_ReplyAndClear(ctx, status);
}
}
void AREQ_Execute_Callback(blockedClientReqCtx *BCRctx) {
AREQ *req = blockedClientReqCtx_getRequest(BCRctx);
// Check if timed out while in the job queue.
if (AREQ_TimedOut(req)) {
// Timeout callback already replied.
AREQ_DecrRef(req);
blockedClientReqCtx_destroy(BCRctx);
return;
}
if (IsProfile(req)) {
req->profileClocks.profileQueueTime = rs_wall_clock_elapsed_ns(&req->profileClocks.initClock);
}
RedisModuleCtx *outctx = RedisModule_GetThreadSafeContext(BCRctx->blockedClient);
QueryError status = QueryError_Default();
// For FAIL policy, we must NOT reply directly from the background thread.
// The reply_callback (QueryReplyCallback) handles all replies to avoid double-reply issues
bool useReplyCallback = (req->reqConfig.timeoutPolicy == TimeoutPolicy_Fail);
StrongRef execution_ref = IndexSpecRef_Promote(BCRctx->spec_ref);
if (!StrongRef_Get(execution_ref)) {
// The index was dropped while the query was in the job queue.
QueryError_SetCode(&status, QUERY_ERROR_CODE_DROPPED_BACKGROUND);
ReplyOrStoreError(useReplyCallback, req, outctx, &status);
RedisModule_FreeThreadSafeContext(outctx);
blockedClientReqCtx_destroy(BCRctx);
return;
}
// Cursors are created with a thread-safe context, so we don't want to replace it
RedisSearchCtx *sctx = AREQ_SearchCtx(req);
if (!(AREQ_RequestFlags(req) & QEXEC_F_IS_CURSOR)) {
sctx->redisCtx = outctx;
}
// lock spec
RedisSearchCtx_LockSpecRead(sctx);
if (prepareExecutionPlan(req, &status) != REDISMODULE_OK) {
RedisSearchCtx_UnlockSpec(sctx);
goto error;
}
if (AREQ_RequestFlags(req) & QEXEC_F_IS_CURSOR) {
RedisModule_Reply _reply = RedisModule_NewReply(outctx), *reply = &_reply;
int rc = AREQ_StartCursor(req, reply, execution_ref, &status, false);
RedisModule_EndReply(reply);
if (rc != REDISMODULE_OK) {
goto error;
}
} else {
AREQ_Execute(req, outctx);
}
// If the execution was successful, we either:
// 1. Freed the request (if it was a regular query)
// 2. Kept it as the cursor's state (if it was a cursor query)
// Either way, we don't want to free `req` here. we set it to NULL so that it won't be freed with the context.
blockedClientReqCtx_setRequest(BCRctx, NULL);
goto cleanup;
error:
ReplyOrStoreError(useReplyCallback, req, outctx, &status);
cleanup:
// No need to unlock spec as it was unlocked by `AREQ_Execute` or will be unlocked by `blockedClientReqCtx_destroy`
RedisModule_FreeThreadSafeContext(outctx);
IndexSpecRef_Release(execution_ref);
blockedClientReqCtx_destroy(BCRctx);
}
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 16 out of 16 changed files in this pull request and generated 6 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
ca0d48a to
f222a2e
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 16 out of 16 changed files in this pull request and generated 3 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
fe4093f to
06f8b70
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 16 out of 16 changed files in this pull request and generated 8 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| QueryError_ClearError(status); | ||
| } else { | ||
| return ctx->areq ? AREQ_GetReplyState(ctx->areq) : ReplyState_NotReplied; | ||
| QueryError_ReplyAndClear(ctx, status); |
There was a problem hiding this comment.
Missing ClearError before CloneFrom causes silent clone failure
Medium Severity
CoordRequestCtx_ReplyOrStoreError calls QueryError_CloneFrom(status, &req->preRequestError) without first calling QueryError_ClearError(&req->preRequestError). The Rust implementation of QueryError_CloneFrom silently returns without cloning if the destination already holds an error (i.e., is not in OK state). Both AREQ_ReplyOrStoreError and HREQ_ReplyOrStoreError correctly call QueryError_ClearError on the destination before cloning, but this function omits it, breaking the established pattern.
Additional Locations (2)
| CoordRequestCtx_ReplyOrStoreError(reqCtx, ctx, status); | ||
| } else { | ||
| HREQ_ReplyOrStoreError(hreq, ctx, status); | ||
| } |
There was a problem hiding this comment.
Error statistics double-counted in coordinator hybrid FAIL path
Medium Severity
When useReplyCallback is true (FAIL policy), DistHybridCleanups calls QueryErrorsGlobalStats_UpdateError at line 779 before storing the error. Then DistHybridReplyCallback calls QueryErrorsGlobalStats_UpdateError again (lines 917 and 930) when it processes the stored error. This causes every coordinator hybrid error to be counted twice in global statistics. The standalone AREQ path (AREQ_Execute_Callback) avoids this by not tracking stats before calling AREQ_ReplyOrStoreError.
Additional Locations (1)
| * - In normal flow, QueryReplyCallback calls Cursor_Free/Cursor_Pause and clears this field. | ||
| * | ||
| * **Timeout edge case**: | ||
| * - If timeout fires before QueryReplyCallback runs, AREQ_Free must clean up the cursor. |
There was a problem hiding this comment.
Why? Can't we leave it for the worker always?
There was a problem hiding this comment.
Changed comment, and replied to that thread
| QueryError_ClearError(status); | ||
| } else { | ||
| return ctx->areq ? AREQ_GetReplyState(ctx->areq) : ReplyState_NotReplied; | ||
| QueryError_ReplyAndClear(ctx, status); |
There was a problem hiding this comment.
Missing pre-clear before clone risks memory leak
Medium Severity
CoordRequestCtx_ReplyOrStoreError calls QueryError_CloneFrom into preRequestError without first calling QueryError_ClearError on the destination. Both peer functions AREQ_ReplyOrStoreError and HREQ_ReplyOrStoreError clear the destination before cloning to avoid leaking any existing heap-allocated error strings. If preRequestError ever holds data when this function is called, the old strings would be overwritten without being freed.
Additional Locations (2)
| typedef struct { | ||
| SearchResult **results; // Aggregated results array (NULL if not aggregated yet) | ||
| int rc; // Pipeline return code (RS_RESULT_OK, RS_RESULT_EOF, etc.) | ||
| bool cursor_done; // Whether cursor is exhausted (for cursor queries) |
There was a problem hiding this comment.
Unused cursor_done field in ChunkReplyState struct
Low Severity
The cursor_done field in ChunkReplyState is declared and documented as "Whether cursor is exhausted (for cursor queries)" but is never set or read anywhere. The actual cursor-done computation happens in ChunkSerializeState (a separate struct), not in ChunkReplyState. This dead field adds confusion since readers might expect it to be part of the stored state used by the reply_callback.
| """Test timeout occurring after storing results for FT.AGGREGATE in standalone.""" | ||
| self._test_fail_timeout_after_store_impl(['FT.AGGREGATE', 'idx', '*']) | ||
|
|
||
| def test_no_timeout_cursor(self): |
There was a problem hiding this comment.
Same test name? Under a different class?
There was a problem hiding this comment.
Same name under different class (SA & Cluster)
|
|
||
| if (req) { | ||
| // Cursor reads don't use reply_callback, so clear the flag. | ||
| req->useReplyCallback = false; |
There was a problem hiding this comment.
Why not? By design, or will it be added in a follow-up?
There was a problem hiding this comment.
| stored->cursor = NULL; | ||
| } | ||
|
|
||
| // No AREQ_DecrRef here - BlockedQueryNode holds the reference, released via FreeQueryNode. |
There was a problem hiding this comment.
But in the case of a cursor, we may have already freed it. Is this intended?
There was a problem hiding this comment.
Without Cursor:
AREQ ownership: shared between blockedClientReqCtx (background thread) and BlockedQueryNode (timeout callback, reply callback).
Take a reference for the timeout callback access via node->privdata.
The BlockedQueryNode reference is released in FreeQueryNode via the freePrivData callback after timeout/reply callback completes.
The blockedClientReqCtx reference is released in blockedClientReqCtx_destroy,
With Cursor:
The cursor takes ownership of AREQ from the blockedClientReqCtx
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
| CoordRequestCtx_ReplyOrStoreError(reqCtx, ctx, status); | ||
| } else { | ||
| HREQ_ReplyOrStoreError(hreq, ctx, status); | ||
| } |
There was a problem hiding this comment.
Missing QueryError_HasError guard in DistHybridCleanups
Low Severity
DistHybridCleanups removed the old guard that skipped error reply when !QueryError_HasError(status). The new code reaches QueryErrorsGlobalStats_UpdateError and CoordRequestCtx_ReplyOrStoreError/HREQ_ReplyOrStoreError even when status has no error. While all current callers either set an error or are caught by the timeout check, the removed defensive guard makes this function fragile against future callers that might invoke it without setting an error when not timed out, leading to tracking a bogus error code and storing/replying with an empty error.
| hreq->storedReplyState.rc = rc; | ||
| hreq->storedReplyState.cv = cv; | ||
| hreq->storedReplyState.hasStoredResults = true; | ||
| } |
There was a problem hiding this comment.
Stored error not cloned in HREQ_StoreResults unlike AREQ path
Medium Severity
HREQ_StoreResults doesn't clone the qctx->err error state into storedReplyState.err, unlike AREQ_StoreResults which explicitly clones it. In serializeStoredResults_hybrid, the error is recovered via HybridRequest_GetError, but qctx->err still points to a now-invalid stack variable from the background thread's RSExecDistHybrid frame. The workaround at line 464 (qctx->err = &err) only patches over this, but any code that accessed qctx->err between sendChunk_hybrid returning and serializeStoredResults_hybrid running would hit a dangling pointer.
Additional Locations (1)
|
Pull request was converted to draft
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
| CoordRequestCtx_ReplyOrStoreError(reqCtx, ctx, status); | ||
| } else { | ||
| HREQ_ReplyOrStoreError(hreq, ctx, status); | ||
| } |
There was a problem hiding this comment.
Missing error guard in DistHybridCleanups before stats update
Low Severity
DistHybridCleanups unconditionally calls QueryErrorsGlobalStats_UpdateError(QueryError_GetCode(status), ...) without first checking QueryError_HasError(status). The old code had a !QueryError_HasError(status) guard that skipped the reply/stats path when no error was present. While current call sites always have an error set when not timed out, removing this guard means a future call without an error would increment a stats counter for a default/zero error code and attempt to store/reply with a non-error through CoordRequestCtx_ReplyOrStoreError or HREQ_ReplyOrStoreError.
| hreq->storedReplyState.rc = rc; | ||
| hreq->storedReplyState.cv = cv; | ||
| hreq->storedReplyState.hasStoredResults = true; | ||
| } |
There was a problem hiding this comment.
HREQ_StoreResults doesn't deep copy pipeline error state
Medium Severity
HREQ_StoreResults does not deep-copy the pipeline error state into storedReplyState.err, unlike AREQ_StoreResults which clones qctx->err. Instead, serializeStoredResults_hybrid retrieves errors via HybridRequest_GetError and points qctx->err at a local QueryError. If qctx->err originally pointed to a stack variable in the background thread's call frame (e.g., in RSExecDistHybrid), any code that accesses qctx->err before it is re-pointed in serializeStoredResults_hybrid would read a dangling pointer. The asymmetry with AREQ_StoreResults makes this fragile.




Describe the changes in the pull request
Current: FT.AGGREGATE, FT.SEARCH, and FT.HYBRID coordinator commands with
ON_TIMEOUT FAILpolicy reply directly from background threads. If timeout fires while the background thread replies, the timeout callback busy-waits on the main thread, waiting for the background thread to finish replying. The background thread successfully writes the reply to the buffer, but the reply buffer flush to the client happens on the main thread. Since the main thread is occupied by the busy-waiting timeout callback, the buffer is never flushed and the client never receives the response.Change: Refactor the coordinator execution path to use a
reply_callbackpattern. Background threads now store results in the request structure and callUnblockClient, allowing the main thread's reply callback to handle serialization.Outcome: Consistent timeout handling across all coordinator commands with FAIL policy, eliminating double-reply races and ensuring thread-safe serialization.
Which additional issues this PR fixes
Related to #8420
Main objects this PR modified
aggregate_exec.c- RefactoredsendChunk_Resp2/3to use modular helpers (handleSendChunkError,prepareSendChunkReply,finishSendChunkReply,serializeAndReplyResults)hybrid_exec.c- Added equivalent helpers for hybrid path (serializeAndReplyResults_hybrid,serializeStoredResults_hybrid,HREQ_StoreResults)coord_request_ctx.c/h- Unified request context for coordinator timeout synchronizationdist_hybrid.c- UpdatedDistHybridReplyCallbackto use stored resultshybrid_request.h- AddedisCoordflag andChunkReplyStatefor reply_callback pathMark if applicable
Release Notes
If a release note is required (bug fix / new feature / enhancement), describe the user impact of this PR in the title.
Note
Medium Risk
Changes coordinator/worker execution to serialize replies on the main thread via
reply_callback, affecting timeout, cursor lifecycle, and error propagation paths acrossFT.SEARCH/FT.AGGREGATE/FT.HYBRID. Risk is moderate due to concurrency/ownership refactors and new stored-state cleanup logic that could impact memory management or double-reply edge cases.Overview
Switches
ON_TIMEOUT FAILexecution to areply_callbackmodel so background workers no longer write replies directly; instead they store results/errors on the request andUnblockClienttriggers main-thread serialization.Adds
ChunkReplyState(stored results, clonedQueryError, cached serialization state, and a non-owning cursor handle) and ensures cleanup viaChunkReplyState_Destroy, removing the prior atomic reply-claim/busy-wait mechanism.Updates blocking-client plumbing (
BlockQueryClientWithTimeout,ConcurrentSearchBlockClientCtx, coordinator hybrid wiring) to require bothreply_callbackand timeout callbacks for FAIL policy, and extends tests + debug controls to pause before/after result storage to cover timeout races (including cursor reads under FAIL).Written by Cursor Bugbot for commit 072a16a. This will update automatically on new commits. Configure here.