Skip to content

MOD-14076 FT.CURSOR READ: honor RETURN_STRICT timeout policy on the coordinator - #9451

Merged
meiravgri merged 26 commits into
masterfrom
meiravg_cursor_read_return_strict_coord
May 14, 2026
Merged

meiravgri merged 26 commits into
masterfrom
meiravg_cursor_read_return_strict_coord

Conversation

@meiravgri

@meiravgri meiravgri commented May 6, 2026 •

Copy link
Copy Markdown
Contributor
  1. Current: On the coordinator, FT.CURSOR READ did not honor the RETURN_STRICT timeout policy. A cursor created by an FT.AGGREGATE … TIMEOUT … ON_TIMEOUT RETURN_STRICT command fell through the same path used by the default Return policy, so the coord-side BC timeout was never armed and partial results / errors were not surfaced under the strict contract. As a side issue, the coord-path cursor reply always wrote 0 as the cursor id rather than echoing the live cid.

  2. Change: Wires the coordinator FT.CURSOR READ end-to-end for RETURN_STRICT:

    • CursorCommand (module.c) —
      • Main thread cid validation: previously a non-existent cid was reported as "Cursor not found" only after RSCursorReadCommand ran on the worker (post DIST_THPOOL dispatch and BC arming). With the new found field on Cursors_PeekTimeoutInfo, CursorCommand now rejects unknown cids inline on the main thread (no worker dispatch, no BC arming) so the RETURN_STRICT timer can later trust argv[3] without re-peeking.
      • Arms the BC with a custom reply_callback/timeout_callback also for RETURN_STRICT. For RETURN_STRICT, installs the new DistCursorReadTimeoutReturnStrictClient timeout callback and tags the CoordRequestCtx via CoordRequestCtx_SetCursorReadReturnStrict(true) so RSCursorReadCommand later routes into coordCursorReadReturnStrict.
    • coordCursorReadReturnStrict (aggregate_exec.c) — new worker entrypoint that RSCursorReadCommand dispatches to when the request ctx is flagged for RETURN_STRICT. Atomically performs TimedOut check + Cursors_TakeForExecution + AREQ_ResetForCursorReadReturnStrict + CoordRequestCtx_SetRequest under a single setRequestLock critical section, so the timer can treat req == NULL as proof that BG has not yet taken the cursor.
    • DistCursorReadTimeoutReturnStrictClient (dist_aggregate.c) — new BC timeout callback. Locks setRequestLock, sets TimedOut, and reads req:
    • req == NULL (scenario 1: BG didn’t take the cursor): replies [empty, cid] directly via coord_cursor_read_reply_timeout_empty. Cursor stays paused and is reusable on the user’s next read.
    • req != NULL (scenarios 2/3): wakes the abort channel, waits on aggregateResultsDone, then either drains residual shard replies and serializes the (possibly empty) partial results envelope (hasStoredResults == true) or flushes the stored QueryError to the client (hasStoredResults == false).
    • rpnetNext (coord/rpnet.c) — checks AREQ_TimedOut(req) at the top of every iteration and returns RS_RESULT_TIMEDOUT if set. Makes the timer's TimedOut flag take effect immediately.
      • serializeAndReplyResults_Resp{2,3} (aggregate_exec.c) — cursor_done no longer flips on RS_RESULT_TIMEDOUT under RETURN_STRICT (previously only Return was treated this way). Keeps the cursor reusable across RETURN_STRICT timeout reads.
    • AREQ_ReplyOrStoreError (aggregate_exec.c) — adds a defensive AREQ_SignalAggregateResultsComplete in the useReplyCallback branch. Currently unreachable on the coord cursor-read path (no coord caller bails here while the timer is waiting); kept as a future-proof invariant for any error bail that happens after the timer has begun waiting. No-op for the existing FAIL callers.
    • AREQ_ResetForCursorReadReturnStrict (aggregate_request.c) — replaces the narrower AREQ_ResetAggregateResultsClaim. Clears aggregatingResults, aggregateResultsDone, timedOut, and RPNet::drainOnly between cursor chunks.
      • RPSorter::base.Next is intentionally NOT reset by AREQ_ResetForCursorReadReturnStrict. The rpsortNext_Yield latch installed by the SORTBY TIMEDOUT path freezes the heap as a sorted snapshot drained one chunk per follow-up cursor read; resetting it would restart sorting from scratch and break snapshot-pop semantics.
    • runCursor (aggregate_exec.c) — stash storedReplyState.cursor before sendChunk so the timer that wakes from the store+signal site never observes a NULL handle and skip cursor disposal.
    • sendChunk (aggregate_exec.c) — emits req->cursor_id instead of literal 0 in both the results and end-of-cursor replies so cursor-shaped envelopes always preserve the live cid.
    • Cursors_PeekTimeoutInfo (cursor.{c,h}) — adds a found field so callers can disambiguate "no such cursor" from "cursor exists with TIMEOUT 0".
    Timer-vs-BG scenarios handled by DistCursorReadTimeoutReturnStrictClient
    # When the timer fires Timer observes BG bail-out Client reply Cursor
    1 Before BG calls Cursors_TakeForExecution req == NULL Pre-take TimedOut check in coordCursorReadReturnStrict short-circuits without taking [empty, cid] via coord_cursor_read_reply_timeout_empty Stays paused at prior position; reusable on next read
    2 After take, before BG enters the pipeline req != NULL; hasStoredResults true (TIMEDOUT bail) or false (pre-pipeline error) Either the existing (!TryClaim || TimedOut) check at startPipelineCommon bails with RS_RESULT_TIMEDOUT and stores an empty result set, or an early-exit in cursorRead (e.g. spec dropped) routes through AREQ_ReplyOrStoreError [results, cid] after drainPartialResultsAfterTimeout harvests any shard replies already buffered in the MR channel — typically non-empty (results bail), or -ERR … (error bail) Reusable (results bail) / freed by BG (error bail)
    3 While BG is inside the pipeline req != NULL; hasStoredResults == true rpnetNext returns RS_RESULT_TIMEDOUT once the flag is observed; sendChunk stores the partial prefix and signals [results, cid] combining the pipeline's stored prefix with anything drainPartialResultsAfterTimeout harvests from residual channel replies Reusable across reads

    SORTBY-shaped pipelines: the rpsortNext_Yield latch from PR [MOD-13617] [Agg] Coordinator: extend RETURN_STRICT partial results to SORTBY pipelines #9366 is installed during the original FT.AGGREGATE when the sorter is mid-accumulation and gets RS_RESULT_TIMEDOUT from RPNet. By the time the cursor is open, the sorter is already in pop mode (either a fully sorted heap or the latched snapshot) and no longer pulls from RPNet, so cursor reads just drain the heap one chunk at a time. AREQ_ResetForCursorReadReturnStrict deliberately preserves RPSorter::base.Next between reads so the snapshot survives.

  3. Outcome: Coordinator FT.CURSOR READ now honors RETURN_STRICT:

    • On timeout, the client gets a cursor-shaped [partial-results, cid] (with cid preserved), or [empty, cid] if BG never took the cursor — the cursor remains reusable.
    • On a pre-pipeline BG bail (e.g. index dropped while idle), the client gets the original -ERR reply with stats parity to the inline path, and the cursor is freed.
    • Invalid/expired cids are reported synchronously on the main thread instead of after a worker round-trip.

Testing & debug helpers

  • New pytest coverage in tests/pytests/test_blocked_client_timeout.py (~565 lines) for the coord RETURN_STRICT cursor-read flow: scenarios 1/2/3, SORTBY-shaped pipelines, and free-counter assertions.
  • New #ifdef ENABLE_ASSERT sync point SYNC_POINT_BEFORE_RPNET_NEXT (in rpnetNext) for deterministic race exercising in tests.
  • New #ifdef ENABLE_ASSERT debug counter CoordReqCtxFreeDebug_Increment / _GetCount, bumped on every CoordRequestCtx_Free, exposed via FT.DEBUG QUERY_CONTROLLER GET_COORD_REQ_CTX_FREE_COUNT so tests can observe free_privdata has fired without blocking inside the callback.

Main objects this PR modified

  1. CursorCommand / RSCursorReadCommand — coord-side dispatch for RETURN_STRICT cursor reads.
  2. DistCursorReadTimeoutReturnStrictClient (new) — BC timeout callback for the coord cursor-read path.
  3. coordCursorReadReturnStrict (new) — worker entrypoint enforcing the take + publish lock window.
  4. rpnetNext — TimedOut short-circuit on follow-up cursor reads.
  5. serializeAndReplyResults_Resp{2,3} — keep cursor open on RETURN_STRICT timeout.
  6. AREQ_ReplyOrStoreError — defensive timer signal on the useReplyCallback error branch.
  7. AREQ_ResetForCursorReadReturnStrict (replaces AREQ_ResetAggregateResultsClaim) — per-chunk sync-state reset.
  8. runCursor / sendChunk — earlier cursor stash; cid preserved in cursor-shaped replies.
  9. Cursors_PeekTimeoutInfo — adds found to allow main-thread cid validation.
  10. CoordRequestCtx — new isCursorReadReturnStrict flag and getter/setter.
  11. coord_cursor_read_reply_timeout_empty (new in reply_empty.{c,h}) — scenario-1 cursor-shaped empty + cid reply.
  12. Debug-only sync points + free counter (debug_commands.{c,h}) and pytest coverage in tests/pytests/test_blocked_client_timeout.py.

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

Coordinator FT.CURSOR READ now correctly enforces the RETURN_STRICT timeout policy: on deadline expiry the client receives the standard cursor-shaped envelope with any partial results and the live cursor id, and the cursor remains reusable for subsequent reads.


Note

Medium Risk
Touches coordinator cursor-read timeout handling and cross-thread synchronization (blocked-client timers, cursor lifecycle, rpnet), which can affect correctness and resource cleanup under race conditions.

Overview
Coordinator FT.CURSOR READ now honors ON_TIMEOUT RETURN_STRICT by validating cursor existence on the main thread (Cursors_PeekTimeoutInfo.found), arming a blocked client with a new DistCursorReadTimeoutReturnStrictClient, and routing worker execution through a RETURN_STRICT-aware path that checks TimedOut before taking the cursor.

Timeout handling is updated to wait for BG completion, wake abort channels, drain partial shard replies, and reply with preserved cursor ids (including a new coord_cursor_read_empty_reply_timeout fast-path when the timer fires before BG takes the cursor). Cursor-read sync state is reset per chunk via new AREQ_ResetForCursorReadReturnStrict (clears timedOut + rpnet drainOnly), rpnetNext short-circuits on TimedOut, and cursor-shaped replies now echo req->cursor_id instead of 0.

Adds debug/test support (new sync points, coord-cursor delete debug command, free counter) and expands pytest coverage for multiple timeout race scenarios, RESP2/RESP3 reply shapes, and regression checks around delayed free_privdata behavior.

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

@github-actions github-actions Bot added the size:M label May 6, 2026
@jit-ci

jit-ci Bot commented May 6, 2026 •

Copy link
Copy Markdown

🛡️ Jit Security Scan Results

CRITICAL HIGH MEDIUM

✅ No security findings were detected in this PR


Security scan by Jit

Comment thread src/aggregate/aggregate_exec.c Resolved
@codecov

codecov Bot commented May 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.17391% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.82%. Comparing base (4a740b1) to head (3cee641).
⚠️ Report is 30 commits behind head on master.

Files with missing lines Patch % Lines
src/coord/dist_aggregate.c 78.26% 5 Missing ⚠️
src/debug_commands.c 80.95% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9451      +/-   ##
==========================================
+ Coverage   81.71%   81.82%   +0.11%     
==========================================
  Files         501      502       +1     
  Lines       68232    68898     +666     
  Branches    24668    25091     +423     
==========================================
+ Hits        55756    56379     +623     
- Misses      12238    12281      +43     
  Partials      238      238              
Flag Coverage Δ
flow 83.71% <92.17%> (-0.14%) ⬇️
unit 51.25% <0.00%> (+0.32%) ⬆️

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.

imp DistCursorReadTimeoutReturnStrictClient
Comment thread src/aggregate/aggregate_exec.c Resolved
Comment thread src/aggregate/aggregate_exec.c Resolved
@meiravgri meiravgri changed the title Meiravg_cursor_read_return_strict_coord MOD-14076 FT.CURSOR READ: honor RETURN_STRICT timeout policy on the coordinator May 7, 2026
@github-actions github-actions Bot added size:L and removed size:M labels May 7, 2026
@meiravgri
meiravgri requested a review from lerman25 May 9, 2026 15:17

@lerman25 lerman25 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 jobs without any ASAK at all
Some comments

Comment thread src/aggregate/aggregate.h Resolved
Comment thread src/aggregate/aggregate_exec.c Resolved
Comment thread src/aggregate/reply_empty.c Resolved
Comment thread src/module.c Resolved
disconnect after BG calls `RM_UnblockClient`, while `reply_callback` is
skipped when `bc->client == NULL`. Pause is rejected because BG-side rows
already drained from the pipeline are lost when the AREQ is freed; pausing
would let a retry silently skip those rows. Free is loud and consistent.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Design document accidentally committed to repository

Low Severity

A 1209-line internal design document was committed to the repository root. A reviewer explicitly commented "Remove file" on this document, indicating it was not intended for inclusion in the final PR.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 571486b. Configure here.

@meiravgri
meiravgri requested a review from lerman25 May 11, 2026 15:54
Comment thread src/coord/coord_request_ctx.c Resolved
@lerman25
lerman25 marked this pull request as draft May 12, 2026 05:58
@lerman25
lerman25 marked this pull request as ready for review May 12, 2026 05:58
Comment thread src/aggregate/reply_empty.c Resolved
Comment thread src/aggregate/aggregate_exec.c Resolved
@github-actions github-actions Bot added size:XL and removed size:L labels May 13, 2026
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
8.1% Duplication on New Code (required ≤ 3%)
E 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

@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 4 total unresolved issues (including 3 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 3cee641. Configure here.

CoordRequestCtx_UnlockSetRequest(reqCtx);
cursorRead(ctx, cursor, count, false);
return REDISMODULE_OK;
}

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 requiresAggregateResultsSync propagation for cursor-read AREQ path

Low Severity

coordCursorReadReturnStrict relies on the AREQ's requiresAggregateResultsSync being true (set during the original FT.AGGREGATE), which enables the startPipelineCommon bail-out. If the originating FT.AGGREGATE did not use RETURN_STRICT but the cursor's timeout policy was later changed (e.g., via global config), or if the AREQ was created through a path that doesn't set this flag, the TryClaim || TimedOut check at startPipelineCommon would be skipped and the timer's wait could hang indefinitely. The code should assert or explicitly set requiresAggregateResultsSync = true in this function since the path is exclusively for RETURN_STRICT.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3cee641. Configure here.

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 would that happen?
@meiravgri He is wrong right?

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.

yes. we cache the timeout policy in the cursor

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

Your amazing grand finale
Thank you 💚

@lerman25
lerman25 enabled auto-merge May 13, 2026 16:12
@lerman25
lerman25 disabled auto-merge May 13, 2026 16:12
@meiravgri
meiravgri added this pull request to the merge queue May 14, 2026
Merged via the queue into master with commit 122ae06 May 14, 2026
86 of 88 checks passed
@meiravgri
meiravgri deleted the meiravg_cursor_read_return_strict_coord branch May 14, 2026 05:47
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.

2 participants