Skip to content

fix: filter non-serializable objects from stream events in prepare()#1941

Open
Exploreunive wants to merge 1 commit intostrands-agents:mainfrom
Exploreunive:fix/non-serializable-stream-events
Open

fix: filter non-serializable objects from stream events in prepare()#1941
Exploreunive wants to merge 1 commit intostrands-agents:mainfrom
Exploreunive:fix/non-serializable-stream-events

Conversation

@Exploreunive
Copy link

Problem

ModelStreamEvent.prepare() merges the entire invocation_state dict into yielded event dicts. invocation_state contains non-serializable objects like Agent instances, OpenTelemetry Spans, and Trace objects. When consumers (e.g., AgentCore SSE streaming) attempt to serialize these events, it fails with TypeError and potentially dumps >100MB of object repr data.

Related issue: #1928

Solution

Added _is_json_serializable() and _sanitize_invocation_state() helpers to dynamically filter out non-serializable values before merging in prepare(). This approach is:

  • Generic: works with any non-serializable objects added in the future
  • Non-breaking: only filters values that can't survive json.loads(json.dumps(v))
  • Conservative: wraps serialization checks in try/except to avoid side effects

Changes

  • src/strands/types/_events.py: Added _is_json_serializable() and _sanitize_invocation_state(), updated ModelStreamEvent.prepare()
  • tests/strands/agent/hooks/test_agent_events.py: Updated any_props to remove filtered fields
  • tests/strands/agent/test_agent.py: Updated stream test expectation

Testing

  • All 160 existing tests pass
  • Verified agent, event_loop_cycle_span, event_loop_cycle_trace are properly filtered from stream events

Non-serializable objects (Agent instances, OpenTelemetry Spans, etc.) from
invocation_state were being merged into event dicts via prepare(), causing
JSON serialization failures when consumers attempt to serialize yielded events.

Added _is_json_serializable() and _sanitize_invocation_state() helpers to
dynamically filter non-serializable values before merging. This approach is
more robust than maintaining a hardcoded blocklist.

Fixes strands-agents#1928
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant