Skip to content

[8.10] [MOD-16215] hybrid: lock the spec once for single-threaded execution - #10940

Merged
kei-nan merged 1 commit into
8.10from
backport-agent/pr-10071-to-8.10
Aug 20, 2026
Merged

kei-nan merged 1 commit into
8.10from
backport-agent/pr-10071-to-8.10

Conversation

@redisearch-backport-pull-request

@redisearch-backport-pull-request redisearch-backport-pull-request Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Backport of #10071 to 8.10.

Original PR

Cherry-pick result

Clean cherry-pick — no conflicts.

Release notes

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

🤖 Generated by the auto-backport workflow.

…10071)

* [MOD-16215] hybrid: lock the spec once for single-threaded execution

The single-threaded hybrid path (WORKERS 0) built its pipeline without the
spec read lock, while the background path took it in HREQ_Execute_Callback.
QAST_Iterate consults the trie/stats and SearchCtx_TakeDiskSnapshot documents
the lock as a precondition, so the unlocked build races with GC.

Move the lock into buildPipelineAndExecute so both paths acquire it in one
place, and take it exactly once per execution. Every sub-request has its own
RedisSearchCtx but they all share the spec's rwlock, which is writer-preferring
and non-recursive: letting the sub-request iterators re-acquire it during an
inline depletion would deadlock on this thread against a queued writer such as
fork-GC. So the foreground in-memory path marks the sub-request contexts as
borrowing the lock (SPEC_LOCK_READ_BORROWED) - they read the spec but never
touch the rwlock, and skip revalidation since the lock was never dropped. The
lock is therefore held across the whole depletion, giving the single-threaded
path the same consistent index snapshot the background path gets from the
RPSafeDepleter handoff.

Foreground disk specs release the lock after the build instead: their iterators
read from the snapshot taken during the build, so holding it across disk IO
would only block writers.

This replaces the earlier approach on this branch, which released the lock
before foreground depletion and let each iterator re-lock; it addresses the
review request to lock the index once and keep it until execution finishes.

Failures now funnel through a single `error:` label, so a future early return
cannot leak the lock.

* hybrid: add foreground spec-lock coverage; fold the borrow guard

Addresses the review asks on the lock-once change.

Tests (tests/pytests/test_hybrid_foreground_lock.py): the foreground path must
always release the read lock, and a leaked one is silent until the next writer,
so each case is followed by a forced GC that needs the write lock. Covers a
successful non-cursor query, the internal WITHCURSOR path (user-facing
FT.HYBRID WITHCURSOR is rejected at the public boundary, so the cursor path is
only reachable via _FT.HYBRID), the two pre-borrow error exits, and the
cursor-limit failure - which is the error exit taken *after* the sub-requests
borrowed the lock. A GC-churn test then checks results stay coherent while GC
mutates the trie between queries.

Not covered, and called out in the file docstring: the interleaving where a
writer queues on the rwlock while the query holds the read lock and before a
sub-request's first read. It is not deterministically reachable at WORKERS 0 -
the main thread is inside the query so no client can drive a sync point, and
fork-GC has no sync point at its write-lock acquisition. The churn test reaches
for it opportunistically.

Also folds the `borrowedByRequests` check into returnBorrowedSpecReadLocks so
both exits read as a single call.

* hybrid: rename the borrowed-lock helpers, drop a redundant comment

Review feedback on #10071: a void function whose name starts with "return"
reads like a return statement. The pair is a marker handoff, not a lock
operation, so name the clearing side for what it does.

  RedisSearchCtx_ReturnSpecReadLock -> RedisSearchCtx_ClearBorrowedSpecReadLock
  returnBorrowedSpecReadLocks       -> clearBorrowedSpecReadLocks

Also drops the lock comment in HREQ_Execute_Callback, which restated what
buildPipelineAndExecute already documents.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* hybrid: add a deterministic foreground spec-lock regression test

Review feedback on #10071: the existing coverage pinned the borrow protocol but
passed on master too, so it was not a regression test. This adds one that fails
if the foreground build stops holding the spec read lock.

The discriminating window is the pipeline build alone - during depletion the
sub-request iterators take the lock themselves on either side of the fix, so the
timing is identical there. Observing that window needs a writer running while the
main thread is inside the query, and no command can release either side, because
the main thread is exactly what is parked. So both parks release themselves:

  * fork-GC's term apply parks after the fork, just short of the spec write lock,
    until a foreground hybrid build is parked (SyncPoint_WaitUntilOnce predicate),
    and again once it holds the lock, on a short window.
  * the foreground build parks with the read lock taken until GC reports it holds
    the write lock, on a long window.

The query's own elapsed time is then the oracle: with the read lock held GC never
gets in, so the build runs out its full window; without it GC takes the write lock
at once and the build resumes immediately. Verified both ways - 3000ms with the
lock, 3ms with the RedisSearchCtx_LockSpecRead call reverted.

SyncPoint_WaitUntilOnce is new: WaitUntil ignores the arm's auto-release window,
which would park the main thread forever in the green case, and the term apply
runs per term so the park has to be single-shot.

Also replaces the vacuous assertTrue(True) in the writer check with the forced
GC's actual reply, and corrects the claim that a leaked read lock hangs - the
blocked client times out and replies with an error.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* hybrid: assert recorded state, not elapsed time, in the spec-lock tests

Two Codex findings on the tests added earlier, both real.

The regression test used the query's elapsed time as its only oracle, on the
"slow means the lock was held" reading. That cannot produce a false failure, but a
host stall can push the unlocked path past the threshold and let a real regression
pass. SyncPoint_WaitUntilOnce now records how the park ended - SIGNAL, PREDICATE
or TIMEOUT - exposed as FT.DEBUG SYNC_POINT LAST_EXIT. The test asserts TIMEOUT on
the build park: the predicate firing means GC reached the write lock while the
build was in progress, which is exactly the regression. Elapsed time is kept only
as a diagnostic in the failure message.

The release probe was vacuous wherever the test deleted nothing. The spec write
lock is only taken per collected term or tag, and FGC_parentHandleTerms returns at
its terminator when the child sent no delta, so a cycle with nothing to collect
never takes it - GC_FORCEINVOKE replies DONE whether or not the read lock leaked.
Measured with the new LAST_EXIT probe: with no seeded deletion GC never reaches the
post-write-lock site (NONE), with one it does (TIMEOUT). The helper now creates and
deletes a probe doc first, so every probe has a writer to block.

Kept the forced GC rather than switching to FT.ALTER, which the review suggested:
FT.ALTER takes the write lock on the main thread, so a leaked read lock would wedge
the server into a test-framework timeout instead of failing with a diagnostic.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* debug: fold the three SyncPoint wait loops into one park

SyncPoint_Wait, SyncPoint_WaitUntil and SyncPoint_WaitUntilOnce were three
copies of the same spin loop. They now share SyncPoint_Park and differ only in
what they pass it, so each public entry point is one line.

This also settles an inconsistency that WaitUntilOnce was invented to work
around: Wait honoured the arm's auto-release window and WaitUntil silently
ignored it, so arming a WaitUntil point with a timeout did nothing. Every
ARM-with-timeout call site in the suite is a Wait point, so no test changes
behaviour. WaitUntilOnce now differs from WaitUntil only by disarming on exit.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* hybrid: give buildPipelineAndExecute a single exit for the spec lock

The success and error epilogues did the same two things, and a mutable
borrowedByRequests flag tracked state that already lives on the sub-request
contexts. Both exits now funnel through one `done:` block, and whether the
sub-requests borrow the lock is a const bool derived from the inputs.

Cleanup still has to be gated on that predicate rather than run
unconditionally: on the background path the sub-request contexts are locked by
other worker threads during depletion, so reading their lock_state from this
thread would race. ClearBorrowedSpecReadLock is now a no-op on a context that
never borrowed, so the build-failure exit can share the same epilogue while the
assert still catches clearing a genuinely held lock.

Also splits the borrow bookkeeping into borrowSpecReadLocks /
returnSpecReadLocks, so neither helper opens with a bare return.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* hybrid: trim the spec-lock comments and test setup

Cuts restated prose down to the facts a maintainer cannot infer, per the
comment guidelines, and drops two pieces of dead weight from the test file: a
NUMERIC field no query touches and a _blob parameter never passed. No test
logic changes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* hybrid: check writer exclusion in the build instead of racing fork-GC

The regression test needed a writer running concurrently with the foreground
build, which at WORKERS 0 meant sync points inside fork-GC's term apply: the
main thread is parked in the query, so no command can release either side and
both parks had to self-release. That cost two sync points in the GC write path,
a third in the build, SyncPoint_WaitUntilOnce, a recorded exit reason and a
LAST_EXIT debug subcommand - and it put test scaffolding in the GC.

None of it is needed to check the property. pthread_rwlock_trywrlock cannot
block and fails with EBUSY while any thread holds the lock, this one included
for read, so the build can simply ask whether a writer could get in.
RedisSearchCtx_AssertWritersExcluded does that and aborts if the answer is yes.

The oracle is stronger as a result: it tests the rwlock rather than our own
lock_state bookkeeping, no second thread has to be scheduled, and there is no
window for a loaded host to distort. It also covers the background path and
every other hybrid test in the suite rather than one bespoke test.

debug_commands.c/h and fork_gc/terms.c are no longer touched by this PR.

Verified both ways: removing the RedisSearchCtx_LockSpecRead call fails all 5
tests in test_hybrid_foreground_lock.py with "a writer could take the spec lock
here" in the server log; restored, 367 tests pass across the hybrid suite,
test_gc.py, test_multithread.py, test_aggregate_barrier.py and
test_debug_commands.py.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* hybrid: drop the spec-lock tests, keep the fix

Removes tests/pytests/test_hybrid_foreground_lock.py and the
RedisSearchCtx_AssertWritersExcluded helper it existed to drive. What remains is
the fix itself: buildPipelineAndExecute takes the spec read lock for both
execution paths and lends it to the sub-request contexts across foreground
in-memory depletion.

Proving writer exclusion at WORKERS 0 needs a writer running while the main
thread is parked inside the query, and every way to arrange that costs more
scaffolding than the fix. Not worth it here.

The change stays covered indirectly: flow tests default to WORKERS 0, so the
borrowed-lock path is what the whole hybrid suite exercises, and
test_hybrid_multithread.py covers the background path where the lock moved out
of HREQ_Execute_Callback. 362 tests pass across the hybrid suite, test_gc.py,
test_multithread.py, test_aggregate_barrier.py and test_debug_commands.py.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@sonarqubecloud

Copy link
Copy Markdown

@kei-nan
kei-nan enabled auto-merge August 19, 2026 21:17
@kei-nan
kei-nan added this pull request to the merge queue Aug 19, 2026
@kei-nan kei-nan self-assigned this Aug 19, 2026
Merged via the queue into 8.10 with commit 64ba96d Aug 20, 2026
34 checks passed
@kei-nan
kei-nan deleted the backport-agent/pr-10071-to-8.10 branch August 20, 2026 01:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auto-backport This PR was automatically backported by an agent size:S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant