Skip to content

Refactor: Drop the vector fetch for ES - #14970

Merged
KevinHuSh merged 2 commits into
infiniflow:mainfrom
KevinHuSh:drop-vect-fetch
May 18, 2026
Merged

KevinHuSh merged 2 commits into
infiniflow:mainfrom
KevinHuSh:drop-vect-fetch

Conversation

@KevinHuSh

Copy link
Copy Markdown
Contributor

Summary

  • Stop pulling chunk vectors (q_*_vec) back from Elasticsearch in the main retrieval path. ES already knows them; shipping them was pure bandwidth/memory overhead.
  • Recover the per-chunk cosine similarity via a second KNN-only ES call filtered by the candidate chunk ids. The new _score is merged with locally computed term similarity using the user-configured vector_similarity_weight.
  • Lazily fetch the chunk embedding only for the chunks insert_citations actually needs.

Details

rag/nlp/search.py

  • Dealer.search: no longer appends q_*_vec to the ES select list. OceanBase still gets it (its rerank path is unchanged).
  • New Dealer._knn_scores(sres, idx_names, kb_ids): a MatchDenseExpr over the cached query vector filtered by id IN sres.ids, returning {chunk_id: cosine_score} via ES _score.
  • New Dealer.rerank_with_knn(...): term similarity from qryr.token_similarity plus the ES-supplied KNN score, combined with tkweight/vtweight and the existing rank-feature bonus.
  • New Dealer.fetch_chunk_vectors(chunk_ids, tenant_ids, kb_ids, dim): on-demand vector fetch for citation use.
  • Dealer.retrieval routes Infinity → unchanged, OceanBase → existing local rerank, ES → new KNN-score path.

common/doc_store/es_conn_base.py

  • New get_scores(res) helper returning {_id: _score} directly from hit headers (ES doesn't surface _score through get_fields).

api/db/services/dialog_service.py

  • New top-level _hydrate_chunk_vectors(...) helper. On ES it back-fills ck["vector"] from fetch_chunk_vectors right before insert_citations. No-op on Infinity / OB (their chunks already carry vectors).
  • Both decorate_answer closures became async and are await-ed at all call sites in async_chat and async_ask.

Backend behavior

Backend Returns chunk vec in main search Sim source Vectors for citations
ES No second KNN call (_score) merged with term sim fetched on demand
Infinity No (unchanged) normalized _score already on chunks
OceanBase Yes (kept) local hybrid rerank already on chunks

Test plan

  • Chat with ES backend: retrieval still returns ranked chunks; similarity / vector_similarity / term_similarity populated.
  • Citation insertion works (compare against pre-change behavior; same chunks get [ID:n] markers).
  • Infinity backend still serves chats unchanged.
  • OceanBase backend still serves chats unchanged (local rerank path).
  • Empty-result and min_match fallback paths still pass.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 18, 2026
@coderabbitai

coderabbitai Bot commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e7d39963-2b75-4e27-af97-94b58a20701c

📥 Commits

Reviewing files that changed from the base of the PR and between 88b5233 and b77aa89.

📒 Files selected for processing (1)
  • rag/utils/es_conn.py

📝 Walkthrough

Walkthrough

Refactors retrieval: defer chunk vector fetching from first-pass ES search to on-demand steps, add ES KNN scoring and vector-fetch helpers, and make dialog citation decoration async to hydrate missing vectors before inserting citations.

Changes

Deferred Vector Loading for Search and Citation

Layer / File(s) Summary
Vector-fetch and reranking helpers
common/doc_store/es_conn_base.py, rag/nlp/search.py
Adds ESConnectionBase.get_scores to map ES hit ids to float scores; adds Dealer._knn_scores (second-pass ES cosine on candidate ids), Dealer.fetch_chunk_vectors (fetch/normalize vectors by chunk id and dimension), and Dealer.rerank_with_knn (merge token similarity, KNN cosine, and rank-feature scores).
Search deferred loading and two-pass reranking
rag/nlp/search.py, rag/utils/es_conn.py
Search now conditionally skips fetching chunk vector fields for non-OceanBase backends. Retrieval derives idx_names from normalized tenant ids, runs _knn_scores on candidate ids, reranks via rerank_with_knn, and emits placeholder vectors when vectors were not fetched in the main pass. Also removed explicit _source=True from the low-level ES search call.
Async citation decoration with vector hydration
api/db/services/dialog_service.py
Adds _hydrate_chunk_vectors to lazily populate missing chunk vector fields for non-Infinity/OceanBase backends. Converts nested decorate_answer in both async_chat and async_ask to async, awaits hydration before insert_citations, and awaits decoration in streaming and non-streaming completion paths.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰
Vectors delayed, then gently found,
Citations stitched where gaps were round.
Two-pass scores hum, reranks sing,
Hydrated chunks make answers spring. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.41% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main refactoring: dropping vector fetching from Elasticsearch in the main retrieval path.
Description check ✅ Passed The PR description is comprehensive and follows the template with detailed explanations of problem, solution, backend behavior, and test plan.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@KevinHuSh KevinHuSh changed the title Drop the vector fetch for ES Refactor: Drop the vector fetch for ES May 18, 2026
@KevinHuSh KevinHuSh added the ci Continue Integration label May 18, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft May 18, 2026 02:44
@KevinHuSh
KevinHuSh marked this pull request as ready for review May 18, 2026 02:44
@codecov

codecov Bot commented May 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (128a64e) to head (b77aa89).
⚠️ Report is 95 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14970   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@KevinHuSh
KevinHuSh merged commit 7cdc74b into infiniflow:main May 18, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request May 22, 2026
1 task done
yingfeng pushed a commit that referenced this pull request May 29, 2026
…5390)

### What problem does this PR solve?

On the OpenSearch backend (`DOC_ENGINE=opensearch`), every retrieval
that
performs the KNN second-pass scoring crashes with:

    AttributeError: 'OSConnection' object has no attribute 'get_scores'

**Root cause.** #14970 ("Refactor: Drop the vector fetch for ES") added
a
`get_scores()` helper to `ESConnectionBase`
(`common/doc_store/es_conn_base.py`)
and introduced `Dealer._knn_scores()` in `rag/nlp/search.py`, which
calls
`self.dataStore.get_scores(res)`. `search.py` routes Infinity and
OceanBase to
their own similarity paths via `DOC_ENGINE_INFINITY` /
`DOC_ENGINE_OCEANBASE`,
but OpenSearch sets neither flag, so it falls into the Elasticsearch
branch and
calls `get_scores`. `OSConnection` (which subclasses
`DocStoreConnection`
directly, not `ESConnectionBase`) never received that method, so any
vector-search hit triggers the crash. It reproduces with any normal
embedding
(e.g. 1024-dim mistral-embed) as soon as a KNN query returns hits.

### Fix

Add `OSConnection.get_scores()`, mirroring
`ESConnectionBase.get_scores()`.
OpenSearch hit headers expose `_score` exactly like Elasticsearch (the
existing
`OSConnection.__getSource` already reads `d["_score"]`), so the
implementation
is identical.

Scope note: Infinity and OceanBase deliberately do not use `get_scores`
(#14970 routes them elsewhere), so this fix is intentionally limited to
the
OpenSearch backend, which is the only one reaching the ES KNN-score
path.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)

### Affected backends
OpenSearch only. Elasticsearch already implements `get_scores`; Infinity
/
OceanBase are routed away from it.

### How to reproduce
1. `DOC_ENGINE=opensearch` (docker `.env`), restart the stack.
2. Create a knowledge base with any dense embedding model and parse a
document.
3. Run a retrieval / chat over that KB -> 500 with the AttributeError
above.

### Risk & backward compatibility
None for the default Elasticsearch deployment -- the change only adds a
method
to `OSConnection`. No default values or ES/Infinity/OceanBase behavior
change.

### Test plan
- [ ] With `DOC_ENGINE=opensearch`, retrieval over a KB returns scored
chunks
      (no AttributeError).
- [ ] `DOC_ENGINE=elasticsearch` regression: retrieval unchanged.
- [ ] Empty-result path: `_knn_scores` early-returns `{}` (guarded),
get_scores
      handles an empty `hits` list gracefully.
JinHai-CN pushed a commit that referenced this pull request Aug 24, 2026
…knn boost (#18662)

### Summary

Fix OpenSearch retrieval returning `vector_similarity = 0.000` for every
chunk when hybrid search is enabled.

On the OpenSearch backend, retrieval uses a second KNN-only search
(`Dealer._knn_scores()`) to recover per-chunk cosine scores for
reranking. That pass intentionally sends `MatchDenseExpr(...,
{"similarity": 0.0})` to mean “no minimum similarity cutoff.”

However, `OSConnection.search()` was incorrectly mapping `similarity` to
the KNN clause `boost` field:

```python
knn_query[vector_column_name]["boost"] = similarity
```

With `similarity=0.0`, this produced `boost=0.0`, which zeroed out KNN
`_score` values. `get_scores()` then returned `0.0` for every hit, so
`vector_similarity` was always zero and hybrid ranking ignored the
vector component — with no exception raised.

This is separate from the `get_scores()` `AttributeError` crash
addressed in #14970 / #15390; here retrieval succeeds but vector scores
are silently lost.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant