Repository navigation
fix(dialog): guard async_ask() against empty or invalid kb_ids - #15530
Conversation
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.
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds 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. ChangesEmpty KB Guard and Tests
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
test/unit_test/api/db/services/test_dialog_service_final_answer.py (1)
320-340: ⚡ Quick winAssert the full stale-KB SSE contract here too.
This regression test currently checks
finalandanswer, but not the emptyreferencepayload 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 winLog the early-exit KB guard.
This adds a new terminal branch, but it exits silently. A warning with
tenant_id,search_id, and the requestedkb_idswould 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} returnAs 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
📒 Files selected for processing (2)
api/db/services/dialog_service.pytest/unit_test/api/db/services/test_dialog_service_final_answer.py
|
@yingfeng |
|
@wangq8 , @Haruko386 , @JinHai-CN @yingfeng @xugangqiang |
|
|
||
| kbs = KnowledgebaseService.get_by_ids(kb_ids) | ||
| if not kbs: | ||
| yield {"answer": "**ERROR**: No KB selected", "reference": {}, "final": True} |
There was a problem hiding this comment.
No KB selected ? Or the KB selected is not valid?
There was a problem hiding this comment.
I have solved this issue.
@xugangqiang Please check again.
dcfd122 to
77550d8
Compare
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.
77550d8 to
72ce888
Compare
There was a problem hiding this comment.
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 winAssert
referencein 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
📒 Files selected for processing (2)
api/db/services/dialog_service.pytest/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 | ||
|
|
There was a problem hiding this comment.
Is it possible to test this on UI or curl? We'd like to see what will happen with this fix.
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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 winAdd 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 whetherkb_idswas 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
📒 Files selected for processing (1)
api/db/services/dialog_service.py
Fixes #15529 .
Problem
async_ask()accessedkbs[0]without verifying thatKnowledgebaseService.get_by_ids()returned any knowledge bases. Empty or stalekb_idsraisedIndexError, which surfaced as HTTP 500 on search/bot SSE endpoints.Fix
kbsis empty, yielding a final SSE error event (consistent withgen_mindmap()in the same module).kb_idsand 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"POST /api/v1/searchbots/askwith invalidkb_idsreturns SSE error, not HTTP 500