Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions ccflow/exttypes/exprtk.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import ctypes
import functools
import sys
import sysconfig
from typing import Any

from pydantic import TypeAdapter
Expand All @@ -6,14 +10,32 @@

__all__ = ("ExprTkExpression",)

# Slot id of tp_clear in CPython's typeslots.h, and its offset in PyTypeObject on default (non free-threaded) builds.
_PY_TP_CLEAR = 51
_TP_CLEAR_OFFSET = 24 * ctypes.sizeof(ctypes.c_void_p)


def _disable_gc_clear(tp: type) -> None:
# cexprtk's Symbol_Table.__dealloc__ writes through attributes that its tp_clear has already set to None, so a
# Symbol_Table freed by the cyclic garbage collector corrupts the memory next to the None object. Without tp_clear,
# the collector breaks such cycles through the other objects and the table is freed by reference counting.
# This is what @cython.no_gc_clear would do; remove once cexprtk applies it to Symbol_Table.
if sys.implementation.name != "cpython" or sysconfig.get_config_var("Py_GIL_DISABLED"):
return
get_slot = ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.py_object, ctypes.c_int)(("PyType_GetSlot", ctypes.pythonapi))
slot = ctypes.c_void_p.from_address(id(tp) + _TP_CLEAR_OFFSET)
if slot.value is not None and slot.value == get_slot(tp, _PY_TP_CLEAR):
slot.value = None


@functools.cache
def _import_cexprtk():
try:
import cexprtk

return cexprtk
except ImportError:
raise ValueError("Unable to import cexprtk. Please make sure you have it installed.")
_disable_gc_clear(cexprtk.Symbol_Table)
return cexprtk


class ExprTkExpression(str):
Expand Down
20 changes: 20 additions & 0 deletions ccflow/tests/exttypes/test_exprtk.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import ctypes
import gc
import sys
import sysconfig
import unittest
from unittest import TestCase

Expand Down Expand Up @@ -56,3 +60,19 @@ def test_model(self):
self.assertAlmostEqual(2.0, m.expression.expression(symbol_table)())
else:
self.assertRaisesRegex(ValueError, "Unable to import cexprtk. Please make sure you have it installed.", MyModel, expression=expression)

@unittest.skipIf(not _has_cexprtk(), "Requires cexprtk to be installed")
@unittest.skipIf(sys.implementation.name != "cpython" or sysconfig.get_config_var("Py_GIL_DISABLED"), "Requires a default CPython build")
def test_symbol_table_freed_by_gc(self):
import cexprtk

ExprTkExpression.validate("1.0")
table = cexprtk.Symbol_Table({"a": 1.0})
cycle = [table]
cycle.append(cycle)
del table, cycle
after_none = id(None) + sys.getsizeof(None)
before = ctypes.string_at(after_none, 64)
gc.collect()
# Freeing a Symbol_Table through the cyclic garbage collector must not write to the memory next to None.
self.assertEqual(before, ctypes.string_at(after_none, 64))
Loading