GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — mypyc leaks owned left operand for binary bytes concatenation · Issue #1192 · mypyc/mypyc Closed python/mypy #21469DescriptionSummarymypyc appears to generate IR/C code that leaks the owned left operand for binary This reproduces with a minimal example using only two operands: class A: def f(self) -> bytes: return (1).to_bytes(4, "big") + (2).to_bytes(4, "big") The generated IR calls Generated IRFor the example above, mypyc generates: Here: After calling I would expect something like: or equivalent cleanup on both success and error paths. CPyBytes_Concat does not steal references
PyObject *CPyBytes_Concat(PyObject *a, PyObject *b) { Py_ssize_t a_len = ((PyVarObject *)a)->ob_size; Py_ssize_t b_len = ((PyVarObject *)b)->ob_size; PyBytesObject *ret = (PyBytesObject *)PyBytes_FromStringAndSize(NULL, a_len + b_len); if (ret != NULL) { memcpy(ret->ob_sval, ((PyBytesObject *)a)->ob_sval, a_len); memcpy(ret->ob_sval + a_len, ((PyBytesObject *)b)->ob_sval, b_len); } return (PyObject *)ret; } So the caller should still be responsible for releasing any owned references passed as arguments. ImpactThis causes memory growth in mypyc-compiled code, while the same code does not leak when run as pure Python. The issue is especially visible in code that performs high-frequency return self.layer.to_bytes(4, "big") + self.tree.to_bytes(12, "big") + self.typ.to_bytes(4, "big") and subclasses used: return super().to_bytes() + self.keypair.to_bytes(4, "big") + ... This made the leak large enough to show up clearly in Memray. Profiling resultUsing Memray with Python allocator tracking enabled: python -m memray run --native --trace-python-allocators -o repro.bin repro.py python -m memray flamegraph --leaks repro.bin The leaked allocations are attributed to: With chained concatenation, the problem is amplified. For example: class A: def f(self) -> bytes: return (1).to_bytes(4, "big") + (2).to_bytes(4, "big") + (3).to_bytes(4, "big") generates IR like: Expected behaviorThe generated IR/C code should decref both owned operands after Actual behaviorThe generated IR decrefs only the right operand. The owned left operand remains alive and leaks. EnvironmentAlready reproduced in Linux-GNU Python 3.12 and Windows Python 3.13. Activity
MetadataMetadataAssigneesLabelsNo labels TypeProjectsMilestoneRelationshipsDevelopmentIssue actions |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |