diff --git a/src/agents/tracing/traces.py b/src/agents/tracing/traces.py index a703acf317..adb7ac932a 100644 --- a/src/agents/tracing/traces.py +++ b/src/agents/tracing/traces.py @@ -2,6 +2,7 @@ import abc import contextvars +import copy import hashlib import threading from collections import OrderedDict @@ -178,7 +179,7 @@ def to_json(self, *, include_tracing_api_key: bool = False) -> dict[str, Any] | exported = self.export() if exported is None: return None - payload = dict(exported) + payload = copy.deepcopy(exported) if include_tracing_api_key and self.tracing_api_key: payload["tracing_api_key"] = self.tracing_api_key return payload diff --git a/tests/test_trace_json_isolation.py b/tests/test_trace_json_isolation.py new file mode 100644 index 0000000000..07599d4852 --- /dev/null +++ b/tests/test_trace_json_isolation.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from agents.tracing.provider import SynchronousMultiTracingProcessor +from agents.tracing.traces import TraceImpl + + +def test_trace_to_json_detaches_nested_metadata() -> None: + trace = TraceImpl( + name="workflow", + trace_id="trace_test", + group_id=None, + metadata={"nested": {"value": "original"}}, + processor=SynchronousMultiTracingProcessor(), + ) + + payload = trace.to_json() + assert payload is not None + payload["metadata"]["nested"]["value"] = "changed" + + assert trace.metadata == {"nested": {"value": "original"}}