Skip to content

Commit ccbeca4

Browse files
authored
Fix reference leak in to_builtins for array-like Structs (msgspec#1177)
Remove the extra reference increment for converted fields before inserting them into the result list or tuple. This prevents leaked references on successful conversion and when a later field fails to convert. Fixes msgspec#1175. Co-authored-by: Siyet <[email protected]>
1 parent 8be1966 commit ccbeca4

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

‎src/msgspec/_core.c‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20367,7 +20367,6 @@ to_builtins_struct(ToBuiltinsState *self, PyObject *obj, bool is_key) {
2036720367
if (val == NULL) goto cleanup;
2036820368
PyObject *val2 = to_builtins(self, val, is_key);
2036920369
if (val2 == NULL) goto cleanup;
20370-
Py_INCREF(val2);
2037120370
if (is_key) {
2037220371
PyTuple_SET_ITEM(out, i + tagged, val2);
2037320372
}

‎tests/unit/test_to_builtins.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,27 @@ class Ex(Struct, array_like=True, tag=tagged, frozen=True):
475475
sol = {("Ex", 1, -1) if tagged else (1, -1): "abc"}
476476
assert to_builtins(msg) == sol
477477

478+
@pytest.mark.parametrize("tagged", [False, True])
479+
@pytest.mark.parametrize("is_key", [False, True])
480+
@pytest.mark.parametrize("error", [False, True])
481+
def test_struct_array_field_refcounts(self, tagged, is_key, error):
482+
class Ex(Struct, array_like=True, tag=tagged, frozen=True):
483+
x: Any
484+
y: Any
485+
486+
value = float("1.5")
487+
obj = Ex((value,), Bad() if error else value)
488+
msg = {obj: None} if is_key else obj
489+
count = sys.getrefcount(value)
490+
491+
if error:
492+
with pytest.raises(TypeError, match="Encoding objects of type Bad"):
493+
to_builtins(msg)
494+
else:
495+
to_builtins(msg)
496+
497+
assert sys.getrefcount(value) == count
498+
478499
@pytest.mark.parametrize("array_like", [False, True])
479500
def test_struct_unsupported_value(self, array_like):
480501
class Ex(Struct):

0 commit comments

Comments
 (0)