Repository navigation
fix(connection): stop caching execute() statements that scan a DataFrame or Arrow table - #84
Merged
Conversation
`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 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This work was produced with the help of language models.
On 0.23.0, calling
conn.execute("COPY trips FROM $df", {"df": df})with a new 1,000-row Arrow table each time kept about 12 MB of buffer pool per call.CHECKPOINTdid not release it, andCOPYeventually failed withRuntimeError: Buffer manager exception: Unable to allocate memory! The buffer pool is full and no memory could be freed!. Running a query again on the same DataFrame after a column was replaced returned the old values:LOAD FROM $df RETURN sum(a)still returned 45 afterdf["a"] = df["a"] * 10, and a polarsdf[0, "a"] = 7was not seen either.Fix. For a DataFrame or Arrow table, the key of
execute()'s statement cache included the object's identity. Every new object added an entry that no later call used, and each entry kept its plan's memory untilclose(). Reusing an entry with the same object read the column buffers it was prepared with. Statements with a pandas, polars or pyarrow parameter, also inside a list or struct, are now prepared on each call and not cached, and the per-object key and its weakref tracker are removed. On the C-API backend the object becomes a scan table with a new name on each call, so queries with other parameters are not cached either. Other parameterized queries still are. Re-preparing no longer grows memory (#37): since 0.20.0 the engine frees a statement's plan with the statement (LadybugDB/ladybug#849).Not fixed here. The uncached statement is destroyed while the cache lock is held, also when the execute raises, which keeps it apart from other
execute(query, params)calls. An explicit prepared statement executing on another thread can still race it on the engine's statement map: LadybugDB/ladybug#1718. On an in-memory database the C-API backend still keeps 1 MB per scan for its scan table: LadybugDB/ladybug#1717.Cost. A query run again on the same object is compiled every time:
count(*)over a 1,000-row Arrow table takes 0.63 ms instead of 0.40 ms, a filtered aggregate 1.43 ms instead of 0.72 ms. With a new object per call,COPYof 1,000 rows takes 42.2 ms instead of 46.6 ms, andLOAD0.77 ms instead of 0.80 ms.Tests.
test_pyarrow_scan_statements_are_not_cachedrunsCOPYand aLOADwith a second parameter over three tables and checks that the cache stays empty.test_scan_pandas_after_column_replacedandtest_polars_scan_after_value_setchange a DataFrame between two runs of one query. Tests with fake connections check that two tables, passed directly or nested, are prepared twice, and that on both backends the statement is destroyed under the cache lock whether the execute returns or raises. Onmain, the pyarrow and fake-connection tests fail on both backends, and the pandas and polars tests fail on pybind. Full suites on Python 3.12 and 3.14: no new failures on either backend.Fixes LadybugDB/ladybug#1676