Skip to content

[MOD-15855] disk numeric: add IndexDiskAPI hooks and route writes/queries - #9917

Merged
kei-nan merged 15 commits into
masterfrom
master_jk_numeric_disk_api
Jun 7, 2026
Merged

kei-nan merged 15 commits into
masterfrom
master_jk_numeric_disk_api

Conversation

@kei-nan

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

Copy link
Copy Markdown
Collaborator

Describe the changes in the pull request

  1. Current: Numeric writes and queries always go through the in-memory NumericRangeTree. After MOD-14727: Improve Disk Indexing Time - Use Write Batches #9756 introduced the per-document disk write batch, numericIndexer hard-asserts !SearchDisk_IsEnabled() — a disk-mode spec with a numeric field crashes the indexer.
  2. Change: Add the OSS hookup half of the numeric-on-disk design (MOD-15855, design doc). Adds indexNumeric / newNumericIterator to IndexDiskAPI, the SearchDisk_* thin wrappers, the parallel SearchEnterpriseIterators::new_numeric_on_disk Rust trait method, and routes numericIndexer and the three NewNumericFilterIterator call sites on spec->diskSpec.
  3. Outcome: When the enterprise repo ships its NumericInvertedIndex behind these hooks, FT.CREATE ... ON DISK ... NUMERIC writes and range queries flow through the disk path; without it (OSS-only or memory-mode specs) behavior is byte-for-byte unchanged. Disk-mode geo stays explicitly unsupported via a narrowed assert inside numericIndexer — the indexer dispatches for both IXFLDPOS_NUMERIC and IXFLDPOS_GEO, and only the numeric path is wired up.

The Rust NumericInvertedIndex impl (BTreeMap routing, per-bucket disk reader, union iterator, BeingCreated split handling) lives in the enterprise repo. This PR is purely the OSS surface it plugs into. E2E tests will live alongside the impl in enterprise (OSS pytests have no ON DISK test infrastructure).

Which additional issues this PR fixes

  1. MOD-15855

Main objects this PR modified

  1. IndexDiskAPI (search_disk_api.h) — new indexNumeric / newNumericIterator function pointers
  2. SearchDisk_IndexNumeric / SearchDisk_NewNumericIterator (search_disk.c) — thin wrappers through disk->index.*
  3. SearchEnterpriseIterators::new_numeric_on_disk (rqe_iterators) — Rust trait method + unimplemented!() mock stub
  4. numericIndexer (document.c) — disk-batch staging branch on aCtx->disk.batch, geo path still asserts
  5. Query_EvalNumericNode (query.c) and the two NewNumericFilterIterator sites in optimizer_reader.c — spec->diskSpec branch routes to SearchDisk_NewNumericIterator

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

Internal-only change — adds an FFI surface used by the enterprise NumericInvertedIndex impl. No user-visible behavior change until that impl is wired up downstream.

🤖 Generated with Claude Code


Note

Medium Risk
Touches indexing, query iterators, and request flags for disk specs; full behavior depends on the enterprise NumericInvertedIndex implementation behind the new API pointers.

Overview
Adds disk-backed numeric support on the OSS side: IndexDiskAPI / SearchDisk_* gain indexNumeric and newNumericIterator, with a matching SearchEnterpriseIterators::new_numeric_on_disk Rust hook (mock stub only in OSS).

Indexing: numericIndexer stages values on the per-document write batch via SearchDisk_IndexNumeric (including multi-value loops); in-memory NumericRangeTree is unchanged when no batch is active. Disk GEO through the same indexer path still asserts as unsupported.

Queries: Numeric filter evaluation on spec->diskSpec uses SearchDisk_NewNumericIterator instead of NewNumericFilterIterator. QEXEC_OPTIMIZE is cleared for disk indexes at parse time (and asserted in the optimizer path) because optimization relies on RAM DocTable / NumericRangeTree.

Schema: Disk/Flex validation now allows NUMERIC fields (error text updated); GEO/GEOSHAPE flex tests unchanged aside from dropping the expectation that NUMERIC is invalid.

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

@jit-ci

jit-ci Bot commented May 31, 2026 •

Copy link
Copy Markdown

🛡️ Jit Security Scan Results

CRITICAL HIGH MEDIUM

✅ No security findings were detected in this PR


Security scan by Jit

@kei-nan kei-nan self-assigned this May 31, 2026
@kei-nan
kei-nan requested a review from raz-mon May 31, 2026 12:08

@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: 5369542f8d

ℹ️ 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/iterators/optimizer_reader.c Resolved
@codecov

codecov Bot commented May 31, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 28.00000% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.69%. Comparing base (6ac03d1) to head (92e2435).
⚠️ Report is 6 commits behind head on master.

Files with missing lines Patch % Lines
src/document.c 8.33% 11 Missing ⚠️
src/search_disk.c 0.00% 6 Missing ⚠️
src/query.c 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9917      +/-   ##
==========================================
- Coverage   81.73%   81.69%   -0.04%     
==========================================
  Files         515      515              
  Lines       70262    70375     +113     
  Branches    26162    26183      +21     
==========================================
+ Hits        57427    57492      +65     
- Misses      12585    12633      +48     
  Partials      250      250              
Flag Coverage Δ
flow 84.34% <28.00%> (-0.03%) ⬇️
unit 50.28% <8.00%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 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.

The companion disk-side work (RediSearchDisk Rust changes) wires
SearchDisk_IndexNumeric and SearchDisk_NewNumericIterator through to a
real NumericInvertedIndex + BucketMap, so the Flex-side validation that
rejected NUMERIC schemas can be retired.

Two gates in spec.c:

1. parseFieldSpec — the SPEC_NUMERIC_STR branch no longer short-circuits
   on disk-enabled specs.
2. IndexSpec_AddFieldsInternal — INDEXFLD_T_NUMERIC is added to the set
   of disk-supported field types alongside FULLTEXT, VECTOR, and TAG.

NOINDEX / SORTABLE / INDEXMISSING continue to be rejected for disk
specs; only the NUMERIC type itself is now allowed.

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

@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 83e2f78. Configure here.

Comment thread src/iterators/optimizer_reader.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: 83e2f784af

ℹ️ 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/iterators/optimizer_reader.c Resolved
@kei-nan
kei-nan force-pushed the master_jk_numeric_disk_api branch from 8619ec7 to 83e2f78 Compare June 1, 2026 12:57
kei-nan and others added 3 commits June 1, 2026 15:58
OptimizerIterator reads spec->docs.size for numDocs and calls
DocTable_Borrow per match, both of which target the RAM DocTable —
empty on disk specs. The Q_OPT_UNDECIDED numeric fallback in
QOptimizer_Iterators also unconditionally builds the RAM-only
NewNumericFilterIterator. Without this guard a disk-mode numeric
SORTBY+LIMIT query would return empty or underfilled results.

Disable the optimizer entirely for disk specs so we fall back to the
unoptimized pipeline; a disk-aware optimizer is left for a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
When the first numeric write creates a new column family, the disk side
needs `RedisModuleCtx` so it can call `register_cf` against Redis
BigModule — otherwise the dynamically-added CF isn't tracked by SST
replication / checkpoint snapshots until the next reopen.

Tag indexing already takes this approach: `indexTags` carries `ctx` and
the disk implementation registers each newly-created tag CF on the
first write. This commit lifts the same pattern to numeric.

Touched:

* `IndexDiskAPI::indexNumeric` in search_disk_api.h gains a leading
  `RedisModuleCtx *` parameter (matches `indexTags`).
* `SearchDisk_IndexNumeric` wrapper in search_disk.{h,c} threads `ctx`
  through to the vtable call.
* `numericIndexer` in document.c passes `ctx->redisCtx` to the new
  signature on both the single- and multi-value paths.

Addresses Codex P1 review comment on RediSearchEnterprise PR #465.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/spec.c Resolved
Comment thread src/spec.c Resolved
Comment thread src/query_optimizer.c Resolved
Comment thread src/document.c Resolved
Comment thread src/document.c Resolved
Comment thread src/query.c Resolved
kei-nan and others added 2 commits June 2, 2026 13:18
# Conflicts:
#	src/redisearch_rs/rqe_iterators/src/lib.rs
Address PR review: instead of a runtime early-return in QOptimizer_Iterators,
clear QEXEC_OPTIMIZE upstream in parseQueryArgs for disk specs and assert
the invariant at the iterator entry.

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: 17a992cde4

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

kei-nan and others added 5 commits June 2, 2026 13:33
- spec.c: drop MOD-15855/15853 comment annotations.
- document.c: extract the disk-batch numeric-indexing branch into
  indexNumericOnDiskBatch helper to flatten the single/multi duplication;
  simplify numericApplier comment.
- mock_enterprise_iterators: match the trait's RQEIteratorPrintable
  return type for new_numeric_on_disk.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Numeric iterators don't use weight for scoring — RAM-mode
NewNumericFilterIterator hardcodes 1.0 in the union builder and
NumericIterator::intersection_sort_weight returns 1.0. Drop the
parameter from SearchDisk_NewNumericIterator, IndexDiskAPI.newNumericIterator,
and the Rust new_numeric_on_disk trait method to stop pretending it
matters and to keep the disk API consistent with RAM behavior.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
MOD-15855 opened the Flex schema gate for NUMERIC fields, so
test_invalid_field_type's assertion that NUMERIC is rejected on Flex no
longer matches behavior. GEO/GEOSHAPE remain rejected and are still
covered.

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

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

Small stuff

Comment thread src/aggregate/aggregate_request.c Resolved
Comment thread src/iterators/optimizer_reader.c Resolved
kei-nan and others added 3 commits June 7, 2026 12:49
…k_numeric_disk_api

# Conflicts:
#	src/search_disk.c
- aggregate_request.c: tighten the comment on the QEXEC_OPTIMIZE kill-
  switch to call out both paths it guards — dialect-4 default and the
  explicit WITHOUTCOUNT token.
- optimizer_reader.c: restore the original filterCtx / numericFieldIndex
  ordering; assert+comment slot above the unchanged NewNumericFilterIterator
  call instead of reordering the surrounding lines.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@kei-nan
kei-nan enabled auto-merge June 7, 2026 13:05
@sonarqubecloud

sonarqubecloud Bot commented Jun 7, 2026

Copy link
Copy Markdown

@kei-nan
kei-nan added this pull request to the merge queue Jun 7, 2026
Merged via the queue into master with commit e4a5cae Jun 7, 2026
49 of 50 checks passed
@kei-nan
kei-nan deleted the master_jk_numeric_disk_api branch June 7, 2026 14:44
kei-nan added a commit that referenced this pull request Jun 9, 2026
The disk numeric iterator path landed on master (#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]>
pull Bot pushed a commit to Mu-L/RediSearch that referenced this pull request Jun 14, 2026
…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]>
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