Skip to content

fix: handle non-serializable objects in agent canvas SSE and state se… - #14210

Merged
yuzhichang merged 3 commits into
infiniflow:mainfrom
RazmikGevorgyan:fix/agent-canvas-serialization
Jul 1, 2026
Merged

yuzhichang merged 3 commits into
infiniflow:mainfrom
RazmikGevorgyan:fix/agent-canvas-serialization

Conversation

@RazmikGevorgyan

@RazmikGevorgyan RazmikGevorgyan commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor

…rialization

Agent components (llm.py, agent_with_tools.py, message.py) store functools.partial objects as deferred streaming handles in their output slots. When the canvas state gets serialized for SSE events, Redis commits, or logging, these partials — plus non-copyable objects like Langfuse clients — crash json.dumps and deepcopy.

Changes:

  • canvas_app.py: add default=str to json.dumps for SSE event serialization (lines 238, 296)
  • canvas.py: wrap deepcopy calls in try/except to handle non-copyable objects (Langfuse clients, etc.), add default=str to final json.dumps
  • base.py: add default=str to ComponentParamBase.str to handle non-serializable objects in component parameters

Closes #14229

What problem does this PR solve?

Briefly describe what this PR aims to solve. Include background context that will help reviewers understand the purpose of the PR.

Type of change

  • 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):

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Apr 18, 2026
@coderabbitai

coderabbitai Bot commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds exception-safe deepcopy fallbacks in Graph.__str__ and introduces custom json.dumps default callbacks in three locations (agent/canvas.py, agent/component/base.py, api/apps/restful_apis/agent_api.py) to prevent serialization failures when agent components contain non-serializable callables such as functools.partial.

Changes

JSON Serialization Fallbacks

Layer / File(s) Summary
Canvas deepcopy guards and JSON default
agent/canvas.py
Graph.__str__ wraps per-key and per-component-field deepcopy calls in try/except, logging warnings and using original references on failure. Adds a custom json.dumps default that returns None for callables and str(obj) for other unsupported types.
ComponentParamBase JSON default
agent/component/base.py
ComponentParamBase.__str__ adds the same callable/fallback default pattern to its json.dumps call.
SSE API JSON default
api/apps/restful_apis/agent_api.py
Introduces module-level _canvas_json_default and applies it to json.dumps in both SSE streaming generators.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 A deepcopy stumbled, a callable hid,
But the rabbit patched up what the error forbid.
With default= in hand and a warning to log,
No JSON shall crash in the SSE fog.
Hop on, dear stream — no more stuck in the bog! 🌿

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The changes fix serialization failures, but the linked issue requires making /api/v1/chats more RESTful. Refactor the chat/search API endpoints and request/response shapes to match the RESTful requirements in #14229.
Out of Scope Changes check ⚠️ Warning The serialization fixes in canvas, base, and SSE streaming are unrelated to the RESTful API refactor requested in #14229. Remove or split the unrelated serialization changes into a separate PR focused on the RESTful chat/search API work.
Docstring Coverage ⚠️ Warning Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: handling non-serializable objects during agent canvas serialization.
Description check ✅ Passed The PR description includes a summary, problem context, changed files, linked issue, and change type.

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.

@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: 2

🧹 Nitpick comments (1)
agent/canvas.py (1)

138-138: Prefer deterministic fallback values over raw str(obj) in persisted canvas snapshots.

At Line 138, default=str may store unstable repr strings (e.g., memory-address-bearing object representations) into committed DSL state. Consider a controlled serializer (e.g., None or typed placeholder) for unsupported runtime-only objects.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@agent/canvas.py` at line 138, Replace the unstable default=str fallback used
in the json.dumps call (json.dumps(dsl, ensure_ascii=False, default=str)) with a
deterministic serializer function that returns controlled placeholders for
unsupported runtime-only objects (for example None or a dict like {"__type__":
type(obj).__name__} or {"__placeholder__": "<type>"}); implement a small helper
(e.g., fallback_serializer(obj)) and pass it as default=fallback_serializer so
persisted canvas snapshots never contain unpredictable reprs from objects in
dsl.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@agent/canvas.py`:
- Around line 122-125: Add logging inside the deepcopy fallback branches so
failures are not silently swallowed: before assigning the original reference in
the except blocks, call the module/class logger (e.g., logger.exception or
logger.warning) to record the key k, a representation and type of self.dsl[k]
(e.g., repr(self.dsl[k]) and type(self.dsl[k]).__name__) and the caught
exception; apply the same change to both occurrences around the deepcopy of
self.dsl[k] (the try/except that assigns dsl[k]) so the component/key/type and
stacktrace are logged prior to falling back to the original reference.

In `@api/apps/canvas_app.py`:
- Line 238: The SSE payload currently uses json.dumps(..., default=str) which
coerces arbitrary objects to opaque strings and breaks client expectations;
replace that by ensuring the emitted ans is JSON-serializable without
default=str: implement a sanitizer/encoder (e.g., sanitize_for_json or
_sse_json_default) and use it when producing the SSE payload where yield "data:"
+ json.dumps(ans, ensure_ascii=False, ...) is called (the generator that yields
SSE lines in canvas_app.py); the sanitizer should recursively convert known
non-serializable types to safe representations (e.g., datetimes -> ISO strings,
UUIDs -> str, bytes -> base64) and raise or omit unsupported types so callers
can notice errors, then call json.dumps(ans_sanitized, ensure_ascii=False) (or
json.dumps(ans, default=_sse_json_default) if your default only handles specific
types and raises TypeError for others) instead of using default=str.

---

Nitpick comments:
In `@agent/canvas.py`:
- Line 138: Replace the unstable default=str fallback used in the json.dumps
call (json.dumps(dsl, ensure_ascii=False, default=str)) with a deterministic
serializer function that returns controlled placeholders for unsupported
runtime-only objects (for example None or a dict like {"__type__":
type(obj).__name__} or {"__placeholder__": "<type>"}); implement a small helper
(e.g., fallback_serializer(obj)) and pass it as default=fallback_serializer so
persisted canvas snapshots never contain unpredictable reprs from objects in
dsl.
🪄 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: 569bf9e2-debd-4366-bfb0-a50f06de42db

📥 Commits

Reviewing files that changed from the base of the PR and between 6712b50 and 907efe0.

📒 Files selected for processing (3)
  • agent/canvas.py
  • agent/component/base.py
  • api/apps/canvas_app.py

Comment thread agent/canvas.py Resolved
Comment thread api/apps/canvas_app.py Resolved
@RazmikGevorgyan
RazmikGevorgyan force-pushed the fix/agent-canvas-serialization branch from 907efe0 to 8faee2d Compare April 18, 2026 10:40
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Apr 18, 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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@agent/canvas.py`:
- Around line 140-144: The current _serialize_default used in Graph.__str__
raises TypeError for non-callable non-JSON-serializable objects, which still
lets json.dumps crash; change _serialize_default (the function used as the
default= handler in the json.dumps(...) call) to return a safe string
representation (e.g., str(obj) or repr(obj)) instead of raising, while still
returning None for callables if you want them as null; this ensures json.dumps
will not raise and Graph.__str__ will always produce a serializable output.

In `@api/apps/canvas_app.py`:
- Around line 24-35: Update _canvas_json_default to log a warning before
returning None for callables: import or obtain a module logger (e.g.
logging.getLogger(__name__)) and call logger.warning with context including the
object's type and a short repr (e.g. f"Coercing callable to None in canvas SSE
payload: type=%s repr=%s", type(obj).__name__, repr(obj)) right before the
"return None" line in _canvas_json_default so that callable-to-None coercions
are recorded without changing behavior for non-callables.
🪄 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: 94bcec32-4ce8-4f14-90da-23ff8bd92d8e

📥 Commits

Reviewing files that changed from the base of the PR and between 907efe0 and 8faee2d.

📒 Files selected for processing (3)
  • agent/canvas.py
  • agent/component/base.py
  • api/apps/canvas_app.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • agent/component/base.py

Comment thread agent/canvas.py Resolved
Comment thread api/apps/canvas_app.py Resolved
…rialization

Agent components (llm.py, agent_with_tools.py, message.py) store
functools.partial objects as deferred streaming handles in their
output slots. When the canvas state gets serialized for SSE events,
Redis commits, or logging, these partials — plus non-copyable objects
like Langfuse clients — crash json.dumps and deepcopy.

Reproduced with Azure OpenAI (gpt-5.4-nano via LiteLLM) and Langfuse
tracing enabled on agent workflows.

Changes:
- canvas_app.py: add _canvas_json_default() that converts callables
  to None (not str) to preserve client JSON contracts, re-raises for
  all other non-serializable types
- canvas.py: wrap deepcopy calls in try/except with logging.warning
  so failures are diagnosable, add callable→None serializer for
  final json.dumps
- base.py: add callable→None serializer to ComponentParamBase.__str__

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@RazmikGevorgyan
RazmikGevorgyan force-pushed the fix/agent-canvas-serialization branch from 8faee2d to 734efd5 Compare April 18, 2026 12:25
@KevinHuSh

Copy link
Copy Markdown
Contributor

Appreciations!
Could you resolve the conflicts?

@KevinHuSh KevinHuSh added ci Continue Integration and removed ci Continue Integration labels May 22, 2026
@yuzhichang
yuzhichang self-requested a review June 28, 2026 00:49
@yuzhichang

yuzhichang commented Jun 28, 2026 •

Copy link
Copy Markdown
Member

This PR currently has merge conflicts with main and cannot be auto-synced.

Please run locally:

git fetch origin main
git rebase origin/main
# or
git merge origin/main

After resolving the conflicts, push to the current head branch and CI will re-run the review checks.

Triggered by reviewer yuzhichang (request-for-action)

@yuzhichang yuzhichang added the ci Continue Integration label Jun 30, 2026
yuzhichang added a commit to RazmikGevorgyan/ragflow that referenced this pull request Jun 30, 2026
…as SSE and state serialization

Conflict resolution notes:
- agent/canvas.py, agent/component/base.py: auto-merged cleanly
- api/apps/canvas_app.py: deleted in main by PR infiniflow#14393 (Add task API);
  PR 14210's _canvas_json_default helper and its two usages have been
  ported to api/apps/restful_apis/agent_api.py (lines 75-86 helper, 303
  and 1517 apply it to the canvas session/agent chat SSE yields).

Closes infiniflow#14229

@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: 2

🤖 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 293-300: Guard the remaining deepcopy paths in agent_api so
non-copyable objects don’t fail before serialization: in the response assembly
logic around the structured output and trace handling, wrap the deepcopy calls
in the same exception-safe fallback used in the canvas layer. Update the
relevant blocks in the code that builds structured_output and trace_items, plus
the other listed deepcopy sites in the API module, so they preserve the original
object or a safe fallback when copy fails instead of aborting stream/non-stream
responses.
- Around line 74-85: The canvas SSE fallback in _canvas_json_default only
handles callable values, so non-serializable objects like client instances can
still bubble up and break JSON encoding. Update this helper to act as a broader
API-layer sanitization point: detect and replace any unsupported value types
with None instead of raising, while still preserving native JSON-safe primitives
unchanged. Keep the change localized in _canvas_json_default so downstream SSE
event serialization remains consistent across agent component propagation.
🪄 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: 71e234f6-6d84-47f3-a336-d633a5b8fa8d

📥 Commits

Reviewing files that changed from the base of the PR and between 734efd5 and 2fd24ca.

📒 Files selected for processing (3)
  • agent/canvas.py
  • agent/component/base.py
  • api/apps/restful_apis/agent_api.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • agent/component/base.py
  • agent/canvas.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

🤖 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 293-300: Guard the remaining deepcopy paths in agent_api so
non-copyable objects don’t fail before serialization: in the response assembly
logic around the structured output and trace handling, wrap the deepcopy calls
in the same exception-safe fallback used in the canvas layer. Update the
relevant blocks in the code that builds structured_output and trace_items, plus
the other listed deepcopy sites in the API module, so they preserve the original
object or a safe fallback when copy fails instead of aborting stream/non-stream
responses.
- Around line 74-85: The canvas SSE fallback in _canvas_json_default only
handles callable values, so non-serializable objects like client instances can
still bubble up and break JSON encoding. Update this helper to act as a broader
API-layer sanitization point: detect and replace any unsupported value types
with None instead of raising, while still preserving native JSON-safe primitives
unchanged. Keep the change localized in _canvas_json_default so downstream SSE
event serialization remains consistent across agent component propagation.
🪄 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: 71e234f6-6d84-47f3-a336-d633a5b8fa8d

📥 Commits

Reviewing files that changed from the base of the PR and between 734efd5 and 2fd24ca.

📒 Files selected for processing (3)
  • agent/canvas.py
  • agent/component/base.py
  • api/apps/restful_apis/agent_api.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • agent/component/base.py
  • agent/canvas.py
🛑 Comments failed to post (2)
api/apps/restful_apis/agent_api.py (2)

74-85: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Broaden the fallback beyond callables.

This helper still raises for any non-callable object, so the SSE stream can still fail on the other non-serializable values called out in the PR (for example client objects). That means the new API-layer fallback does not actually match the intended cross-layer contract.

Suggested fix
 def _canvas_json_default(obj):
     """Fallback serializer for canvas SSE events.
@@
     """
     if callable(obj):
         return None
-    raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
+    return str(obj)
📝 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 _canvas_json_default(obj):
    """Fallback serializer for canvas SSE events.

    Agent components store functools.partial objects as deferred streaming
    handles (see llm.py, agent_with_tools.py, message.py). These leak into
    SSE event dicts via component input/output propagation and are not
    JSON-serializable. This handler converts them to None so that downstream
    consumers never receive opaque ``str(partial(...))`` representations.
    """
    if callable(obj):
        return None
    return str(obj)
🤖 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 74 - 85, The canvas SSE
fallback in _canvas_json_default only handles callable values, so
non-serializable objects like client instances can still bubble up and break
JSON encoding. Update this helper to act as a broader API-layer sanitization
point: detect and replace any unsupported value types with None instead of
raising, while still preserving native JSON-safe primitives unchanged. Keep the
change localized in _canvas_json_default so downstream SSE event serialization
remains consistent across agent component propagation.

293-300: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard these deepcopy calls too.

These blocks can still throw before json.dumps(..., default=_canvas_json_default) runs, so a functools.partial or other non-copyable object in structured/data still aborts the stream or non-stream response. The companion canvas-layer change already added exception-safe deepcopy; this API layer needs the same treatment or the serialization fix is incomplete.

Suggested fix
+def _safe_deepcopy(value):
+    try:
+        return copy.deepcopy(value)
+    except Exception:
+        logging.warning("Falling back to shallow value during agent event serialization", exc_info=True)
+        return value
+
@@
-                            structured_output[component_id] = copy.deepcopy(node_out["structured"])
+                            structured_output[component_id] = _safe_deepcopy(node_out["structured"])
@@
-                                    "trace": [copy.deepcopy(data)],
+                                    "trace": [_safe_deepcopy(data)],
@@
-                    structured_output[component_id] = copy.deepcopy(node_out["structured"])
+                    structured_output[component_id] = _safe_deepcopy(node_out["structured"])
@@
-                            "trace": [copy.deepcopy(data)],
+                            "trace": [_safe_deepcopy(data)],

Also applies to: 341-348, 553-559, 1537-1544

🤖 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 293 - 300, Guard the
remaining deepcopy paths in agent_api so non-copyable objects don’t fail before
serialization: in the response assembly logic around the structured output and
trace handling, wrap the deepcopy calls in the same exception-safe fallback used
in the canvas layer. Update the relevant blocks in the code that builds
structured_output and trace_items, plus the other listed deepcopy sites in the
API module, so they preserve the original object or a safe fallback when copy
fails instead of aborting stream/non-stream responses.

Source: Coding guidelines

…as SSE and state serialization

Conflict resolution notes:
- agent/canvas.py, agent/component/base.py: auto-merged cleanly
- api/apps/canvas_app.py: deleted in main by PR infiniflow#14393 (Add task API);
  PR 14210's _canvas_json_default helper and its two usages have been
  ported to api/apps/restful_apis/agent_api.py (helper at L75, applied
  to the canvas session SSE yield at L326 and the agent chat completion
  SSE yield at L1588).

Closes infiniflow#14229
@yuzhichang
yuzhichang force-pushed the fix/agent-canvas-serialization branch from 2fd24ca to fd49ca8 Compare June 30, 2026 09:41

@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: 4

🤖 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 456-460: The debug logging in Canvas workflow execution is leaking
raw payload data, so update the logging in canvas.py (including the workflow
start path and the later input/output/kwargs debug statements) to avoid
serializing values directly. Replace the verbatim json.dumps/default=str logging
with redacted summaries that only include shapes, keys, counts, or types, and
explicitly scrub sensitive fields before logging in the relevant Canvas methods.
- Around line 449-452: Task cancellation is being turned into a generic 500
because TaskCanceledException has an empty string representation when it reaches
the generic exception handling in agent_api. Fix this by updating
TaskCanceledException in common/exceptions.py to initialize the base Exception
with the message via super().__init__(msg), and verify the raise sites in
agent/canvas.py (including the is_canceled() path) still pass the intended
message so cancellation is surfaced correctly instead of as an empty server
error.

In `@agent/component/base.py`:
- Around line 492-512: The debug logging in Base.resolve-style input handling is
leaking resolved values, including refs and literal payloads. Update the logging
in the input-resolution loop to avoid serializing actual resolved data from
get_variable_value, get_input_elements_from_text, and set_input_value; instead
log only the variable name plus safe metadata like type, length, or count. Add
redaction for sensitive namespaces such as env.* before any debug output in the
Component input resolution path.

In `@api/apps/restful_apis/agent_api.py`:
- Around line 74-85: The _canvas_json_default fallback in agent_api.py only
handles callable objects, so non-serializable values in node_finished payloads
can still raise TypeError and break SSE at the json.dumps call sites. Update
_canvas_json_default to safely neutralize any unsupported object type used in
canvas event dicts, not just callables, so json.dumps(...,
default=_canvas_json_default) can serialize all streamed component
inputs/outputs without tearing down the stream.
🪄 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: 87698f65-0f6e-481e-abc2-f5e986ce1208

📥 Commits

Reviewing files that changed from the base of the PR and between 2fd24ca and fd49ca8.

📒 Files selected for processing (3)
  • agent/canvas.py
  • agent/component/base.py
  • api/apps/restful_apis/agent_api.py

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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: 4

🤖 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 456-460: The debug logging in Canvas workflow execution is leaking
raw payload data, so update the logging in canvas.py (including the workflow
start path and the later input/output/kwargs debug statements) to avoid
serializing values directly. Replace the verbatim json.dumps/default=str logging
with redacted summaries that only include shapes, keys, counts, or types, and
explicitly scrub sensitive fields before logging in the relevant Canvas methods.
- Around line 449-452: Task cancellation is being turned into a generic 500
because TaskCanceledException has an empty string representation when it reaches
the generic exception handling in agent_api. Fix this by updating
TaskCanceledException in common/exceptions.py to initialize the base Exception
with the message via super().__init__(msg), and verify the raise sites in
agent/canvas.py (including the is_canceled() path) still pass the intended
message so cancellation is surfaced correctly instead of as an empty server
error.

In `@agent/component/base.py`:
- Around line 492-512: The debug logging in Base.resolve-style input handling is
leaking resolved values, including refs and literal payloads. Update the logging
in the input-resolution loop to avoid serializing actual resolved data from
get_variable_value, get_input_elements_from_text, and set_input_value; instead
log only the variable name plus safe metadata like type, length, or count. Add
redaction for sensitive namespaces such as env.* before any debug output in the
Component input resolution path.

In `@api/apps/restful_apis/agent_api.py`:
- Around line 74-85: The _canvas_json_default fallback in agent_api.py only
handles callable objects, so non-serializable values in node_finished payloads
can still raise TypeError and break SSE at the json.dumps call sites. Update
_canvas_json_default to safely neutralize any unsupported object type used in
canvas event dicts, not just callables, so json.dumps(...,
default=_canvas_json_default) can serialize all streamed component
inputs/outputs without tearing down the stream.
🪄 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: 87698f65-0f6e-481e-abc2-f5e986ce1208

📥 Commits

Reviewing files that changed from the base of the PR and between 2fd24ca and fd49ca8.

📒 Files selected for processing (3)
  • agent/canvas.py
  • agent/component/base.py
  • api/apps/restful_apis/agent_api.py
🛑 Comments failed to post (4)
agent/canvas.py (2)

449-452: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Cancellation currently degrades into an empty 500 response.

This raise path goes through the generic except Exception as exc handlers in api/apps/restful_apis/agent_api.py, but TaskCanceledException does not initialize the base Exception, so str(exc) is empty there. Canceling before start or during batch execution therefore surfaces as a generic server error instead of a clean canceled workflow response. Either initialize the exception with super().__init__(msg) in common/exceptions.py or avoid routing cancellation through the generic exception path here.

🤖 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 449 - 452, Task cancellation is being turned
into a generic 500 because TaskCanceledException has an empty string
representation when it reaches the generic exception handling in agent_api. Fix
this by updating TaskCanceledException in common/exceptions.py to initialize the
base Exception with the message via super().__init__(msg), and verify the raise
sites in agent/canvas.py (including the is_canceled() path) still pass the
intended message so cancellation is surfaced correctly instead of as an empty
server error.

456-460: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

These debug logs expose raw workflow payloads.

The new logs serialize inputs, component call kwargs, and outputs verbatim. Those objects can contain prompts, uploaded file contents/base64, webhook headers, env-backed secrets, and model responses, so truncating to 200/500 chars still leaks sensitive data into logs. Please log shapes/keys/types or redact known sensitive fields instead of dumping payload values.

Also applies to: 505-510, 521-527

🧰 Tools
🪛 ast-grep (0.44.0)

[info] 458-458: use jsonify instead of json.dumps for JSON output
Context: json.dumps(kwargs.get("inputs", {}), ensure_ascii=False, default=str)
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 `@agent/canvas.py` around lines 456 - 460, The debug logging in Canvas workflow
execution is leaking raw payload data, so update the logging in canvas.py
(including the workflow start path and the later input/output/kwargs debug
statements) to avoid serializing values directly. Replace the verbatim
json.dumps/default=str logging with redacted summaries that only include shapes,
keys, counts, or types, and explicitly scrub sensitive fields before logging in
the relevant Canvas methods.
agent/component/base.py (1)

492-512: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Input-resolution debug logs leak resolved values.

These messages now emit resolved refs and literal inputs after substitution, which includes env.* values and any user/file payloads pulled through the canvas. That turns ordinary debug logging into a secrets/PII sink. Prefer logging variable names plus type/size metadata, or redact sensitive namespaces before serialization.

🧰 Tools
🪛 ast-grep (0.44.0)

[info] 503-503: use jsonify instead of json.dumps for JSON output
Context: json.dumps(resolved, ensure_ascii=False, default=str)
Note: [CWE-116] Improper Encoding or Escaping of Output.

(use-jsonify)


[info] 508-508: use jsonify instead of json.dumps for JSON output
Context: json.dumps(kv, ensure_ascii=False, default=str)
Note: [CWE-116] Improper Encoding or Escaping of Output.

(use-jsonify)


[info] 511-511: use jsonify instead of json.dumps for JSON output
Context: json.dumps(v, ensure_ascii=False, default=str)
Note: [CWE-116] Improper Encoding or Escaping of Output.

(use-jsonify)


[warning] 504-504: Regex pattern passed to re is built from a non-literal (variable, call, concatenation, or f-string) value. If that value is attacker-controlled it can introduce a malicious pattern with catastrophic backtracking (ReDoS). Use a hardcoded literal pattern, or validate/escape untrusted input with re.escape() and bound the regex complexity before compiling.
Context: re.search(self.variable_ref_patt, v)
Note: [CWE-1333] Inefficient Regular Expression Complexity.

(redos-non-literal-regex-python)

🪛 Ruff (0.15.20)

[warning] 496-496: Loop control variable o not used within loop body

Rename unused o to _o

(B007)

🤖 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/component/base.py` around lines 492 - 512, The debug logging in
Base.resolve-style input handling is leaking resolved values, including refs and
literal payloads. Update the logging in the input-resolution loop to avoid
serializing actual resolved data from get_variable_value,
get_input_elements_from_text, and set_input_value; instead log only the variable
name plus safe metadata like type, length, or count. Add redaction for sensitive
namespaces such as env.* before any debug output in the Component input
resolution path.
api/apps/restful_apis/agent_api.py (1)

74-85: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

_canvas_json_default still lets non-callable objects break SSE.

The new handler only neutralizes callables. node_finished events still carry arbitrary component inputs/outputs, so any other unsupported object type will re-raise TypeError here and tear down the stream at the new json.dumps(..., default=_canvas_json_default) call sites. That misses the PR’s stated “non-serializable objects” goal.

Suggested fix
 def _canvas_json_default(obj):
     """Fallback serializer for canvas SSE events.
@@
     if callable(obj):
         return None
-    raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
+    logging.warning(
+        "SSE JSON fallback via str() for type=%s",
+        type(obj).__name__,
+    )
+    return str(obj)
📝 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 _canvas_json_default(obj):
    """Fallback serializer for canvas SSE events.

    Agent components store functools.partial objects as deferred streaming
    handles (see llm.py, agent_with_tools.py, message.py). These leak into
    SSE event dicts via component input/output propagation and are not
    JSON-serializable. This handler converts them to None so that downstream
    consumers never receive opaque ``str(partial(...))`` representations.
    """
    if callable(obj):
        return None
    logging.warning(
        "SSE JSON fallback via str() for type=%s",
        type(obj).__name__,
    )
    return str(obj)
🤖 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 74 - 85, The
_canvas_json_default fallback in agent_api.py only handles callable objects, so
non-serializable values in node_finished payloads can still raise TypeError and
break SSE at the json.dumps call sites. Update _canvas_json_default to safely
neutralize any unsupported object type used in canvas event dicts, not just
callables, so json.dumps(..., default=_canvas_json_default) can serialize all
streamed component inputs/outputs without tearing down the stream.

@codecov

codecov Bot commented Jun 30, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (3633d08) to head (5102c39).
⚠️ Report is 4 commits behind head on main.

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

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yuzhichang
yuzhichang merged commit 38f8f8a into infiniflow:main Jul 1, 2026
3 checks passed
yuzhichang pushed a commit that referenced this pull request Jul 2, 2026
### Summary

Port the following PRs to GO in this PR

#14210
#14641
#15220
#15228
#15384
#15754
#16413
#16483
#16419
#16361   
#16050
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants