Skip to content

[MOD-13617] [Agg] Coordinator: extend RETURN_STRICT partial results to SORTBY pipelines - #9366

Merged
lerman25 merged 33 commits into
masterfrom
omerl-agg-coord-expand-sortby
May 4, 2026
Merged

lerman25 merged 33 commits into
masterfrom
omerl-agg-coord-expand-sortby

Conversation

@lerman25

@lerman25 lerman25 commented Apr 29, 2026 •

Copy link
Copy Markdown
Collaborator

Describe the changes in the pull request

Stacked on top of #9234. That PR shipped the coordinator RETURN_STRICT machinery for FT.AGGREGATE (CAS handshake, drain mode, abort wake-up) but only classified two pipeline shapes as yielding partial results: bare RPNet and RPPager_Limiter -> RPNet. This PR widens that classification to the SORTBY shapes and is intended to serve as the template for adding further shapes in follow-ups.

  1. Current: SORTBY pipelines fall into the discard class — on RETURN_STRICT timeout the coordinator replies [] + total_results: 0 + timeout warning, even when responsive shards delivered rows that the sorter had already merged into its heap.
  2. Change:
    • RPSorter (rpsortNext_innerLoop) handles all three timeout policies explicitly and switches to yield mode under RETURN_STRICT while propagating TIMEDOUT in O(1), so the main-thread drain can pop the sorted prefix without delaying the BG abort.
    • pipelineCanYieldPartialResults is rewritten as a peel chain (optional RPPager_Limiter, optional RPSorter, then RPNet root) instead of an enumerated shape switch. Adding new shapes is now a one-line peel-step insertion.
    • Three deterministic pytest cases mirror the trivial-pipeline coverage from [MOD-13617] [Agg] Coordinator handle return-strict #9234 across the three regions (in-pipeline / all-shards-paused / post-store).
  3. Outcome: SORTBY pipelines now surface a sorted partial prefix on RETURN_STRICT timeout instead of []. Behaviour for the shapes already supported by [MOD-13617] [Agg] Coordinator handle return-strict #9234 is unchanged. The classifier is shaped so each future shape addition is a small, mechanical patch.

How to extend (template for follow-up PRs)

The recipe demonstrated here for SORTBY generalizes to any RP that can be made to surface a coherent partial prefix:

  1. Make the operator timeout-policy-aware: under RETURN_STRICT either
    (a) propagate TIMEDOUT in O(1) without buffering anything new, or
    (b) freeze its accumulated state and switch to yield mode so the drain on the main thread can pop a coherent prefix. Decide which based on whether a partial output of that operator is a valid answer to the query.
  2. Add the operator type to the peel chain in pipelineCanYieldPartialResults. Order matters: peel from the end (closest to the client) toward RPNet.
  3. Add deterministic pytest coverage for the three timeout regions (in-pipeline via SYNC_POINT, all-shards-paused, post-store) using the existing helpers in TestCoordinatorTimeout.

Which additional issues this PR fixes

  1. MOD-13617
  2. Builds on [MOD-13617] [Agg] Coordinator handle return-strict #9234

Main objects this PR modified

  1. rpsortNext_innerLoop (src/result_processor.c) — explicit per-policy handling, RETURN_STRICT switches to yield + immediate TIMEDOUT.
  2. pipelineCanYieldPartialResults (src/coord/dist_aggregate.c) — refactored to a peel chain over RPPager_Limiter / RPSorter / RPNet.
  3. tests/pytests/test_blocked_client_timeout.py::TestCoordinatorTimeout — three new SORTBY cases and an upgraded one_shard_paused SORTBY case (now sync-pointed for exact partial-row count).

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

Note

Medium Risk
Changes coordinator timeout behavior for distributed FT.AGGREGATE by allowing partial draining through RPSorter, which can affect result shape and total_results under timeout scenarios. Risk is moderated by targeted state-machine changes in RPSorter and extensive new deterministic timeout tests.

Overview
Extends FT.AGGREGATE coordinator RETURN_STRICT timeouts to return a sorted partial prefix for SORTBY pipelines, instead of always replying with an empty result set.

This updates pipelineCanYieldPartialResults to accept pipelines ending in RPSorter (optionally under RPPager_Limiter, with arbitrary processors between sorter and RPNet) and adjusts RPSorter timeout handling so RETURN_STRICT switches to yield mode but propagates TIMEDOUT immediately for fast background unwind. Adds/rewrites pytest coverage to deterministically exercise one-shard-paused, all-shards-paused, and post-store timeout races for these SORTBY shapes.

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

lerman25 added 24 commits April 22, 2026 18:42
(cherry picked from commit 94a9a63)
Classify the coordinator result-processor chain as trivial when it is
exactly RPNet -> RPPager_Limiter -> end (i.e. a plain query with at
most a LIMIT, no sort / group / buffering). Profile queries are
excluded because RPProfile wraps each RP.

The flag is consumed in a subsequent commit to decide whether the
RETURN-STRICT timeout callback may safely drain queued shard replies on
the main thread after the background pipeline aborts.
After a successful AREQ_TryClaimAggregateResults, re-check AREQ_TimedOut
before invoking the pipeline. Handles the narrow race where the
RETURN-STRICT timeout callback set the flag and woke the abort channel
between our CAS and the first Next() — in that case the timeout
callback is already blocked in AREQ_WaitForAggregateResultsComplete and
expects to read whatever we store. Skipping the pipeline leaves the
stored state with zero results and rc=RS_RESULT_TIMEDOUT, which the
main thread will honor.
Add a drainOnly flag on RPNet, set by the RETURN-STRICT timeout
callback on the main thread once the background pipeline has aborted
and exited. In this mode rpnetNext:

  * skips the wall-clock TimedOut check (the deadline has by
    definition already passed); and
  * treats an empty channel pop as RS_RESULT_EOF rather than
    RS_RESULT_TIMEDOUT.

MRChannel_PopWithTimeout already returns NULL immediately when the
abort flag is set and the channel is empty, so no new channel
primitive is needed - the drain loop simply keeps calling the
existing pop path until it returns EOF.

Safe as a plain bool: set by the main thread only after the
background thread is guaranteed to have exited the pipeline.
When the upstream signals RS_RESULT_TIMEDOUT during RPDepleter's
accumulation phase and the effective timeout policy is RETURN-STRICT,
return TIMEDOUT immediately instead of transitioning to the yield
phase and draining the already-buffered results.

This matches the behavior already in RPSorter,
RPMaxScoreNormalizer, and RPSafeLoader (via their
"rc != RS_RESULT_OK" fallthrough which only consumes
TimeoutPolicy_Return on the yield-transition path). RETURN-STRICT
requires a strict empty-results response on timeout for pipelines
that contain buffering result processors.
When the RETURN-STRICT timeout callback observes that the background
thread has already claimed the aggregation results, it now waits for
the background pipeline to exit (as before) and then — for pipelines
classified as trivial (`RPNet -> RPPager -> end`) — resumes the
pipeline on the main thread to harvest shard replies that were already
queued in the channel before the deadline.

The pager's internal `remaining` and `qctx->resultLimit` were both
decremented by the background's partial run, so the drain loop
naturally respects the user's LIMIT and terminates when either the
budget is exhausted or RPNet reports EOF (empty channel under
`drainOnly`).

`storedReplyState.results` may be NULL in the post-claim bail path
(background exited before allocating the results array); the drain
allocates a fresh array in that case so downstream serialization has a
valid pointer.

Non-trivial pipelines are unaffected: the drain is a no-op and the
callback continues to reply with whatever the background stored.
@jit-ci

jit-ci Bot commented Apr 29, 2026 •

Copy link
Copy Markdown

🛡️ Jit Security Scan Results

CRITICAL HIGH MEDIUM

✅ No security findings were detected in this PR


Security scan by Jit

@codecov

codecov Bot commented Apr 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.42%. Comparing base (edefb25) to head (c57aae3).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9366      +/-   ##
==========================================
- Coverage   81.42%   81.42%   -0.01%     
==========================================
  Files         493      493              
  Lines       67270    67286      +16     
  Branches    23882    23882              
==========================================
+ Hits        54775    54788      +13     
- Misses      12254    12257       +3     
  Partials      241      241              
Flag Coverage Δ
flow 83.57% <100.00%> (-0.05%) ⬇️
unit 50.41% <0.00%> (+<0.01%) ⬆️

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.

Base automatically changed from omerl-agg-coord-return-strict to master April 29, 2026 16:34
RPSorter (rpsortNext_innerLoop) now handles all three timeout policies
explicitly:
  - FAIL: propagate TIMEDOUT in O(1) (no yield transition).
  - RETURN: existing behavior (switch to yield, surface buffered rows).
  - RETURN_STRICT: switch to yield (so the main-thread drain can pop the
    buffered, sorted prefix) and propagate TIMEDOUT immediately so the BG
    abort path is not delayed by per-row yields.

pipelineCanYieldPartialResults is consolidated from a per-shape boolean
enumeration to a peel chain: optional RPPager_Limiter, optional RPSorter,
then RPNet root. Adds the two SORTBY shapes (RPSorter -> RPNet and
RPPager_Limiter -> RPSorter -> RPNet) without changing behavior for the
shapes already supported in #9234.

Adds three pytest cases mirroring the trivial-pipeline coverage:
SORTBY one-shard-paused (sync-pointed for exact partial count),
all-shards-paused, and post-store.
@lerman25
lerman25 force-pushed the omerl-agg-coord-expand-sortby branch 2 times, most recently from 5c7ae78 to 81c3ac4 Compare April 29, 2026 19:47
@CLAassistant

CLAassistant commented Apr 30, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Comment thread src/coord/dist_aggregate.c Outdated
Comment on lines +282 to +283
if (rp && rp->type == RP_SORTER) {
rp = rp->upstream;

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.

In the sorter case, why do we only want to support it if its upstream is the root?
Aren't we going to only read from the sorter heap in this case?

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.

You are right, need to expand that

Comment thread src/result_processor.c Outdated
return rc;
}
// Both Return and ReturnStrict switch to the yield state; they only
// differ in whether buffered results are surfaced before the timeout.

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.

Why do we have this difference? Why not start the yield immediately for return-strict as well?

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.

Since the main-thread is waiting for the BG thread to exit the pipeline, my idea is to go out of the pipeline ASAP - and let the main thread continue the extraction

@lerman25
lerman25 force-pushed the omerl-agg-coord-expand-sortby branch from 81c3ac4 to 1a439fe Compare April 30, 2026 16:19
@github-actions github-actions Bot added size:L and removed size:M labels Apr 30, 2026
@lerman25
lerman25 force-pushed the omerl-agg-coord-expand-sortby branch from 1a439fe to 6aad03e Compare April 30, 2026 16:56

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

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 2e6118f. Configure here.

Comment thread src/coord/dist_aggregate.c Outdated
return false;
// Shape 3: drain pops from the sorter's heap, so what sits between RPSorter
// and RPNet doesn't matter.
return rp->type == RP_SORTER;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Shape 3 classifier causes inconsistent total_results for buffering pipelines

Medium Severity

Shape 3 in pipelineCanYieldPartialResults accepts any RP between RPSorter and RPNet, including fully-buffering ones like RPGrouper. When a grouper sits between the network root and the sorter, TIMEDOUT propagates before the grouper flushes, so the sorter's heap is empty and the drain harvests zero rows. However, because canYieldPartialResults is true, the post-drain zeroing of totalResults at line 717–719 is skipped, producing a reply where total_results equals the responsive-shard doc count but results is [] — an inconsistency not present before this PR (previously the shape was rejected, and totalResults was zeroed to match the empty results).

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 2e6118f. Configure here.

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.

This discrepancy is known and is the current behavior of return policy as well.
@GuyAv46 WDYT - should I zero out totalresults?

return true;
// Optionally peel a single RPPager_Limiter at the very end.
ResultProcessor *rp = end;
if (rp->type == RP_PAGER_LIMITER) {

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 moving this up, since shapes 1+2 are the same as the two variants of 3. Basically, RP_PAGER_LIMITER is "transparent" in this context

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.

Good idea

Comment thread src/coord/dist_aggregate.c Outdated
if (rp->type == RP_PAGER_LIMITER) {
rp = rp->upstream;
if (!rp) {
return false;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

If this even possible?

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.

No, replaced with ASSERT

@sonarqubecloud

sonarqubecloud Bot commented May 4, 2026

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
28.4% Duplication on New Code (required ≤ 3%)
D Reliability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

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

🎉

@lerman25
lerman25 enabled auto-merge May 4, 2026 11:03
@lerman25
lerman25 added this pull request to the merge queue May 4, 2026
Merged via the queue into master with commit 2bbc0fe May 4, 2026
49 of 50 checks passed
@lerman25
lerman25 deleted the omerl-agg-coord-expand-sortby branch May 4, 2026 16:01
pierrelambert pushed a commit to pierrelambert/RediSearch that referenced this pull request May 13, 2026
…o SORTBY pipelines (RediSearch#9366)

* Setup callback and mechanism

* Implement Abort Channel Pop + Use

(cherry picked from commit 94a9a63)

* Add test for no-tail Case

* Expand

* Cover before RPNET

* Remove timeout check from RETURN polcy

* refactor comments

* Reset claim of aggregate results

* Make test more accurate and robust

* Add isTrivialPipeline classifier on coordinator

Classify the coordinator result-processor chain as trivial when it is
exactly RPNet -> RPPager_Limiter -> end (i.e. a plain query with at
most a LIMIT, no sort / group / buffering). Profile queries are
excluded because RPProfile wraps each RP.

The flag is consumed in a subsequent commit to decide whether the
RETURN-STRICT timeout callback may safely drain queued shard replies on
the main thread after the background pipeline aborts.

* startPipeline: bail post-claim when already timed out

After a successful AREQ_TryClaimAggregateResults, re-check AREQ_TimedOut
before invoking the pipeline. Handles the narrow race where the
RETURN-STRICT timeout callback set the flag and woke the abort channel
between our CAS and the first Next() — in that case the timeout
callback is already blocked in AREQ_WaitForAggregateResultsComplete and
expects to read whatever we store. Skipping the pipeline leaves the
stored state with zero results and rc=RS_RESULT_TIMEDOUT, which the
main thread will honor.

* Add drainOnly mode to RPNet

Add a drainOnly flag on RPNet, set by the RETURN-STRICT timeout
callback on the main thread once the background pipeline has aborted
and exited. In this mode rpnetNext:

  * skips the wall-clock TimedOut check (the deadline has by
    definition already passed); and
  * treats an empty channel pop as RS_RESULT_EOF rather than
    RS_RESULT_TIMEDOUT.

MRChannel_PopWithTimeout already returns NULL immediately when the
abort flag is set and the channel is empty, so no new channel
primitive is needed - the drain loop simply keeps calling the
existing pop path until it returns EOF.

Safe as a plain bool: set by the main thread only after the
background thread is guaranteed to have exited the pipeline.

* RPDepleter: O(1) TIMEDOUT abort under RETURN-STRICT

When the upstream signals RS_RESULT_TIMEDOUT during RPDepleter's
accumulation phase and the effective timeout policy is RETURN-STRICT,
return TIMEDOUT immediately instead of transitioning to the yield
phase and draining the already-buffered results.

This matches the behavior already in RPSorter,
RPMaxScoreNormalizer, and RPSafeLoader (via their
"rc != RS_RESULT_OK" fallthrough which only consumes
TimeoutPolicy_Return on the yield-transition path). RETURN-STRICT
requires a strict empty-results response on timeout for pipelines
that contain buffering result processors.

* Coordinator: drain trivial pipelines on main after timeout

When the RETURN-STRICT timeout callback observes that the background
thread has already claimed the aggregation results, it now waits for
the background pipeline to exit (as before) and then — for pipelines
classified as trivial (`RPNet -> RPPager -> end`) — resumes the
pipeline on the main thread to harvest shard replies that were already
queued in the channel before the deadline.

The pager's internal `remaining` and `qctx->resultLimit` were both
decremented by the background's partial run, so the drain loop
naturally respects the user's LIMIT and terminates when either the
budget is exhausted or RPNet reports EOF (empty channel under
`drainOnly`).

`storedReplyState.results` may be NULL in the post-claim bail path
(background exited before allocating the results array); the drain
allocates a fresh array in that case so downstream serialization has a
valid pointer.

Non-trivial pipelines are unaffected: the drain is a no-op and the
callback continues to reply with whatever the background stored.

* Improve + Tests

* cursor comment

* Improve

* More fixes

* Review comment fixes

* Use the new SyncPointfunctionality

* Fix no results

* Fix format

* MOD-13617: extend RETURN_STRICT partial results to SORTBY pipelines

RPSorter (rpsortNext_innerLoop) now handles all three timeout policies
explicitly:
  - FAIL: propagate TIMEDOUT in O(1) (no yield transition).
  - RETURN: existing behavior (switch to yield, surface buffered rows).
  - RETURN_STRICT: switch to yield (so the main-thread drain can pop the
    buffered, sorted prefix) and propagate TIMEDOUT immediately so the BG
    abort path is not delayed by per-row yields.

pipelineCanYieldPartialResults is consolidated from a per-shape boolean
enumeration to a peel chain: optional RPPager_Limiter, optional RPSorter,
then RPNet root. Adds the two SORTBY shapes (RPSorter -> RPNet and
RPPager_Limiter -> RPSorter -> RPNet) without changing behavior for the
shapes already supported in RediSearch#9234.

Adds three pytest cases mirroring the trivial-pipeline coverage:
SORTBY one-shard-paused (sync-pointed for exact partial count),
all-shards-paused, and post-store.

* MOD-13617: WIP add APPLY+SORTBY tests for partial results

* Update tests

* Merge

* Shorten Comments

* Fix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants