Repository navigation
Callback-based InvertedIndex::for_each_token_id - #8905
Conversation
There was a problem hiding this comment.
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
unwrapin 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 winUse explicit
Matchvariants instead of_catch-all.Please replace
_ => Nonewith explicit non-supportedMatchvariants 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 valueMinor: signature could drop the
Optionwrapper.The doc comment explicitly states "Never returns [
None]", and the body unconditionally wraps inSome(...). TheOptionis only kept for symmetry withparse_text_query/parse_phrase_queryso callers infilter(line 526) andestimate_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 winPerformance:
parse_documenttokenizes 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 secondtokenizecall. 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
📒 Files selected for processing (14)
lib/common/common/src/iterator_ext/mod.rslib/segment/src/index/field_index/field_index_base.rslib/segment/src/index/field_index/full_text_index/inverted_index/immutable_inverted_index.rslib/segment/src/index/field_index/full_text_index/inverted_index/mmap_inverted_index/mod.rslib/segment/src/index/field_index/full_text_index/inverted_index/mod.rslib/segment/src/index/field_index/full_text_index/inverted_index/mutable_inverted_index.rslib/segment/src/index/field_index/full_text_index/tests/mod.rslib/segment/src/index/field_index/full_text_index/tests/test_congruence.rslib/segment/src/index/field_index/full_text_index/text_index.rslib/segment/src/index/field_index/full_text_index/tokenizers/mod.rslib/segment/src/index/field_index/full_text_index/tokenizers/multilingual.rslib/segment/src/index/query_optimization/condition_converter.rslib/segment/src/index/query_optimization/condition_converter/match_converter.rslib/segment/src/payload_storage/query_checker.rs
309cce4 to
d2268ec
Compare
|
I am not sure we need to change |
d2268ec to
c76c787
Compare
|
Wait, it seems |
|
cc @coszio |
It is used for parsing phrase queries, but also to check against payload directly (in |
coszio
left a comment
There was a problem hiding this comment.
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.
| 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); |
There was a problem hiding this comment.
I assume the MmapHashmap preparation is here, to make use of batched reads once it supports it?
* TokenizerTextKind * IteratorExt::try_any * Callback-based InvertedIndex::for_each_token_id
Preparation refactoring for
UniversalHashMap.This PR replaces
InvertedIndex::get_token_id(non-batched, infallible) withInvertedIndex::for_each_token_id(batched, returnsOperationResult).Caveat: these changes cause some potential changes in performance. Summarized:
FullTextIndex::parse_document:Cow<str>.Vec<u32>.Cow<str>.AHashMap<Cow<str>, Option<u32>>. (!)Vec<u32>.FullTextIndex::parse_text_query,FullTextIndex::parse_text_any_query:Cow<str>.AHashSet<Option<u32>>Vec::collect()andVec::sort_unstable(). (seeimpl From<AHashSet<u32>> for TokenSet {)Cow<str>.AHashMap<Cow<str>, Option<u32>>.Vec::collect()+Vec::sort_unstable()+Vec::dedup(). (seeimpl 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_documentto be faster but less readable.