Skip to content

Commit d7e52c3

Browse files
fix: omit unserializable dataclass run contexts (#5303)
1 parent a726a9c commit d7e52c3

2 files changed

Lines changed: 71 additions & 17 deletions

File tree

‎src/agents/run_state.py‎

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1679,23 +1679,27 @@ def _serialize_context_payload(
16791679
)
16801680

16811681
if dataclasses.is_dataclass(raw_context_payload):
1682-
serialized = dataclasses.asdict(cast(Any, raw_context_payload))
1683-
if not isinstance(serialized, Mapping):
1684-
raise UserError("RunState dataclass context must serialize to a mapping.")
1685-
# Dataclass instances serialize to dicts, so reconstruction requires a deserializer.
1686-
logger.warning(
1687-
"RunState context was serialized from a dataclass. "
1688-
"Provide context_deserializer or context_override to restore the original type."
1689-
)
1690-
return (
1691-
dict(serialized),
1692-
_build_context_meta(
1693-
raw_context_payload,
1694-
serialized_via="asdict",
1695-
requires_deserializer=True,
1696-
omitted=False,
1697-
),
1698-
)
1682+
try:
1683+
serialized = dataclasses.asdict(cast(Any, raw_context_payload))
1684+
# Copyable dataclass fields are not necessarily JSON serializable.
1685+
json.dumps(serialized)
1686+
except (TypeError, ValueError):
1687+
pass # Use the same omission fallback as other unsupported contexts.
1688+
else:
1689+
# Dataclass instances become dicts, so restoring the type needs a deserializer.
1690+
logger.warning(
1691+
"RunState context was serialized from a dataclass. "
1692+
"Provide context_deserializer or context_override to restore the original type."
1693+
)
1694+
return (
1695+
serialized,
1696+
_build_context_meta(
1697+
raw_context_payload,
1698+
serialized_via="asdict",
1699+
requires_deserializer=True,
1700+
omitted=False,
1701+
),
1702+
)
16991703

17001704
# Fall back to an empty dict so the run state remains serializable, but
17011705
# explicitly warn because the original context will be unavailable on restore.

‎tests/test_run_state.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import importlib
77
import json
88
import logging
9+
import threading
910
from collections.abc import Callable, Mapping
1011
from copy import deepcopy
1112
from dataclasses import dataclass, replace
@@ -612,6 +613,50 @@ class NonMappingContext:
612613
with pytest.raises(UserError, match="context_serializer"):
613614
state.to_json(strict_context=True)
614615

616+
@pytest.mark.asyncio
617+
@pytest.mark.parametrize("resource", [threading.Lock(), {"not-json"}], ids=["lock", "set"])
618+
async def test_dataclass_context_serialization_failure_warns_and_omits(self, resource, caplog):
619+
@dataclass
620+
class AppContext:
621+
tenant_id: str
622+
resource: Any
623+
624+
context = AppContext(tenant_id="synthetic-private-tenant", resource=resource)
625+
agent = Agent(name="AgentMapping")
626+
state = make_state(
627+
agent, context=RunContextWrapper(context), original_input="input", max_turns=1
628+
)
629+
630+
with caplog.at_level(logging.WARNING, logger="openai.agents"):
631+
json_data = state.to_json()
632+
string_data = json.loads(state.to_string())
633+
634+
for payload in (json_data, string_data):
635+
assert payload["context"]["context"] == {}
636+
meta = payload["context"]["context_meta"]
637+
assert meta["original_type"] == "dataclass"
638+
assert meta["serialized_via"] == "omitted"
639+
assert meta["requires_deserializer"] is True
640+
assert meta["omitted"] is True
641+
assert "not serializable; storing empty context" in caplog.text
642+
assert context.tenant_id not in caplog.text
643+
assert context.resource is resource
644+
645+
restored = await RunState.from_json(agent, string_data, context_override=context)
646+
assert restored._context is not None
647+
assert restored._context.context is context
648+
with pytest.raises(UserError, match="context_serializer"):
649+
state.to_string(strict_context=True)
650+
651+
serialized = json.loads(
652+
state.to_string(
653+
context_serializer=lambda ctx: {"tenant_id": ctx.tenant_id}, strict_context=True
654+
)
655+
)
656+
assert serialized["context"]["context"] == {"tenant_id": context.tenant_id}
657+
assert serialized["context"]["context_meta"]["serialized_via"] == "context_serializer"
658+
assert serialized["context"]["context_meta"]["omitted"] is False
659+
615660
@pytest.mark.asyncio
616661
async def test_from_json_with_context_deserializer(self, caplog):
617662
"""Ensure context_deserializer restores non-mapping contexts."""
@@ -630,6 +675,11 @@ class SampleContext:
630675
def deserialize_context(payload: Mapping[str, Any]) -> SampleContext:
631676
return SampleContext(**payload)
632677

678+
assert json_data["context"]["context"] == {"value": "hello"}
679+
assert json.loads(state.to_string())["context"] == json_data["context"]
680+
assert json_data["context"]["context_meta"]["serialized_via"] == "asdict"
681+
assert json_data["context"]["context_meta"]["omitted"] is False
682+
633683
new_state = await RunState.from_json(
634684
agent,
635685
json_data,

0 commit comments

Comments
 (0)