Skip to content

Fix search vector_similarity_weight - #15108

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
wangq8:bugfix/fix-search-vector-similarity-weight
May 22, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
wangq8:bugfix/fix-search-vector-similarity-weight

Conversation

@wangq8

@wangq8 wangq8 commented May 21, 2026 •

Copy link
Copy Markdown
Collaborator

What problem does this PR solve?

Fix search vector_similarity_weight

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@coderabbitai

coderabbitai Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Remove vector weight inversion in the UI and propagate explicit vector_similarity_weight (and derived full-text weight) plus search_id/trace_id through REST API, dataset service, dialog service, and retrieval/reranking with added debug logging.

Changes

Vector similarity weight persistence & propagation

Layer / File(s) Summary
Frontend: persist weight without inversion
web/src/pages/next-search/search-setting.tsx
resetForm initializes vector_similarity_weight with ?? 0.3; onSubmit sends vector_similarity_weight directly to updateSearch (no 1 - weight).
REST API: helper and debug logging
api/apps/restful_apis/search_api.py
Add Real import and _full_text_weight() helper; emit debug logs on PUT /searches/ updates and completion stream; pass search_id into async_ask.
Dataset API service: load search config and pass runtime weights
api/apps/services/dataset_api_service.py
When search_id present, load search_config to override similarity_threshold, vector_similarity_weight, top_k, use_kg, languages, and reranker choice; forward similarity params and trace_id=search_id to retrieval.
Dialog service: async_ask signature and retrieval args
api/db/services/dialog_service.py
Extend async_ask(..., search_id=None), compute full_text_weight = 1 - vector_similarity_weight with fallback, log weights with search_id, and pass vector_similarity_weight, top_k, doc_ids, and trace_id into retriever.
Retriever/reranker: trace and term weight propagation
rag/nlp/search.py
Add trace_id to Dealer.retrieval, compute term_similarity_weight = 1 - vector_similarity_weight, log retrieval/rerank state including trace_id, and pass term_similarity_weight into reranking calls.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#14760: Related UI changes adjusting slider/inversion mapping and persistence of vector similarity weight.
  • infiniflow/ragflow#14970: Related reranking/term-weight changes in rag/nlp/search.py that touch similar weight handling and reranker behavior.

Suggested labels

size:M

Suggested reviewers

  • KevinHuSh

Poem

🐰 A little rabbit hops in code so bright,
No more flips where weights took flight.
From form to API, a faithful trace,
We pass the weight and log its place.
Puff of debug, tidy and light—hooray, good night!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% 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 'Fix search vector_similarity_weight' is directly related to the main changes across multiple files that adjust how vector_similarity_weight is initialized, passed, and handled throughout the search pipeline.
Description check ✅ Passed The description includes the required 'What problem does this PR solve?' section and correctly identifies the type of change as Bug Fix, matching the template structure.
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.

@wangq8
wangq8 marked this pull request as ready for review May 21, 2026 11:42
@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label May 21, 2026
@wangq8
wangq8 requested a review from dcc123456 May 21, 2026 12:10
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels May 22, 2026

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

Caution

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

⚠️ Outside diff range comments (2)
api/apps/restful_apis/search_api.py (1)

164-177: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate and bound vector_similarity_weight before persisting config.

Line 167 merges search_config without validating vector_similarity_weight. A non-numeric or out-of-range value can later break retrieval math (1 - vector_similarity_weight) or produce invalid negative full-text weight.

Suggested fix
         current_config = search_app.search_config or {}
         new_config = req["search_config"]
         if not isinstance(new_config, dict):
             return get_data_error_result(message="search_config must be a JSON object")
+        if "vector_similarity_weight" in new_config:
+            try:
+                vsw = float(new_config["vector_similarity_weight"])
+            except (TypeError, ValueError):
+                return get_data_error_result(message="vector_similarity_weight must be a number")
+            if vsw < 0 or vsw > 1:
+                return get_data_error_result(message="vector_similarity_weight must be between 0 and 1")
+            new_config["vector_similarity_weight"] = vsw
         req["search_config"] = {**current_config, **new_config}
🤖 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 `@api/apps/restful_apis/search_api.py` around lines 164 - 177, The merged
search_config currently accepts any vector_similarity_weight value; validate and
bound it before persisting: in the code around new_config handling in
search_api.py, ensure new_config.get("vector_similarity_weight") is checked,
coerce to a float (or return get_data_error_result if non-numeric), clamp it to
a sensible range [0.0, 1.0] (or use a default like 0.3 if missing), then set
req["search_config"]["vector_similarity_weight"] to that sanitized value prior
to logging and calling _full_text_weight so downstream math (e.g., 1 -
vector_similarity_weight) is safe and deterministic.
api/db/services/dialog_service.py (1)

1564-1587: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Normalize vector_similarity_weight to a bounded float before retrieval.

Line 1564 currently forwards raw config value. If it is a string/invalid type, retrieval can fail at runtime when weight arithmetic runs.

Suggested fix
-    vector_similarity_weight = search_config.get("vector_similarity_weight", 0.3)
-    try:
-        full_text_weight = 1 - vector_similarity_weight
-    except TypeError:
-        full_text_weight = None
+    try:
+        vector_similarity_weight = float(search_config.get("vector_similarity_weight", 0.3))
+    except (TypeError, ValueError):
+        vector_similarity_weight = 0.3
+    vector_similarity_weight = min(max(vector_similarity_weight, 0.0), 1.0)
+    full_text_weight = 1 - vector_similarity_weight
🤖 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 `@api/db/services/dialog_service.py` around lines 1564 - 1587, The code
forwards a raw config value for vector_similarity_weight (set where
vector_similarity_weight = search_config.get(...)) which can be a string or
invalid type and cause runtime errors; before computing full_text_weight and
calling retriever.retrieval, coerce vector_similarity_weight to a float with a
safe fallback (default 0.3), clamp it to the [0.0, 1.0] range, and then compute
full_text_weight = 1.0 - vector_similarity_weight (or None only if coercion
fails); update the debug log to reflect the normalized value and ensure the
normalized vector_similarity_weight is what is passed into retriever.retrieval
and related downstream calls (reference the vector_similarity_weight variable,
full_text_weight computation, and the retriever.retrieval call).
🤖 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.

Outside diff comments:
In `@api/apps/restful_apis/search_api.py`:
- Around line 164-177: The merged search_config currently accepts any
vector_similarity_weight value; validate and bound it before persisting: in the
code around new_config handling in search_api.py, ensure
new_config.get("vector_similarity_weight") is checked, coerce to a float (or
return get_data_error_result if non-numeric), clamp it to a sensible range [0.0,
1.0] (or use a default like 0.3 if missing), then set
req["search_config"]["vector_similarity_weight"] to that sanitized value prior
to logging and calling _full_text_weight so downstream math (e.g., 1 -
vector_similarity_weight) is safe and deterministic.

In `@api/db/services/dialog_service.py`:
- Around line 1564-1587: The code forwards a raw config value for
vector_similarity_weight (set where vector_similarity_weight =
search_config.get(...)) which can be a string or invalid type and cause runtime
errors; before computing full_text_weight and calling retriever.retrieval,
coerce vector_similarity_weight to a float with a safe fallback (default 0.3),
clamp it to the [0.0, 1.0] range, and then compute full_text_weight = 1.0 -
vector_similarity_weight (or None only if coercion fails); update the debug log
to reflect the normalized value and ensure the normalized
vector_similarity_weight is what is passed into retriever.retrieval and related
downstream calls (reference the vector_similarity_weight variable,
full_text_weight computation, and the retriever.retrieval call).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7d7e8920-caec-43ae-8b67-a950d9ad22f5

📥 Commits

Reviewing files that changed from the base of the PR and between a4c76cb and 3dca46f.

📒 Files selected for processing (4)
  • api/apps/restful_apis/search_api.py
  • api/apps/services/dataset_api_service.py
  • api/db/services/dialog_service.py
  • rag/nlp/search.py

@wangq8
wangq8 requested a review from KevinHuSh May 22, 2026 06:47
@wangq8 wangq8 added the ci Continue Integration label May 22, 2026
@wangq8
wangq8 marked this pull request as draft May 22, 2026 06:47
@wangq8
wangq8 marked this pull request as ready for review May 22, 2026 06:48
@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label May 22, 2026
@codecov

codecov Bot commented May 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (c5a46fd) to head (3dca46f).
⚠️ Report is 15 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15108   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  Misses         29       29           
  Partials       20       20           

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

@wangq8
wangq8 merged commit 7e68441 into infiniflow:main May 22, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants