Skip to content

fix(dialog): guard async_ask() against empty or invalid kb_ids - #15530

Merged
wangq8 merged 4 commits into
infiniflow:mainfrom
bohdansolovie:fix/async-ask-empty-kb-guard
Jun 11, 2026
Merged

wangq8 merged 4 commits into
infiniflow:mainfrom
bohdansolovie:fix/async-ask-empty-kb-guard

Conversation

@bohdansolovie

Copy link
Copy Markdown
Contributor

Fixes #15529 .

Problem

async_ask() accessed kbs[0] without verifying that KnowledgebaseService.get_by_ids() returned any knowledge bases. Empty or stale kb_ids raised IndexError, which surfaced as HTTP 500 on search/bot SSE endpoints.

Fix

  • Add an early guard when kbs is empty, yielding a final SSE error event (consistent with gen_mindmap() in the same module).
  • Add regression tests for empty kb_ids and deleted/invalid KB IDs.

Test plan

  • pytest test/unit_test/api/db/services/test_dialog_service_final_answer.py -k "async_ask_empty or async_ask_stale"
  • Manual: POST /api/v1/searchbots/ask with invalid kb_ids returns SSE error, not HTTP 500

When KnowledgebaseService.get_by_ids() returns no rows, yield a final SSE
error event instead of raising IndexError on kbs[0]. Mirrors the existing
guard in gen_mindmap().
Add regression tests for empty kb_ids and stale/deleted KB IDs.
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 2, 2026
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • ✅ Review completed - (🔄 Check again to review again)

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: e4092d7b-6ad2-4670-bee0-58832a8608a8

📥 Commits

Reviewing files that changed from the base of the PR and between 2028c8f and f838915.

📒 Files selected for processing (1)
  • api/db/services/dialog_service.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/db/services/dialog_service.py

📝 Walkthrough

Walkthrough

Adds an early guard in dialog_service.async_ask() that yields a terminal SSE error and returns when KnowledgebaseService.get_by_ids(kb_ids) returns no KBs. Adds two unit tests verifying the final SSE event for empty and stale KB selections.

Changes

Empty KB Guard and Tests

Layer / File(s) Summary
Early KB validation guard
api/db/services/dialog_service.py
async_ask() checks whether KnowledgebaseService.get_by_ids(kb_ids) returns any KBs; if none are found it yields {"answer": "**ERROR**: No KB selected", "reference": {}, "final": True} (or a "not valid" message when kb_ids was provided) and returns.
Regression tests for empty/stale KB selection
test/unit_test/api/db/services/test_dialog_service_final_answer.py
Adds two tests that stub KnowledgebaseService.get_by_ids to return [] and assert async_ask() yields exactly one terminal SSE final event with the expected error message and empty reference.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant async_ask
  participant KnowledgebaseService
  participant SSEStream
  Client->>async_ask: POST /ask (question, kb_ids)
  async_ask->>KnowledgebaseService: get_by_ids(kb_ids)
  KnowledgebaseService-->>async_ask: []
  async_ask->>SSEStream: final event {"answer":"**ERROR**: No KB selected"/"not valid","reference":{},"final":true}
  SSEStream-->>Client: SSE final event
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#13917: Both PRs modify dialog_service.async_ask()'s SSE final event behavior in api/db/services/dialog_service.py.

Suggested reviewers

  • yingfeng
  • xugangqiang
  • JinHai-CN

🐰 I sniffed the KBs and gave a thump,
When none were found I stopped the jump.
A single final note, calm and neat,
"No KB selected" — the stream's complete.
Tests hop by to keep things neat.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% 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 describes the main change: adding a guard against empty or invalid kb_ids in the async_ask() function.
Description check ✅ Passed The description includes the problem statement, the fix explanation, and test plan. It follows the template with problem context and references the linked issue.
Linked Issues check ✅ Passed The PR fully addresses all objectives from issue #15529: adds guard for empty KB results, yields graceful SSE error, implements pattern consistent with gen_mindmap(), and includes regression tests.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the empty/invalid kb_ids issue: modified async_ask() guard logic and added corresponding regression tests.

✏️ 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.

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

🧹 Nitpick comments (2)
test/unit_test/api/db/services/test_dialog_service_final_answer.py (1)

320-340: ⚡ Quick win

Assert the full stale-KB SSE contract here too.

This regression test currently checks final and answer, but not the empty reference payload that the new guard returns. Adding that assertion keeps the stale-ID path pinned to the same terminal event shape as the empty-list path.

♻️ Proposed fix
     assert len(events) == 1
     assert events[0].get("final") is True
     assert "No KB selected" in events[0]["answer"]
+    assert events[0]["reference"] == {}
🤖 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 `@test/unit_test/api/db/services/test_dialog_service_final_answer.py` around
lines 320 - 340, Update the test_async_ask_stale_kb_ids_yields_error_final_event
to also assert the SSE terminal event includes an empty "reference" payload like
the empty-list path: after calling dialog_service.async_ask (the test already
monkeypatches KnowledgebaseService.get_by_ids), add an assertion that
events[0]["reference"] equals [] (or the exact empty-shape your guard returns)
in addition to the existing checks for events[0]["final"] and
events[0]["answer"], so the stale-KB terminal event contract matches the
empty-list terminal event.
api/db/services/dialog_service.py (1)

1536-1538: ⚡ Quick win

Log the early-exit KB guard.

This adds a new terminal branch, but it exits silently. A warning with tenant_id, search_id, and the requested kb_ids would make these SSE failures traceable in production.

♻️ Proposed fix
     if not kbs:
+        logger.warning(
+            "async_ask received no knowledge bases: tenant_id=%s search_id=%s kb_ids=%s",
+            tenant_id,
+            search_id,
+            kb_ids,
+        )
         yield {"answer": "**ERROR**: No KB selected", "reference": {}, "final": True}
         return

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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 1536 - 1538, The early-return
when no KBs are selected (the kbs guard that yields {"answer": "**ERROR**: No KB
selected", ...} and returns) exits silently; add a warning log immediately
before the yield that records tenant_id, search_id, and the requested kb_ids
(use the existing module logger instance, e.g., logger.warning(...)) so SSE
failures are traceable in production; ensure the log includes clear context and
the variables tenant_id, search_id, and kb_ids, then proceed with the existing
yield and return.
🤖 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.

Nitpick comments:
In `@api/db/services/dialog_service.py`:
- Around line 1536-1538: The early-return when no KBs are selected (the kbs
guard that yields {"answer": "**ERROR**: No KB selected", ...} and returns)
exits silently; add a warning log immediately before the yield that records
tenant_id, search_id, and the requested kb_ids (use the existing module logger
instance, e.g., logger.warning(...)) so SSE failures are traceable in
production; ensure the log includes clear context and the variables tenant_id,
search_id, and kb_ids, then proceed with the existing yield and return.

In `@test/unit_test/api/db/services/test_dialog_service_final_answer.py`:
- Around line 320-340: Update the
test_async_ask_stale_kb_ids_yields_error_final_event to also assert the SSE
terminal event includes an empty "reference" payload like the empty-list path:
after calling dialog_service.async_ask (the test already monkeypatches
KnowledgebaseService.get_by_ids), add an assertion that events[0]["reference"]
equals [] (or the exact empty-shape your guard returns) in addition to the
existing checks for events[0]["final"] and events[0]["answer"], so the stale-KB
terminal event contract matches the empty-list terminal event.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 330fc387-b7f2-4b23-a34d-a6c689cda04c

📥 Commits

Reviewing files that changed from the base of the PR and between 9799f33 and 01bf372.

📒 Files selected for processing (2)
  • api/db/services/dialog_service.py
  • test/unit_test/api/db/services/test_dialog_service_final_answer.py

@bohdansolovie

Copy link
Copy Markdown
Contributor Author

@yingfeng
Could you please review?

@bohdansolovie

Copy link
Copy Markdown
Contributor Author

@wangq8 , @Haruko386 , @JinHai-CN @yingfeng @xugangqiang
Please review this PR

Comment thread api/db/services/dialog_service.py Outdated

kbs = KnowledgebaseService.get_by_ids(kb_ids)
if not kbs:
yield {"answer": "**ERROR**: No KB selected", "reference": {}, "final": True}

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.

No KB selected ? Or the KB selected is not valid?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I have solved this issue.
@xugangqiang Please check again.

@bohdansolovie
bohdansolovie force-pushed the fix/async-ask-empty-kb-guard branch from dcfd122 to 77550d8 Compare June 3, 2026 13:15
Return "No KB selected" when kb_ids is empty, and "The selected KB is
not valid" when IDs were provided but get_by_ids() found no rows.
@bohdansolovie
bohdansolovie force-pushed the fix/async-ask-empty-kb-guard branch from 77550d8 to 72ce888 Compare June 3, 2026 13:16

@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 (1)
test/unit_test/api/db/services/test_dialog_service_final_answer.py (1)

320-339: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Assert reference in stale-KB final event as well.

Line 338 verifies error text, but this test should also lock the SSE terminal payload contract (reference == {}) like the empty-KB case does. That prevents silent regressions in final-event shape.

Proposed test hardening
 def test_async_ask_stale_kb_ids_yields_error_final_event(monkeypatch):
@@
     assert len(events) == 1
     assert events[0].get("final") is True
     assert "not valid" in events[0]["answer"]
+    assert events[0]["reference"] == {}

Based on learnings: "Applies to tests/**/*.py : Add/adjust tests for behavior changes".

🤖 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 `@test/unit_test/api/db/services/test_dialog_service_final_answer.py` around
lines 320 - 339, Update the test_async_ask_stale_kb_ids_yields_error_final_event
case to also assert that the final SSE payload includes an empty reference
object; specifically, inside the test function
(test_async_ask_stale_kb_ids_yields_error_final_event) after asserting
events[0].get("final") is True and checking the error text, add an assertion
that events[0]["reference"] == {} so the final-event shape contract is locked
down for stale KB selection (this mirrors the empty-KB test behavior).
🤖 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 `@test/unit_test/api/db/services/test_dialog_service_final_answer.py`:
- Around line 320-339: Update the
test_async_ask_stale_kb_ids_yields_error_final_event case to also assert that
the final SSE payload includes an empty reference object; specifically, inside
the test function (test_async_ask_stale_kb_ids_yields_error_final_event) after
asserting events[0].get("final") is True and checking the error text, add an
assertion that events[0]["reference"] == {} so the final-event shape contract is
locked down for stale KB selection (this mirrors the empty-KB test behavior).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 188d517c-f743-4871-8656-c6567edffecf

📥 Commits

Reviewing files that changed from the base of the PR and between 01bf372 and dcfd122.

📒 Files selected for processing (2)
  • api/db/services/dialog_service.py
  • test/unit_test/api/db/services/test_dialog_service_final_answer.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/db/services/dialog_service.py

Lock down the final SSE payload shape for invalid KB selection, matching
the empty-kb_ids test contract.
error = "**ERROR**: The selected KB is not valid"
yield {"answer": error, "reference": {}, "final": True}
return

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.

Is it possible to test this on UI or curl? We'd like to see what will happen with this fix.

@xugangqiang
xugangqiang marked this pull request as draft June 4, 2026 03:01
@xugangqiang xugangqiang added the ci Continue Integration label Jun 4, 2026
@xugangqiang
xugangqiang marked this pull request as ready for review June 4, 2026 03:01
@codecov

codecov Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15530   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

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

@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 (1)
api/db/services/dialog_service.py (1)

1603-1609: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add a debug/info log for the new early-return branch.

Line 1603 introduces a new terminal flow for empty/invalid KB selection, but it exits silently. Please log this branch (e.g., with search_id, tenant_id, and whether kb_ids was empty) to keep SSE failure diagnostics traceable.

As per coding guidelines, “**/*.py: Add logging for new flows”.

Suggested patch
     kbs = KnowledgebaseService.get_by_ids(kb_ids)
     if not kbs:
+        logger.info(
+            "async_ask early exit: no valid KBs found (search_id=%s tenant_id=%s kb_ids_provided=%s)",
+            search_id,
+            tenant_id,
+            bool(kb_ids),
+        )
         if not kb_ids:
             error = "**ERROR**: No KB selected"
         else:
             error = "**ERROR**: The selected KB is not valid"
         yield {"answer": error, "reference": {}, "final": True}
         return
🤖 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 1603 - 1609, Add an
info/debug log in the early-return branch that handles empty/invalid KB
selection so the SSE failure is traceable: inside the block that checks "if not
kbs:" (where it sets error and yields the final answer), log an event including
search_id, tenant_id, and a boolean/description of whether kb_ids was empty or
invalid (and optionally the raw kb_ids) using the module logger (e.g.,
logger.info or logger.debug) before yielding/returning; keep the existing error
message and yield behavior unchanged.

Source: Coding guidelines

🤖 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/db/services/dialog_service.py`:
- Around line 1603-1609: Add an info/debug log in the early-return branch that
handles empty/invalid KB selection so the SSE failure is traceable: inside the
block that checks "if not kbs:" (where it sets error and yields the final
answer), log an event including search_id, tenant_id, and a boolean/description
of whether kb_ids was empty or invalid (and optionally the raw kb_ids) using the
module logger (e.g., logger.info or logger.debug) before yielding/returning;
keep the existing error message and yield behavior unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b68ce859-a40e-4d24-86a0-dc49e23e7046

📥 Commits

Reviewing files that changed from the base of the PR and between 2028c8f and f838915.

📒 Files selected for processing (1)
  • api/db/services/dialog_service.py

@wangq8
wangq8 merged commit 381091d into infiniflow:main Jun 11, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: async_ask() crashes with IndexError when kb_ids is empty or all IDs are invalid

3 participants