Skip to content

[MOD-16229] disk: per-query snapshot for query iterators - #9874

Merged
kei-nan merged 55 commits into
masterfrom
master_jk_disk_snapshot_per_query
Jun 14, 2026
Merged

kei-nan merged 55 commits into
masterfrom
master_jk_disk_snapshot_per_query

Conversation

@kei-nan

@kei-nan kei-nan commented May 28, 2026 •

Copy link
Copy Markdown
Collaborator

Describe the changes in the pull request

  1. Current: Each on-disk query iterator (term, tag, wildcard) reads directly from the live database, so iterators created during a single query can observe writes/compactions that landed mid-query — producing inconsistent views across sibling iterators.
  2. Change: Adds a per-index snapshot to the disk API. RedisSearchCtx gains a diskSnapshot field that query setup populates once; every iterator built from that sctx reads from the same point-in-time view by routing through iterator_cf_opt + ReadOptions::set_snapshot. NULL means "no snapshot, read live" (current behavior).
  3. Outcome: Disk queries can be made snapshot-consistent without threading the snapshot through every call site — SearchDisk_NewTermIterator / SearchDisk_NewTagIterator now take const RedisSearchCtx *sctx and pull sctx->diskSnapshot themselves; NewWildcardIterator reads q.sctx.diskSnapshot internally.

Which additional issues this PR fixes

  1. MOD-14727

Main objects this PR modified

  1. IndexDiskAPI — new createSnapshot / freeSnapshot function pointers
  2. RedisSearchCtx — new diskSnapshot field
  3. SearchEnterpriseIterators trait (rqe_iterators) — all four methods carry a snapshot pointer
  4. SearchDisk_NewTermIterator / SearchDisk_NewTagIterator C wrappers — now take sctx
  5. NewWildcardIterator FFI — reads snapshot from q.sctx.diskSnapshot
  6. New opaque type RedisSearchDiskSnapshot in search_disk_api.h

Mark if applicable

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

The disk-side IndexDiskAPI struct gains two function pointers and two iterator entry points lose the snapshot parameter (replaced by sctx).

Release Notes

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

Internal disk-storage plumbing only — no user-visible command surface changes. The actual snapshot implementation lives in the enterprise repo.

🤖 Generated with Claude Code


Note

High Risk
Changes core query execution, lock release timing, and disk read semantics for Flex/disk indexes; incorrect snapshot lifetime or ordering could cause races or inconsistent results.

Overview
Introduces a per-query disk snapshot on RedisSearchCtx so all disk iterators and related reads in one query share the same on-disk view instead of reading the live database mid-query.

Query setup calls SearchCtx_TakeDiskSnapshot under the spec read lock in prepareExecutionPlan, hybrid depletion, and aligned single-threaded hybrid paths. Snapshot creation must succeed on disk-backed indexes (no live-read fallback). After iterators are built, the spec lock is released when sctx->diskSnapshot is set (replacing checks on spec->diskSpec).

Disk API gains createSnapshot / freeSnapshot and threads the snapshot through term/tag/numeric iterators, document metadata, and async read pools via sctx. Rust SearchEnterpriseIterators and wildcard/optional/NOT paths require a non-null diskSnapshot for disk-backed queries.

Hybrid teardown frees subquery iterators before releasing diskSnapshot, and tests/mocks were updated for the new snapshot contract.

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

kei-nan and others added 30 commits May 20, 2026 14:47
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]>
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]>
…here

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]>
- 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]>
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]>
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]>
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]>
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]>
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]>
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]>
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]>
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]>
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]>
- 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]>
…ntry 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]>
…eometry

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]>
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]>
@kei-nan
kei-nan requested a review from raz-mon June 11, 2026 08:25
@JoanFM

JoanFM commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator

Can you explain in the PR description why we need changes in the Teardown/freeing just because we have a snapshot?

Comment thread src/hybrid/hybrid_request.c Resolved
Comment thread src/hybrid/hybrid_request.c Resolved
JoanFM
JoanFM previously approved these changes Jun 11, 2026

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

LGTM, just small suggestion on the SearchDisk_IsEnabled check for taking snapshot

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]>

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b940b243ed

ℹ️ 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".

Comment thread src/index_result_async_read.c Resolved
@kei-nan kei-nan changed the title [MOD-14727] disk: per-query snapshot for query iterators [MOD-16229] disk: per-query snapshot for query iterators Jun 11, 2026
JoanFM
JoanFM previously approved these changes Jun 11, 2026
@kei-nan
kei-nan enabled auto-merge June 14, 2026 11:06

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

One open comment

kei-nan and others added 2 commits June 14, 2026 14:19
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]>
- 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]>
raz-mon
raz-mon previously approved these changes Jun 14, 2026

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e5b929ab53

ℹ️ 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".

Comment thread src/result_processor.c Resolved
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]>
@sonarqubecloud

Copy link
Copy Markdown

@kei-nan
kei-nan requested a review from raz-mon June 14, 2026 12:42
@kei-nan
kei-nan added this pull request to the merge queue Jun 14, 2026
Merged via the queue into master with commit 642e22d Jun 14, 2026
47 of 48 checks passed
@kei-nan
kei-nan deleted the master_jk_disk_snapshot_per_query branch June 14, 2026 13:51
@lerman25 lerman25 mentioned this pull request Jul 2, 2026
1 of 4 tasks
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