Repository navigation
fix(agent): return session_id when chat completion produces no events (#15169) - #15228
Conversation
|
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:
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughAdds session-id fallback handling for empty workflow and continuation responses. Streaming paths now emit a final SSE payload containing ChangesSession ID Guarantee on Empty Workflow Responses
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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.
Actionable comments posted: 1
🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)
285-294: ⚡ Quick winAdd logging for the new empty-events fallback path.
These branches silently take a new control flow that now defines the endpoint contract for empty agent output. A small info/debug log with
agent_id,session_id, andstreamwould make these cases diagnosable in production.As per coding guidelines,
**/*.py: Add logging for new flows.Also applies to: 338-343, 1478-1482
🤖 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/agent_api.py` around lines 285 - 294, The new fallback branches that yield an empty SSE payload (the code that yields json.dumps({"session_id": session_id, "data": {}})) should log the event so these silent control flows are diagnosable; add a logger call (e.g., logger.info or logger.debug) immediately before each yield that includes agent_id, session_id, and stream (use the existing variable names agent_id, session_id, stream) and a short message like "empty agent output - returning session_id"; apply the same logging change to the other analogous fallback locations that produce the empty data JSON so all three branches consistently log this info.
🤖 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 `@api/apps/restful_apis/agent_api.py`:
- Around line 1478-1482: When handling existing-session streaming (the path that
calls _iter_session_completion_events with stream=true), ensure the stream does
not end with a bare [DONE] when the generator yields nothing by emitting an echo
event containing the session_id before completing; i.e., detect when
_iter_session_completion_events yields no events for the given session_id and
yield a final event with {"session_id": session_id} (the same shape returned by
get_result) prior to closing the stream so clients using stream=true can recover
the session_id.
---
Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 285-294: The new fallback branches that yield an empty SSE payload
(the code that yields json.dumps({"session_id": session_id, "data": {}})) should
log the event so these silent control flows are diagnosable; add a logger call
(e.g., logger.info or logger.debug) immediately before each yield that includes
agent_id, session_id, and stream (use the existing variable names agent_id,
session_id, stream) and a short message like "empty agent output - returning
session_id"; apply the same logging change to the other analogous fallback
locations that produce the empty data JSON so all three branches consistently
log this info.
🪄 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: 32a4eb6c-5071-41c3-97e4-fa69a7ff1d5d
📒 Files selected for processing (1)
api/apps/restful_apis/agent_api.py
|
Actionable comments posted: 0 |
78db4e9 to
f86a0e7
Compare
12389d6 to
a9ccdb6
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
api/apps/restful_apis/agent_api.py (1)
493-505: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winAuthorize session read/delete with
tenant_id.Binding the session to
agent_idprevents cross-agent access, but any authenticated caller who knows a validagent_id/session_idpair can still read or delete it becausetenant_idis unused here. Mirror the access check used inagent_chat_completionbefore returning or deleting the session.Proposed fix
def get_agent_session(agent_id, session_id, tenant_id): exists, conv = API4ConversationService.get_by_id(session_id) if not exists or conv.dialog_id != agent_id: return get_data_error_result(message="Session not found!") + if not UserCanvasService.accessible(agent_id, tenant_id): + logging.warning( + "get_agent_session denied: tenant_id=%s agent_id=%s session_id=%s", + tenant_id, + agent_id, + session_id, + ) + return get_data_error_result(message="Session not found!") return get_json_result(data=conv.to_dict()) @@ def delete_agent_session_item(agent_id, session_id, tenant_id): exists, conv = API4ConversationService.get_by_id(session_id) if not exists or conv.dialog_id != agent_id: return get_data_error_result(message="Session not found!") + if not UserCanvasService.accessible(agent_id, tenant_id): + logging.warning( + "delete_agent_session_item denied: tenant_id=%s agent_id=%s session_id=%s", + tenant_id, + agent_id, + session_id, + ) + return get_data_error_result(message="Session not found!") return get_json_result(data=API4ConversationService.delete_by_id(session_id))🤖 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/agent_api.py` around lines 493 - 505, The session read/delete handlers in agent_api.py only verify session ownership by agent_id, so they still allow cross-tenant access when tenant_id is ignored. Update the logic in get_agent_session_item and delete_agent_session_item to mirror the tenant authorization used in agent_chat_completion by checking that the fetched conversation matches tenant_id before returning data or deleting it, alongside the existing session_id/dialog_id validation.
🤖 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 `@api/apps/restful_apis/agent_api.py`:
- Around line 600-607: `workflow_finished` is being forwarded in the streaming
path but not preserved as the final payload in the non-stream response flow, so
it can fall through to the empty fallback. Update the response handling in
`agent_api.py` so the same final-answer selection logic used around the
`message_end`/`user_inputs` branch also treats `workflow_finished` as a terminal
non-stream result, and verify the code paths around the event forwarding block
and the non-stream fallback preserve the actual payload instead of discarding
it.
- Around line 326-340: The empty streaming fallback in agent_api’s session
handling returns a session_id but never commits the runtime replica because
persist_workflow_session() exits early when final_ans is empty. Update the
workflow in the empty-output branch to ensure the runtime replica is committed
on this path as well, matching the non-streaming fallback behavior in
persist_workflow_session() and the surrounding agent output handling logic.
---
Outside diff comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 493-505: The session read/delete handlers in agent_api.py only
verify session ownership by agent_id, so they still allow cross-tenant access
when tenant_id is ignored. Update the logic in get_agent_session_item and
delete_agent_session_item to mirror the tenant authorization used in
agent_chat_completion by checking that the fetched conversation matches
tenant_id before returning data or deleting it, alongside the existing
session_id/dialog_id validation.
🪄 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: f57fda37-531d-499e-9021-201939b79b2f
📒 Files selected for processing (1)
api/apps/restful_apis/agent_api.py
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
api/apps/restful_apis/agent_api.py (1)
493-505: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winAuthorize session read/delete with
tenant_id.Binding the session to
agent_idprevents cross-agent access, but any authenticated caller who knows a validagent_id/session_idpair can still read or delete it becausetenant_idis unused here. Mirror the access check used inagent_chat_completionbefore returning or deleting the session.Proposed fix
def get_agent_session(agent_id, session_id, tenant_id): exists, conv = API4ConversationService.get_by_id(session_id) if not exists or conv.dialog_id != agent_id: return get_data_error_result(message="Session not found!") + if not UserCanvasService.accessible(agent_id, tenant_id): + logging.warning( + "get_agent_session denied: tenant_id=%s agent_id=%s session_id=%s", + tenant_id, + agent_id, + session_id, + ) + return get_data_error_result(message="Session not found!") return get_json_result(data=conv.to_dict()) @@ def delete_agent_session_item(agent_id, session_id, tenant_id): exists, conv = API4ConversationService.get_by_id(session_id) if not exists or conv.dialog_id != agent_id: return get_data_error_result(message="Session not found!") + if not UserCanvasService.accessible(agent_id, tenant_id): + logging.warning( + "delete_agent_session_item denied: tenant_id=%s agent_id=%s session_id=%s", + tenant_id, + agent_id, + session_id, + ) + return get_data_error_result(message="Session not found!") return get_json_result(data=API4ConversationService.delete_by_id(session_id))🤖 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/agent_api.py` around lines 493 - 505, The session read/delete handlers in agent_api.py only verify session ownership by agent_id, so they still allow cross-tenant access when tenant_id is ignored. Update the logic in get_agent_session_item and delete_agent_session_item to mirror the tenant authorization used in agent_chat_completion by checking that the fetched conversation matches tenant_id before returning data or deleting it, alongside the existing session_id/dialog_id validation.
🤖 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 `@api/apps/restful_apis/agent_api.py`:
- Around line 600-607: `workflow_finished` is being forwarded in the streaming
path but not preserved as the final payload in the non-stream response flow, so
it can fall through to the empty fallback. Update the response handling in
`agent_api.py` so the same final-answer selection logic used around the
`message_end`/`user_inputs` branch also treats `workflow_finished` as a terminal
non-stream result, and verify the code paths around the event forwarding block
and the non-stream fallback preserve the actual payload instead of discarding
it.
- Around line 326-340: The empty streaming fallback in agent_api’s session
handling returns a session_id but never commits the runtime replica because
persist_workflow_session() exits early when final_ans is empty. Update the
workflow in the empty-output branch to ensure the runtime replica is committed
on this path as well, matching the non-streaming fallback behavior in
persist_workflow_session() and the surrounding agent output handling logic.
---
Outside diff comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 493-505: The session read/delete handlers in agent_api.py only
verify session ownership by agent_id, so they still allow cross-tenant access
when tenant_id is ignored. Update the logic in get_agent_session_item and
delete_agent_session_item to mirror the tenant authorization used in
agent_chat_completion by checking that the fetched conversation matches
tenant_id before returning data or deleting it, alongside the existing
session_id/dialog_id validation.
🪄 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: f57fda37-531d-499e-9021-201939b79b2f
📒 Files selected for processing (1)
api/apps/restful_apis/agent_api.py
🛑 Comments failed to post (2)
api/apps/restful_apis/agent_api.py (2)
326-340: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Commit the runtime replica on the empty streaming path.
Line 340 calls
persist_workflow_session(), but that helper returns immediately whenfinal_ansis empty, so this streaming fallback never reachescommit_runtime_replica(). The non-streaming fallback commits at Line 391; keep the stream path consistent.Proposed fix
else: # Canvas produced no events (e.g. empty query). Still # surface the session_id so the client can resume the # conversation — without it the SSE stream is just a # bare [DONE] (fixes `#15169`). logging.info( "empty agent output - returning session_id (agent_id=%s session_id=%s stream=%s)", agent_id, session_id, True, ) + await commit_runtime_replica() yield ( "data:" + json.dumps({"session_id": session_id, "data": {}}, ensure_ascii=False) + "\n\n" )📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.else: # Canvas produced no events (e.g. empty query). Still # surface the session_id so the client can resume the # conversation — without it the SSE stream is just a # bare [DONE] (fixes `#15169`). logging.info( "empty agent output - returning session_id (agent_id=%s session_id=%s stream=%s)", agent_id, session_id, True, ) await commit_runtime_replica() yield ( "data:" json.dumps({"session_id": session_id, "data": {}}, ensure_ascii=False) "\n\n" ) await persist_workflow_session()🧰 Tools
🪛 ast-grep (0.44.0)
[info] 336-336: use jsonify instead of json.dumps for JSON output
Context: json.dumps({"session_id": session_id, "data": {}}, ensure_ascii=False)
Note: [CWE-116] Improper Encoding or Escaping of Output.(use-jsonify)
🤖 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/agent_api.py` around lines 326 - 340, The empty streaming fallback in agent_api’s session handling returns a session_id but never commits the runtime replica because persist_workflow_session() exits early when final_ans is empty. Update the workflow in the empty-output branch to ensure the runtime replica is committed on this path as well, matching the non-streaming fallback behavior in persist_workflow_session() and the surrounding agent output handling logic.
600-607: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Treat
workflow_finishedas a final non-stream answer.Line 600 now forwards
workflow_finished, but Lines 1620-1623 only preservemessage_endoruser_inputs. If a continuation emitsworkflow_finishedwithoutmessage_end, the non-stream response falls through to the empty fallback and drops the actual payload.Proposed fix
- if ans.get("event") == "message_end": + if ans.get("event") in ["message_end", "workflow_finished"]: final_ans = ans elif ans.get("event") == "user_inputs" and not final_ans: final_ans = ansAlso applies to: 1620-1636
🤖 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/agent_api.py` around lines 600 - 607, `workflow_finished` is being forwarded in the streaming path but not preserved as the final payload in the non-stream response flow, so it can fall through to the empty fallback. Update the response handling in `agent_api.py` so the same final-answer selection logic used around the `message_end`/`user_inputs` branch also treats `workflow_finished` as a terminal non-stream result, and verify the code paths around the event forwarding block and the non-stream fallback preserve the actual payload instead of discarding it.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15228 +/- ##
=======================================
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:
|
…infiniflow#15169) (infiniflow#15228) ## Summary Fixes infiniflow#15169 — `POST /api/v1/agents/chat/completions` returned `data: {}` with no `session_id` when the agent produced no events (e.g. the reporter's payload sent `"query": ""`). ## Root cause For `{"agent_id": "...", "query": "", "stream": false}`: 1. No `session_id` in the request → new-session branch at `agent_api.py:1278`. 2. `session_id = get_uuid()` at `agent_api.py:1294`. 3. Falls into `_run_workflow_session`. 4. `canvas.run(query="")` produces no events, so `final_ans` stays `{}`. 5. Non-streaming path then hit: ```python if not final_ans: await commit_runtime_replica() return get_result(data={}) ``` `session_id` was allocated but silently dropped on the way out. The streaming path had the same shape (only a bare `[DONE]` was yielded — no SSE event carrying `session_id`). The session-continuation path at `agent_api.py:1463` had the same bug for callers that passed `session_id` and got `{}` back. The successful (non-empty) paths were fine because every canvas event has `ans["session_id"] = session_id` attached before being yielded / captured into `final_ans` (see `agent_api.py:255` and `:303`). ## Fix Three minimal changes, all in `api/apps/restful_apis/agent_api.py`: 1. **`_run_workflow_session` (non-streaming)**: `return get_result(data={"session_id": session_id})` instead of `data={}`. 2. **`_run_workflow_session` (SSE)**: if the canvas loop emits no events, yield one `data:{"session_id": "...", "data": {}}` event before `[DONE]`, so the client receives the id over the wire. 3. **`agent_chat_completion` session-continuation**: echo the caller-supplied `session_id` back in the empty-events case instead of `{}`. No change needed on the happy paths — they already attach `session_id` to every event. ## Test plan - [ ] Repro from the issue: `POST /api/v1/agents/chat/completions` with `{"agent_id": "<id>", "query": "", "stream": false}`. Response `data` should now contain `session_id`. - [ ] Same payload with `"stream": true`. SSE stream should contain one event with `session_id` before `data:[DONE]`. - [ ] Same shape but with a real, non-empty `"query"` (new session). Response should be unchanged from before — every event still carries `session_id`, final response still includes it on `final_ans`. - [ ] Pass an existing `session_id` plus `"query": ""`. Response should echo that `session_id` back instead of `{}`. - [ ] Pass an existing `session_id` plus a normal query. Response should be unchanged from before. - [ ] `openai-compatible: true` path is untouched — sanity-check it still works. - [ ] Run `uv run pytest` to make sure no existing tests regress. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) - [ ] New Feature (non-breaking change which adds functionality) - [ ] Documentation Update - [ ] Refactoring - [ ] Performance Improvement - [ ] Other (please describe):
Summary
Fixes #15169 —
POST /api/v1/agents/chat/completionsreturneddata: {}with nosession_idwhen the agent produced no events(e.g. the reporter's payload sent
"query": "").Root cause
For
{"agent_id": "...", "query": "", "stream": false}:No
session_idin the request → new-session branch atagent_api.py:1278.session_id = get_uuid()atagent_api.py:1294.Falls into
_run_workflow_session.canvas.run(query="")produces no events, sofinal_ansstays
{}.Non-streaming path then hit:
session_idwas allocated but silently dropped on the way out.The streaming path had the same shape (only a bare
[DONE]wasyielded — no SSE event carrying
session_id). Thesession-continuation path at
agent_api.py:1463had the same bugfor callers that passed
session_idand got{}back.The successful (non-empty) paths were fine because every canvas
event has
ans["session_id"] = session_idattached before beingyielded / captured into
final_ans(seeagent_api.py:255and:303).Fix
Three minimal changes, all in
api/apps/restful_apis/agent_api.py:_run_workflow_session(non-streaming):return get_result(data={"session_id": session_id})instead ofdata={}._run_workflow_session(SSE): if the canvas loop emits noevents, yield one
data:{"session_id": "...", "data": {}}event before[DONE], so the client receives the id over the wire.agent_chat_completionsession-continuation: echo thecaller-supplied
session_idback in the empty-events caseinstead of
{}.No change needed on the happy paths — they already attach
session_idto every event.Test plan
POST /api/v1/agents/chat/completionswith
{"agent_id": "<id>", "query": "", "stream": false}.Response
datashould now containsession_id."stream": true. SSE stream shouldcontain one event with
session_idbeforedata:[DONE]."query"(newsession). Response should be unchanged from before — every
event still carries
session_id, final response stillincludes it on
final_ans.session_idplus"query": "". Responseshould echo that
session_idback instead of{}.session_idplus a normal query. Responseshould be unchanged from before.
openai-compatible: truepath is untouched — sanity-checkit still works.
uv run pytestto make sure no existing tests regress.Type of change