Skip to content
Merged
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
102 changes: 39 additions & 63 deletions src_py/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import threading
import uuid
import warnings
import weakref
from typing import TYPE_CHECKING, Any, TypeVar, cast
from weakref import WeakSet

Expand Down Expand Up @@ -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",)
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
131 changes: 131 additions & 0 deletions test/test_pybind_implicit_prepare_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 == {}
11 changes: 11 additions & 0 deletions test/test_scan_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]]
10 changes: 10 additions & 0 deletions test/test_scan_polars.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]
17 changes: 17 additions & 0 deletions test/test_scan_pyarrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 == {}
Loading