Repository navigation
[MOD-14073] Coordinator-level FAIL timeout for FT.HYBRID - #8420
Conversation
There was a problem hiding this comment.
Pull request overview
This pull request implements coordinator-level FAIL timeout policy for FT.HYBRID commands to provide consistent timeout handling across the distributed search architecture. The implementation mirrors the existing AREQ timeout pattern by introducing reference counting and reply state management for HybridRequest objects.
Changes:
- Adds
CoordRequestCtxwrapper for managing shared ownership of requests between timeout callbacks (main thread) and execution handlers (background thread) - Extends
HybridRequestwith atomic timeout and reply state fields plus reference counting (mirroring AREQ) - Exposes AREQ reply state management functions (TryClaimReply, MarkReplied, GetReplyState) as public API for reuse with HybridRequest
- Updates all test code to use
HybridRequest_DecrRefinstead of directHybridRequest_Free
Reviewed changes
Copilot reviewed 20 out of 20 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| src/hybrid/hybrid_request.h | Adds timeout fields (timedOut, replyState, refcount) and new API functions for reference counting and reply state management |
| src/hybrid/hybrid_request.c | Implements HybridRequest_Init, IncrRef/DecrRef, timeout helpers, and reply state functions |
| src/hybrid/hybrid_exec.c | Adds timeout checks before and after pipeline execution in sendChunk_hybrid |
| src/hybrid/hybrid_debug.c | Updates to use HybridRequest_DecrRef |
| src/coord/coord_request_ctx.h | New file defining CoordRequestCtx wrapper for unified AREQ/HybridRequest timeout handling |
| src/coord/coord_request_ctx.c | Implements CoordRequestCtx creation, freeing, and forwarding to underlying request functions |
| src/coord/hybrid/dist_hybrid.h | Declares DistHybridTimeoutFailClient callback |
| src/coord/hybrid/dist_hybrid.c | Implements timeout callback and updates cleanup paths to handle reply ownership coordination |
| src/module.c | Integrates timeout handling in DistHybridCommand with CoordRequestCtx creation and callback registration |
| src/concurrent_ctx.h | Adds ConcurrentSearchBlockClientCtx struct and reqCtx field to ConcurrentSearchHandlerCtx |
| src/concurrent_ctx.c | Updates to use blocking client context configuration and adds GetBlockedClient accessor |
| src/aggregate/aggregate.h | Exposes reply state management functions as public API |
| src/aggregate/aggregate_request.c | Implements public TryClaimReply, MarkReplied, GetReplyState functions |
| src/aggregate/aggregate_exec.c | Removes static versions of reply state functions (now public) |
| tests/cpptests/*.cpp | All test files updated to use HybridRequest_DecrRef instead of HybridRequest_Free |
💡 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 21 out of 21 changed files in this pull request and generated 2 comments.
Comments suppressed due to low confidence (3)
src/module.c:84
- Duplicate include directive. The header "coord/coord_request_ctx.h" is already included at line 75.
#include "coord/coord_request_ctx.h"
src/coord/hybrid/dist_hybrid.c:875
- Extra blank line. This should be removed for consistency with the rest of the codebase.
src/coord/hybrid/dist_hybrid.c:868 - Missing space after 'if' keyword. The codebase consistently uses 'if (' rather than 'if('. Please add a space before the opening parenthesis for consistency.
if(!CoordRequestCtx_HasRequest(CoordReqCtx)) {
💡 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 21 out of 21 changed files in this pull request and generated 4 comments.
Comments suppressed due to low confidence (3)
src/concurrent_ctx.h:71
ConcurrentSearchHandlerCtx_Initusesmemset, butconcurrent_ctx.hdoes not include<string.h>. Any translation unit that includes this header without already including<string.h>will get an implicit declaration / compile error formemset(depending on flags). Add#include <string.h>(or equivalent) in this header.
// Initialize a ConcurrentSearchHandlerCtx to zero
static inline void ConcurrentSearchHandlerCtx_Init(ConcurrentSearchHandlerCtx *ctx) {
memset(ctx, 0, sizeof(*ctx));
}
src/module.c:84
coord_request_ctx.his included twice in this file. While#pragma onceprevents duplicate definitions, the second include is redundant and should be removed to keep includes tidy and avoid confusion during future merges.
#include "hybrid/hybrid_exec.h"
#include "coord/coord_request_ctx.h"
#include "coord/hybrid/dist_hybrid.h"
#include "util/redis_mem_info.h"
#include "notifications.h"
#include "aggregate/reply_empty.h"
#include "module_init.h"
#include "asm_state_machine.h"
#include "search_disk_utils.h"
#include "config.h"
#include "coord/coord_request_ctx.h"
src/hybrid/hybrid_request.h:17
hybrid_request.hredefinesRS_Atomicafter includingaggregate.h. In C builds,aggregate.halready definesRS_Atomicand does not#undefit, so this is a macro redefinition that can produce warnings (and potentially fail with-Werror). Add#undef RS_Atomicbefore redefining, or only redefine it in the__cpluspluscase whereaggregate.hundefs it.
// Re-define RS_Atomic macro for use in HybridRequest struct.
// aggregate.h undefs RS_Atomic at the end, so we need to define it again here.
#ifdef __cplusplus
#include <atomic>
#define RS_Atomic(T) std::atomic<T>
#else
#include <stdatomic.h>
#define RS_Atomic(T) _Atomic(T)
#endif
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
4f93ce0 to
8f6e680
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 21 out of 21 changed files in this pull request and generated 3 comments.
Comments suppressed due to low confidence (3)
src/coord/hybrid/dist_hybrid.c:785
DistHybridCleanupsonly callsRedisModule_EndReply(reply)when it successfully claims reply ownership. In the other branch it jumps tocleanup:and never ends the reply object, which can leak reply resources for timeout-owned cases and for early-error paths.RedisModule_EndReply(reply)should be called exactly once regardless of who owns the client reply (it’s separate from writing to the client).
QueryError_ReplyAndClear(ctx, status);
RedisModule_EndReply(reply);
CoordRequestCtx_MarkReplied(reqCtx);
cleanup:
WeakRef_Release(ConcurrentCmdCtx_GetWeakRef(cmdCtx));
if (sp) {
IndexSpecRef_Release(*strong_ref);
}
if (hreq) {
HybridRequest_DecrRef(hreq);
}
}
src/module.c:85
src/module.cincludescoord/coord_request_ctx.htwice. It’s harmless with#pragma oncebut adds noise and can slow compiles; drop the duplicate include.
#include "coord/coord_request_ctx.h"
#include "coord/hybrid/dist_hybrid.h"
#include "util/redis_mem_info.h"
#include "notifications.h"
#include "aggregate/reply_empty.h"
#include "module_init.h"
#include "asm_state_machine.h"
#include "search_disk_utils.h"
#include "config.h"
#include "coord/coord_request_ctx.h"
#ifdef ENABLE_ASSERT
src/hybrid/hybrid_request.h:17
hybrid_request.hredefinesRS_Atomicbut never#undefs it, unlikeaggregate.hwhich explicitly undefines it to avoid leaking the macro to downstream includes. This can cause surprising macro capture in unrelated headers included afterhybrid_request.h. Consider mirroring theaggregate.hpattern: defineRS_Atomiclocally for this header and#undef RS_Atomicbefore the final#endif/extern "C"close.
// Re-define RS_Atomic macro for use in HybridRequest struct.
// aggregate.h undefs RS_Atomic at the end, so we need to define it again here.
#ifdef __cplusplus
#include <atomic>
#define RS_Atomic(T) std::atomic<T>
#else
#include <stdatomic.h>
#define RS_Atomic(T) _Atomic(T)
#endif
💡 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 21 out of 21 changed files in this pull request and generated 3 comments.
Comments suppressed due to low confidence (2)
src/concurrent_ctx.h:71
ConcurrentSearchHandlerCtx_Initusesmemsetbutconcurrent_ctx.hdoes not include<string.h>. This can cause implicit declaration / compile failures depending on include order. Include<string.h>(or provide a dedicated zero-init via compound literal) in the header wherememsetis used.
// Initialize a ConcurrentSearchHandlerCtx to zero
static inline void ConcurrentSearchHandlerCtx_Init(ConcurrentSearchHandlerCtx *ctx) {
memset(ctx, 0, sizeof(*ctx));
}
src/module.c:84
src/module.cincludescoord/coord_request_ctx.htwice (lines 75 and 84). Remove the duplicate include to avoid redundant compilation and keep the include list tidy.
#include "hybrid/hybrid_exec.h"
#include "coord/coord_request_ctx.h"
#include "coord/hybrid/dist_hybrid.h"
#include "util/redis_mem_info.h"
#include "notifications.h"
#include "aggregate/reply_empty.h"
#include "module_init.h"
#include "asm_state_machine.h"
#include "search_disk_utils.h"
#include "config.h"
#include "coord/coord_request_ctx.h"
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| CoordRequestCtx *reqCtx = CoordRequestCtx_New(COMMAND_HYBRID); | ||
|
|
||
|
|
||
| ConcurrentSearchHandlerCtx handlerCtx; | ||
| ConcurrentSearchHandlerCtx_Init(&handlerCtx); | ||
|
|
||
| handlerCtx.coordStartTime = coordInitialTime; | ||
| handlerCtx.spec_ref = StrongRef_Demote(spec_ref); | ||
| handlerCtx.numShards = NumShards; // Capture NumShards from main thread for thread-safe access | ||
| handlerCtx.reqCtx = reqCtx; | ||
|
|
||
| handlerCtx.bcCtx.privdata = reqCtx; | ||
| handlerCtx.bcCtx.free_privdata = DistHybridFreePrivData; | ||
|
|
||
| if (RSGlobalConfig.requestConfigParams.timeoutPolicy == TimeoutPolicy_Fail) { | ||
| handlerCtx.bcCtx.callback = DistHybridTimeoutFailClient; | ||
| handlerCtx.bcCtx.timeoutMS = queryTimeoutMS; | ||
| } |
There was a problem hiding this comment.
reqCtx is stored as blocked-client private data and freed via bcCtx.free_privdata, but the background thread also dereferences it in RSExecDistHybrid (locks it, checks timedOut, sets request, etc.). In Redis modules the block-client free callback can run after the timeout callback, while the background thread may still be executing, which can lead to use-after-free of CoordRequestCtx. Consider adding reference counting to CoordRequestCtx itself (background thread holds a ref; free_privdata just DecrRef), or otherwise guarantee the context isn't freed until the worker finishes.
There was a problem hiding this comment.
Blocked Client private data is not freed until the free private data callback is called,
No matter the case, the free callback is not called until the background thread calls unblockClient
afbe486 to
4a026cc
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 21 out of 21 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (2)
src/hybrid/hybrid_request.h:17
hybrid_request.hredefinesRS_Atomicbut never#undefs it in C++ mode, unlikeaggregate.hwhich explicitly undefinesRS_Atomicbefore closingextern "C". This leaks the macro into includers and can cause unexpected macro redefinition/conflicts depending on include order. Consider adding an#undef RS_Atomicat the end of this header (for__cplusplus) to match the pattern inaggregate.h.
// Re-define RS_Atomic macro for use in HybridRequest struct.
// aggregate.h undefs RS_Atomic at the end, so we need to define it again here.
#ifdef __cplusplus
#include <atomic>
#define RS_Atomic(T) std::atomic<T>
#else
#include <stdatomic.h>
#define RS_Atomic(T) _Atomic(T)
#endif
src/module.c:85
coord/coord_request_ctx.his included twice in this file. It’s harmless due to include guards/#pragma once, but should be removed to avoid redundant includes and keep the include list clean.
#include "hybrid/hybrid_exec.h"
#include "coord/coord_request_ctx.h"
#include "coord/hybrid/dist_hybrid.h"
#include "util/redis_mem_info.h"
#include "notifications.h"
#include "aggregate/reply_empty.h"
#include "module_init.h"
#include "asm_state_machine.h"
#include "search_disk_utils.h"
#include "config.h"
#include "coord/coord_request_ctx.h"
#ifdef ENABLE_ASSERT
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| } | ||
|
|
||
| static inline void HybridRequest_SetSkipTimeoutChecks(HybridRequest *req, bool skipTimeoutChecks) { | ||
| req->skipTimeoutChecks = skipTimeoutChecks; |
There was a problem hiding this comment.
Shouldn't we propagate skipTimeoutChecks to sctx and AREQ subqueries?
🛡️ Jit Security Scan Results✅ No security findings were detected in this PR
Security scan by Jit
|
| */ | ||
| typedef struct CoordRequestCtx { | ||
| CommandType type; | ||
| union { |
There was a problem hiding this comment.
Now that we have RequestSyncCtx, can't we replace the union with the new RequestSyncCtx?
This could simplify also the implementation of CoordRequestCtx_TryClaimReply, CoordRequestCtx_MarkReplied, etc.
|
|
||
| // Create and set request atomically while holding lock | ||
| HybridRequest *hreq = MakeDefaultHybridRequest(sctx); | ||
| CoordRequestCtx_SetSyncCtx(reqCtx, &hreq->syncCtx); |
There was a problem hiding this comment.
Use-after-free: missing IncrRef for shared syncCtx pointer
High Severity
CoordRequestCtx_SetSyncCtx stores a raw pointer to the HybridRequest's embedded syncCtx, but the HybridRequest refcount (initialized to 1) is never incremented for the timeout callback's access. The background thread calls HybridRequest_DecrRef after sendChunk_hybrid returns, freeing the request. If the timeout callback (DistHybridTimeoutFailClient) wins TryClaimReply and then calls CoordRequestCtx_MarkReplied, it dereferences the now-freed syncCtx pointer — a use-after-free. The analogous FT.SEARCH path correctly calls AREQ_IncrRef in BlockQueryClientWithTimeout to share ownership, but HybridRequest_IncrRef is never called here.
Additional Locations (1)
| // Assert that timeout only occurs when skipTimeoutChecks is false (if not in debug) | ||
| RS_ASSERT(!(rc == RS_RESULT_TIMEDOUT) || !req->skipTimeoutChecks || IsDebug(req)); | ||
| // Assert that timeout only occurs when skipTimeoutChecks is true (if not in debug) | ||
| RS_ASSERT(!(rc == RS_RESULT_TIMEDOUT) || !AREQ_ShouldCheckTimeout(req) || IsDebug(req)); |
There was a problem hiding this comment.
Inverted assertion condition for timeout check
Medium Severity
The assertion !AREQ_ShouldCheckTimeout(req) evaluates to req->skipTimeoutChecks, which is the opposite of the original !req->skipTimeoutChecks. The old assert correctly required that RS_RESULT_TIMEDOUT only occurs when timeout checks are enabled (skip is false). The new assert incorrectly requires that RS_RESULT_TIMEDOUT only occurs when timeout checks are disabled. The negation of AREQ_ShouldCheckTimeout needs to be removed.
Additional Locations (1)
fc4841c to
608fe46
Compare
| // No error - just cleanup | ||
| // This can happen if during request creation we realized the query timed out, and the timeout callback already replied. | ||
| goto cleanup; | ||
| } |
There was a problem hiding this comment.
Missing MarkReplied causes potential main-thread deadlock
Medium Severity
When hreq is non-NULL and CoordRequestCtx_TryClaimReply succeeds but QueryError_HasError(status) returns false, the code jumps to cleanup without calling CoordRequestCtx_MarkReplied. This leaves the reply state stuck at ReplyState_Replying. If the timeout callback then fires, its TryClaimReply CAS fails (state is Replying, not NotReplied), and the busy-wait loop in DistHybridTimeoutFailClient spins forever since the state never transitions to Replied — deadlocking the Redis main thread.
Additional Locations (1)
| WeakRef spec_ref; // Weak reference to the index spec | ||
| bool isProfile; // Whether this is an FT.PROFILE command | ||
| size_t numShards; // Number of shards in the cluster (captured from main thread) | ||
| struct CoordRequestCtx *reqCtx; // Coordinator request context (for timeout handling) |
There was a problem hiding this comment.
Unused reqCtx field is dead code
Low Severity
The reqCtx field in ConcurrentSearchHandlerCtx is written to in DistHybridCommand but never read anywhere in the codebase. The CoordRequestCtx is actually accessed through the blocked client's private data (RedisModule_BlockClientGetPrivateData), making this field and its assignment entirely dead code.
Additional Locations (1)
|
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
| // We should check for timeout in pipeline if policy is return and timeout > 0 | ||
| return req->reqConfig.queryTimeoutMS > 0 && | ||
| (req->reqConfig.timeoutPolicy == TimeoutPolicy_Return); | ||
| } |
There was a problem hiding this comment.
ReturnStrict timeout disabled without alternative mechanism
Medium Severity
shouldCheckInPipelineTimeoutCoord only enables pipeline timeout checks for TimeoutPolicy_Return, excluding TimeoutPolicy_ReturnStrict. Meanwhile, DistHybridCommand only sets up a blocked client timeout callback for TimeoutPolicy_Fail. Before this PR, all policies had clock-based pipeline checks (via default skipTimeoutChecks = false). Now ReturnStrict has neither pipeline checks nor a blocked client timeout, so FT.HYBRID queries on the coordinator will never time out under this policy. Compare with DistSearchBlockClientWithTimeout, which handles both Fail and ReturnStrict.





Title: [Hybrid] Coordinator handle
failtimeout policyDescription:
Implements the
failtimeout policy forFT.HYBRIDat the coordinator level, ensuring that when a timeout occurs, the command returns an error immediately and discards any partial results.Background
The
failtimeout policy requires special handling at the coordinator level because:Implementation
This PR introduces
CoordRequestCtx- a coordinator-level request context that wrapsHybridRequestand provides synchronization primitives for timeout handling:Key Components:
CoordRequestCtxstruct (coord_request_ctx.h/c): Wrapper that holds a pointer to the actual request with timeout coordination fieldssetReqLockmutex: Protects the critical window between request creation and registrationtimedOutatomic flag: Signals timeout to the background threadNOT_REPLIED → REPLYING → REPLIEDtransitions using CAS operations to ensure only one thread repliesSynchronization Protocol:
Before request creation (background thread holds lock):
timedOutflag, replies with errorAfter request creation (lock released):
TryClaimReply()Timeout Callback (
DistHybridTimeoutFailClient):Background Thread (
RSExecDistHybrid):Related PRs
failtimeout for FT.SEARCH coordinatorMark 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
Touches coordinator blocked-client timeout callbacks and cross-thread reply/ownership coordination for
FT.HYBRID, where subtle races could cause double replies or leaks. Scope is mostly limited to hybrid/coordinator execution and is covered by expanded timeout tests.Overview
FT.HYBRIDon clustered deployments now honorsON_TIMEOUT failat the coordinator: when the client-side timeout triggers, the command returns a timeout error immediately and avoids emitting partial results.This adds a coordinator request wrapper (
CoordRequestCtx) plus shared sync primitives (RequestSyncCtx) to coordinate timeout signaling, reply ownership, and lifetime between the main-thread timeout callback and the coordinator worker thread. The concurrent execution wrapper is extended to pass blocked-client timeout callbacks/privdata, and tests are expanded to cover hybrid timeout before pickup, after fanout, and inFT.PROFILEhybrid flows.Written by Cursor Bugbot for commit e632fa0. This will update automatically on new commits. Configure here.