Skip to content

MOD-14727: Improve Disk Indexing Time - Use Write Batches - #9756

Merged
kei-nan merged 31 commits into
masterfrom
master_jk_support_batch_indexing
May 31, 2026
Merged

kei-nan merged 31 commits into
masterfrom
master_jk_support_batch_indexing

Conversation

@kei-nan

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

Copy link
Copy Markdown
Collaborator

We would like to improve the indexing time for a single document in disk.
This PR tries to use a single write batch for the text and tag fields in the schema.

Our hope is this will improve the overall indexing time of documents in disk.

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

If a release note is required (bug fix / new feature / enhancement), describe the user impact of this PR in the title.


Note

High Risk
Changes the core disk indexing consistency model (stage/commit/apply) and treats some post-commit or batch-open failures as fatal asserts; numeric/geo/geometry on disk remain unsupported via asserts.

Overview
Disk document indexing now uses a per-document write batch so doc-table, full-text, and tag durable writes can be committed together instead of one storage call per term/tag.

The disk API gains SearchDiskWriteBatchHandle plus create / commit / abort / free; SearchDisk_IndexTerm, SearchDisk_IndexTags, and SearchDisk_PutDocument all take an open batch. RSAddDocumentCtx carries disk.batch, oldDocId, and oldDocLen, and the batch is always freed from AddDocumentCtx_Free.

Disk pipeline: doAssignIds opens the batch and stages the doc row (doc-id assigned before commit); indexDocumentDisk runs stage (stageText, bulkStageFields / tag staging), commit (commitDocument), then apply only on success (applyDocTable, applyTextIndex with ForwardIndexEntry.staged, bulkApplyFields / TagIndex_Commit, applyVectorInserts). In-memory trie/stats/GC/DocIdMeta_Set move to apply so a failed commit does not leave RAM ahead of disk. VecSim inserts are deferred until after commit on disk; numeric/geo/geometry indexers assert disk mode is off (still not batched).

Memory mode is refactored into indexDocumentMemory (indexText, bulkIndexFields + new IndexerBulkApply appliers) without the batch fence. Tag indexing splits into TagIndex_Index (postings) and TagIndex_Commit (trie/suffix/stats).

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

@kei-nan
kei-nan requested review from JoanFM and raz-mon May 20, 2026 11:51
@kei-nan kei-nan self-assigned this May 20, 2026
@jit-ci

jit-ci Bot commented May 20, 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/indexer.c Resolved

@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

RediSearch/src/indexer.c

Lines 239 to 243 in 2461044

if (oldLen > 0) {
// We deleted a document in the above call, update the stats accordingly
RS_ASSERT(spec->stats.scoring.numDocuments > 0);
spec->stats.scoring.numDocuments--;
RS_ASSERT(spec->stats.scoring.totalDocsLen >= oldLen);

P1 Badge Restore stats when aborting a staged replace

In the disk batch path, REPLACE updates decrement numDocuments/totalDocsLen as soon as oldLen > 0, before the batch is committed. If a later step in doAssignIds fails (for example DocIdMeta_Set), the code aborts the batch, which cancels the staged delete of the old document, but the earlier stats decrement is not reverted; this leaves scoring stats inconsistent with actual on-disk documents.

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/indexer.c Resolved
Comment thread src/indexer.c Resolved
Comment thread src/tag_index.c Resolved
Comment thread src/indexer.c Resolved
Comment thread src/indexer.c Resolved
Comment thread src/indexer.c Resolved
Comment thread src/indexer.c Resolved
@codecov

codecov Bot commented May 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 49.60630% with 128 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.60%. Comparing base (fa2a9ea) to head (f37ee20).
⚠️ Report is 6 commits behind head on master.

Files with missing lines Patch % Lines
src/indexer.c 40.00% 105 Missing ⚠️
src/search_disk.c 9.52% 19 Missing ⚠️
src/tag_index.c 85.71% 3 Missing ⚠️
src/document.c 97.14% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9756      +/-   ##
==========================================
- Coverage   81.66%   81.60%   -0.06%     
==========================================
  Files         511      512       +1     
  Lines       69391    69590     +199     
  Branches    25664    25665       +1     
==========================================
+ Hits        56666    56792     +126     
- Misses      12484    12557      +73     
  Partials      241      241              
Flag Coverage Δ
flow 84.49% <49.40%> (-0.12%) ⬇️
unit 49.86% <40.55%> (-0.05%) ⬇️

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.

@kei-nan

kei-nan commented May 20, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the review feedback in eac56a9. The recurring shape: the previous PR turned several disk writes from eager into staged-on-a-batch, but the in-memory mutations that paired with them (DocIdMeta_Set, scoring stats, term trie, suffix tries, tag tries, numRecords, GC notify) were left eager — so an aborted or failed-commit batch would leave them out of sync with disk.

Fix shape: a new C-side SearchDisk_WriteBatch_OnCommit(batch, on_commit, user_data, user_data_free) API. The hook list is owned by the C side (no FFI traffic for the callbacks); the underlying storage handle is exposed as the opaque SearchDiskWriteBatchHandle and the public SearchDiskWriteBatch is a thin C struct wrapping that handle plus the hook list. Commit fires the hooks then their user_data_free runs; abort or commit failure runs only the destructors.

Three hooks today:

  • onCommit_AssignIds — DocIdMeta_Set + scoring stats + GC notify
  • onCommit_WriteCurEntries — IndexSpec_AddTerm + suffix trie + FieldsGlobalStats_UpdateFieldDocsIndexed (re-walks fwIdx)
  • onCommit_TagIndex — tag-trie + suffix-trie + numRecords++

Plus the reply-correctness fix: commit failure sets aCtx->status so the reply callback returns an error.

@github-actions github-actions Bot added size:L and removed size:M labels May 20, 2026
Comment thread src/indexer.c Resolved

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

I like the idea. I would ask still for some unit tests for this node machinery and put somewhere outisde search_disk to have some better modularity.

Comment thread src/search_disk.c Resolved
Comment thread src/tag_index.c Resolved
Comment thread src/indexer.c Resolved
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]>
Comment thread src/indexer.c Resolved

@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: f7748188a4

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

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

@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: fd30faee99

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/indexer.c Resolved
Comment thread src/indexer.c Resolved
Comment thread src/tag_index.c Resolved
…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]>

@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: 8dbeb2a404

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/indexer.c Resolved
- 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]>
Comment thread src/document.c Resolved
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]>
Comment thread src/document.c Resolved

@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: f54bf0089b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/indexer.c Resolved
JoanFM
JoanFM previously approved these changes May 27, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit f54bf00. Configure here.

Comment thread src/indexer.c Resolved
raz-mon
raz-mon previously approved these changes May 27, 2026
…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]>
@kei-nan
kei-nan dismissed stale reviews from raz-mon and JoanFM via 01b3f4b May 27, 2026 13:57
@kei-nan
kei-nan requested a review from raz-mon May 27, 2026 14:02
raz-mon
raz-mon previously approved these changes May 27, 2026
Comment thread src/indexer.c Resolved
…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]>
raz-mon
raz-mon previously approved these changes May 27, 2026
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]>
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
1 Security Hotspot
3.5% Duplication on New Code (required ≤ 3%)
C 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

@kei-nan
kei-nan requested a review from raz-mon May 28, 2026 08:12
raz-mon
raz-mon previously approved these changes May 28, 2026
`SearchDiskWriteBatchHandle` is now owned by `RSAddDocumentCtx` for its
full lifetime and released by `AddDocumentCtx_Free` via a new
`SearchDisk_FreeWriteBatch`. Commit and abort still finalize the staged
writes but leave the handle valid (and empty) instead of consuming it.

The previous "pointer is invalid after this call, you must NULL it"
contract required every caller to clear `aCtx->disk.batch` after commit
or abort, and only the `RS_ASSERT(!aCtx->disk.batch)` in
`AddDocumentCtx_Free` caught the case of an indexing path that bailed
out between staging and commit. With this change the cleanup is
unconditional in `AddDocumentCtx_Free` and that class of leak is
structurally impossible.

`SearchDisk_FreeWriteBatch` is null-safe so memory-mode contexts (where
no batch was ever created) can call it without a guard.

Addresses review feedback on PR #431 (RediSearchEnterprise).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@kei-nan
kei-nan added this pull request to the merge queue May 31, 2026
@kei-nan
kei-nan removed this pull request from the merge queue due to a manual request May 31, 2026
@kei-nan
kei-nan added this pull request to the merge queue May 31, 2026
Merged via the queue into master with commit 0d3b32d May 31, 2026
57 of 62 checks passed
@kei-nan
kei-nan deleted the master_jk_support_batch_indexing branch May 31, 2026 09:31
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