Skip to content

Faster query responses, and API workers no longer hold table locks - #272

Merged
fcollman merged 7 commits into
masterfrom
fast-query-path
Nov 8, 2026
Merged

fcollman merged 7 commits into
masterfrom
fast-query-path

Conversation

@fcollman

@fcollman fcollman commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Speeds up the query endpoints about 2× and fixes a connection leak that kept tables locked. Measured on ltv7 (minnie65 v2253, synapses_pni_2, in-cluster HTTP):

request before after
versions 44 ms 10 ms
query, 1 neuron (4.8k rows) 162 ms 104 ms
query, 20 neurons (54.7k rows) 785 ms 437 ms

Changes

ADBC fetch (client/query.py). For direct_sql_pandas queries, fetch rows over ADBC straight into Arrow instead of pd.read_sql, which built a Python object per cell (0.67 s → 0.33 s for 54.7k rows). It only applies when every selected column is a plain scalar type (ints, double, bool, strings, timestamps). Geometry, Numeric, float4 and other types keep the pd.read_sql path. Integers map to Int64 and double to Float64 before the dtype_map casts, which matches what pd.read_sql infers. It replicates pd.read_sql's inference where it differs: NaN becomes a missing value, and a column without a dtype_map type becomes object on an empty result and string when every returned row is SQL NULL (a column of NaNs stays Float64, as in pd.read_sql). Strings and booleans take the ADBC path and come out unchanged (pandas string / boolean, Arrow string / bool). Each worker thread keeps at most ADBC_CONNECTIONS_KEPT ADBC connections (default 4, least recently used closed first), and a dead connection is retried once on a new one. ADBC returns PostGIS geometry in its binary wire format, not hex WKB, which is why geometry stays on the old path. QUERY_FETCH_WITH_ADBC=False turns the new path off; it is parsed with config.as_bool. ADBC's query_canceled maps to the same 504 as before.

Connection pools kept across API requests (database.py). The app-context teardown disposed every engine, so each request reconnected through the Cloud SQL proxy (~20–35 ms). API workers now keep their WEB_DB_ENGINES_KEPT (default 4) most recently used engines and dispose the rest. Celery is unchanged. A before_request hook marks API requests on g; has_request_context() can't be used because Flask pops the request context before app-context teardown. Dropping an expired version is still safe: periodic_database_removal terminates its connections first, and pool_pre_ping replaces a killed one.

Cached sessions' transactions are ended after every request and task (database.py). QueryManager queries through the cached DynamicAnnotationInterface clients' scoped sessions, and nothing committed or rolled them back. Each API worker therefore kept one transaction open for its whole life, holding an AccessShareLock on every table it had queried. On minnie, 11 sessions idle in transaction for up to 4.6 h held synapses_pni_2 in mat1926, and every pg_repack of it timed out waiting for its lock. Teardown now calls session.remove() on each cached client. After this change, ltv7 shows 0 idle-in-transaction sessions under traffic.

Workers pre-warm after fork (prewarm.py). A uwsgi postfork hook opens the aligned-volume and recent-version connections (WEB_PREWARM_VERSIONS, default 2) and fills the datastack-info cache, so a newly spawned worker's first request isn't cold. It takes about 1 s per worker. The hook first forgets the database clients inherited from the uwsgi master (reset_database_connections(close_connections=False)), even when prewarming is off. Virtual versions resolve to their parent's database. It's a no-op outside uwsgi, and WEB_PREWARM=False (or off, 0, …) disables it.

Same responses for users

  • test_query_endpoint_parity posts to the frozen-version query endpoint with QUERY_FETCH_WITH_ADBC on and off, over eight request shapes. It requires an identical Arrow schema (including the pandas metadata, so names, order and dtypes), DataFrame and headers.
  • The test table has no timestamp or string columns. test_adbc_matches_read_sql covers those, plus NULLs, through _execute_query. I checked that this test fails when timestamps come back in µs instead of ns.
  • On ltv7 I also ran the endpoint both ways over every table in mat2253: 20k-row limit, both split_positions values, two resolutions, plus an empty result for each table. All 162 combinations matched exactly, covering timestamps, strings, floats, booleans and ints.

Tests

The full suite passes locally on fresh PostGIS (860 passed, 2 skipped). The session-leak test fails if the fix is removed.

Running on ltv7 as vFastQuery7; the comparison above was run on that image.

🤖 Generated with Claude Code

fcollman and others added 3 commits November 8, 2026 12:59
…rm workers

Measured on ltv7 (minnie65 v2253 synapses_pni_2, in-process Flask requests):
one neuron (4.8k rows) 192 -> 91 ms, 20 neurons (54.7k rows) 771 -> 400 ms,
identical DataFrames.

- query.py: direct_sql_pandas queries fetch over ADBC (binary COPY into Arrow)
  instead of pd.read_sql, which built a Python object per cell. Only for plain
  scalar columns; geometry, numeric and other types keep the pd.read_sql path.
  QUERY_FETCH_WITH_ADBC=False turns it off. ADBC's query_canceled maps to the
  same 504 as psycopg2's.
- database.py: an API request no longer disposes every engine pool at teardown
  (each request reconnected through the Cloud SQL proxy). Workers keep the
  WEB_DB_ENGINES_KEPT (default 4) most recently used pools. Celery is unchanged.
- prewarm.py: after each uwsgi fork, open the aligned-volume and recent-version
  connections and fill the datastack-info cache (WEB_PREWARM, WEB_PREWARM_VERSIONS).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The keep-pools branch never ran: Flask pops the request context before the app
  context's teardown, so has_request_context() was always False there. A
  before_request hook now marks the request on g. init_db_lifecycle registers both
  hooks, and the tests go through real requests.
- test_query_endpoint_parity: POSTs the frozen-version query endpoint with
  QUERY_FETCH_WITH_ADBC on and off and requires the same Arrow schema (with pandas
  metadata), DataFrame and headers, over eight request shapes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
QueryManager queries through the cached DynamicAnnotationInterface clients' scoped
sessions, and nothing committed or rolled them back, so each API worker kept one
transaction open for its whole life, holding an AccessShareLock on every table it
had queried. On minnie (2026-11-08) 11 sessions, idle in transaction for up to
4.6 h, held synapses_pni_2 in mat1926, and every pg_repack of it timed out waiting
for its lock. cleanup_after_app_context now removes those sessions first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unbounded ADBC connection caching can exhaust PostgreSQL connections, while failure to reset inherited staging sockets after fork risks rollbacks and interleaved protocol traffic across workers.

5 open issues
What changed in this PR

This PR reduces query latency through Arrow-based fetching and connection reuse, while ending cached session transactions to release table locks.

Changes:

  • Adds an optional ADBC fetch path for scalar queries, with pandas fallback and response-parity tests.
  • Retains a bounded set of API database engines and cleans up cached session transactions.
  • Adds postfork worker prewarming for database connections and datastack metadata.
File Description
tests/​test_query_endpoint_parity.py Compares endpoint schemas, data, and headers between fetch paths.
tests/​test_query_adbc.py Tests ADBC conversion, pool retention, and transaction cleanup.
tests/​conftest.py Orders endpoint parity tests after frozen-version creation.
materializationengine/​prewarm.py Adds configurable worker prewarming after uWSGI forks.
materializationengine/​database.py Adds engine retention and cached-session cleanup hooks.
materializationengine/​blueprints/​client/​query.py Implements ADBC fetching, dtype conversion, and timeout handling.
materializationengine/​app.py Registers database lifecycle and prewarming hooks.

Review effort: Balanced

Comment thread materializationengine/prewarm.py Resolved
Comment thread materializationengine/database.py Resolved
…pes, reset after fork

- ADBC connections: at most ADBC_CONNECTIONS_KEPT (default WEB_DB_ENGINES_KEPT, 4) per
  worker thread, least recently used closed first. A dead cached connection (no sqlstate,
  08xxx, 57P01-03) is retried once on a new one; cancellations and SQL errors are not.
- Dtypes: every integer width maps to Int64 and double to Float64, which is what
  pd.read_sql infers without a dtype_map override (SmallInteger was Int16). float4 columns
  use pd.read_sql: it parses Postgres's text form, so widening float32 gives other values.
- After fork, always forget the database clients inherited from the uwsgi master
  (reset_database_connections(close_connections=False)), then prewarm if enabled.
- get_session_factory refreshes engine recency, so session_scope use counts for trim().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Unresolved issues can change empty-result schemas, mishandle ADBC and prewarming configuration flags, and break prewarming for virtual versions.

No open issues 🎉

4 previously missed issues

In code that hasn't changed since last review

Medium severity Preserve dtypes for empty ADBC query results

materializationengine/​blueprints/​client/​query.py:522

For empty results, columns without a dtype_map override, such as SmallInteger and String, retain different dtypes under ADBC than under pd.read_sql, changing the response's Arrow schema and pandas metadata. Fall back to pd.read_sql for empty tables to preserve the existing response. Extend test_empty_result_matches in tests/test_query_adbc.py to use pd.testing.assert_frame_equal, since it currently checks only row count and column names.

Medium severity Use boolean parsing for the ADBC rollback flag

materializationengine/​blueprints/​client/​query.py:556

The disable-value list misses "off", "no", and "FALSE", so these settings leave ADBC enabled instead of restoring the legacy fetch path. The repository's config.as_bool explicitly recognizes these boolean representations. Use that helper here so the rollback flag behaves consistently for string-valued configuration.

Medium severity Resolve virtual datastacks before prewarming

materializationengine/​prewarm.py:58

Valid versions can be virtual: blueprints/materialize/api.py:857–865 creates rows with valid=True and parent_version, but no database under the virtual datastack's name. For such a configured datastack, this constructs a nonexistent database name, and the connection failure exits the entire warmup loop for that datastack. Resolve the parent datastack/version as validate_datastack does before constructing mat_db, or explicitly exclude virtual versions from prewarming.

Medium severity Normalize prewarm config and honor environment fallback

materializationengine/​prewarm.py:77

String settings such as WEB_PREWARM="False" or "0" still enable prewarming, and an environment-only setting is ignored. Normalize the flag with config.as_bool and honor the environment fallback while keeping the inherited-connection reset unconditional. Read from the supplied app.config first, since this postfork hook runs before prewarm_worker enters an app context.

5 resolved since last review

Review effort: Balanced

…sions in prewarm

- Empty ADBC results: columns without a dtype_map type (String, SmallInteger) become
  object, as pd.read_sql returns them, so an empty response's Arrow schema does not
  depend on the fetch path. Strings and booleans otherwise already matched and keep
  the ADBC path; TestStringsAndBooleans pins that down (ADBC used, string/boolean
  dtypes, Arrow string/bool, NULLs, all-NULL columns, empty results).
- QUERY_FETCH_WITH_ADBC and WEB_PREWARM go through config.as_bool ("off", "no",
  "FALSE" now turn them off); prewarm settings fall back to the environment.
- Prewarm resolves a virtual version to its parent's database, and one failing
  database no longer skips the rest of the datastack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fcollman

fcollman commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the four issues from the latest review in 3001ea3:

  • Empty ADBC results: confirmed. With zero rows, pd.read_sql leaves a column without a dtype_map type (String, SmallInteger) as object, which the response declares as Arrow null; ADBC returned string / Int64. Instead of falling back, the ADBC path now converts exactly those columns to object when there are no rows. Columns with a dtype_map type (Boolean, Integer, BigInteger, Float, DateTime) already matched. test_empty_result_matches now uses assert_frame_equal and compares the full Arrow schema, including the pandas metadata. Strings and booleans are common, so TestStringsAndBooleans also requires that varchar, text and boolean columns take the ADBC path (no fallback) and match pd.read_sql: pandas string / boolean, Arrow string / bool, with NULLs, all-NULL columns and empty results.
  • QUERY_FETCH_WITH_ADBC parsing: now config.as_bool, so "off", "no" and "FALSE" turn it off (test_the_adbc_flag_accepts_config_strings).
  • Virtual versions in prewarm: a version with a parent_version now resolves to its parent's database, the way validate_datastack does. A failing database is logged and skipped without stopping the rest of the datastack (test_virtual_versions_resolve_to_their_parent_database).
  • WEB_PREWARM parsing: as_bool, read from app.config first and then the environment, since the hook runs before any app context. The inherited-connection reset still runs unconditionally (test_web_prewarm_accepts_config_strings_and_the_environment).

Full suite: 855 passed. On ltv7 (vFastQuery5) I compared the endpoint both ways over all 27 tables of mat2253: default, desired_resolution, and an empty result for each, with both split_positions values. 162 comparisons, all on the ADBC path, 0 differences in schema, dtypes, values or headers.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

ADBC changes NaN null masks and all-NULL column schemas, while the transaction-cleanup test does not verify cleanup immediately after a real API request.

No open issues 🎉

3 previously missed issues

In code that hasn't changed since last review

Medium severity Normalize PostgreSQL NaNs to missing values for ADBC parity

materializationengine/​blueprints/​client/​query.py:529

For PostgreSQL floating-point NaN values, the ADBC conversion preserves valid NaNs, while pd.read_sql(dtype_backend="numpy_nullable") treats them as missing. Enabling ADBC therefore changes the null mask and serializes Arrow NaNs instead of nulls. Normalize NaNs to masked missing values before applying dtype overrides, and add a parity case containing both NaN and NULL.

Medium severity Preserve inferred types for all-NULL unmapped columns

materializationengine/​blueprints/​client/​query.py:539

For a non-empty result containing only NULLs in an unmapped column, such as AdbcProbe.tiny when filtering to id = 50, pd.read_sql infers nullable string while ADBC forces Int64. Toggling the flag therefore changes the returned Arrow schema. Preserve all-NULL inference for columns without a dtype override, and add a parity case selecting only the NULL row.

Medium severity Test transaction cleanup in a separate request app context

tests/​test_query_adbc.py:381

This request reuses the already-active app context, so Flask does not run teardown_appcontext when get() returns. The final assertion only checks cleanup when the enclosing app_context exits; the test would still pass if non-request contexts released transactions but real API requests leaked them. Use a separate app so it gets its own request app context, execute the SELECT inside its handler, and check the idle-transaction count immediately after the request returns.

Review effort: Balanced

…oped cleanup test

- A Postgres NaN in a float column is now a missing value on the ADBC path, as
  pd.read_sql makes it (it was a valid NaN, so the response's null mask differed).
- An unmapped column (no dtype_map type) that is NULL in every returned row becomes
  string, which is what pd.read_sql infers; ADBC gave its database type.
- test_a_request_ends_the_cached_session_transaction runs the read inside a request
  handler of a separate app and checks right after that request returns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fcollman

fcollman commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the three issues from the latest review in d38a6c4. Each one reproduced against Postgres first:

  • NaN: reproduced. With a NaN in a Float and in a DOUBLE PRECISION column, pd.read_sql returned it as missing (Arrow null), while ADBC kept a valid nan. The ADBC path now turns NaN into null in the Arrow float columns before converting to pandas. test_nan_is_missing_like_read_sql covers a row with NaN, a row with NULL and a row with a value.
  • All-NULL unmapped columns: reproduced. In a non-empty result, a column with no dtype_map type that is NULL in every row (SmallInteger, DOUBLE PRECISION) is inferred as string by pd.read_sql, while ADBC kept the database type. Such columns are now string on the ADBC path too. Columns that have a dtype_map type (Integer, Float, Boolean, DateTime), and string columns, already matched. test_only_null_rows_match_read_sql selects only the NULL row and compares the frame and the full Arrow schema.
  • Transaction-cleanup test: agreed, it was checking the enclosing context's teardown. It now uses a separate app: the read runs inside a request handler (and sees its own open transaction), and the idle-in-transaction count is checked right after the request returns.

With each fix removed, its test fails. Full suite: 857 passed. On ltv7 (vFastQuery6) the all-tables endpoint comparison again matched in all 162 combinations, all on the ADBC path.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

An unmapped floating column containing only NaNs or NaNs mixed with SQL NULLs is incorrectly cast to string, causing pandas dtype and Arrow schema differences between fetch modes.

1 open issue

Review effort: Balanced

Comment on lines +533 to +550
for i, field in enumerate(table.schema):
if pa.types.is_floating(field.type):
column = table.column(i)
table = table.set_column(i, field, pc.if_else(pc.is_nan(column), pa.scalar(None, field.type), column))
df = table.to_pandas(types_mapper=_ADBC_PANDAS_TYPES.get, coerce_temporal_nanoseconds=True)
for k, dtype in dtypes.items():
if k in df.columns and str(df[k].dtype) != str(dtype) and not str(dtype).startswith("datetime"):
df[k] = df[k].astype(dtype)
# A column without a dtype_map type gets its dtype from pd.read_sql's inference, which has
# nothing to go on when there are no values: with no rows it stays object (the response then
# declares Arrow null); with only NULLs it becomes string.
for k in df.columns:
if k in dtypes:
continue
if table.num_rows == 0:
df[k] = df[k].astype(object)
elif table.column(k).null_count == table.num_rows and str(df[k].dtype) != "string":
df[k] = df[k].astype(pd.StringDtype())

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced and fixed in 46217d0. For an unmapped DOUBLE PRECISION column, pd.read_sql gives Float64 for only-NaN and for NaN+NULL, and string only for only-NULL; the ADBC path gave string for all three. The all-NULL set is now taken from the Arrow null counts before NaNs are turned into nulls. test_unmapped_double_of_nan_and_null_matches_read_sql covers the three cases and compares the frame and the full Arrow schema; with the old check, the only-NaN and NaN+NULL cases fail. Full suite: 860 passed. On ltv7 (vFastQuery7) the all-tables endpoint comparison matched in all 162 combinations, now in a single run paced under the rate limit.

Decide which columns are SQL NULL in every row before NaNs are turned into nulls:
pd.read_sql infers Float64 for a column of NaNs (or NaNs and NULLs) and string only
for a column of NULLs. Parity cases for all three on an unmapped DOUBLE PRECISION.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@fcollman
fcollman merged commit 2b62c7b into master Nov 8, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants