Skip to content

Fix: support non-stream runtime agent completion - #14596

Merged
wangq8 merged 1 commit into
infiniflow:mainfrom
buua436:b034
May 6, 2026
Merged

wangq8 merged 1 commit into
infiniflow:mainfrom
buua436:b034

Conversation

@buua436

@buua436 buua436 commented May 6, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

support non-stream runtime agent completion

Type of change

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

@buua436 buua436 changed the title fix: support non-stream runtime agent completion Fix: support non-stream runtime agent completion May 6, 2026
@coderabbitai

coderabbitai Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The agent chat completion flow is refactored to support unified streaming and non-streaming execution paths with a dedicated runtime replica commit step that ensures replicas are committed after execution completion.

Changes

Agent Chat Completion Flow Refactoring

Layer / File(s) Summary
Data Shape
api/apps/restful_apis/agent_api.py
final_ans initialization changes from empty string to empty dictionary to support structured output format.
Commit Helper
api/apps/restful_apis/agent_api.py
New commit_runtime_replica coroutine added to commit in-flight runtime replicas after a run completes, with error logging on failure.
Streaming Path
api/apps/restful_apis/agent_api.py
Streaming execution yields Server-Sent Events from canvas run and commits the runtime replica upon completion.
Non-Streaming Path
api/apps/restful_apis/agent_api.py
Non-streaming execution accumulates final answer content, references, structured outputs, and optional traces before committing the runtime replica and returning the aggregated result.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Agent API
    participant Canvas Runtime
    participant Runtime Replica

    alt Streaming Path
        Client->>Agent API: POST /chat (streaming=true)
        Agent API->>Canvas Runtime: Execute run
        loop Stream Events
            Canvas Runtime->>Agent API: Yield event
            Agent API->>Client: Send SSE
        end
        Agent API->>Runtime Replica: Commit replica
        Runtime Replica->>Agent API: Commit complete
        Agent API->>Client: Stream end
    else Non-Streaming Path
        Client->>Agent API: POST /chat (streaming=false)
        Agent API->>Canvas Runtime: Execute run
        Canvas Runtime->>Agent API: Return final state
        Agent API->>Agent API: Aggregate content, references, traces
        Agent API->>Runtime Replica: Commit replica
        Runtime Replica->>Agent API: Commit complete
        Agent API->>Client: Return aggregated result
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

A rabbit refactored the flow with care, 🐰
Two paths where once was just one there,
Streaming and steady, both find their way,
To commit and complete the async day!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description covers the required template sections but lacks detail about what problem is being solved and why this fix is necessary. Expand the problem statement to explain why non-stream runtime agent completion support is needed and what issue this resolves.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: adding support for non-stream runtime agent completion, which aligns with the code modifications and PR objectives.
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.

@buua436 buua436 added the ci Continue Integration label May 6, 2026
@buua436
buua436 marked this pull request as ready for review May 6, 2026 11:59
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. labels May 6, 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
api/apps/restful_apis/agent_api.py (1)

1037-1081: ⚡ Quick win

Add structured logs for the new non-stream runtime flow.

This branch is the new execution path in the PR, but today it only logs failures. Please add at least start/success logs with agent_id, tenant_id, and runtime_user_id so this path is observable in production.

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/apps/restful_apis/agent_api.py` around lines 1037 - 1081, Add structured
start and success logs around the non-stream runtime path: log a start message
before entering the try/async-for loop and a success message right before await
commit_runtime_replica()/return get_result(...). Include agent_id, tenant_id,
and runtime_user_id in both logs (pull these from the available
context/req/inputs as appropriate), use the existing logging facility (e.g.,
logging.info) consistent with logging.exception used on errors, and reference
the non-stream flow by mentioning symbols from this block like canvas.run,
final_ans, full_content, canvas.cancel_task, and commit_runtime_replica to
locate where to insert the messages.
🤖 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 1001-1010: The call to CanvasReplicaService.commit_after_run
inside commit_runtime_replica blocks the Quart event loop because it performs
synchronous Redis I/O; change commit_runtime_replica to invoke
CanvasReplicaService.commit_after_run via the existing thread_pool_exec helper
(await thread_pool_exec(lambda: CanvasReplicaService.commit_after_run(...))) so
the blocking Redis call runs off the event loop, and propagate/log any returned
boolean appropriately; also add structured logging statements (start and
completion with success/failure) around the non-stream runtime flow so the new
flow (the non-stream runtime branch) logs when it begins and when it finishes
(include the runtime identifier like agent_id/canvas_title and success status)
to match the "Add logging for new flows" guideline.

---

Nitpick comments:
In `@api/apps/restful_apis/agent_api.py`:
- Around line 1037-1081: Add structured start and success logs around the
non-stream runtime path: log a start message before entering the try/async-for
loop and a success message right before await commit_runtime_replica()/return
get_result(...). Include agent_id, tenant_id, and runtime_user_id in both logs
(pull these from the available context/req/inputs as appropriate), use the
existing logging facility (e.g., logging.info) consistent with logging.exception
used on errors, and reference the non-stream flow by mentioning symbols from
this block like canvas.run, final_ans, full_content, canvas.cancel_task, and
commit_runtime_replica to locate where to insert the messages.
🪄 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: e466f06c-a3f4-42c8-a4aa-aef85e568b60

📥 Commits

Reviewing files that changed from the base of the PR and between 04c5f1b and f40139a.

📒 Files selected for processing (1)
  • api/apps/restful_apis/agent_api.py

Comment on lines +1001 to +1010
async def commit_runtime_replica():
commit_ok = CanvasReplicaService.commit_after_run(
canvas_id=agent_id,
tenant_id=str(tenant_id),
runtime_user_id=user_id,
dsl=json.loads(str(canvas)),
canvas_category=canvas_category,
title=canvas_title,
)
if not commit_ok:

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== commit_after_run implementation =="
sed -n '223,259p' api/apps/services/canvas_replica_service.py

echo
echo "== surrounding async handler =="
sed -n '938,1085p' api/apps/restful_apis/agent_api.py

echo
echo "== existing thread_pool_exec usage in this handler =="
rg -n "thread_pool_exec\\(" api/apps/restful_apis/agent_api.py

Repository: infiniflow/ragflow

Length of output: 7735


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Checking imports at top of agent_api.py ==="
head -50 api/apps/restful_apis/agent_api.py | grep -E "^import|^from"

echo
echo "=== Checking for partial import ==="
rg "from functools import|import functools" api/apps/restful_apis/agent_api.py

echo
echo "=== Finding thread_pool_exec definition ==="
rg -n "def thread_pool_exec" --type py

echo
echo "=== Checking thread_pool_exec usage pattern in agent_api.py ==="
rg -B2 -A4 "await thread_pool_exec" api/apps/restful_apis/agent_api.py | head -60

echo
echo "=== Checking logging in non-stream runtime path (lines 1030-1080) ==="
sed -n '1030,1080p' api/apps/restful_apis/agent_api.py

Repository: infiniflow/ragflow

Length of output: 4701


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== thread_pool_exec signature and implementation ==="
sed -n '128,150p' common/misc_utils.py

echo
echo "=== Check if thread_pool_exec is imported in agent_api.py ==="
rg "thread_pool_exec" api/apps/restful_apis/agent_api.py | head -3
</script>

Repository: infiniflow/ragflow

Length of output: 801


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Stream path logging (lines 1015-1035) ==="
sed -n '1015,1035p' api/apps/restful_apis/agent_api.py

echo
echo "=== Non-stream path start (lines 1036-1055) ==="
sed -n '1036,1055p' api/apps/restful_apis/agent_api.py

echo
echo "=== Ruff linting check on the file ==="
rg "ruff" . --type py | head -5
python3 -m pip install ruff 2>/dev/null >/dev/null || true
python3 -m ruff check api/apps/restful_apis/agent_api.py 2>&1 | head -20

Repository: infiniflow/ragflow

Length of output: 1985


Offload the replica commit from the async request path.

CanvasReplicaService.commit_after_run() is synchronous Redis I/O, so calling it directly here will block the Quart event loop at the end of every runtime completion. The handler already uses thread_pool_exec() for other blocking operations (lines 938, 945, 983), so this should follow the same pattern.

Additionally, the new non-stream runtime flow (lines 1036–1080) lacks structured logging for the start and completion of the flow, which violates the "Add logging for new flows" guideline.

♻️ Suggested change
         async def commit_runtime_replica():
-            commit_ok = CanvasReplicaService.commit_after_run(
-                canvas_id=agent_id,
-                tenant_id=str(tenant_id),
-                runtime_user_id=user_id,
-                dsl=json.loads(str(canvas)),
-                canvas_category=canvas_category,
-                title=canvas_title,
-            )
+            commit_ok = await thread_pool_exec(
+                partial(
+                    CanvasReplicaService.commit_after_run,
+                    canvas_id=agent_id,
+                    tenant_id=str(tenant_id),
+                    runtime_user_id=user_id,
+                    dsl=json.loads(str(canvas)),
+                    canvas_category=canvas_category,
+                    title=canvas_title,
+                )
+            )
             if not commit_ok:
                 logging.error(
🤖 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 1001 - 1010, The call to
CanvasReplicaService.commit_after_run inside commit_runtime_replica blocks the
Quart event loop because it performs synchronous Redis I/O; change
commit_runtime_replica to invoke CanvasReplicaService.commit_after_run via the
existing thread_pool_exec helper (await thread_pool_exec(lambda:
CanvasReplicaService.commit_after_run(...))) so the blocking Redis call runs off
the event loop, and propagate/log any returned boolean appropriately; also add
structured logging statements (start and completion with success/failure) around
the non-stream runtime flow so the new flow (the non-stream runtime branch) logs
when it begins and when it finishes (include the runtime identifier like
agent_id/canvas_title and success status) to match the "Add logging for new
flows" guideline.

@codecov

codecov Bot commented May 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (04c5f1b) to head (f40139a).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14596   +/-   ##
=======================================
  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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐖api The modified files are located under directory 'api/apps/sdk' 🐞 bug Something isn't working, pull request that fix bug. 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.

2 participants