Repository navigation
Fix: close MCP sessions after canvas execution to prevent connection leaks - #13295
Conversation
…leaks Add Graph.close() method that finds and closes all MCPToolCallSessions held by Agent components. Call it in finally blocks after canvas.run() in canvas_service.py and canvas_app.py. Also move session cleanup to finally blocks in test_tool endpoint and get_mcp_tools to ensure sessions are closed even on exceptions.
There was a problem hiding this comment.
Pull request overview
This PR addresses MCP connection leaks by ensuring MCPToolCallSession instances created during canvas/agent execution are reliably closed after use, preventing accumulated threads/SSE connections from exhausting resources over time.
Changes:
- Add
Graph.close()to close any MCP tool-call sessions held by Agent tools. - Ensure
canvas.close()is invoked infinallyblocks after streaming execution paths complete. - Move MCP session cleanup into
finallyblocks for MCP-related API endpoints/utilities to run even on exceptions.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| api/utils/api_utils.py | Ensures MCP sessions created during get_mcp_tools are always closed via finally. |
| api/db/services/canvas_service.py | Adds finally cleanup to close the canvas after streamed completion. |
| api/apps/mcp_server_app.py | Ensures MCP tool-call sessions are closed even when test_tool errors/returns early. |
| api/apps/canvas_app.py | Closes the canvas in a finally block for the SSE streaming route. |
| agent/canvas.py | Introduces Graph.close() to clean up MCP tool-call sessions referenced by Agent tools. |
Comments suppressed due to low confidence (4)
api/db/services/canvas_service.py:247
canvas.close()is a synchronous, potentially blocking cleanup (it callsMCPToolCallSession.close_sync()with timeouts). Calling it directly inside this async generatorfinallycan block the event loop for up to several seconds per MCP session, impacting concurrent requests. Consider running the close in the thread pool (e.g.,await thread_pool_exec(canvas.close)) or providing an async close path so cleanup doesn’t block the loop.
finally:
canvas.close()
api/apps/canvas_app.py:230
canvas.close()performs synchronous cleanup (including waiting on MCP session shutdown). Calling it directly in this async generatorfinallycan block the Quart event loop during client disconnects/errors. Prefer executing the close viaawait thread_pool_exec(canvas.close)(already imported in this module) or implement an async close method.
finally:
canvas.close()
agent/canvas.py:152
Graph.close()currently only closesMCPToolCallSessions but does not shut down the per-canvasThreadPoolExecutorcreated in__init__(self._thread_pool). If callers start usingcanvas.close()for lifecycle management, this leaves worker threads alive and undermines the goal of preventing resource leaks. Consider callingself._thread_pool.shutdown(...)(and clearing references if appropriate) as part ofclose().
def close(self):
from common.mcp_tool_call_conn import MCPToolCallSession
seen = set()
for cpn in self.components.values():
obj = cpn.get("obj")
if obj and hasattr(obj, "tools"):
for tool in obj.tools.values():
if isinstance(tool, MCPToolCallSession) and id(tool) not in seen:
seen.add(id(tool))
try:
tool.close_sync(timeout=3)
except Exception:
pass
agent/canvas.py:152
Graph.close()swallows all exceptions (except Exception: pass) when closing MCP sessions. If a session fails to close, this can silently reintroduce the original leak and makes diagnosing shutdown issues difficult. Consider at least logging the exception (or relying onclose_sync’s internal logging without an outer blankettry/except).
try:
tool.close_sync(timeout=3)
except Exception:
pass
You can also share your feedback on Copilot code review. Take the survey.
|
Hi — just a gentle bump on this. Happy to make any changes if needed! |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #13295 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…leaks Add Graph.close() method that finds and closes all MCPToolCallSessions held by Agent components. Call it in finally blocks after canvas.run() in canvas_service.py and canvas_app.py. Also move session cleanup to finally blocks in test_tool endpoint and get_mcp_tools to ensure sessions are closed even on exceptions.
|
This PR currently has merge conflicts with Please run locally: git fetch origin main
git rebase origin/main
# or
git merge origin/mainAfter resolving the conflicts, push to the current head branch and CI will re-run the review checks.
|
# Conflicts: # api/apps/canvas_app.py # api/apps/restful_apis/mcp_api.py # api/db/services/canvas_service.py
|
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)
📝 WalkthroughWalkthroughAdds Canvas API and MCP Cleanup
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 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 |
f3caa7d to
06211dd
Compare
There was a problem hiding this comment.
Actionable comments posted: 16
🧹 Nitpick comments (1)
api/apps/canvas_app.py (1)
160-238: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd structured logging for the new operational flows.
Completion streaming, DB connectivity checks, and session mutations should log key lifecycle events and failures consistently. As per coding guidelines,
**/*.py: Add logging for new flows.Also applies to: 421-523, 653-700
🤖 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/canvas_app.py` around lines 160 - 238, The new completion streaming flow in run() lacks consistent operational logging for key lifecycle events and failures. Add structured logs around CanvasReplicaService.load_for_run, the Canvas creation and canvas.run streaming loop, the commit_after_run result, and the exception/cancel/close path so successes and failures are traceable. Use the existing run, sse, CanvasReplicaService, and Canvas methods as anchors, and follow the same logging style used elsewhere in the module for DB/session mutation flows.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.
Inline comments:
In `@agent/canvas.py`:
- Around line 155-158: The cleanup path in the `close_sync()` call is swallowing
exceptions silently, so update the new cleanup flow in `Canvas` to log any
failure instead of using a bare `except Exception: pass`. Use the existing
cleanup logic around `tool.close_sync(timeout=3)` to catch the exception, emit
an error-level log with the exception details, and keep the rest of the shutdown
path intact so MCP connection leaks can be diagnosed.
- Around line 146-158: The teardown in Graph.close currently closes
MCPToolCallSession instances but leaves the graph-owned ThreadPoolExecutor
alive, so add executor shutdown to the same cleanup path after the tool/session
loop. Locate the Graph.close method and ensure the per-graph executor created by
the Graph class is explicitly shut down during close, with any necessary guard
so repeated close calls remain safe.
In `@api/apps/canvas_app.py`:
- Line 53: The route decorators in canvas_app are using manager before it
exists, causing import-time failures when the module is loaded. Define or import
the shared manager object in this module before any `@manager.route` decorators,
and make sure the existing route functions in canvas_app register against that
same manager instance.
- Around line 526-546: The canvas version endpoints currently return
history/version data without an ownership check; update getlistversion and
getversion in canvas_app to verify current_user has access to the underlying
canvas before returning anything. Use the existing UserCanvasVersionService
lookups in these handlers to resolve the canvas/version owner, compare it
against current_user, and return an error response when the user is not
authorized.
- Around line 421-523: The test_db_connect endpoint is allowing unrestricted
user-controlled outbound connections, which can be abused as a network probe. In
test_db_connect, add an allowlist and/or privileged-role check before creating
any database client (MySQLDatabase, PostgresqlDatabase, pyodbc.connect,
ibm_db.connect, trino.dbapi.connect) so only approved hosts/ports can be tested.
Also set driver-level connection/login timeouts for each branch to prevent
hanging workers, and keep the existing success/failure flow unchanged.
- Around line 603-615: The trace endpoint is currently public and can return
sensitive execution logs without any authorization. Update the trace() handler
in canvas_app.py to require authentication and verify the caller has access to
the requested canvas before reading Redis, using the existing request/context
auth helpers and canvas permission checks already used by other endpoints. Make
sure the /trace route only serves data after validating canvas_id and message_id
against the authenticated user’s permitted canvas, and return a
forbidden/unauthorized response when access is not allowed.
- Around line 688-700: The session read/delete handlers in canvas_app.py only
check canvas ownership and then operate on API4ConversationService by
session_id, which leaves an IDOR gap. In both the session fetch flow and
del_session, use the existing canvas_id and session_id to verify the loaded
conversation belongs to the requested canvas before calling conv.to_dict() or
API4ConversationService.delete_by_id. Update the relevant logic around
API4ConversationService.get_by_id, del_session, and UserCanvasService.accessible
so the session is scoped to the canvas and rejected if it does not match.
- Around line 337-341: The Canvas usage in the affected routes leaves MCP tool
sessions open because `canvas.close()` is never called after `Canvas(...)` and
`canvas.reset()`. Update each route that creates a `Canvas` in
`api/apps/canvas_app.py` to wrap the existing Canvas work in a `try/finally` and
call `canvas.close()` in the `finally` block, matching the teardown path used by
`Graph.close()` in `agent/canvas.py`. Apply this to every `Canvas` instance in
the listed handlers so the session is always released even on errors.
- Around line 445-449: The database branches currently leave cursor/db handles
open when execution exits early or throws, especially in the MSSQL, DB2, and
Trino paths. Update the connection logic around the `req["db_type"]` branches to
use `try/finally` so every `cursor` is always closed and every `db` connection
is closed after use, even on exceptions. Make sure the MSSQL path that uses
`pyodbc.connect` closes both `cursor` and `db`, and apply the same cleanup
pattern consistently to the DB2 and Trino blocks.
- Around line 346-359: The upload endpoint currently allows file writes using
cvs["user_id"] without any authentication or canvas ownership/access validation.
Add the same login and canvas access guard used by other canvas routes to the
upload handler in upload(canvas_id), ensuring the caller is authenticated and
authorized for that canvas before calling UserCanvasService.get_by_canvas_id or
FileService.upload_info. Keep the existing upload flow intact, but block
unauthorized requests early with an appropriate error result.
- Around line 190-196: The DataFlow branch in canvas_app’s request handling
indexes files[0] without verifying that files is non-empty, which can crash a
valid completion request. Add an explicit guard before calling thread_pool_exec
in the canvas_category == CanvasCategory.DataFlow path to return a
get_data_error_result when files is empty, and keep the existing Pipeline,
queue_dataflow, and get_json_result flow unchanged for the valid case.
- Around line 138-146: The getsse endpoint currently assumes
request.headers.get('Authorization') always exists, so missing or malformed auth
headers can crash before the intended error response. Update getsse to validate
the Authorization header before calling split(), and return
get_data_error_result with the existing auth error message when the header is
missing or not in the expected two-part format. Keep the fix localized to getsse
and preserve the APIToken.query(beta=token) flow for valid tokens.
- Around line 718-723: The download endpoint currently trusts caller-supplied
query parameters, so update the download() route to authorize access before
calling FileService.get_blob. Use the authenticated user/context instead of the
request.args values for created_by, and validate that the requested blob id
belongs to that user or is otherwise permitted. Keep the fix localized around
download() and FileService.get_blob so unauthorized blob fetch attempts are
blocked.
- Around line 653-677: The set_session route currently loads the canvas with
UserCanvasService.get_by_id before checking whether the current user can access
it, so add an authorization check using UserCanvasService.accessible(canvas_id,
tenant_id) before any canvas data is read or used. Update the logic in
set_session to reject unauthorized requests early, then proceed with the
existing Canvas and API4ConversationService flow only after access is confirmed;
keep the Canvas(..., canvas_id=cvs.id) call consistent with the intended canvas
identifier usage.
In `@api/db/services/canvas_service.py`:
- Around line 360-371: `completion()` currently calls `canvas.close()` directly
in the async `finally` block, which can block the event loop while MCP sessions
shut down. Update the cleanup in `canvas_service.py` so the `finally` path
offloads `canvas.close()` to a background thread or equivalent non-blocking
executor, preserving the existing `canvas.run` streaming flow and `session_id`
handling while avoiding synchronous shutdown work on the event loop.
In `@api/utils/api_utils.py`:
- Around line 664-666: The cleanup in get_mcp_tools() is unguarded, so an
exception from close_multiple_mcp_toolcall_sessions() can override the intended
(dict, str) return path. Wrap the finally-time
close_multiple_mcp_toolcall_sessions(tool_call_sessions) call in its own
try/except inside get_mcp_tools(), and log any failure with the module’s logger
instead of letting teardown escape. Keep the return contract intact and preserve
the existing tool_call_sessions cleanup behavior.
---
Nitpick comments:
In `@api/apps/canvas_app.py`:
- Around line 160-238: The new completion streaming flow in run() lacks
consistent operational logging for key lifecycle events and failures. Add
structured logs around CanvasReplicaService.load_for_run, the Canvas creation
and canvas.run streaming loop, the commit_after_run result, and the
exception/cancel/close path so successes and failures are traceable. Use the
existing run, sse, CanvasReplicaService, and Canvas methods as anchors, and
follow the same logging style used elsewhere in the module for DB/session
mutation flows.
🪄 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: 482965bc-85f6-4b1a-b28e-3f7d0beba830
📒 Files selected for processing (4)
agent/canvas.pyapi/apps/canvas_app.pyapi/db/services/canvas_service.pyapi/utils/api_utils.py
| def close(self): | ||
| from common.mcp_tool_call_conn import MCPToolCallSession | ||
| seen = set() | ||
| for cpn in self.components.values(): | ||
| obj = cpn.get("obj") | ||
| if obj and hasattr(obj, "tools"): | ||
| for tool in obj.tools.values(): | ||
| if isinstance(tool, MCPToolCallSession) and id(tool) not in seen: | ||
| seen.add(id(tool)) | ||
| try: | ||
| tool.close_sync(timeout=3) | ||
| except Exception: | ||
| pass |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Graph.close() still leaks the graph-owned thread pool.
Line 95 allocates a per-graph ThreadPoolExecutor, but this new teardown path never shuts it down. That means short-lived canvases can still accumulate worker threads even after MCP sessions are closed.
Suggested fix
def close(self):
from common.mcp_tool_call_conn import MCPToolCallSession
seen = set()
for cpn in self.components.values():
obj = cpn.get("obj")
if obj and hasattr(obj, "tools"):
for tool in obj.tools.values():
if isinstance(tool, MCPToolCallSession) and id(tool) not in seen:
seen.add(id(tool))
try:
tool.close_sync(timeout=3)
except Exception:
- pass
+ logging.exception("Failed to close MCP tool session")
+ self._thread_pool.shutdown(wait=False, cancel_futures=True)📝 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.
| def close(self): | |
| from common.mcp_tool_call_conn import MCPToolCallSession | |
| seen = set() | |
| for cpn in self.components.values(): | |
| obj = cpn.get("obj") | |
| if obj and hasattr(obj, "tools"): | |
| for tool in obj.tools.values(): | |
| if isinstance(tool, MCPToolCallSession) and id(tool) not in seen: | |
| seen.add(id(tool)) | |
| try: | |
| tool.close_sync(timeout=3) | |
| except Exception: | |
| pass | |
| def close(self): | |
| from common.mcp_tool_call_conn import MCPToolCallSession | |
| seen = set() | |
| for cpn in self.components.values(): | |
| obj = cpn.get("obj") | |
| if obj and hasattr(obj, "tools"): | |
| for tool in obj.tools.values(): | |
| if isinstance(tool, MCPToolCallSession) and id(tool) not in seen: | |
| seen.add(id(tool)) | |
| try: | |
| tool.close_sync(timeout=3) | |
| except Exception: | |
| logging.exception("Failed to close MCP tool session") | |
| self._thread_pool.shutdown(wait=False, cancel_futures=True) |
🤖 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 `@agent/canvas.py` around lines 146 - 158, The teardown in Graph.close
currently closes MCPToolCallSession instances but leaves the graph-owned
ThreadPoolExecutor alive, so add executor shutdown to the same cleanup path
after the tool/session loop. Locate the Graph.close method and ensure the
per-graph executor created by the Graph class is explicitly shut down during
close, with any necessary guard so repeated close calls remain safe.
| try: | ||
| tool.close_sync(timeout=3) | ||
| except Exception: | ||
| pass |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Don't swallow cleanup failures silently.
If close_sync() fails here, the MCP connection leak remains but there is no signal to debug it. At minimum, log the exception in this new cleanup flow. 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 `@agent/canvas.py` around lines 155 - 158, The cleanup path in the
`close_sync()` call is swallowing exceptions silently, so update the new cleanup
flow in `Canvas` to log any failure instead of using a bare `except Exception:
pass`. Use the existing cleanup logic around `tool.close_sync(timeout=3)` to
catch the exception, emit an error-level log with the exception details, and
keep the rest of the shutdown path intact so MCP connection leaks can be
diagnosed.
Source: Coding guidelines
| from api.db.services.canvas_service import completion as agent_completion | ||
|
|
||
|
|
||
| @manager.route('/templates', methods=['GET']) # noqa: F821 |
There was a problem hiding this comment.
🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win
Define or import manager before registering routes.
manager is referenced by decorators throughout this new module but is never defined in the file, so importing api/apps/canvas_app.py will fail at route registration time.
🤖 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/canvas_app.py` at line 53, The route decorators in canvas_app are
using manager before it exists, causing import-time failures when the module is
loaded. Define or import the shared manager object in this module before any
`@manager.route` decorators, and make sure the existing route functions in
canvas_app register against that same manager instance.
| @manager.route('/getsse/<canvas_id>', methods=['GET']) # type: ignore # noqa: F821 | ||
| def getsse(canvas_id): | ||
| token = request.headers.get('Authorization').split() | ||
| if len(token) != 2: | ||
| return get_data_error_result(message='Authorization is not valid!') | ||
| token = token[1] | ||
| objs = APIToken.query(beta=token) | ||
| if not objs: | ||
| return get_data_error_result(message='Authentication error: API key is invalid!"') |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Handle missing or malformed Authorization headers.
request.headers.get('Authorization') can be None; unauthenticated requests currently crash before returning the intended auth error.
Proposed fix
- token = request.headers.get('Authorization').split()
- if len(token) != 2:
+ auth_header = request.headers.get("Authorization", "")
+ token = auth_header.split()
+ if len(token) != 2:
return get_data_error_result(message='Authorization is not valid!')📝 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.
| @manager.route('/getsse/<canvas_id>', methods=['GET']) # type: ignore # noqa: F821 | |
| def getsse(canvas_id): | |
| token = request.headers.get('Authorization').split() | |
| if len(token) != 2: | |
| return get_data_error_result(message='Authorization is not valid!') | |
| token = token[1] | |
| objs = APIToken.query(beta=token) | |
| if not objs: | |
| return get_data_error_result(message='Authentication error: API key is invalid!"') | |
| `@manager.route`('/getsse/<canvas_id>', methods=['GET']) # type: ignore # noqa: F821 | |
| def getsse(canvas_id): | |
| auth_header = request.headers.get("Authorization", "") | |
| token = auth_header.split() | |
| if len(token) != 2: | |
| return get_data_error_result(message='Authorization is not valid!') | |
| token = token[1] | |
| objs = APIToken.query(beta=token) | |
| if not objs: | |
| return get_data_error_result(message='Authentication error: API key is invalid!"') |
🤖 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/canvas_app.py` around lines 138 - 146, The getsse endpoint currently
assumes request.headers.get('Authorization') always exists, so missing or
malformed auth headers can crash before the intended error response. Update
getsse to validate the Authorization header before calling split(), and return
get_data_error_result with the existing auth error message when the header is
missing or not in the expected two-part format. Keep the fix localized to getsse
and preserve the APIToken.query(beta=token) flow for valid tokens.
| if canvas_category == CanvasCategory.DataFlow: | ||
| task_id = get_uuid() | ||
| Pipeline(dsl_str, tenant_id=tenant_id, doc_id=CANVAS_DEBUG_DOC_ID, task_id=task_id, flow_id=req["id"]) | ||
| ok, error_message = await thread_pool_exec(queue_dataflow, user_id, req["id"], task_id, CANVAS_DEBUG_DOC_ID, files[0], 0) | ||
| if not ok: | ||
| return get_data_error_result(message=error_message) | ||
| return get_json_result(data={"message_id": task_id}) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Validate files before indexing DataFlow input.
files defaults to an empty list, but Line 193 unconditionally uses files[0], so a valid /completion request for a DataFlow canvas can crash.
Proposed fix
if canvas_category == CanvasCategory.DataFlow:
+ if not files:
+ return get_data_error_result(message="files is required for DataFlow completion.")
task_id = get_uuid()📝 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.
| if canvas_category == CanvasCategory.DataFlow: | |
| task_id = get_uuid() | |
| Pipeline(dsl_str, tenant_id=tenant_id, doc_id=CANVAS_DEBUG_DOC_ID, task_id=task_id, flow_id=req["id"]) | |
| ok, error_message = await thread_pool_exec(queue_dataflow, user_id, req["id"], task_id, CANVAS_DEBUG_DOC_ID, files[0], 0) | |
| if not ok: | |
| return get_data_error_result(message=error_message) | |
| return get_json_result(data={"message_id": task_id}) | |
| if canvas_category == CanvasCategory.DataFlow: | |
| if not files: | |
| return get_data_error_result(message="files is required for DataFlow completion.") | |
| task_id = get_uuid() | |
| Pipeline(dsl_str, tenant_id=tenant_id, doc_id=CANVAS_DEBUG_DOC_ID, task_id=task_id, flow_id=req["id"]) | |
| ok, error_message = await thread_pool_exec(queue_dataflow, user_id, req["id"], task_id, CANVAS_DEBUG_DOC_ID, files[0], 0) | |
| if not ok: | |
| return get_data_error_result(message=error_message) | |
| return get_json_result(data={"message_id": task_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/canvas_app.py` around lines 190 - 196, The DataFlow branch in
canvas_app’s request handling indexes files[0] without verifying that files is
non-empty, which can crash a valid completion request. Add an explicit guard
before calling thread_pool_exec in the canvas_category ==
CanvasCategory.DataFlow path to return a get_data_error_result when files is
empty, and keep the existing Pipeline, queue_dataflow, and get_json_result flow
unchanged for the valid case.
| @manager.route('/<canvas_id>/sessions', methods=['PUT']) # noqa: F821 | ||
| @login_required | ||
| async def set_session(canvas_id): | ||
| req = await get_request_json() | ||
| tenant_id = current_user.id | ||
| e, cvs = UserCanvasService.get_by_id(canvas_id) | ||
| assert e, "Agent not found." | ||
| if not isinstance(cvs.dsl, str): | ||
| cvs.dsl = json.dumps(cvs.dsl, ensure_ascii=False) | ||
| session_id=get_uuid() | ||
| canvas = Canvas(cvs.dsl, tenant_id, canvas_id, canvas_id=cvs.id) | ||
| canvas.reset() | ||
| conv = { | ||
| "id": session_id, | ||
| "name": req.get("name", ""), | ||
| "dialog_id": cvs.id, | ||
| "user_id": tenant_id, | ||
| "exp_user_id": tenant_id, | ||
| "message": [], | ||
| "source": "agent", | ||
| "dsl": cvs.dsl, | ||
| "reference": [] | ||
| } | ||
| API4ConversationService.save(**conv) | ||
| return get_json_result(data=conv) |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== canvas_app slice ==\n'
sed -n '620,710p' api/apps/canvas_app.py
printf '\n== accessible usages ==\n'
rg -n "UserCanvasService\.accessible|accessible\(canvas_id" api -g '*.py'
printf '\n== Canvas constructor usages ==\n'
rg -n "Canvas\(" api -g '*.py'
printf '\n== Canvas class definition ==\n'
rg -n "class Canvas|def __init__" api -g '*.py'Repository: infiniflow/ragflow
Length of output: 11002
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== canvas_service slice around Canvas ==\n'
sed -n '1,220p' api/db/services/canvas_service.py
printf '\n== constructor signature and call sites around relevant lines ==\n'
sed -n '300,360p' api/db/services/canvas_service.py
sed -n '180,220p' api/apps/canvas_app.py
sed -n '430,470p' api/apps/restful_apis/agent_api.pyRepository: infiniflow/ragflow
Length of output: 14270
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== Canvas definition ==\n'
fd -a 'canvas.py' agent api | sed -n '1,20p'
rg -n "^class Canvas\b|^ def __init__\(" agent api -g 'canvas.py' -g '*.py'
printf '\n== get_by_id implementations ==\n'
rg -n "def get_by_id\b" api/db/services api -g '*.py'
printf '\n== get_by_id on UserCanvasService/CommonService ==\n'
sed -n '1,240p' api/db/services/common_service.py
sed -n '220,320p' api/db/services/canvas_service.pyRepository: infiniflow/ragflow
Length of output: 19850
Authorize this session route before loading the canvas. set_session skips UserCanvasService.accessible(canvas_id, tenant_id), so any logged-in user who knows a canvas id can read its DSL and create a session for it. The Canvas(..., canvas_id=cvs.id) call is consistent with other call sites; the third positional argument is task_id.
🧰 Tools
🪛 ast-grep (0.44.0)
[info] 660-660: use jsonify instead of json.dumps for JSON output
Context: json.dumps(cvs.dsl, 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/canvas_app.py` around lines 653 - 677, The set_session route
currently loads the canvas with UserCanvasService.get_by_id before checking
whether the current user can access it, so add an authorization check using
UserCanvasService.accessible(canvas_id, tenant_id) before any canvas data is
read or used. Update the logic in set_session to reject unauthorized requests
early, then proceed with the existing Canvas and API4ConversationService flow
only after access is confirmed; keep the Canvas(..., canvas_id=cvs.id) call
consistent with the intended canvas identifier usage.
| _, conv = API4ConversationService.get_by_id(session_id) | ||
| return get_json_result(data=conv.to_dict()) | ||
|
|
||
|
|
||
| @manager.route('/<canvas_id>/sessions/<session_id>', methods=['DELETE']) # noqa: F821 | ||
| @login_required | ||
| def del_session(canvas_id, session_id): | ||
| tenant_id = current_user.id | ||
| if not UserCanvasService.accessible(canvas_id, tenant_id): | ||
| return get_json_result( | ||
| data=False, message='Only owner of canvas authorized for this operation.', | ||
| code=RetCode.OPERATING_ERROR) | ||
| return get_json_result(data=API4ConversationService.delete_by_id(session_id)) |
There was a problem hiding this comment.
🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win
Scope session reads/deletes to the requested canvas.
After checking canvas access, also verify the fetched session belongs to canvas_id before returning or deleting it; otherwise session_id is an IDOR.
🤖 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/canvas_app.py` around lines 688 - 700, The session read/delete
handlers in canvas_app.py only check canvas ownership and then operate on
API4ConversationService by session_id, which leaves an IDOR gap. In both the
session fetch flow and del_session, use the existing canvas_id and session_id to
verify the loaded conversation belongs to the requested canvas before calling
conv.to_dict() or API4ConversationService.delete_by_id. Update the relevant
logic around API4ConversationService.get_by_id, del_session, and
UserCanvasService.accessible so the session is scoped to the canvas and rejected
if it does not match.
| @manager.route('/download', methods=['GET']) # noqa: F821 | ||
| async def download(): | ||
| id = request.args.get("id") | ||
| created_by = request.args.get("created_by") | ||
| blob = FileService.get_blob(created_by, id) | ||
| return await make_response(blob) |
There was a problem hiding this comment.
🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win
Authorize downloads instead of trusting query parameters.
/download is unauthenticated and trusts caller-supplied created_by, allowing arbitrary blob fetch attempts by 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/canvas_app.py` around lines 718 - 723, The download endpoint
currently trusts caller-supplied query parameters, so update the download()
route to authorize access before calling FileService.get_blob. Use the
authenticated user/context instead of the request.args values for created_by,
and validate that the requested blob id belongs to that user or is otherwise
permitted. Keep the fix localized around download() and FileService.get_blob so
unauthorized blob fetch attempts are blocked.
| try: | ||
| async for ans in canvas.run(**run_kwargs): | ||
| ans["session_id"] = session_id | ||
| if ans["event"] == "message": | ||
| txt += ans["data"]["content"] | ||
| if ans["data"].get("start_to_think", False): | ||
| txt += "<think>" | ||
| elif ans["data"].get("end_to_think", False): | ||
| txt += "</think>" | ||
| yield "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n" | ||
| finally: | ||
| canvas.close() |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Offload canvas.close() from the event loop.
completion() is async, but canvas.close() now runs synchronously and ultimately calls close_sync(timeout=3) per MCP session. On canvases with multiple sessions, this finally block can block the event loop for seconds and stall unrelated requests.
Suggested fix
try:
async for ans in canvas.run(**run_kwargs):
ans["session_id"] = session_id
if ans["event"] == "message":
txt += ans["data"]["content"]
if ans["data"].get("start_to_think", False):
txt += "<think>"
elif ans["data"].get("end_to_think", False):
txt += "</think>"
yield "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n"
finally:
- canvas.close()
+ await thread_pool_exec(canvas.close)📝 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.
| try: | |
| async for ans in canvas.run(**run_kwargs): | |
| ans["session_id"] = session_id | |
| if ans["event"] == "message": | |
| txt += ans["data"]["content"] | |
| if ans["data"].get("start_to_think", False): | |
| txt += "<think>" | |
| elif ans["data"].get("end_to_think", False): | |
| txt += "</think>" | |
| yield "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n" | |
| finally: | |
| canvas.close() | |
| try: | |
| async for ans in canvas.run(**run_kwargs): | |
| ans["session_id"] = session_id | |
| if ans["event"] == "message": | |
| txt += ans["data"]["content"] | |
| if ans["data"].get("start_to_think", False): | |
| txt += "<think>" | |
| elif ans["data"].get("end_to_think", False): | |
| txt += "</think>" | |
| yield "data:" + json.dumps(ans, ensure_ascii=False) + "\n\n" | |
| finally: | |
| await thread_pool_exec(canvas.close) |
🧰 Tools
🪛 ast-grep (0.44.0)
[info] 368-368: use jsonify instead of json.dumps for JSON output
Context: json.dumps(ans, 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/db/services/canvas_service.py` around lines 360 - 371, `completion()`
currently calls `canvas.close()` directly in the async `finally` block, which
can block the event loop while MCP sessions shut down. Update the cleanup in
`canvas_service.py` so the `finally` path offloads `canvas.close()` to a
background thread or equivalent non-blocking executor, preserving the existing
`canvas.run` streaming flow and `session_id` handling while avoiding synchronous
shutdown work on the event loop.
| finally: | ||
| # PERF: blocking call to close sessions — consider moving to background thread or task queue | ||
| close_multiple_mcp_toolcall_sessions(tool_call_sessions) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Guard cleanup inside finally or it will break the return contract.
If close_multiple_mcp_toolcall_sessions() raises here, it overrides both return paths above and get_mcp_tools() no longer returns the declared (dict, str) tuple. Wrap the close in its own try/except and log failures instead of letting teardown escape. As per coding guidelines, **/*.py: Add logging for new flows.
Suggested fix
except Exception as e:
return {}, str(e)
finally:
- # PERF: blocking call to close sessions — consider moving to background thread or task queue
- close_multiple_mcp_toolcall_sessions(tool_call_sessions)
+ try:
+ close_multiple_mcp_toolcall_sessions(tool_call_sessions)
+ except Exception:
+ logging.exception("Failed to close MCP tool call sessions")📝 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.
| finally: | |
| # PERF: blocking call to close sessions — consider moving to background thread or task queue | |
| close_multiple_mcp_toolcall_sessions(tool_call_sessions) | |
| finally: | |
| try: | |
| close_multiple_mcp_toolcall_sessions(tool_call_sessions) | |
| except Exception: | |
| logging.exception("Failed to close MCP tool call sessions") |
🤖 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/utils/api_utils.py` around lines 664 - 666, The cleanup in
get_mcp_tools() is unguarded, so an exception from
close_multiple_mcp_toolcall_sessions() can override the intended (dict, str)
return path. Wrap the finally-time
close_multiple_mcp_toolcall_sessions(tool_call_sessions) call in its own
try/except inside get_mcp_tools(), and log any failure with the module’s logger
instead of letting teardown escape. Keep the return contract intact and preserve
the existing tool_call_sessions cleanup behavior.
Source: Coding guidelines
2540f8a to
06211dd
Compare
…leaks (infiniflow#13295) ### What problem does this PR solve? Closes infiniflow#12962 MCPToolCallSessions created during agent execution (in `Agent.__init__`) are never explicitly closed. Each session starts its own event loop thread and opens an SSE/HTTP connection to the MCP server. When the canvas goes out of scope, these threads and connections remain alive indefinitely, accumulating over time and causing resource exhaustion after prolonged use. ### Solution 1. Add a `Graph.close()` method that iterates all components, finds MCPToolCallSessions held by Agent tools, and calls `close_sync()` on each to properly shut down the event loop, thread, and connection. 2. Call `canvas.close()` in `finally` blocks after `canvas.run()` completes in `canvas_service.py` and `canvas_app.py`. 3. Move MCP session cleanup to `finally` blocks in `test_tool` endpoint (`mcp_server_app.py`) and `get_mcp_tools` (`api_utils.py`) to ensure sessions are closed even on exceptions. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) --------- Co-authored-by: conflict-resolver <conflict-resolver@local> Co-authored-by: Zhichang Yu <[email protected]>
### Summary Port the following PRs to GO in this PR infiniflow#16420 infiniflow#13295
…leaks (infiniflow#13295) ### What problem does this PR solve? Closes infiniflow#12962 MCPToolCallSessions created during agent execution (in `Agent.__init__`) are never explicitly closed. Each session starts its own event loop thread and opens an SSE/HTTP connection to the MCP server. When the canvas goes out of scope, these threads and connections remain alive indefinitely, accumulating over time and causing resource exhaustion after prolonged use. ### Solution 1. Add a `Graph.close()` method that iterates all components, finds MCPToolCallSessions held by Agent tools, and calls `close_sync()` on each to properly shut down the event loop, thread, and connection. 2. Call `canvas.close()` in `finally` blocks after `canvas.run()` completes in `canvas_service.py` and `canvas_app.py`. 3. Move MCP session cleanup to `finally` blocks in `test_tool` endpoint (`mcp_server_app.py`) and `get_mcp_tools` (`api_utils.py`) to ensure sessions are closed even on exceptions. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) --------- Co-authored-by: conflict-resolver <conflict-resolver@local> Co-authored-by: Zhichang Yu <[email protected]>
### Summary Port the following PRs to GO in this PR infiniflow#16420 infiniflow#13295
What problem does this PR solve?
Closes #12962
MCPToolCallSessions created during agent execution (in
Agent.__init__) are never explicitly closed. Each session starts its own event loop thread and opens an SSE/HTTP connection to the MCP server. When the canvas goes out of scope, these threads and connections remain alive indefinitely, accumulating over time and causing resource exhaustion after prolonged use.Solution
Graph.close()method that iterates all components, finds MCPToolCallSessions held by Agent tools, and callsclose_sync()on each to properly shut down the event loop, thread, and connection.canvas.close()infinallyblocks aftercanvas.run()completes incanvas_service.pyandcanvas_app.py.finallyblocks intest_toolendpoint (mcp_server_app.py) andget_mcp_tools(api_utils.py) to ensure sessions are closed even on exceptions.Type of change