Skip to content

[MOD-13954] Shard Level FT.SEARCH/AGGREGATE - new mechanism for fail - #8335

Merged
lerman25 merged 29 commits into
masterfrom
omerl-search-shard-new-timeout-fail
Feb 17, 2026
Merged

lerman25 merged 29 commits into
masterfrom
omerl-search-shard-new-timeout-fail

Conversation

@lerman25

@lerman25 lerman25 commented Feb 10, 2026 •

Copy link
Copy Markdown
Collaborator

Description

This PR implements proper timeout handling for shard-level queries when running in "Run in Threads" mode with TIMEOUT_POLICY FAIL. Previously, when a query timed out on a shard, the timeout was only detected via clock checks during query execution. This PR adds block-client timeout mechanism that allows the main thread to signal timeouts to background worker threads, ensuring consistent timeout behavior across coordinator and shard queries.

Timeout Coordination

Introduce atomic coordination between the main thread (timeout callback) and background worker thread:

New atomic flags in AREQ:

  • timedOut: Signals that a timeout occurred (set by timeout callback, read by worker)
  • replyState: 3-state enum coordinating reply ownership between threads (prevents double replies)
  • skipTimeoutChecks: Disables clock-based timeout checks when using callback-based timeouts

Timeout callback (QueryTimeoutFailCallback):

  • Registered when blocking the client for background execution
  • Sets timedOut flag to signal the worker thread
  • Uses atomic compare-exchange on replyState to claim reply ownership
  • Either replies with timeout error or skips if worker already replied

Worker thread coordination:

  • Checks timedOut before starting pipeline execution
  • Uses atomic compare-exchange on replyState to claim reply ownership before replying
  • If timeout callback already claimed ownership, skips reply and cleans up

Skip clock-based timeout checks:

  • When using callback-based timeouts, clock checks are disabled via skipTimeoutChecks
  • This prevents redundant timeout detection and ensures consistent behavior
  • Assertions added to verify timeouts only occur when clock checks are enabled

AREQ Reply State and Reference Counting

Three-State Reply Coordination:

Replaced the original boolean replying field with a 3-state atomic enum for clearer semantics:

typedef enum {
  ReplyState_NotReplied = 0,  // Initial state - no reply sent yet
  ReplyState_Replying = 1,    // Reply in progress
  ReplyState_Replied = 2,     // Reply completed
} ReplyState;

This fixes an ambiguity where replying=false could mean either "not started" or "finished".

Added helper functions for better readability:

  • AREQ_TryClaimReply() - Atomically tries to claim reply ownership (CAS from NotReplied → Replying)
  • AREQ_MarkReplied() - Marks reply as complete (sets state to Replied)
  • AREQ_TryReplyWithError() - Combines claim + reply + mark in one call

AREQ Reference Counting:

Added reference counting to AREQ to handle shared ownership between blockedClientReqCtx (background thread) and BlockedQueryNode (timeout callback):

  • Added uint32_t refcount field to AREQ struct (initialized to 1)
  • AREQ_IncrRef() - Increment reference count
  • AREQ_DecrRef() - Decrement reference count, free when reaches 0
  • Made AREQ_Free() static/internal - only called by AREQ_DecrRef
  • Converted all external AREQ_Free calls to AREQ_DecrRef

Reference counting flow:

  1. AREQ created with refcount=1 (owned by blockedClientReqCtx)
  2. BlockQueryClientWithTimeout calls AREQ_IncrRef → refcount=2
  3. Background thread finishes, calls AREQ_DecrRef → refcount=1
  4. FreeQueryNode calls AREQ_DecrRef → refcount=0 → AREQ freed

BlockedQueryNode Cleanup Callback:

Added freePrivData callback to BlockedQueryNode to decouple it from assuming privdata is an AREQ:

  • Added BlockedQueryNode_FreePrivData callback typedef
  • Added freePrivData field to BlockedQueryNode struct
  • Updated BlockedQueries_AddQuery() to accept the callback

This includes all the changes we made. Would you like any modifications to this description?

Mark if applicable

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

Release Notes

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

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


Note

High Risk
Touches core query execution, timeout behavior, and cross-thread reply/lifetime coordination using new atomics and refcounting; bugs here could cause double replies, hangs, or memory safety issues under load.

Overview
Shard-level FT.SEARCH/FT.AGGREGATE running with WORKERS > 0 and ON_TIMEOUT FAIL now uses a Redis blocked-client timeout callback (main thread) to deterministically fail timed-out queries, instead of relying solely on in-query clock polling.

To prevent double replies and use-after-free across main/background threads, the PR adds atomic reply ownership (ReplyState), an atomic timedOut signal, and refcounted AREQ lifetime management; it also propagates a new skipTimeoutChecks flag through pipelines/iterators/trie/suffix expansion to disable clock-based timeout checks when the callback mechanism is active. Tests and debug tooling are updated to enforce/cover the new timeout-policy constraints and shard timeout behavior.

Written by Cursor Bugbot for commit 9cdb253. This will update automatically on new commits. Configure here.

@lerman25 lerman25 added action:run-benchmark enforce:coverage Run coverage flow even on draft pull request enforce:sanitize Run sanitizer flow even on draft pull request action:run-msmarco-benchmark labels Feb 10, 2026
@fcostaoliveira

Copy link
Copy Markdown
Contributor

Automated performance analysis summary

This comment was automatically generated given there is performance data available.

In summary:

  • Detected a total of 3 stable tests between versions.

You can check a comparison in detail via the grafana link

##

Details

Tests with No Significant Changes (3 tests)

Tests with No Significant Changes

Test Case Baseline master (median obs. +- std.dev) Comparison omerl-search-shard-new-timeout-fail (median obs. +- std.dev) % change (higher-better) Note
search-filtering-tag-numeric-filter-pipeline 10787 +- 1.8% (7 datapoints) 10882 0.9% No Change
vecsim-arxiv-titles-384-angular-filters-m16-ef-128-fulltext-filter 622 +- 4.2% (7 datapoints) 617 -0.8% No Change
vecsim-arxiv-titles-384-angular-filters-m16-ef-128-tag-filter 15918 +- 1.4% (7 datapoints) 15419 -3.1% potential REGRESSION

@fcostaoliveira

fcostaoliveira commented Feb 10, 2026 •

Copy link
Copy Markdown
Contributor

Automated performance analysis summary

This comment was automatically generated given there is performance data available.

In summary:

  • Detected a total of 32 stable tests between versions.
  • Detected a total of 8 highly unstable benchmarks (8 baseline).
  • Detected a total of 2 improvements above the improvement water line.
  • Detected a total of 1 regressions bellow the regression water line 8.0%.

You can check a comparison in detail via the grafana link

Performance Improvements - Comparison between master and omerl-search-shard-new-timeout-fail.

Time Period from a month ago. (environment used: oss-standalone)

Test Case Baseline master (median obs. +- std.dev) Comparison omerl-search-shard-new-timeout-fail (median obs. +- std.dev) % change (higher-better) Note
search-numeric 2239 +- 5.0% (7 datapoints) 3543 58.2% IMPROVEMENT
search-numeric-sortby-desc 2235 +- 1.3% (4 datapoints) 2518 12.7% IMPROVEMENT

Performance Regressions and Issues - Comparison between master and omerl-search-shard-new-timeout-fail.

Time Period from a month ago. (environment used: oss-standalone)

Test Case Baseline master (median obs. +- std.dev) Comparison omerl-search-shard-new-timeout-fail (median obs. +- std.dev) % change (higher-better) Note
ftsb-1M-enwiki_abstract-hashes-fulltext-2word-intersection-query-non-sortable 42 +- 39.7% UNSTABLE (4 datapoints) 29 -30.7% UNSTABLE (baseline high variance); server: FT.SEARCH p50 increased 8.3% (baseline CV=13.2%); client: client latency stable; neither server nor client side confirms regression
ftsb-1M-enwiki_abstract-hashes-fulltext-2word-union-query 3046 +- 10.6% UNSTABLE (4 datapoints) 2471 -18.9% UNSTABLE (baseline high variance); server: p50 latency stable; client: OverallQuantiles.allCommands.q50 increased 6.1% (baseline CV=8.1%); neither server nor client side confirms regression
search-ftsb-10K-enwiki_abstract-hashes-fulltext-aggregate-sortby-limit-0-100 947 +- 1.4% (4 datapoints) 816 -13.8% REGRESSION
search-numeric-sortby 2544 +- 26.9% UNSTABLE (7 datapoints) 2204 -13.4% UNSTABLE (baseline high variance); server: FT.SEARCH p50 increased 16.0% (baseline CV=22.2%); client: client latency stable; only server side confirms regression (client side stable) - insufficient evidence
ftsb-1M-enwiki_abstract-hashes-fulltext-2word-intersection-query 428 +- 22.2% UNSTABLE (4 datapoints) 385 -10.2% UNSTABLE (baseline high variance); server: p50 latency stable; client: client latency stable; neither server nor client side confirms regression
ftsb-1M-enwiki_abstract-hashes-fulltext-simple-1word-query 854 +- 11.8% UNSTABLE (4 datapoints) 789 -7.6% UNSTABLE (baseline high variance); server: FT.SEARCH p50 increased 10.1% (baseline CV=13.6%); client: OverallQuantiles.allCommands.q50 increased 6.6% (baseline CV=12.5%); only server side confirms regression (client side stable) - insufficient evidence
search-numeric-sortby-desc-optimize 31 +- 12.6% UNSTABLE (4 datapoints) 31 -1.6% UNSTABLE (baseline high variance); server: p50 latency stable; client: client latency stable; neither server nor client side confirms regression
ftsb-1M-enwiki_abstract-hashes-fulltext-2word-union-query-non-sortable 989 +- 11.2% UNSTABLE (4 datapoints) 997 0.8% UNSTABLE (baseline high variance); server: p50 latency stable; client: client latency stable; neither server nor client side confirms regression
search-filtering-tag-numeric 247 +- 10.7% UNSTABLE (4 datapoints) 252 2.2% UNSTABLE (baseline high variance); server: FT.AGGREGATE p50 increased 6.6% (baseline CV=7.4%); client: Latency increased 6.8% (baseline CV=7.3%); neither server nor client side confirms regression
Tests with No Significant Changes (32 tests)

Tests with No Significant Changes

Test Case Baseline master (median obs. +- std.dev) Comparison omerl-search-shard-new-timeout-fail (median obs. +- std.dev) % change (higher-better) Note
ftsb-10K-enwiki_abstract-hashes-fulltext-sortby 71 +- 2.8% (7 datapoints) 73.00 2.9% No Change
ftsb-10K-enwiki_abstract-hashes-term-prefix 6380 +- 6.1% (4 datapoints) 6196.00 -2.9% No Change
ftsb-10K-enwiki_abstract-hashes-term-suffix 2209 +- 0.7% (4 datapoints) 2261.00 2.4% No Change
ftsb-10K-enwiki_abstract-hashes-term-suffix-withsuffixtrie 16565 +- 1.4% (4 datapoints) 15994.00 -3.4% potential REGRESSION
ftsb-10K-enwiki_abstract-hashes-term-wildcard 8688 +- 4.1% (7 datapoints) 8122.00 -6.5% potential REGRESSION
ftsb-10K-enwiki_pages-hashes-fulltext-mixed_simple-1word-query_write_1_to_read_20.yml 1011 +- 6.6% (7 datapoints) 978.00 -3.2% potential REGRESSION
ftsb-10K-enwiki_pages-hashes-load 63242 +- 0.7% (4 datapoints) 62688.00 -0.9% No Change
ftsb-10K-multivalue-numeric-json 973 +- 1.2% (7 datapoints) 994.00 2.1% No Change
ftsb-10K-singlevalue-numeric-json 475 +- 0.3% (7 datapoints) 472.00 -0.7% No Change
ftsb-1K-enwiki_abstract-hashes-term-contains 1950 +- 0.8% (7 datapoints) 1969.00 1.0% No Change
ftsb-1M-enwiki_abstract-hashes-load 22405 +- 4.0% (7 datapoints) 23086.00 3.0% potential IMPROVEMENT
ftsb-1M-nyc_taxis-ftadd-load 27980 +- 2.4% (7 datapoints) 28277.00 1.1% No Change
ftsb-1M-nyc_taxis-hashes-load 29816 +- 2.7% (7 datapoints) 29056.00 -2.5% No Change
search-aggregate-post-filter-simple.yml 17337 +- 1.8% (4 datapoints) 17049.00 -1.7% No Change
search-filtering-tag-numeric-filter-pipeline 10562 +- 1.7% (7 datapoints) 10454.00 -1.0% No Change
search-ftsb-10K-enwiki_abstract-hashes-fulltext-search-sortby-limit-0-100 780 +- 2.8% (7 datapoints) 800.00 2.5% No Change
search-ftsb-10K-enwiki_abstract-hashes-term-withoutsuffix-trie 14047 +- 1.0% (7 datapoints) 14097.00 0.4% No Change
search-ftsb-10K-enwiki_abstract-hashes-term-withsuffix-trie 14019 +- 1.2% (7 datapoints) 13852.00 -1.2% No Change
search-ftsb-1700K-docs-union-iterators-q3 8.0 +- 0.8% (7 datapoints) 8.20 1.9% No Change
search-ftsb-1M-enwiki_abstract-hashes-fulltext-simple-1word-query-non-sortable 166 +- 9.1% (7 datapoints) 157.00 -5.7% waterline=9.1%. potential REGRESSION
search-ftsb-1M-enwiki_abstract-hashes-fulltext-simple-1word-query-one-indexed-field 6946 +- 2.6% (7 datapoints) 6797.00 -2.1% No Change
search-ftsb-370K-docs-union-iterators-q4 8.4 +- 0.9% (7 datapoints) 8.40 0.1% No Change
search-ftsb-5200K-docs-union-iterators-q1 0.83 +- 1.5% (7 datapoints) 0.86 3.6% potential IMPROVEMENT
search-ftsb-5500K-docs-union-iterators-q2 1.2 +- 0.7% (7 datapoints) 1.20 1.7% No Change
search-geo 220 +- 2.1% (7 datapoints) 219.00 -0.3% No Change
search-high-cardinality-negation-term-baseline 39 +- 0.8% (4 datapoints) 36.00 -7.2% potential REGRESSION
search-high-cardinality-negation-term-comparison_union_all_other_terms 14 +- 1.5% (4 datapoints) 15.00 4.7% potential IMPROVEMENT
search-numeric-optimize 8124 +- 1.8% (4 datapoints) 7735.00 -4.8% potential REGRESSION
search-numeric-sortby-optimize 25 +- 6.2% (7 datapoints) 25.00 -2.7% No Change
vecsim-arxiv-titles-384-angular-filters-m16-ef-128-fulltext-filter 578 +- 6.8% (7 datapoints) 546.00 -5.5% potential REGRESSION
vecsim-arxiv-titles-384-angular-filters-m16-ef-128-numeric-filter 150 +- 9.3% (7 datapoints) 143.00 -4.6% waterline=9.3%. potential REGRESSION
vecsim-arxiv-titles-384-angular-filters-m16-ef-128-tag-filter 15568 +- 1.0% (7 datapoints) 15619.00 0.3% No Change

@lerman25
lerman25 force-pushed the omerl-search-shard-new-timeout-fail branch from 6deebad to 07a0aa5 Compare February 11, 2026 15:55
@codecov

codecov Bot commented Feb 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.93711% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.49%. Comparing base (27e2e31) to head (9cdb253).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
src/aggregate/aggregate_exec.c 81.25% 12 Missing ⚠️
...rc/redisearch_rs/rqe_iterators/src/util/timeout.rs 0.00% 2 Missing ⚠️
src/aggregate/aggregate.h 83.33% 1 Missing ⚠️
src/aggregate/reply_empty.c 66.66% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##           master    #8335    +/-   ##
========================================
  Coverage   82.48%   82.49%            
========================================
  Files         415      415            
  Lines       59254    59361   +107     
  Branches    17310    17313     +3     
========================================
+ Hits        48877    48968    +91     
- Misses      10196    10212    +16     
  Partials      181      181            
Flag Coverage Δ
flow 84.19% <90.60%> (+0.04%) ⬆️
unit 50.87% <25.78%> (-0.07%) ⬇️

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

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

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

@lerman25
lerman25 force-pushed the omerl-search-shard-new-timeout-fail branch from e3e60cb to 601952a Compare February 12, 2026 07:32
@lerman25
lerman25 requested a review from GuyAv46 February 14, 2026 18:51
@lerman25
lerman25 marked this pull request as ready for review February 14, 2026 18:51
Comment thread src/aggregate/aggregate_exec.c Resolved
Comment thread src/aggregate/aggregate_exec.c Resolved
@lerman25
lerman25 requested a review from GuyAv46 February 17, 2026 13:15
Comment thread src/aggregate/aggregate.h Outdated
#define AREQ_RP(req) AREQ_QueryProcessingCtx(req)->endProc

#ifdef __cplusplus
#undef _Atomic

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.

remove (or undef RS_Atomic)

Comment thread src/aggregate/aggregate.h Outdated
RS_Atomic(bool) timedOut;
// Reply ownership state, coordinates reply between main and background thread
// Uses ReplyState enum: NOT_REPLIED -> REPLYING -> REPLIED transitions
RS_Atomic(int) replyState;

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.

Consider using atomic uint8_t

Comment thread src/aggregate/aggregate.h Outdated
bool skipTimeoutChecks;
// Reference count for shared ownership between QueryNode (timeout callback) and background thread.
// Initialized to 1. Free when reaches 0.
uint32_t refcount;

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.

We don't expect too many referees, right?
Consier using a u8

return !HasSortBy(req) && !HasGroupBy(req) && !IsCount(req);
}

static bool shouldCheckInPipelineTimeout(AREQ *req) {

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.

Let's mark this function as only safe for the main thread, or avoid using RunInThread() (and check if the request flag QEXEC_F_RUN_IN_BACKGROUND is on instead)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Added a comment since QEXEC_F_RUN_IN_BACKGROUND is net set at that point

@lerman25
lerman25 requested a review from GuyAv46 February 17, 2026 14:24
Comment thread src/aggregate/aggregate_exec.c Resolved
@lerman25
lerman25 force-pushed the omerl-search-shard-new-timeout-fail branch from bc0c119 to c2c7cef Compare February 17, 2026 15:07
GuyAv46
GuyAv46 previously approved these changes Feb 17, 2026

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

Great job

Comment thread src/aggregate/aggregate.h Outdated
// Reply state for coordinating replies between main thread (timeout callback) and background thread
// Transitions: NOT_REPLIED -> REPLYING -> REPLIED
typedef enum {
typedef enum : uint8_t {

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.

Is this valid for C?

Comment thread src/aggregate/aggregate.h
Comment on lines 214 to 215
} ReplyState;
typedef struct AREQ {

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.

Let's have a gap

@sonarqubecloud

Copy link
Copy Markdown

@sonarqubecloud

Copy link
Copy Markdown

❌ The last analysis has failed.

See analysis details on SonarQube Cloud

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

// Background thread owns reply - wait for it to finish if still in progress
while (atomic_load_explicit(&req->replyState, memory_order_acquire) == ReplyState_Replying) {
// Busy wait until background thread transitions to REPLIED
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Busy spin on main thread without yield

Medium Severity

The QueryTimeoutFailCallback runs on the main Redis thread and contains a tight busy-wait loop (while with atomic_load) when the background thread is in the ReplyState_Replying state. This spin loop with no yield, sleep, or pause instruction blocks the main thread and wastes CPU cycles. Although the replying duration is typically short, any delay in the background thread (e.g., slow I/O during reply serialization) would stall the entire Redis event loop.

Fix in Cursor Fix in Web

Comment thread src/aggregate/aggregate.h
#define RS_Atomic(T) std::atomic<T>
extern "C" {
#else
#define RS_Atomic(T) _Atomic(T)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

RS_Atomic macro not undefined in C mode

Low Severity

The RS_Atomic(T) macro is defined in both C (_Atomic(T)) and C++ (std::atomic<T>) paths, but the #undef RS_Atomic at the end of the header is only inside the #ifdef __cplusplus block. In C mode, the macro leaks to all translation units that include aggregate.h, polluting the global macro namespace. A reviewer also flagged this issue.

Additional Locations (1)

Fix in Cursor Fix in Web

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

Comment thread src/aggregate/aggregate.h

#ifdef __cplusplus
#undef RS_Atomic

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

RS_Atomic macro not undefined in C path

Low Severity

The RS_Atomic macro is defined for both C (_Atomic(T)) and C++ (std::atomic<T>) paths, but #undef RS_Atomic only appears inside the #ifdef __cplusplus block. In C compilation units, the macro leaks out of this header, potentially polluting the macro namespace. A reviewer already flagged this ("remove (or undef RS_Atomic)").

Fix in Cursor Fix in Web

@lerman25
lerman25 added this pull request to the merge queue Feb 17, 2026
Merged via the queue into master with commit c97936e Feb 17, 2026
55 of 56 checks passed
@lerman25
lerman25 deleted the omerl-search-shard-new-timeout-fail branch February 17, 2026 18:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enforce:coverage Run coverage flow even on draft pull request enforce:sanitize Run sanitizer flow even on draft pull request size:L size:M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants