From f8dcad13ee65974b3cd5c864d23d529db7184f83 Mon Sep 17 00:00:00 2001 From: Darek Date: Sat, 28 Nov 2026 06:23:03 +0100 Subject: [PATCH] fix: don't cache statements that scan a DataFrame or Arrow table `Connection.execute()` caches each parameterized statement by query text and parameter types. For a pandas or polars DataFrame or an Arrow table, the key also holds the object's identity (a generation number checked through a weakref) and a schema fingerprint. A cached entry is therefore reused only when the same live object is passed again. Every new object adds an entry, nothing evicts them, and each entry keeps its plan and the buffer pool memory that plan holds: about 12 MB per `COPY t FROM $df` of 1,000 rows, until the pool is full (LadybugDB/ladybug#1676). The one case the cache serves returns stale data. The plan keeps the column buffers it was bound to, so after `df["a"] = new_values`, or a polars `df[0, "a"] = 7`, running the same query on the same object reads the old values. Prepare statements with a pandas, polars or pyarrow parameter, also one nested in a list or struct, on each call instead, and remove the per-object key (`_pybind_pointer_tracker`, `_get_pointer_schema_fingerprint`). It existed only to make that reuse safe. On the C-API backend the driver registers the object as a scan table with a fresh name and drops it after the call, so a query that still has other parameters is not cached either. An uncached statement is destroyed while the cache lock is still held, also when the execute raises. Destroying it removes its entry from the engine's statement map, which an execute on another thread reads without that map's lock. Re-preparing does not grow memory: since 0.20.0 the engine frees a statement's plan when the statement is destroyed (LadybugDB/ladybug#849). Cost: a query run again on the same object is compiled again. A count over a 1,000-row Arrow table goes from 0.40 to 0.63 ms (from 0.75 to 1.16 ms as a pandas DataFrame), a filtered aggregate from 0.72 to 1.43 ms. With a new object per call, the usual case, nothing gets slower: COPY of 1,000 rows 46.6 -> 42.2 ms, LOAD 0.80 -> 0.77 ms. Co-Authored-By: Claude Opus 5.5 --- src_py/connection.py | 102 ++++++---------- test/test_pybind_implicit_prepare_cache.py | 131 +++++++++++++++++++++ test/test_scan_pandas.py | 11 ++ test/test_scan_polars.py | 10 ++ test/test_scan_pyarrow.py | 17 +++ 5 files changed, 208 insertions(+), 63 deletions(-) diff --git a/src_py/connection.py b/src_py/connection.py index 0d5038b..ccdcaa4 100644 --- a/src_py/connection.py +++ b/src_py/connection.py @@ -9,7 +9,6 @@ import threading import uuid import warnings -import weakref from typing import TYPE_CHECKING, Any, TypeVar, cast from weakref import WeakSet @@ -115,41 +114,6 @@ def _capi_param_signature(parameters: dict[str, Any]) -> tuple: ) -# Maps id(object) to (generation, weakref) for pointer-type parameters -# (DataFrames, Arrow tables, etc.). We use weakref to detect when the -# original object has been garbage-collected. If the object is gone and -# its id is recycled, the tracker assigns a new generation so the -# prepared-statement cache does not return a stale entry compiled for -# the old (now freed) object. -_pybind_pointer_gen = 0 -_pybind_pointer_tracker: dict[int, tuple[int, weakref.ref]] = {} - - -def _get_pointer_schema_fingerprint(value: Any) -> int: - """ - Compute a hash of the schema for a pandas/pyarrow/polars object. - - Two objects with the same shape, column names, and column dtypes - produce the same fingerprint. If the object is mutated in place - (e.g. columns dropped, renamed, or dtypes changed) the fingerprint - changes, causing a cache miss so a fresh prepared statement is - compiled for the new schema. - """ - module_name = type(value).__module__ - if module_name == "pandas.core.frame": - cols = list(value.columns) - return hash( - (value.shape, tuple(cols), tuple(str(value[col].dtype) for col in cols)) - ) - if module_name.startswith("pyarrow"): - schema = value.schema - return hash(tuple((f.name, str(f.type)) for f in schema)) - if module_name.startswith("polars"): - schema = value.schema - return hash(tuple(sorted((name, str(dtype)) for name, dtype in schema.items()))) - return 0 - - def _pybind_int_signature(value: int) -> tuple[str]: if -(2**7) <= value <= 2**7 - 1: return ("int8",) @@ -206,24 +170,6 @@ def _pybind_value_signature(value: Any) -> tuple: return ("blob",) if isinstance(value, str): return ("string",) - module_name = type(value).__module__ - if module_name.startswith(("pandas", "polars", "pyarrow")): - global _pybind_pointer_gen, _pybind_pointer_tracker - obj_id = id(value) - fp = _get_pointer_schema_fingerprint(value) - entry = _pybind_pointer_tracker.get(obj_id) - if entry is not None: - gen, weak = entry - if weak() is not None: - return ("pointer", module_name, type(value).__name__, gen, fp) - # Original object was GC'd and a new object now occupies the - # same memory address. Purge the stale entry and fall - # through to assign a fresh generation. - del _pybind_pointer_tracker[obj_id] - _pybind_pointer_gen += 1 - gen = _pybind_pointer_gen - _pybind_pointer_tracker[obj_id] = (gen, weakref.ref(value)) - return ("pointer", module_name, type(value).__name__, gen, fp) if isinstance(value, dict): items = list(value.items()) if ( @@ -707,6 +653,15 @@ def _is_python_scan_object(self, value: Any) -> bool: module_name = type(value).__module__ return module_name.startswith(("pandas", "polars", "pyarrow")) + def _contains_python_scan_object(self, value: Any) -> bool: + if self._is_python_scan_object(value): + return True + if isinstance(value, dict): + value = value.values() + elif not isinstance(value, (list, tuple)): + return False + return any(self._contains_python_scan_object(item) for item in value) + def _has_scan_pattern(self, query: str) -> bool: stripped = query.lstrip() if not ( @@ -922,7 +877,12 @@ def _execute_with_pybind( prepared = self._get_or_prepare_pybind_statement( py_connection, query, parameters ) - return py_connection.execute(prepared, parameters) + try: + return py_connection.execute(prepared, parameters) + finally: + # An uncached statement is destroyed here, before another + # thread's implicit execute can run on this connection. + del prepared def _get_or_prepare_pybind_statement( self, @@ -931,6 +891,12 @@ def _get_or_prepare_pybind_statement( parameters: dict[str, Any], ) -> Any: # Caller must hold ``self._prepared_cache_lock``. + # A pandas, polars or pyarrow value, at any depth, marks a statement + # that may scan it. Such a statement keeps the column buffers it was + # prepared with: reusing it can read stale data, and caching one per + # object holds buffer pool memory for each. + if self._contains_python_scan_object(parameters): + return py_connection.prepare(query, parameters) cache_key = (query, _pybind_param_signature(parameters)) prepared = self._pybind_implicit_prepared_cache.get(cache_key) if prepared is None: @@ -1061,14 +1027,24 @@ def execute( # only protects the C-API ``_bound_values`` map and the # cache itself. with self._prepared_cache_lock: - prepared_statement = ( - self._get_or_prepare_capi_statement(query, parameters) - if isinstance(query, str) - else query - ) - query_result_internal = self._connection.execute( - prepared_statement._prepared_statement, parameters - ) + if not isinstance(query, str): + prepared_statement = query + elif scan_tables_to_drop: + # The query names a scan table that is dropped below, so + # no other call can reuse its statement. + prepared_statement = self._prepare(query, parameters) + else: + prepared_statement = self._get_or_prepare_capi_statement( + query, parameters + ) + try: + query_result_internal = self._connection.execute( + prepared_statement._prepared_statement, parameters + ) + finally: + # As in _execute_with_pybind: destroy an uncached statement + # while the lock is held. + del prepared_statement if not query_result_internal.isSuccess(): raise RuntimeError(query_result_internal.getErrorMessage()) for table_name in scan_tables_to_drop: diff --git a/test/test_pybind_implicit_prepare_cache.py b/test/test_pybind_implicit_prepare_cache.py index 1916580..ae634b5 100644 --- a/test/test_pybind_implicit_prepare_cache.py +++ b/test/test_pybind_implicit_prepare_cache.py @@ -241,3 +241,134 @@ def test_pybind_implicit_prepare_segregates_struct_list_by_int_width( # int8 -> uint8 -> uint8 (reuse) -> int16 : 3 prepared statements. assert len(fake_pybind_connection.prepare_calls) == 3 + + +def test_pybind_implicit_prepare_does_not_cache_scanned_objects( + fake_pybind_connection: _FakePybindConnection, +) -> None: + pa = pytest.importorskip("pyarrow") + conn = lb.Connection(_FakeDatabase()) + + for start in (0, 10): + table = pa.table({"id": list(range(start, start + 10))}) + conn.execute("COPY person FROM $rows", {"rows": table}) + + assert len(fake_pybind_connection.prepare_calls) == 2 + assert conn._pybind_implicit_prepared_cache == {} + + +def test_pybind_implicit_prepare_does_not_cache_nested_scanned_objects( + fake_pybind_connection: _FakePybindConnection, +) -> None: + pa = pytest.importorskip("pyarrow") + conn = lb.Connection(_FakeDatabase()) + + for start in (0, 10): + table = pa.table({"id": list(range(start, start + 10))}) + conn.execute("RETURN $x", {"x": {"rows": [table]}}) + + assert len(fake_pybind_connection.prepare_calls) == 2 + assert conn._pybind_implicit_prepared_cache == {} + + +@pytest.mark.parametrize("outcome", ["returns", "raises"]) +def test_pybind_uncached_statement_is_destroyed_under_the_cache_lock( + fake_pybind_connection: _FakePybindConnection, + monkeypatch: pytest.MonkeyPatch, + outcome: str, +) -> None: + pa = pytest.importorskip("pyarrow") + conn = lb.Connection(_FakeDatabase()) + lock_held_at_destroy: list[bool] = [] + + class _TrackedStatement: + def __del__(self) -> None: + lock_held_at_destroy.append(conn._prepared_cache_lock._is_owned()) + + def execute(*args: object) -> _FakeResult: + # A traceback would keep the statement alive through this frame. + del args + if outcome == "raises": + msg = "execute failed" + raise RuntimeError(msg) + return _FakeResult() + + monkeypatch.setattr( + fake_pybind_connection, "prepare", lambda *_: _TrackedStatement() + ) + monkeypatch.setattr(fake_pybind_connection, "execute", execute) + + parameters = {"rows": pa.table({"id": [1]})} + if outcome == "raises": + with pytest.raises(RuntimeError, match="execute failed"): + conn.execute("LOAD FROM $rows RETURN *", parameters) + else: + conn.execute("LOAD FROM $rows RETURN *", parameters) + + assert lock_held_at_destroy == [True] + + +class _FakeCapiConnection(_FakeBackendConnection): + _query_timeout_ms = 0 + + def __init__(self, outcome: str) -> None: + super().__init__() + self.outcome = outcome + + def execute(self, prepared: object, parameters: dict[str, object]) -> _FakeResult: + # A traceback would keep the statement alive through this frame. + del prepared + if self.outcome == "raises": + msg = "execute failed" + raise RuntimeError(msg) + return _FakeResult() + + def drop_arrow_table(self, table_name: str) -> _FakeResult: + return _FakeResult() + + +@pytest.mark.parametrize("outcome", ["returns", "raises"]) +def test_capi_uncached_statement_is_destroyed_under_the_cache_lock( + monkeypatch: pytest.MonkeyPatch, + outcome: str, +) -> None: + lock_held_at_destroy: list[bool] = [] + + class _TrackedStatement: + _prepared_statement = object() + + def __del__(self) -> None: + lock_held_at_destroy.append(conn._prepared_cache_lock._is_owned()) + + def rewrite_scan( + self: lb.Connection, query: str, parameters: dict[str, object] + ) -> tuple[str, dict[str, object]]: + self._capi_scan_tables.add("__lbug_capi_scan_test") + rest = {key: value for key, value in parameters.items() if key != "rows"} + return query.replace("$rows", "__lbug_capi_scan_test"), rest + + database = _FakeDatabase() + database._use_pybind_backend = False + monkeypatch.setattr( + lb.Connection, + "init_connection", + lambda self: setattr(self, "_connection", _FakeCapiConnection(outcome)), + ) + monkeypatch.setattr(lb.Connection, "_using_pybind_backend", lambda self: False) + monkeypatch.setattr(lb.Connection, "_rewrite_capi_python_scan", rewrite_scan) + monkeypatch.setattr( + lb.Connection, "_should_use_pybind_for_scan", lambda self, *_: False + ) + monkeypatch.setattr(lb.Connection, "_prepare", lambda self, *_: _TrackedStatement()) + conn = lb.Connection(database) + + query = "LOAD FROM $rows WHERE v >= $low RETURN count(*)" + parameters = {"rows": object(), "low": 5} + if outcome == "raises": + with pytest.raises(RuntimeError, match="execute failed"): + conn.execute(query, parameters) + else: + conn.execute(query, parameters) + + assert lock_held_at_destroy == [True] + assert conn._pybind_implicit_prepared_cache == {} diff --git a/test/test_scan_pandas.py b/test/test_scan_pandas.py index d797e2a..7a33662 100644 --- a/test/test_scan_pandas.py +++ b/test/test_scan_pandas.py @@ -940,3 +940,14 @@ def test_copy_from_datetime_none(conn_db_empty: ConnDB) -> None: assert row2[0] == 2 assert row2[1] is None assert not result.has_next() + + +def test_scan_pandas_after_column_replaced(conn_db_empty: ConnDB) -> None: + conn, _ = conn_db_empty + df = pd.DataFrame({"a": np.arange(10, dtype=np.int64), "s": ["x"] * 10}) + query = "LOAD FROM $df RETURN sum(a), min(s)" + + assert conn.execute(query, {"df": df}).get_all() == [[45, "x"]] + df["a"] = np.arange(10, dtype=np.int64) * 10 + df["s"] = ["y"] * 10 + assert conn.execute(query, {"df": df}).get_all() == [[450, "y"]] diff --git a/test/test_scan_polars.py b/test/test_scan_polars.py index c1d2c7a..703809f 100644 --- a/test/test_scan_polars.py +++ b/test/test_scan_polars.py @@ -175,3 +175,13 @@ def test_scan_from_df_docs_example(conn_db_empty: ConnDB): df = pl.DataFrame({"name": ["Adam", "Karissa", "Zhang"], "age": [30, 40, 50]}) conn.execute("COPY Person FROM df") + + +def test_polars_scan_after_value_set(conn_db_empty: ConnDB) -> None: + conn, _ = conn_db_empty + df = pl.DataFrame({"a": [0] * 10}) + query = "LOAD FROM $df RETURN sum(a)" + + assert conn.execute(query, {"df": df}).get_all() == [[0]] + df[0, "a"] = 7 + assert conn.execute(query, {"df": df}).get_all() == [[7]] diff --git a/test/test_scan_pyarrow.py b/test/test_scan_pyarrow.py index c3d0b92..bd90c2f 100644 --- a/test/test_scan_pyarrow.py +++ b/test/test_scan_pyarrow.py @@ -333,3 +333,20 @@ def test_arrow_node_and_arrow_rel_with_filtering_query(conn_db_empty: ConnDB) -> conn.drop_arrow_table("knows_arrow_mix") conn.drop_arrow_table("people_arrow_mix") + + +def test_pyarrow_scan_statements_are_not_cached(conn_db_empty: ConnDB) -> None: + conn, _ = conn_db_empty + conn.execute("CREATE NODE TABLE scanned(id SERIAL PRIMARY KEY, v INT64)") + + for start in (0, 10, 20): + tab = pa.table({"v": pa.array(range(start, start + 10), type=pa.int64())}) + conn.execute("COPY scanned FROM $tab", {"tab": tab}) + result = conn.execute( + "LOAD FROM $tab WHERE v >= $low RETURN count(*)", + {"tab": tab, "low": start + 5}, + ) + assert result.get_all() == [[5]] + + assert conn.execute("MATCH (s:scanned) RETURN count(*)").get_all() == [[30]] + assert conn._pybind_implicit_prepared_cache == {}