Skip to content

fix(sdk): stop decorator input/output serialization errors crashing functions - #4776

Draft
doronkopit5 wants to merge 1 commit into
mainfrom
heal/issue-4686-a1
Draft

doronkopit5 wants to merge 1 commit into
mainfrom
heal/issue-4686-a1

Conversation

@doronkopit5

@doronkopit5 doronkopit5 commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

Fixes #4686

Root cause

`_handle_span_input` and `_handle_span_output` in `traceloop/sdk/decorators/base.py` only caught `TypeError` around `json.dumps(..., cls=JSONEncoder)`. `JSONEncoder.default` calls an object's own `to_json()`, `model_dump()`, `dict()` or `json()`, and any of these can raise any exception. For example, `httpx.Response(204).json()` raises `JSONDecodeError`. `json.dumps` also raises `ValueError` on a circular reference. These errors escaped from the two handlers.

- **Input side:** the handler runs after `_setup_span` has attached the workflow/agent name, span and entity-path tokens, but outside the cleanup try/finally. So the decorated function never ran, the span was never ended, and the name and path leaked to later spans.
- **Output side, sync:** the result was lost and the span leaked.
- **Output side, async:** the instrumentation's own failure was recorded on the span as an ERROR and the user's result was lost.

Change

`_handle_span_input` and `_handle_span_output` now catch `Exception` instead of only `TypeError`. On an encoder error only the entity input or output attribute is left out, as already happened for a `TypeError`. The function runs normally, its span is ended and the name and path tokens are detached. All four wrappers (sync, async, generator, async generator) share these handlers.

I added `tests/test_decorator_serialization_errors.py` with one test per contract row (r1–r7). Each test runs with two inputs: an object whose `.json()` raises `JSONDecodeError` (like `httpx.Response(204)`) and a circular list. The tests check that:
- the function returns or yields normally;
- span status is UNSET;
- the failed attribute is absent and the other one is still recorded;
- a later sibling `@task` has no leaked workflow name or entity path;
- the user's own exception still propagates, with one exception event (r3);
- the async output case has no exception event.

All 14 cases failed before the fix with the errors from the issue. After it they pass, with the nearby decorator tests (69 passed). Ruff and mypy report no issues.

Behaviour changes: decorated functions no longer raise when their arguments or return value fail to serialize for reasons other than `TypeError`; the attribute is left out instead. Async tasks whose return value fails to serialize are no longer marked ERROR.
Not addressed: none.

Scope

  • slice 1 of 1
  • covers rows: 7 of 7 in rows

Out of scope:

  • Changing JSONEncoder.default to fall back to the class name when .json()/to_json()/dict() raise: This would change the attribute contents that are recorded. The issue asks only that the function runs and the attribute is omitted, as for TypeError today.
  • Unguarded json.dumps in guardrail/guardrail.py and guardrail/guards.py: These are separate code paths not named in the issue. A follow-up issue is needed if they can raise on real data.
  • Logging or debug-reporting the swallowed serialization exception: The existing TypeError path is a silent pass. Adding logging is a separate design change.
  • Abandoned async generator without aclose leaking the name: This is a documented known limitation in async_gen_wrap and is unrelated to serialization.

Regression evidence

Each test below failed on the base commit and passes with this change, run offline in the heal harness:

  • traceloop-sdk:tests/test_decorator_serialization_errors.py::test_async_generator_unserializable_input_yields (failed before: exception)
  • traceloop-sdk:tests/test_decorator_serialization_errors.py::test_async_unserializable_input_runs_function (failed before: exception)
  • traceloop-sdk:tests/test_decorator_serialization_errors.py::test_async_unserializable_output_returns_result (failed before: exception)
  • traceloop-sdk:tests/test_decorator_serialization_errors.py::test_sync_generator_unserializable_input_yields (failed before: exception)
  • traceloop-sdk:tests/test_decorator_serialization_errors.py::test_sync_unserializable_input_runs_function (failed before: exception)
  • traceloop-sdk:tests/test_decorator_serialization_errors.py::test_sync_unserializable_input_user_exception_propagates (failed before: exception)
  • traceloop-sdk:tests/test_decorator_serialization_errors.py::test_sync_unserializable_output_returns_result (failed before: exception)

Package suites: no new failures against the offline baseline.
Ruff: clean.
Mypy: clean.

Telemetry evidence

tests/test_decorator_serialization_errors.py::test_sync_unserializable_input_runs_function

2 of 2 cases: wf.workflow, sibling.child, sibling.task recorded after the fix (absent before)

case span / metric field before after
[json_decode_error] wf.workflow span absent recorded
[json_decode_error] wf.workflow traceloop.workflow.name absent wf
[json_decode_error] wf.workflow traceloop.span.kind absent workflow
[json_decode_error] wf.workflow traceloop.entity.name absent wf
[json_decode_error] wf.workflow traceloop.entity.output absent "ran"
[json_decode_error] sibling.child span absent recorded
[json_decode_error] sibling.child traceloop.entity.path absent sibling
[json_decode_error] sibling.task span absent recorded
[json_decode_error] sibling.task traceloop.span.kind absent task
[json_decode_error] sibling.task traceloop.entity.name absent sibling
[json_decode_error] sibling.task traceloop.entity.input absent {"args": [], "kwargs": {}}
[json_decode_error] sibling.task traceloop.entity.output absent null
[circular] wf.workflow span absent recorded
[circular] wf.workflow traceloop.workflow.name absent wf
[circular] wf.workflow traceloop.span.kind absent workflow
[circular] wf.workflow traceloop.entity.name absent wf
[circular] wf.workflow traceloop.entity.output absent "ran"
[circular] sibling.child span absent recorded
[circular] sibling.child traceloop.entity.path absent sibling
[circular] sibling.task span absent recorded
[circular] sibling.task traceloop.span.kind absent task
[circular] sibling.task traceloop.entity.name absent sibling
[circular] sibling.task traceloop.entity.input absent {"args": [], "kwargs": {}}
[circular] sibling.task traceloop.entity.output absent null
tests/test_decorator_serialization_errors.py::test_sync_unserializable_output_returns_result

2 of 2 cases: produce.task, sibling.child, sibling.task recorded after the fix (absent before)

case span / metric field before after
[json_decode_error] produce.task span absent recorded
[json_decode_error] produce.task traceloop.span.kind absent task
[json_decode_error] produce.task traceloop.entity.name absent produce
[json_decode_error] produce.task traceloop.entity.input absent {"args": [], "kwargs": {}}
[json_decode_error] sibling.child span absent recorded
[json_decode_error] sibling.child traceloop.entity.path absent sibling
tests/test_decorator_serialization_errors.py::test_sync_unserializable_input_user_exception_propagates

2 of 2 cases: fails.task recorded after the fix (absent before)

tests/test_decorator_serialization_errors.py::test_async_unserializable_input_runs_function

2 of 2 cases: wf.workflow, sibling.child, sibling.task recorded after the fix (absent before)

tests/test_decorator_serialization_errors.py::test_async_unserializable_output_returns_result

2 of 2 cases: sibling.child, sibling.task recorded after the fix (absent before); 3 span fields changed

6 attributes unchanged

tests/test_decorator_serialization_errors.py::test_sync_generator_unserializable_input_yields

2 of 2 cases: gen.task, sibling.child, sibling.task recorded after the fix (absent before)

tests/test_decorator_serialization_errors.py::test_async_generator_unserializable_input_yields

2 of 2 cases: agen.workflow, sibling.child, sibling.task recorded after the fix (absent before)

108 more rows not shown

Review

`_handle_span_input` and `_handle_span_output` in decorators/base.py now catch `Exception`, not only `TypeError`. Encoder failures (JSONDecodeError from `.json()`, ValueError on cycles, errors from a user's `to_json`/`dict`) now leave out only the input/output attribute. Decorated functions run and return normally, spans end and context tokens are detached. Seven tests cover the sync, async, generator and async-generator wrappers, each with two inputs. They check span status, attributes, exception events, user-exception propagation and that no context leaks to a sibling span.

Before merging

  • CI green: Lint, Build Packages, Test Packages (3.10, 3.11, 3.12)
  • Approved by a maintainer other than the author
  • CodeRabbit review read

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Serialization errors encountered while recording span inputs or outputs no longer interrupt task and workflow execution. This includes errors from response-like objects and circular data, across synchronous and asynchronous tasks, workflows, and generators.
    • Functions and generators continue to return or yield their results, and user-raised exceptions continue to behave as expected.

@doronkopit5

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The span input and output handlers now suppress exceptions raised during serialization or span-attribute recording. New tests cover synchronous, asynchronous, and generator decorators with serialization failures.

Changes: Serialization error handling

Layer / File(s) Summary
Suppress span serialization errors
packages/traceloop-sdk/traceloop/sdk/decorators/base.py, packages/traceloop-sdk/tests/test_decorator_serialization_errors.py
The input and output handlers catch exceptions during serialization and span-attribute recording. Tests check function results, propagated user errors, span data, and sibling-span attributes across synchronous, asynchronous, and generator calls.

Estimated code review effort: 2 (Simple) | ~15 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related PRs

  • traceloop/openllmetry#4687: It changes the same handlers to catch serialization exceptions and adds tests for decorated call types.

Suggested reviewers: nirga

Merge Risk: Minimal · up to 7df54

Decorated functions will no longer fail when their inputs or outputs cannot be serialized for tracing; the affected attribute is omitted instead. The change is small and reversible, and no merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: decorator input and output serialization errors no longer crash decorated functions. The raw summary says _handle_span_input and _handle_span_output now suppress any e…
Linked Issues check Passed [#4686] requires that non-TypeError encoder failures in @task/@workflow input and output handling not escape into the decorated function. At the reviewed head, _handle_span_input and `_handle_span_o…
Out of Scope Changes check Passed The PR changes two areas: the exception handling in _handle_span_input and _handle_span_output in packages/traceloop-sdk/traceloop/sdk/decorators/base.py, and the new test file `packages/tracelo…
Full details: Title check

Explanation

The title names the main change: decorator input and output serialization errors no longer crash decorated functions. The raw summary says _handle_span_input and _handle_span_output now suppress any exception during serialization or span recording, not only TypeError. The objectives describe the same behavior for sync, async, generator, and async-generator wrappers. The title uses the fix(sdk) convention and stays within 77 characters, so it is specific and concise.

Full details: Linked Issues check

Explanation

[#4686] requires that non-TypeError encoder failures in @task/@workflow input and output handling not escape into the decorated function. At the reviewed head, _handle_span_input and _handle_span_output in packages/traceloop-sdk/traceloop/sdk/decorators/base.py wrap the json.dumps(..., cls=JSONEncoder) call in except Exception: pass. Both handlers are called from all four wrappers: sync_wrap, async_wrap, async_gen_wrap, and the sync generator path. The input handler runs after _setup_span and before the try/finally that ends the span, so the catch-all keeps the function running. The output handler runs before _cleanup_span, so the span ends and the tokens detach. For async output, the catch-all also stops the failure from being recorded as ERROR. The new file packages/traceloop-sdk/tests/test_decorator_serialization_errors.py covers the issue triggers: an object whose .json() raises JSONDecodeError and a circular list. It runs them through sync, async, generator, and async-generator wrappers. It checks that the function returns or yields normally, span status is UNSET, the failed attribute is omitted, and a later sibling span has no leaked workflow name or entity path. It also checks that a user exception still propagates. The issue has no non-coding requirements. Limitation: the diff tool could not read the changed blobs, so the base-side behavior is inferred from the PR description. The head source and test file were read directly. The pass/fail results and lint claims in the PR description were not re-run.

Full details: Out of Scope Changes check

Explanation

The PR changes two areas: the exception handling in _handle_span_input and _handle_span_output in packages/traceloop-sdk/traceloop/sdk/decorators/base.py, and the new test file packages/traceloop-sdk/tests/test_decorator_serialization_errors.py. Both connect directly to the issue's requirement. The new tests support that requirement. The PR description lists excluded items, including JSONEncoder.default fallback changes, guardrail json.dumps calls, logging, and the async-generator abandonment limitation. None of these appear in the reviewed head file for base.py, so no unrelated change is shown. The telemetry tables in the PR description are evidence text, not code changes. Limitation: the full diff could not be read, so unrelated edits elsewhere in the PR cannot be fully excluded. The files listed in the PR summary are consistent with the stated scope.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b4a8a77a-66c1-45ac-bdf9-7f328d8db973
Commits

Reviewing files that changed from the base of the PR and between b870d8a and 7df54bb.

Files selected for processing: 2

  • packages/traceloop-sdk/tests/test_decorator_serialization_errors.py
  • packages/traceloop-sdk/traceloop/sdk/decorators/base.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 3 remain after this review.

@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 Bug Report: @task/@workflow input/output serialization errors other than TypeError escape into the decorated function

1 participant