Skip to content

Commit 064a765

Browse files
authored
Fix erroneous <circular reference> when object is repeated in list (#664)
1 parent 9297881 commit 064a765

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

logfire/_internal/json_encoder.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,7 @@ def to_json_value(o: Any, seen: set[int]) -> JsonValue:
237237
if id(o) in seen:
238238
return '<circular reference>'
239239

240+
seen = seen.copy()
240241
seen.add(id(o))
241242

242243
if isinstance(o, (list, tuple)):

logfire/_internal/json_schema.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ def create_json_schema(obj: Any, seen: set[int]) -> JsonDict:
115115

116116
if id(obj) in seen:
117117
return {}
118+
119+
seen = seen.copy()
118120
seen.add(id(obj))
119121

120122
if obj_type in {list, tuple, set, frozenset, deque}:

tests/test_json_args.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1200,3 +1200,37 @@ class Dataclass:
12001200
}
12011201
]
12021202
)
1203+
1204+
1205+
def test_repeated_objects(exporter: TestExporter) -> None:
1206+
@dataclass
1207+
class Model:
1208+
x: Any
1209+
1210+
x = Model(x=1)
1211+
m = Model(x=[x, x])
1212+
1213+
logfire.info('hi', m=m)
1214+
1215+
assert exporter.exported_spans_as_dict() == snapshot(
1216+
[
1217+
{
1218+
'name': 'hi',
1219+
'context': {'trace_id': 1, 'span_id': 1, 'is_remote': False},
1220+
'parent': None,
1221+
'start_time': 1000000000,
1222+
'end_time': 1000000000,
1223+
'attributes': {
1224+
'logfire.span_type': 'log',
1225+
'logfire.level_num': 9,
1226+
'logfire.msg_template': 'hi',
1227+
'logfire.msg': 'hi',
1228+
'code.filepath': 'test_json_args.py',
1229+
'code.function': 'test_repeated_objects',
1230+
'code.lineno': 123,
1231+
'm': '{"x":[{"x":1},{"x":1}]}',
1232+
'logfire.json_schema': '{"type":"object","properties":{"m":{"type":"object","title":"Model","x-python-datatype":"dataclass","properties":{"x":{"type":"array","items":{"type":"object","title":"Model","x-python-datatype":"dataclass"}}}}}}',
1233+
},
1234+
}
1235+
]
1236+
)

0 commit comments

Comments
 (0)