Repository navigation
fix: handle non-serializable objects in agent canvas SSE and state se… - #14210
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds exception-safe ChangesJSON Serialization Fallbacks
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (3 warnings)
✅ Passed checks (2 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
agent/canvas.py (1)
138-138: Prefer deterministic fallback values over rawstr(obj)in persisted canvas snapshots.At Line 138,
default=strmay store unstable repr strings (e.g., memory-address-bearing object representations) into committed DSL state. Consider a controlled serializer (e.g.,Noneor 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
📒 Files selected for processing (3)
agent/canvas.pyagent/component/base.pyapi/apps/canvas_app.py
907efe0 to
8faee2d
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
agent/canvas.pyagent/component/base.pyapi/apps/canvas_app.py
🚧 Files skipped from review as they are similar to previous changes (1)
- agent/component/base.py
…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]>
8faee2d to
734efd5
Compare
|
Appreciations! |
|
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.
|
…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
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
agent/canvas.pyagent/component/base.pyapi/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
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 2
🤖 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
📒 Files selected for processing (3)
agent/canvas.pyagent/component/base.pyapi/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
deepcopycalls too.These blocks can still throw before
json.dumps(..., default=_canvas_json_default)runs, so afunctools.partialor other non-copyable object instructured/datastill aborts the stream or non-stream response. The companion canvas-layer change already added exception-safedeepcopy; 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
2fd24ca to
fd49ca8
Compare
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
agent/canvas.pyagent/component/base.pyapi/apps/restful_apis/agent_api.py
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 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
📒 Files selected for processing (3)
agent/canvas.pyagent/component/base.pyapi/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 exchandlers inapi/apps/restful_apis/agent_api.py, butTaskCanceledExceptiondoes not initialize the baseException, sostr(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 withsuper().__init__(msg)incommon/exceptions.pyor 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
onot used within loop bodyRename unused
oto_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_defaultstill lets non-callable objects break SSE.The new handler only neutralizes callables.
node_finishedevents still carry arbitrary component inputs/outputs, so any other unsupported object type will re-raiseTypeErrorhere and tear down the stream at the newjson.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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
…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:
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