Repository navigation
[MOD-16215] hybrid: lock the spec once for single-threaded execution - #10071
Conversation
🛡️ Jit Security Scan Results✅ No security findings were detected in this PR
Security scan by Jit
|
…10071) The single-threaded hybrid path's spec read lock is a self-contained concurrency fix tracked under MOD-16215 and now lives in its own PR (#10071). Remove it here so it is reviewed and merged independently. This PR now depends on #10071: once that lands on master and this branch picks it up, the single-threaded path is again locked while SearchCtx_TakeDiskSnapshot / QAST_Iterate run. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #10071 +/- ##
==========================================
- Coverage 83.16% 82.21% -0.95%
==========================================
Files 606 632 +26
Lines 80987 82158 +1171
Branches 36248 37382 +1134
==========================================
+ Hits 67350 67548 +198
- Misses 13290 14264 +974
+ Partials 347 346 -1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…9874) * initial commit * switch to using post commit callbacks to account for possible batch failure * document write-batch poison contract on FFI staging entry points Codifies that indexTerm / indexTags / putDocument poison the batch on failure so callers that discard the return value still see commit fail. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * post-commit hooks: fallible signature, short-circuit, status propagation Addresses three bot reviews on the previous batch-hook commit: - On-commit callbacks now return `bool`. When a hook returns false the drain skips every subsequent hook's `on_commit` (their `user_data_free` still runs), so downstream in-memory bookkeeping no longer mutates state for a document the failing hook just rolled back. - `SearchDisk_CommitWriteBatch` propagates the hook outcome: a disk commit that succeeded but whose hook failed returns false, so `Indexer_Process` takes the existing commit-failure branch and stamps `aCtx->status` + `ACTX_F_ERRORED`. - `onCommit_AssignIds` is now the only hook that can fail (DocIdMeta_Set). On that path it deletes the orphan disk doc, applies the REPLACE-side stat decrement (the committed old-doc delete must be reflected somewhere), sets the add-document status, and returns false. The other hooks return `true` unconditionally — they only do infallible in-memory bookkeeping. - `AssignIdsHookData` carries `aCtx` for the status stamp; it is borrowed and valid for the lifetime of the batch (the indexing flow commits or aborts before `AddDocumentCtx_Free` runs). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * panic on DocIdMeta_Set failure instead of plumbing fallibility everywhere The previous commit threaded `bool` returns through every on-commit hook, the drain, and `SearchDisk_CommitWriteBatch` so that a single failure site — `DocIdMeta_Set` returning non-OK — could short-circuit the rest of the post-commit work. That failure means `RedisModule_HashSet` failed (OOM / fundamentally-broken Redis): the module cannot continue in any sensible way, and best-effort cleanup (`SearchDisk_DeleteDocumentById`, stat rollback) can itself fail and leave permanent in-memory / on-disk divergence. Switch to `RS_LOG_ASSERT_ALWAYS` so this case crashes loudly and the server restarts from a well-defined state. The fallibility plumbing goes away: - On-commit callbacks return `void` again. - `searchDisk_writeBatchDrain` no longer short-circuits. - `SearchDisk_CommitWriteBatch` reports only the disk-commit result. - `AssignIdsHookData` no longer carries `aCtx`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * address review feedback: status, renames, more deferrals, fewer aborts - docId==0 failure path in doAssignIds now stamps `aCtx->status` with a reason string and uses `RS_LOG_ASSERT_FMT` so the failure surfaces to the reply path instead of silently returning OK (Codex P1, JoanFM). - Hook-data structs renamed `*HookData` -> `*WriteCommitData` per suggestion: `AssignIdsWriteCommitData`, `WriteCurEntriesWriteCommitData`, `TagIndexWriteCommitData` (JoanFM). - `FieldsGlobalStats_UpdateFieldDocsIndexed` for tag fields now fires from `onCommit_TagIndex`; `IndexerBulkAdd` skips the eager bump for disk-mode tags so the counter never advances for a doc that did not reach disk (Codex P2). - `writeExistingDocs` and `writeMissingFieldDocs` split into pure-data helpers (`*_apply`) and disk-aware wrappers that defer the in-memory side-index writes to on-commit hooks. Aborted / failed-to-commit batches no longer leak phantom doc IDs into `spec->existingDocs` or `spec->missingFieldDict` (Codex P2). - Consolidated abort sites: `doAssignIds` no longer aborts eagerly on `docId==0`; `Indexer_Process` only commits and leaves errored batches to be aborted by `AddDocumentCtx_Free`'s existing safety net. One abort path instead of three (JoanFM). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * non-batched indexers: assert for numeric/geo/geometry, defer vector Codex P1 flagged that `indexBulkFields` writes numeric/geo/geometry/ vector indexes eagerly. If the disk batch commit later fails, those in-memory indexes are left referencing a doc that did not reach disk — a regression the pre-batch sync flow did not have. Numeric, geo, and geometry are not implemented on the disk side yet, so the cleanest signal here is `RS_LOG_ASSERT_ALWAYS(!aCtx->diskBatch)`: if a disk-mode spec ever routes through these indexers it surfaces a configuration that we don't fully support, instead of silently leaving phantom entries on commit failure. Vector is implemented on disk (via `vecsim_disk`), so the eager `VecSimIndex_AddVector` calls are now deferred to an on-commit hook on `aCtx->diskBatch`. The vector payload is copied into the hook data so the deferred call doesn't depend on `fdata->vector`'s lifetime. On abort or commit failure the hook never runs, so the VecSim index never sees the doc. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * vectorIndexer: borrow fdata->vector instead of copying The previous commit copied the vector blob into the hook payload, which is unnecessary — `fdata->vector` borrows from the document field (`aCtx->doc->fields[ii]`), and the document outlives the commit (the hook fires from `SearchDisk_CommitWriteBatch` inside `Indexer_Process`, well before `AddDocumentCtx_Free`). `VecSimIndex_AddVector` is synchronous and copies internally; the eager non-batched code path already relies on the same guarantee. Avoids per-vector `rm_malloc` + `memcpy` (vectors are typically a few KB and there can be many per doc). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * drop post-commit hooks: eager mutations + mark-deleted on commit fail Reverts the C-side on-commit hook infrastructure and goes back to applying in-memory mutations eagerly alongside batch staging. On a commit failure `Indexer_Process` calls `SearchDisk_DeleteDocumentById(aCtx->doc->docId)`, which adds the id to `deleted_ids`; query iterators against the term, tag, suffix, existing-docs, missing-field and vector indexes filter the doc out via that bitmap and doc-table lookups for the missing id drop the result. GC reclaims the orphaned trie entries on its own schedule. Removed: - `SearchDiskWriteBatchOnCommit` / `SearchDiskWriteBatchUserDataFree` typedefs and the `SearchDisk_WriteBatch_OnCommit` C wrapper. - `OnCommitNode` list, drain plumbing, and the `hooks_head` / `hooks_tail` fields on the C-side batch wrapper (now just `{ handle }`). - `AssignIdsWriteCommitData`, `WriteCurEntriesWriteCommitData`, `WriteExistingDocs/MissingFieldDocsWriteCommitData`, `TagIndexWriteCommitData`, `VectorIndexWriteCommitData` and their paired `*_apply` / `onCommit_*` / `free*` helpers. - Numeric / geometry `RS_LOG_ASSERT_ALWAYS(!aCtx->diskBatch, ...)` — they ride the same `deleted_ids` mechanism now. Restored: - Eager `DocIdMeta_Set` + scoring stats + GC notify in `doAssignIds`. - Eager `IndexSpec_AddTerm` + `addSuffixTrie` + `FieldsGlobalStats_UpdateFieldDocsIndexed` in `writeCurEntries`. - Eager bodies for `writeExistingDocs` / `writeMissingFieldDocs`. - Eager tag-trie / suffix / `numRecords` updates in `TagIndex_Index`. - Eager `VecSimIndex_AddVector` in `vectorIndexer`. - Unconditional `FieldsGlobalStats_UpdateFieldDocsIndexed(fs->types, 1)` in `IndexerBulkAdd`. Net diff: -482 / +110. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * mark-deleted on errored finalization; drop now-redundant poisoning The mark-deleted-on-commit-fail design from the previous commit had a gap: when `ACTX_F_ERRORED` was set upstream of the batch finalization (e.g. a tag staging UTF-8 failure surfaced via `tagIndexer` → `IndexerBulkAdd` → `indexBulkFields`), `Indexer_Process` skipped the commit and left the batch for `AddDocumentCtx_Free` to abort — but the eager in-memory mutations from `doAssignIds`, `writeExistingDocs`, `writeMissingFieldDocs`, and `writeCurEntries` had already referenced `aCtx->doc->docId`. With nothing adding the id to `deleted_ids`, those orphan references would never be filtered out of query results. Fix: `Indexer_Process` now calls `SearchDisk_DeleteDocumentById` on both the upstream-errored path and the commit-failure path (skipping when `docId == 0`, which means we never got past staging). The batch is aborted explicitly on the errored path. With that handled, the batch-poisoning machinery becomes redundant — every C-side caller of the staging FFI fns already checks the return value and propagates failure via `ACTX_F_ERRORED`, so the `mark_failed` / `is_failed` flag on the Rust `IndexSpecWriteBatch` was no longer load-bearing. Dropped from both sides and refreshed the header docs accordingly. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * try and separate staging from commit phase * address some code review comments * add asserts * address code review comments * reduce code duplication * refactor text to align to tag * try and split flow into index + commit + apply phases * address code review comments * more changes * indexer: tighten disk-mode batch lifecycle, drop unreachable hooks Address review feedback on the per-document disk write batch flow: - Remove writeExistingDocs / writeMissingFieldDocs from indexDocumentDisk Phase 3. Wildcard (`index_all`) and INDEXMISSING are memory-only features with no disk side-effects, so the calls were dead code (and the writeMissingFieldDocs no-op still did a dictCreate + schema walk). - Upgrade `doAssignIds` failure to RS_LOG_ASSERT_FMT_ALWAYS so a NULL batch or staging failure crashes in release builds too — best-effort cleanup of a partial batch risks permanent on-disk / in-memory divergence, and a hard fail lets the server restart from a well-defined state. With that guarantee `commitDocument`'s NULL guard and the dead status-recovery setup are gone. - Hoist the disk-batch early-return out of `vectorIndexer` and into `IndexerBulkAdd`'s VECTOR case. The indexer no longer knows about disk mode; the dispatcher owns "defer to Phase 3 on disk". - Replace `AddDocumentCtx_Free`'s safety-net abort with RS_ASSERT — the branch was unreachable through any current path (commitDocument is the single owner of the batch lifecycle once doAssignIds opens one), and the assertion documents the invariant so a future bailout path is forced to pair its own abort. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * document: drop redundant RedisSearchCtx* from FIELD_BULK_APPLIER Addresses raz-mon's review feedback on the apply-hook signature: the spec is already directly available on `aCtx->spec`, and Redis API access can go through `aCtx->sctx->redisCtx`, so the separate `RedisSearchCtx *ctx` parameter on `FIELD_BULK_APPLIER` was redundant. Drop the parameter from the macro, the five appliers (tagApplier, vectorApplier, numericApplier, geoApplier, geometryApplier), the `IndexerBulkApply` dispatcher, `bulkApplyFields`, and the two call sites in `bulkIndexFields` / `indexDocumentDisk`. `tagApplier` switches from `ctx->spec` to `aCtx->spec`; the four no-op appliers shed the unused `(void)ctx;` line. `FIELD_BULK_INDEXER` and its callees still take `ctx` — the bulk indexers read from it more heavily and untangling them is out of scope here. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * indexer: clean up old VecSim / geometry entries on disk REPLACE Disk-mode REPLACE was leaving stale VecSim and GeometryIndex entries from the previous doc-id. Memory-mode `makeDocumentId` already handled this inline; the disk path never had an equivalent step, so REPLACE on a doc with vectors or geometry quietly leaked phantom entries that queries could still hit. Extract a `removeOldDocAuxIndexes(spec, oldDocId)` helper and call it from both flows: - Memory mode: from `makeDocumentId`, same point as before (replaces the inline VecSim/Geometry loop). - Disk mode: stash `oldDocId` on `aCtx` in `doAssignIds` and call the helper from `applyDocTable` after the disk batch commits — keeps the in-memory cleanup paired with the durable replace. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * indexer: extract stats-delta helpers, unify memory + disk update paths Pulls the REPLACE-decrement block and the new-doc increment out of `makeDocumentId` / `doAssignIds` / `applyDocTable` into two helpers: - `removeOldDocStats(spec, oldDocLen)` — drops the old doc's contribution from `numDocuments` / `totalDocsLen` with the existing assertions. - `addNewDocStats(spec, newDocLen)` — folds the new doc in. Memory mode `makeDocumentId` no longer touches stats for the new doc; `doAssignIds` calls `addNewDocStats` once the DMD is allocated. Disk-mode `applyDocTable` now reads the same as memory mode: optional REPLACE cleanup (stats + aux indexes) followed by `addNewDocStats`. No behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * indexer: fix disk-mode vector index creation; rephrase 'Phase' comments Two follow-ups to review feedback: - Cursor bot caught a real regression from the earlier change that moved the disk-mode vector gate up into `IndexerBulkAdd`. The original `vectorIndexer` did both `openVectorIndex(..., CREATE_INDEX)` and the insert, so skipping the indexer entirely in disk mode meant the VecSim index was never lazily created — `applyVectorInserts` then opened it with `DONT_CREATE_INDEX` and silently no-op'd. Switch `applyVectorInserts` to `CREATE_INDEX` with the live `redisCtx` so the disk-mode insert mirrors the memory-mode behavior. - JoanFM flagged the "Phase 1 / Phase 2 / Phase 3" wording in the comments as session-local jargon that doesn't appear anywhere else in the codebase. Replace with descriptions of what each step actually does (stage / commit fence / apply) without numbering. No behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * indexer: address PR 9756 review feedback - Group disk-mode RSAddDocumentCtx fields (batch / oldDocId / oldDocLen) under an anonymous nested `disk` struct so the disk-only contract is visible at the type level. Per JoanFM. - applyDocTable: split the REPLACE gate. The key-meta `oldDocId` can survive a prior deindex path that removed the disk row, so cleaning up stale VecSim / geometry entries is keyed on `oldDocId != 0`, but the stats decrement and GC OnUpdate signal are keyed on `oldDocLen != 0` (the actual "on-disk row was overwritten" signal). Prevents numDocuments drift for stale-meta-with-no-disk-row. Codex P2. - applyVectorInserts: a NULL from `openVectorIndex(..., CREATE_INDEX)` after the disk commit landed means we have a doc on disk with no matching vector entry, which the next RDB save would persist. Match the post-commit policy from `applyDocTable` and `RS_LOG_ASSERT_ALWAYS` instead of silently skipping. Codex P2. - tag_index: rename `tag_index_write_postings` to `TagIndex_WritePostings` to match the rest of the TagIndex_* helper family. Per JoanFM. - Trim verbose comments on `geometryIndexer` / `numericIndexer` asserts (the assert message itself states the contract), on the `tagIndexer` disk/memory branching (covered by `TagIndex_Index` docs), and on the search_disk.h file-level lifecycle block (covered by per-function docs). Per JoanFM. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * rqe_iterators_test_utils: add missing `staged` field to ForwardIndexEntry literal `ForwardIndexEntry` gained a disk-mode-only `staged: bool` field earlier in this branch; the rqe_iterators_test_utils struct literal was missed and broke the Rust build. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * indexer: rename removeOldDocAuxIndexes to removeReplacedDocVectorAndGeometry Per raz-mon's review feedback: `aux` was vague — the function specifically drops the replaced doc's VecSim and Geometry entries, the two index types whose REPLACE cleanup isn't covered by `SearchDisk_PutDocument` (disk) or `DocTable_PopR` (memory). Expanded the doc comment to spell this out so the grouping isn't load-bearing on jargon. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * ffi: allow clippy::type_complexity for generated bindings The auto-generated bindings.rs for the FFI crate now contains a `putDocument` function pointer whose 10+ parameter signature trips clippy's `type_complexity` lint and breaks `make lint`. Suppress it alongside the other generated-code allows. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * MOD-14727: disk: per-query SpeedB snapshot for query iterators Add `createSnapshot`/`freeSnapshot` to the disk API and a `diskSnapshot` field on `RedisSearchCtx` so every iterator created during one query observes the same on-disk view. - `IndexDiskAPI` gains `createSnapshot(index)` / `freeSnapshot(snapshot)`, wired through `SearchDisk_CreateSnapshot` / `SearchDisk_FreeSnapshot`. - `RedisSearchDiskSnapshot` opaque type added to `search_disk_api.h`. - `RedisSearchCtx.diskSnapshot` holds the per-query snapshot (NULL = live). - `SearchDisk_NewTermIterator` / `SearchDisk_NewTagIterator` now take `const RedisSearchCtx *sctx` and pull `sctx->diskSnapshot` themselves, so OSS callers (`query.c`, `tag_index.c`) don't have to thread the pointer through each call site. - `NewWildcardIterator` (Rust FFI) drops the snapshot parameter and reads `query.sctx.diskSnapshot` internally; `not_reducer` and `optional_reducer` propagate the snapshot through the wildcard child the same way. - `SearchEnterpriseIterators` trait methods carry the snapshot pointer through to the on-disk iterator implementations. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * MOD-14727: disk: take per-query disk snapshot in NewSearchCtxC Populate the `diskSnapshot` field added in the previous commit by calling `SearchDisk_CreateSnapshot` once per `RedisSearchCtx` created via `NewSearchCtxC`, and release it in `SearchCtx_CleanUp`. Static stack-allocated contexts (via `SEARCH_CTX_STATIC` / `{0}` / designated initializers) keep `diskSnapshot = NULL` and continue to read the live database; those are used for internal maintenance flows rather than user queries. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * MOD-14727: disk: address PR RediSearch#9874 review feedback - Remove duplicate SearchDiskWriteBatchHandle typedef in search_disk_api.h. - Take the per-query disk snapshot inside prepareExecutionPlan rather than NewSearchCtxC, so it is opened under the spec read lock and is coherent with the in-memory trie/stats the planner consults for term expansion and IDF/doc-count lookups. - Thread the snapshot through SearchDisk_DocIdDeleted, SearchDisk_GetDocumentMetadata and SearchDisk_CreateAsyncReadPool so the result pipeline's deletion/metadata reads (including async batched reads) observe the same point-in-time view as the postings. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * MOD-14727: disk: drop sctx/snapshot from SearchDisk_DocIdDeleted Deletions live in the storage layer's in-memory deleted-id bitmap, not in SpeedB, so the snapshot pointer threaded through DocTableDiskAPI.isDocIdDeleted and SearchDisk_DocIdDeleted in the previous commit could not actually pin the check to a point-in-time view. Remove the parameter from both the FFI entry and the C wrapper, and update the three callers in result_processor.c accordingly. The remaining snapshot wiring (createSnapshot/freeSnapshot, getDocumentMetadata, createAsyncReadPool, term/tag/wildcard iterators) is unchanged. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * disk-snapshot: pin hybrid subqueries, keep lock if snapshot fails Addresses two correctness gaps in PR RediSearch#9874 review: 1. Hybrid subqueries bypass prepareExecutionPlan and call QAST_Iterate directly, so each subquery's RedisSearchCtx.diskSnapshot was left NULL and the disk iterator/metadata plumbing fell back to live reads. Under concurrent writes, hybrid text/tag/wildcard subqueries could observe changing on-disk state even though regular search and aggregate queries were pinned to a snapshot. Pin each subquery's disk view via SearchCtx_TakeDiskSnapshot before iterator construction, under the spec read lock the hybrid execute callback is holding. 2. SearchCtx_TakeDiskSnapshot silently leaves diskSnapshot = NULL when SearchDisk_CreateSnapshot fails (e.g. OOM, RocksDB iterator-cap exhaustion), but AREQ_Execute_Callback released the spec read lock for any diskSpec index regardless. The combination quietly fell back to live disk reads under concurrent writes. Gate the lock release on sctx->diskSnapshot rather than sctx->spec->diskSpec so a NULL fallback keeps the read lock for the duration of the query. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * disk-snapshot: also gate foreground unlock on snapshot existence Followup to the earlier diskSnapshot-gating change: the synchronous buildPipelineAndExecute branch in AREQ_Execute had the same `if (sctx->spec->diskSpec)` predicate as the background callback, so foreground disk queries also fell back to live reads under concurrent writes whenever SearchDisk_CreateSnapshot returned NULL. Apply the same diskSnapshot gate here so foreground and background paths agree. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * disk-snapshot: lock spec around foreground hybrid pipeline build The single-threaded branch in HybridRequest_BuildPipelineAndExecute (WORKERS=0 / fallback path) called buildPipelineAndExecute without acquiring the spec read lock, while the background HREQ_Execute_Callback acquires it at line 1214. After the previous commit added per-subquery SearchCtx_TakeDiskSnapshot calls inside HybridRequest_BuildDepletionPipeline, the foreground hybrid path was creating snapshots and running QAST_Iterate trie/stats lookups without lock protection, so background GC/compaction could mutate the in-memory state mid-plan and leave the same inconsistent snapshot-vs-planning view that snapshotting is meant to prevent. Acquire and release the read lock around buildPipelineAndExecute to mirror the background path. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * disk-snapshot: free hybrid subquery iterators before releasing the snapshot Disk iterators (term/tag/wildcard) capture `sctx->diskSnapshot` at construction time so every iterator built from one sctx observes the same point-in-time view. After the snapshot lifecycle change in this PR, `SearchCtx_CleanUp` releases `diskSnapshot`, so the snapshot owner (sctx) must outlive every iterator that borrows from it. `HybridRequest_Free` was calling `SearchCtx_Free` on each subquery's sctx before `AREQ_DecrRef` tore down the subquery pipeline/iterators, so disk iterator teardown dereferenced a freed snapshot — use-after- free under disk hybrid queries. Capture sctx/thctx/reqflags off the AREQ, detach `areq->sctx`, then call AREQ_DecrRef first (which triggers Pipeline_Clean → iterator teardown). Release sctx + thctx afterwards. The background path's ScheduleContextCleanup is async and runs after the current command, so its ordering was already correct. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * hybrid: drop duplicate WORKERS=0 lock comment after master merge The PR's b714284 and master's 8988767 (MOD-16034) added the same RedisSearchCtx_LockSpecRead / UnlockSpec pair around the foreground WORKERS=0 buildPipelineAndExecute call in parallel, with different comments. After merging master, only one copy of the lock survives, so keep master's comment and drop the duplicate PR-specific one. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * Revert "hybrid: drop duplicate WORKERS=0 lock comment after master merge" This reverts commit b8cbad5. * disk-snapshot: thread per-query snapshot through numeric iterator The disk numeric iterator path landed on master (RediSearch#9917) without snapshot plumbing, so a query mixing numeric and text/tag predicates could observe iterators at different points in time once this PR landed. Mirror the term/tag iterator API: - search_disk_api.h: add `RedisSearchDiskSnapshot *snapshot` to the `newNumericIterator` function pointer; update the `createSnapshot` doc-comment to list it alongside the other iterators. - search_disk.{h,c}: `SearchDisk_NewNumericIterator` now takes a `const RedisSearchCtx *sctx` and forwards `sctx->diskSnapshot`. - query.c: `Query_EvalNumericNode` passes `q->sctx`. - rqe_iterators (Rust trait + mock impl): `new_numeric_on_disk` gains a `snapshot: *mut ffi::RedisSearchDiskSnapshot` parameter so future Rust callers and the enterprise implementor stay in sync with the C API. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * disk-snapshot: make per-query snapshot mandatory for query iterators The previous commit accepted an optional `snapshot` raw pointer on every disk query iterator constructor. In practice the production query layer always takes a snapshot via `SearchCtx_TakeDiskSnapshot` before any iterator is created, so allowing NULL only kept a latent live-database read path open for future regressions and forced every implementor to handle a None case that should never fire. - search_disk_api.h: drop the "or NULL" wording on `newTermIterator`, `newTagIterator`, and `newNumericIterator`; the snapshot is now required. - search_disk.c: `RS_ASSERT(sctx->diskSnapshot)` in the term/tag/numeric wrappers so callers that forget to take a snapshot trip an assertion. - rqe_iterators trait: every `new_*_on_disk` method now takes `NonNull<RedisSearchDiskSnapshot>` instead of a raw pointer. - wildcard.rs / optional_reducer.rs / not_reducer.rs: unwrap `sctx_ref.diskSnapshot` into `NonNull` at the boundary and pass it on. - Test helpers: `MockContext::set_disk_snapshot` lets disk-path tests install a sentinel non-null snapshot (the mock enterprise iterator never dereferences it); the `optional_reducer` disk-wildcard test now uses it. doc-table reads (`getDocumentMetadata`, async read pool) keep their optional-snapshot interface — those are not iterators and there are legitimate callers that read the live state. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * disk-snapshot: fail the query when CreateSnapshot returns NULL The previous "keep the read lock if no snapshot" fallback was incomplete: - HybridRequest_BuildPipelineAndExecute / HREQ_Execute_Callback always unlock the parent hybrid sctx regardless of subquery snapshot results, so any subquery whose snapshot failed would iterate live under concurrent writes (cursor bot #3379350398). - runCursor unconditionally drops the lock after the first chunk and FT.CURSOR READ does not reacquire it for disk indexes, so a snapshot-less cursor leaks past the fallback's first-chunk protection (codex #3379386349). Rather than thread per-subquery / per-cursor-chunk gating through every caller, treat a NULL disk snapshot as a query error and abort: - SearchCtx_TakeDiskSnapshot now returns REDISMODULE_OK/ERR and writes a QueryError on failure. Non-disk indexes still return OK (no snapshot needed). For disk indexes, only the SearchDisk_CreateSnapshot==NULL path is an error. - prepareExecutionPlan and HybridRequest_BuildDepletionPipeline bail out on ERR, so iterators are never constructed against a missing snapshot. - The existing `if (sctx->diskSnapshot) UnlockSpec` gating is preserved (it now distinguishes "disk + snapshot present" from "RAM, keep lock" rather than guarding the NULL fallback) — comments updated accordingly. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * disk-snapshot: document async-pool snapshot lifetime more precisely `createAsyncReadPool`'s previous doc said "the snapshot must outlive the pool", but `freeAsyncReadPool` does not cancel or drain in-flight reads — SpeedB's I/O completion callbacks still hold a snapshot pointer captured when each `addAsyncRead` was enqueued. So in practice the snapshot must outlive every in-flight callback, which can outlive the pool handle. Spell that out, and tell callers to either drain (poll until pending == 0) before freeing or otherwise keep the snapshot alive. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * disk-snapshot: assert one snapshot per sctx instead of silently no-op'ing The original idempotency in SearchCtx_TakeDiskSnapshot dates back to when the snapshot was taken inside NewSearchCtxC; after the refactor it has exactly two callers (prepareExecutionPlan and HybridRequest_BuildDepletionPipeline), each of which runs once per sctx, so a second call on the same sctx would mean some new caller is silently reusing the first one's point-in-time view. That is a programming bug worth catching, not a no-op worth preserving — switch to RS_ASSERT. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * hybrid: drop single-threaded read-lock change (moved to MOD-16215 / RediSearch#10071) The single-threaded hybrid path's spec read lock is a self-contained concurrency fix tracked under MOD-16215 and now lives in its own PR (RediSearch#10071). Remove it here so it is reviewed and merged independently. This PR now depends on RediSearch#10071: once that lands on master and this branch picks it up, the single-threaded path is again locked while SearchCtx_TakeDiskSnapshot / QAST_Iterate run. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * disk-snapshot: drain async read pool before free so snapshot outlives in-flight reads The disk-side async read pool (IndexDiskAPI.createAsyncReadPool) borrows the per-query snapshot and dereferences it from SpeedB I/O-completion threads. freeAsyncReadPool does NOT cancel or wait for in-flight reads (its Drop debug-asserts pending == 0 and otherwise leaks/UAFs), so the caller must drain the pool before freeing it and before SearchCtx_CleanUp releases the snapshot. IndexResultAsyncRead_Free now polls until pending == 0 (discarding the drained DMDs/results) before SearchDisk_FreeAsyncReadPool. On the normal EOF path pending is already 0, so the drain returns immediately. Also fix the freeAsyncReadPool doc, which wrongly claimed it cancels pending reads. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * test: add MockContext::set_dummy_disk_snapshot for disk-path tests The disk optional-reducer test borrowed the disk_spec_storage address and double-cast it (`as *mut _ as *mut _`) to stand in for the required non-null snapshot. Replace that with a named MockContext::set_dummy_disk_snapshot() helper that installs a dangling, well-aligned non-null sentinel (the mock enterprise iterators never dereference it), making the intent explicit and reusable. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * disk-snapshot: require a non-NULL snapshot for createAsyncReadPool The async read pool already mandates draining to pending == 0 before freeAsyncReadPool (the pool dereferences the snapshot on each in-flight read's I/O completion, and free neither cancels nor waits). Drop the 'drain OR keep the snapshot alive' wording, which advertised an option the sole caller never uses and the Rust-side debug assert forbids, and document that a NULL snapshot is rejected (createAsyncReadPool returns NULL, caller falls back to synchronous reads). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * style: apply rustfmt to disk-snapshot iterator changes Fixes the `make fmt CHECK=1` lint failure on optional_reducer.rs and mock_context.rs (also unblocks the pr-validation gate). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * disk-snapshot: address review feedback - index_result_async_read: drain already-buffered ready results before the first poll in IndexResultAsyncRead_Drain. The poll fills `readyResults` in place and resets the read index, so un-popped entries from a prior poll would otherwise be overwritten and leak their DMDs (Codex). - redis_index: gate SearchCtx_TakeDiskSnapshot on SearchDisk_IsEnabled() to match how the rest of the module guards disk-only paths, and assert SearchDisk_IsInitialized() inside the disk branch instead of using it as the gate (JoanFM, raz-mon). - iterators_ffi/wildcard: strengthen the NewWildcardIterator safety contract to require a non-null diskSnapshot whenever diskSpec is non-null, matching the inner new_wildcard_iterator which panics otherwise (Codex). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * disk-snapshot: regenerate iterators_ffi.h for wildcard snapshot contract Regenerates the cheadergen output so the C header matches the tightened NewWildcardIterator safety doc (non-null diskSnapshot required when diskSpec is non-null). Keeps the generated-files lint check green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Itzikvaknin
left a comment
There was a problem hiding this comment.
I think we should only lock the index once - we can lock it in the main thread and keep it until it finished
|
@Itzikvaknin agreed that locking once and holding it for the whole single-threaded run is the right goal — that's what we want. The wrinkle is where the lock can live. Each hybrid sub-request (search + vector) has its own
And we can't let the separate contexts each just re-take the read lock during depletion either: the spec rwlock is writer-preferring and non-recursive, so a second read-lock on the same (main) thread while a writer such as fork-GC is queued deadlocks — which is exactly why this PR currently releases the lock before foreground depletion. So the alternative I'd propose keeps the contexts separate but still locks exactly once: the main thread takes the read lock for the whole build + depletion, and each sub-request context is marked as borrowing that lock (a new I've implemented this and the full hybrid suite passes under assertions. I'm happy to instead do the larger refactor (deferring/streamlining the sub-request contexts by execution mode) if you think that's cleaner long-term — but it touches request construction, timeout wiring, teardown and cursors, so it's bigger than this fix. Wanted your take first. |
|
JoanFM
left a comment
There was a problem hiding this comment.
I approve but agree on the suggestions of @Itzikvaknin
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cdd20fa54b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
# Conflicts: # src/debug_commands.h
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]>
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]>
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]>
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]>
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]>
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]>
|
❌ The last analysis has failed. |
| /* Read lock held by an outer scope on this thread: read freely, but never lock | ||
| * or unlock the rwlock. See RedisSearchCtx_BorrowSpecReadLock. */ |
There was a problem hiding this comment.
Nitpick: lets remove on this thread, as it is not mandatory
|
🤖 Auto-backport summary
(Summary generated by |




Describe the changes in the pull request
WORKERS 0) builds its pipeline without the spec read lock. The background path takes it inHREQ_Execute_Callback, but the non-threaded branch was missed, soQAST_Iteratereads the trie and stats while fork-GC is free to mutate them.buildPipelineAndExecute, so both execution paths acquire it in one place and exactly once per execution. Foreground in-memory execution keeps holding it across depletion: each sub-request has its ownRedisSearchCtxbut they share the spec's rwlock, which is writer-preferring and non-recursive, so letting the sub-request iterators re-acquire it inline would deadlock this thread against a queued writer such as fork-GC. They are marked as borrowing the lock instead (newSPEC_LOCK_READ_BORROWED): they read the spec, never touch the rwlock, and skip revalidation because the lock was never dropped. Foreground disk specs release it after the build — their iterators read from the snapshot taken there, so holding it across disk IO would only block writers.WORKERS 0hybrid query builds and depletes under one continuously held read lock, giving it the same consistent index snapshot the background path already gets from theRPSafeDepleterhandoff. No API, reply-shape, or configuration change.Both exits funnel through a single
done:label, so a future early return cannot leak the lock or leave a borrow marker behind.This replaces the earlier approach on this branch, which released the lock before foreground depletion and let each iterator re-lock; it implements @Itzikvaknin's request to lock the index once and hold it until execution finishes. The branch was rebuilt on current
masterbecause the previous base was 335 commits behind and conflicting, and because #10353 has since renamed this enum toSpecLockState/SPEC_LOCK_*.Which additional issues this PR fixes
Main objects this PR modified
buildPipelineAndExecute(src/hybrid/hybrid_exec.c) — owns the read lock for both paths, lends it to the sub-requests for foreground in-memory execution, and returns the borrows and unlocks at a single exitSpecLockState(src/search_ctx.h) — newSPEC_LOCK_READ_BORROWEDstate, plusRedisSearchCtx_BorrowSpecReadLock/RedisSearchCtx_ClearBorrowedSpecReadLockRedisSearchCtx_UnlockSpec(src/redis_index.c) — refuses to release a borrowed lock, so a sub-request iterator reaching EOF cannot drop the outer scope's lockhandleSpecLockAndRevalidate(src/result_processor.c) — a borrowed context skips locking and revalidation, already covered by the existinglock_state != SPEC_LOCK_UNSETguardMark if applicable
Release Notes
Fixes a concurrency bug where a single-threaded (
WORKERS 0) hybrid query could read index spec state concurrently with garbage collection.Testing
Debug build with
ENABLE_ASSERT=1. 362 tests pass across the hybrid suite plustest_gc.py,test_multithread.py,test_aggregate_barrier.pyandtest_debug_commands.py. Flow tests default toWORKERS 0, so the borrowed-lock path is what the hybrid suite exercises throughout;test_hybrid_multithread.pycovers the background path, where the lock moved out ofHREQ_Execute_Callback.No dedicated regression test, deliberately. The only window where behaviour differs from
masteris the pipeline build, and catching it needs a writer running while the main thread is parked inside the query — which atWORKERS 0is the same thread that would have to release it. Three approaches were built and measured: an elapsed-time oracle (host-timing dependent), a three-way rendezvous between the build and two new sync points in fork-GC's term apply (~190 lines of scaffolding, including test hooks in the GC write path), and anENABLE_ASSERTtrywrlockcheck inside the build (verified red on reverting the lock, green with it). All three cost more than the fix and reached further into unrelated subsystems than the bug warranted, so none were kept.🤖 Generated with Claude Code