Skip to content

Callback-based InvertedIndex::for_each_token_id - #8905

Merged
xzfc merged 3 commits into
devfrom
uio-for_each_token_id
May 5, 2026
Merged

xzfc merged 3 commits into
devfrom
uio-for_each_token_id

Conversation

@xzfc

@xzfc xzfc commented May 5, 2026

Copy link
Copy Markdown
Member

Preparation refactoring for UniversalHashMap.

This PR replaces InvertedIndex::get_token_id (non-batched, infallible) with InvertedIndex::for_each_token_id (batched, returns OperationResult).


Caveat: these changes cause some potential changes in performance. Summarized:

  • (not minor) FullTextIndex::parse_document:
    • Before this PR:
      1. Tokenize into a sequence of Cow<str>.
      2. Resolve ids and collect into Vec<u32>.
    • This PR:
      1. Tokenize into a sequence of Cow<str>.
      2. Collect tokens into AHashMap<Cow<str>, Option<u32>>. (!)
      3. Resolve ids in-place using batched API.
      4. Tokenize again (!) and collect into Vec<u32>.
  • (minor) FullTextIndex::parse_text_query, FullTextIndex::parse_text_any_query:
    • Before this PR:
      1. Tokenize into a sequence of Cow<str>.
      2. Resolve ids and collect them into AHashSet<Option<u32>>
      3. Vec::collect() and Vec::sort_unstable(). (see impl From<AHashSet<u32>> for TokenSet {)
    • This PR:
      1. Tokenize into a sequence of Cow<str>.
      2. Collect tokens into AHashMap<Cow<str>, Option<u32>>.
      3. Resolve ids in-place using batched API.
      4. Vec::collect() + Vec::sort_unstable() + Vec::dedup(). (see impl FromIterator<TokenId> for TokenSet {)

In other words, the new logic performs more allocations and lookups.
Why: to deduplicate token strings before performing batched reads.
I believe that deduplication would be cheaper than extra read requests in case of duplicated tokens.
If it's an issue, I can rewrite parse_document to be faster but less readable.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/segment/src/payload_storage/query_checker.rs (1)

129-136: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

unwrap in payload checker introduces panic risk.

Filter evaluation should not panic on recoverable index/payload errors. This path should fail closed (and ideally log) instead.

💡 Minimal safe fix
-        )
-        .unwrap(/* TODO(uio): handle errors */),
+        )
+        .unwrap_or(false),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/segment/src/payload_storage/query_checker.rs` around lines 129 - 136, The
current Condition::Field branch uses unwrap on the result of
check_field_condition, which can panic; change it to handle errors gracefully by
matching the Result from check_field_condition(field_condition,
get_payload().deref(), field_indexes, hw_counter) and on Err log the error (or
use the existing module logger) and return a safe “fail closed” value (false)
instead of panicking; keep the Condition::IsEmpty call unchanged. Ensure you
reference the check_field_condition call, get_payload().deref(), and the
Condition::Field arm when applying the match/map_or_else and logging.
🧹 Nitpick comments (3)
lib/segment/src/index/field_index/field_index_base.rs (1)

185-193: ⚡ Quick win

Use explicit Match variants instead of _ catch-all.

Please replace _ => None with explicit non-supported Match variants to keep this logic future-proof when enum variants evolve.

As per coding guidelines: “Prefer explicit exhaustive matches over catch-all _ arm in Rust match expressions, so we don't miss handling new enum variants when they are added later.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/segment/src/index/field_index/field_index_base.rs` around lines 185 -
193, The match on FieldIndex::FullTextIndex currently uses a catch-all `_ =>
None`; replace that with explicit Match variant arms for every non-supported
variant of condition.r#match (e.g., add arms like Match::Number(...),
Match::Geo(...), Match::Bool(...), etc. as applicable in the Match enum) each
returning None so the match is exhaustive without using `_`; this will ensure
the compiler forces updates when new Match variants are added and keep handling
inside FieldIndex::FullTextIndex (the match on condition.r#match and the arms
calling index.check_payload_match::<false/true>) explicit and future-proof.
lib/segment/src/index/field_index/full_text_index/text_index.rs (2)

278-287: 💤 Low value

Minor: signature could drop the Option wrapper.

The doc comment explicitly states "Never returns [None]", and the body unconditionally wraps in Some(...). The Option is only kept for symmetry with parse_text_query / parse_phrase_query so callers in filter (line 526) and estimate_cardinality (line 546) can match all three uniformly. That's defensible — flagging only so the consistency intent is explicit. Feel free to skip.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/segment/src/index/field_index/full_text_index/text_index.rs` around lines
278 - 287, Change parse_text_any_query to return OperationResult<ParsedQuery>
(drop the Option) since it never returns None: update the function signature of
parse_text_any_query and its body to return Ok(ParsedQuery::AnyTokens(tokenset))
instead of Ok(Some(...)). Then update call sites that currently match on Option
(the callers in filter and estimate_cardinality that handle parse_text_query /
parse_phrase_query / parse_text_any_query) to treat parse_text_any_query as
always present — remove the Some(...) arm or unwrap the AnyTokens branch
accordingly while preserving the existing handling for the other two functions
that still return Option; reference parse_text_any_query, parse_text_query,
parse_phrase_query, filter, and estimate_cardinality when making the changes.

318-341: ⚡ Quick win

Performance: parse_document tokenizes twice.

Acknowledged in the PR description ("additional allocations and a second tokenization step"). For phrase-heavy workloads this doubles tokenizer cost on every parse. A single-pass variant — collect tokens into a Vec<Cow<str>> once, build the dedup map from that vec, batch-resolve, then map the vec to ids — keeps deduplication while avoiding the second tokenize call. Worth doing if profiling shows phrase parsing as a hot path; otherwise fine to defer until UniversalHashMap lands.

♻️ Sketch of single-pass alternative
pub fn parse_document(
    &self,
    text: &str,
    hw_counter: &HardwareCounterCell,
) -> OperationResult<Option<Document>> {
    let mut tokens: Vec<Cow<'_, str>> = Vec::new();
    self.get_tokenizer()
        .tokenize(TokenizerTextKind::Document, text, |token| tokens.push(token));

    // Dedup keys for batched resolution
    let mut token_map: AHashMap<&str, Option<TokenId>> = AHashMap::new();
    for token in &tokens {
        token_map.insert(token.as_ref(), None);
    }
    let iter = token_map.iter_mut().map(|(token, cell)| (cell, *token));
    self.for_each_token_id(iter, hw_counter, |cell, token_id| *cell = token_id)?;

    let mut document_tokens = Vec::with_capacity(tokens.len());
    for token in &tokens {
        match token_map.get(token.as_ref()).copied().flatten() {
            Some(id) => document_tokens.push(id),
            None => return Ok(None),
        }
    }
    Ok(Some(Document::new(document_tokens)))
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/segment/src/index/field_index/full_text_index/text_index.rs` around lines
318 - 341, parse_document currently tokenizes text twice (once inside
resolve_tokens and again via get_tokenizer().tokenize); change it to a
single-pass: call get_tokenizer().tokenize once and collect tokens into a
Vec<Cow<str>>; build a deduplicated map of token strings to Option<TokenId> keys
from that vec, call the batch resolver (for_each_token_id or the existing
resolve_tokens-like batch API) to populate the map, then iterate the original
token vec to map tokens to ids, returning Ok(None) if any id is None and
otherwise returning Ok(Some(Document::new(document_tokens))). Update
parse_document to use the single-tokenization flow and reference
get_tokenizer().tokenize, for_each_token_id/resolve_tokens, and Document::new.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/mod.rs`:
- Around line 623-640: The loop in for_each_token_id currently swallows mmap
vocab read errors via .ok(), so change the iterator invocation to a fallible
form (e.g. tokens.try_for_each) and make the closure return Result so errors
propagate; replace .ok().flatten() with the fallible call using ? (e.g. let
token_id = self.storage.vocab.get(token.as_ref())?
.and_then(<[TokenId]>::first).copied();) and propagate that Result from the
closure so the enclosing for_each_token_id returns the error instead of silently
returning None token ids.

In `@lib/segment/src/index/query_optimization/condition_converter.rs`:
- Around line 53-55: Replace the panic-causing unwrap on the Result returned by
check_field_condition in condition_converter.rs with safe error handling: call
check_field_condition(field_condition, &payload, field_indexes, &hw) and handle
the Err case by returning a closed/failing result (e.g., treat the condition as
not satisfied by mapping Err -> false or explicitly matching Err and returning
Ok(false)), optionally logging the error; do not use unwrap so request execution
cannot panic. Ensure you update the surrounding expression that expects the
boolean so it accepts the mapped value from check_field_condition.

In
`@lib/segment/src/index/query_optimization/condition_converter/match_converter.rs`:
- Around line 279-285: The Err arm for query parsing in match_converter.rs
currently swallows errors and returns a fail-closed checker; change it to
capture the error (e) and emit a structured log including context (e.g., the
failing query string or query_opt context) before returning the Box::new(|_|
false) checker so issues (parse failures, I/O/index errors) are visible; update
both the match handling around parsed_query and the similar block at lines
289-293 to log the error via your crate's logger (or tracing::error!) with the
error value and identifying context (function/method: match_converter logic that
produces parsed_query / query_opt and the produced ConditionCheckerFn).

---

Outside diff comments:
In `@lib/segment/src/payload_storage/query_checker.rs`:
- Around line 129-136: The current Condition::Field branch uses unwrap on the
result of check_field_condition, which can panic; change it to handle errors
gracefully by matching the Result from check_field_condition(field_condition,
get_payload().deref(), field_indexes, hw_counter) and on Err log the error (or
use the existing module logger) and return a safe “fail closed” value (false)
instead of panicking; keep the Condition::IsEmpty call unchanged. Ensure you
reference the check_field_condition call, get_payload().deref(), and the
Condition::Field arm when applying the match/map_or_else and logging.

---

Nitpick comments:
In `@lib/segment/src/index/field_index/field_index_base.rs`:
- Around line 185-193: The match on FieldIndex::FullTextIndex currently uses a
catch-all `_ => None`; replace that with explicit Match variant arms for every
non-supported variant of condition.r#match (e.g., add arms like
Match::Number(...), Match::Geo(...), Match::Bool(...), etc. as applicable in the
Match enum) each returning None so the match is exhaustive without using `_`;
this will ensure the compiler forces updates when new Match variants are added
and keep handling inside FieldIndex::FullTextIndex (the match on
condition.r#match and the arms calling index.check_payload_match::<false/true>)
explicit and future-proof.

In `@lib/segment/src/index/field_index/full_text_index/text_index.rs`:
- Around line 278-287: Change parse_text_any_query to return
OperationResult<ParsedQuery> (drop the Option) since it never returns None:
update the function signature of parse_text_any_query and its body to return
Ok(ParsedQuery::AnyTokens(tokenset)) instead of Ok(Some(...)). Then update call
sites that currently match on Option (the callers in filter and
estimate_cardinality that handle parse_text_query / parse_phrase_query /
parse_text_any_query) to treat parse_text_any_query as always present — remove
the Some(...) arm or unwrap the AnyTokens branch accordingly while preserving
the existing handling for the other two functions that still return Option;
reference parse_text_any_query, parse_text_query, parse_phrase_query, filter,
and estimate_cardinality when making the changes.
- Around line 318-341: parse_document currently tokenizes text twice (once
inside resolve_tokens and again via get_tokenizer().tokenize); change it to a
single-pass: call get_tokenizer().tokenize once and collect tokens into a
Vec<Cow<str>>; build a deduplicated map of token strings to Option<TokenId> keys
from that vec, call the batch resolver (for_each_token_id or the existing
resolve_tokens-like batch API) to populate the map, then iterate the original
token vec to map tokens to ids, returning Ok(None) if any id is None and
otherwise returning Ok(Some(Document::new(document_tokens))). Update
parse_document to use the single-tokenization flow and reference
get_tokenizer().tokenize, for_each_token_id/resolve_tokens, and Document::new.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c56e76d3-fa97-4026-ba6b-e32d0cc53af0

📥 Commits

Reviewing files that changed from the base of the PR and between 5ee548a and 309cce4.

📒 Files selected for processing (14)
  • lib/common/common/src/iterator_ext/mod.rs
  • lib/segment/src/index/field_index/field_index_base.rs
  • lib/segment/src/index/field_index/full_text_index/inverted_index/immutable_inverted_index.rs
  • lib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/mod.rs
  • lib/segment/src/index/field_index/full_text_index/inverted_index/mod.rs
  • lib/segment/src/index/field_index/full_text_index/inverted_index/mutable_inverted_index.rs
  • lib/segment/src/index/field_index/full_text_index/tests/mod.rs
  • lib/segment/src/index/field_index/full_text_index/tests/test_congruence.rs
  • lib/segment/src/index/field_index/full_text_index/text_index.rs
  • lib/segment/src/index/field_index/full_text_index/tokenizers/mod.rs
  • lib/segment/src/index/field_index/full_text_index/tokenizers/multilingual.rs
  • lib/segment/src/index/query_optimization/condition_converter.rs
  • lib/segment/src/index/query_optimization/condition_converter/match_converter.rs
  • lib/segment/src/payload_storage/query_checker.rs

coderabbitai[bot]

This comment was marked as resolved.

@generall

generall commented May 5, 2026

Copy link
Copy Markdown
Member

I am not sure we need to change parse_document. AFAIK, it is only needed on insertions, and insertions are going to happen in small segments only (or during re-indexing). In those cases we usually have everything in ram anyway

@xzfc
xzfc force-pushed the uio-for_each_token_id branch from d2268ec to c76c787 Compare May 5, 2026 08:03
coderabbitai[bot]

This comment was marked as resolved.

@qdrant qdrant deleted a comment from coderabbitai Bot May 5, 2026
@generall

generall commented May 5, 2026

Copy link
Copy Markdown
Member

Wait, it seems parse_document is used only for parsing queries on phrase search? I am confused

@generall

generall commented May 5, 2026

Copy link
Copy Markdown
Member

cc @coszio

@coszio

coszio commented May 5, 2026

Copy link
Copy Markdown
Contributor

Wait, it seems parse_document is used only for parsing queries on phrase search? I am confused

It is used for parsing phrase queries, but also to check against payload directly (in FieldIndex::special_check_condition)

@coszio coszio left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Considering that special_check_condition is only used on the path of nested filters, which already needs to read payloads, I don't think the extra allocations are going to cause significant regression.

Comment on lines +623 to +636
tokens.try_for_each(|(meta, token)| {
if self.is_on_disk {
hw_counter.payload_index_io_read_counter().incr_delta(
READ_ENTRY_OVERHEAD + size_of::<TokenId>(), // Avoid check overhead and assume token is always read
);
}

self.storage
.vocab
.get(token)
.ok()
.flatten()
.and_then(<[TokenId]>::first)
.copied()
let token_id = self
.storage
.vocab
.get(token.as_ref())?
.and_then(<[TokenId]>::first)
.copied();
f(meta, token_id);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I assume the MmapHashmap preparation is here, to make use of batched reads once it supports it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct.

@xzfc
xzfc merged commit d5789bb into dev May 5, 2026
15 checks passed
@xzfc
xzfc deleted the uio-for_each_token_id branch May 5, 2026 22:25
timvisee pushed a commit that referenced this pull request May 8, 2026
* TokenizerTextKind

* IteratorExt::try_any

* Callback-based InvertedIndex::for_each_token_id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants