diff --git a/Cargo.lock b/Cargo.lock index 73a3a1b..09429a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -237,9 +237,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.2" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0" dependencies = [ "cmov", ] diff --git a/src/client_live_tests.rs b/src/client_live_tests.rs index 815f80c..89ffdaa 100644 --- a/src/client_live_tests.rs +++ b/src/client_live_tests.rs @@ -431,3 +431,231 @@ async fn pooled_txn_ddl_stays_off_the_pinned_path() { let key = connection_key(¶ms); POOLS.lock().unwrap().remove(&key); } + +/// Regression guard for #166: a `SELECT *` on a table with a custom `enum` +/// column **and wide rows** (enough total bytes to fill tokio-postgres's +/// bounded `responses` channel + the socket buffer) must return rows on a +/// *direct* connection (no pooler, Pooler Mode not set), not hang. +/// +/// The failure mode (#166, the rc.11 gap): tokio-postgres's `query_typed` +/// resolves non-builtin column types (`get_type` → the internal named +/// `typeinfo_statement`) *inside* its `RowDescription` loop, mid-stream over +/// the same channel delivering the query's `DataRow`s. The typeinfo reply is +/// queued behind the pending rows, but `query_typed` won't drain the rows +/// until `get_type` returns → a deadlock once the row data fills the buffer +/// (hence the size threshold — a single tiny row passes on the broken path, +/// which is why `query_with_nonbuiltin_enum_column_returns_rows` above didn't +/// catch the rc.11 regression). The fix pre-resolves column types via a +/// `prepare` on the shared cached client before the data fetch, so the +/// `query_typed`'s `get_type` is a cache hit and never fires +/// `typeinfo_statement` mid-drain. +/// +/// This test is the wide-variant: 600 rows × a 500-byte `pad` column + the +/// enum column, fetched at `limit` 50 (≈25 KB, enough to fill the buffer). +/// rc.11 hangs past 120s on this; the fix returns within 30s. +#[tokio::test] +#[ignore = "needs a live PostgreSQL (PG_PLUGIN_TEST_HOST=127.0.0.1 ... podman 54320)"] +async fn wide_enum_table_returns_rows_on_direct_connection() { + use crate::client; + use crate::handlers::query::execute_query; + use serde_json::json; + + let _guard = POOLS_TEST_LOCK.lock().await; + + let params = live_params(&correct_password()) + .expect("PG_PLUGIN_TEST_HOST not set — set PG_PLUGIN_TEST_HOST=127.0.0.1 (and optionally PG_PLUGIN_TEST_PORT/USER/DB) to run live tests"); + + let type_name = "plugin_test_166_wide_mood"; + let table_name = "plugin_test_166_wide_enum_table"; + + // Setup: a custom enum type + a *wide* table (600 rows × 500-byte pad + + // the enum column). The width is the load-bearing part — it's what makes + // the response large enough to fill the channel buffer and trigger the + // mid-stream `get_type` deadlock. A narrow enum table (the existing + // test) passes on the broken path and can't catch this regression. + for stmt in [ + format!("DROP TABLE IF EXISTS {table_name}"), + format!("DROP TYPE IF EXISTS {type_name}"), + format!("CREATE TYPE {type_name} AS ENUM ('happy', 'sad')"), + format!( + "CREATE TABLE {table_name} AS SELECT g AS id, 'happy'::{type_name} AS m, \ + repeat('x', 500) AS pad FROM generate_series(1, 600) g" + ), + ] { + client::execute_typed(¶ms, &stmt, &[]) + .await + .unwrap_or_else(|e| panic!("setup statement failed ({stmt}): {e}")); + } + + // Direct connection (no `pooler_mode`) + `limit` 50 (≈25 KB — the + // hanging case on rc.11). The fix pre-resolves column types via + // `prepare` on the shared cached client so `query_typed`'s `get_type` is + // a cache hit; without the fix this hangs past 120s. + let request_params = json!({ + "driver": "postgresql", + "host": params.host, + "port": params.port, + "database": params.database, + "username": params.username, + "password": params.password, + "query": format!("SELECT * FROM {table_name}"), + "limit": 50, + "page": 1, + }); + + // Fail fast instead of hanging: the bug manifests as a stall past 120s, + // so a 30s ceiling catches a regression well before the host-style + // timeout would, with headroom for a slow podman container. + let response = tokio::time::timeout( + std::time::Duration::from_secs(30), + execute_query(json!(1), &request_params), + ) + .await + .expect( + "execute_query on a wide enum-typed table hung past 30s on a direct connection — \ + the #166 regression is present (the prepare pre-resolve is missing or broken)", + ); + + assert!( + response.get("error").is_none(), + "execute_query should succeed for a wide enum-typed table on a direct connection; \ + got: {response}" + ); + let result = response + .get("result") + .expect("ok_response carries a `result` object"); + let rows = result + .get("rows") + .and_then(|r| r.as_array()) + .expect("`result.rows` is an array"); + assert!( + !rows.is_empty(), + "the wide enum-typed table has 600 rows; got empty rows: {result}" + ); + // The enum value must decode correctly through the binary path. + assert_eq!( + rows[0].as_array().unwrap()[1], + json!("happy"), + "enum column should decode to \"happy\"; got: {result}" + ); + + // Teardown. + for stmt in [ + format!("DROP TABLE IF EXISTS {table_name}"), + format!("DROP TYPE IF EXISTS {type_name}"), + ] { + let _ = client::execute_typed(¶ms, &stmt, &[]).await; + } + let key = connection_key(¶ms); + POOLS.lock().unwrap().remove(&key); +} + +/// Regression guard for #166 via the **batch** path: `execute_query_batch` +/// routes through `run_batch_in_session` → `exec_query_on_client` (bypassing +/// `exec_query`), so a wide enum result on a direct connection must return rows +/// through the batch path too, not hang. The single-query test above covers +/// `exec_query` → `exec_query_on_client`; this one covers the batch caller, +/// which is a distinct path with its own connection handling. If the +/// pre-resolve were removed from the batch path specifically (e.g. +/// `run_batch_in_session` started passing `is_transaction_pooler = true` to +/// skip it), this test would hang past 30s. +#[tokio::test] +#[ignore = "needs a live PostgreSQL (PG_PLUGIN_TEST_HOST=127.0.0.1 ... podman 54320)"] +async fn wide_enum_table_returns_rows_via_batch_on_direct_connection() { + use crate::client; + use crate::handlers::query::execute_query_batch; + use serde_json::json; + + let _guard = POOLS_TEST_LOCK.lock().await; + + let params = live_params(&correct_password()) + .expect("PG_PLUGIN_TEST_HOST not set — set PG_PLUGIN_TEST_HOST=127.0.0.1 (and optionally PG_PLUGIN_TEST_PORT/USER/DB) to run live tests"); + + let type_name = "plugin_test_166b_wide_mood"; + let table_name = "plugin_test_166b_wide_enum_table"; + + // Same wide-table setup as the single-query test: 600 rows × 500-byte + // pad + the enum column — enough to fill the channel buffer and trigger + // the mid-stream `get_type` deadlock without the pre-resolve. + for stmt in [ + format!("DROP TABLE IF EXISTS {table_name}"), + format!("DROP TYPE IF EXISTS {type_name}"), + format!("CREATE TYPE {type_name} AS ENUM ('happy', 'sad')"), + format!( + "CREATE TABLE {table_name} AS SELECT g AS id, 'happy'::{type_name} AS m, \ + repeat('x', 500) AS pad FROM generate_series(1, 600) g" + ), + ] { + client::execute_typed(¶ms, &stmt, &[]) + .await + .unwrap_or_else(|e| panic!("setup statement failed ({stmt}): {e}")); + } + + // `execute_query_batch` with no `session_id` routes through + // `run_batch_in_session` → `exec_query_on_client` (the batch caller), + // returning a bare `results` array (not the session-aware shape). The + // batch contains the wide enum `SELECT` at limit 50 — the hanging case + // on rc.11. + let request_params = json!({ + "driver": "postgresql", + "host": params.host, + "port": params.port, + "database": params.database, + "username": params.username, + "password": params.password, + "queries": [format!("SELECT * FROM {table_name}")], + "limit": 50, + "page": 1, + }); + + let response = tokio::time::timeout( + std::time::Duration::from_secs(30), + execute_query_batch(json!(1), &request_params), + ) + .await + .expect( + "execute_query_batch on a wide enum-typed table hung past 30s on a direct connection — \ + the #166 regression is present on the batch path (the pre-resolve is missing or broken)", + ); + + assert!( + response.get("error").is_none(), + "execute_query_batch should succeed for a wide enum-typed table; got: {response}" + ); + // Non-session batch: `ok_response(id, json!(results))` puts the bare + // results array under the JSON-RPC `result` field (one entry per query). + let results = response + .get("result") + .and_then(|r| r.as_array()) + .expect("non-session batch returns a bare `result` array"); + assert_eq!(results.len(), 1, "one query in the batch; got {response}"); + let first = &results[0]; + assert!( + first.get("error").and_then(|e| e.as_str()).is_none(), + "the batch query should not error; got: {first}" + ); + let rows = first + .get("result") + .and_then(|r| r.get("rows")) + .and_then(|r| r.as_array()) + .expect("the query's result.rows is an array"); + assert!( + !rows.is_empty(), + "the wide enum-typed table has 600 rows; got empty rows: {first}" + ); + assert_eq!( + rows[0].as_array().unwrap()[1], + json!("happy"), + "enum column should decode to \"happy\"; got: {first}" + ); + + // Teardown. + for stmt in [ + format!("DROP TABLE IF EXISTS {table_name}"), + format!("DROP TYPE IF EXISTS {type_name}"), + ] { + let _ = client::execute_typed(¶ms, &stmt, &[]).await; + } + let key = connection_key(¶ms); + POOLS.lock().unwrap().remove(&key); +} diff --git a/src/handlers/query.rs b/src/handlers/query.rs index 51ca974..9fe90ac 100644 --- a/src/handlers/query.rs +++ b/src/handlers/query.rs @@ -293,12 +293,22 @@ async fn exec_query( // Transaction-pooler result-set queries take a pinned one-shot path // (#160 / #163): tokio-postgres's internal cached named `typeinfo_statement` // — fired for non-builtin result column types (custom enums, composites, - // extension types like `citext`/Supabase `auth.uid`) — collides with stale - // server-side prepared statements across pooler backend reassignment, or - // hangs on Supavisor. Pinning the backend with an explicit transaction, - // clearing stale statements, pre-resolving column types, then running the - // #149-unnamed data fetch on a connection that is *not* returned to the - // pool closes that. See `exec_query_pooled_txn`. + // extension types like `citext`/Supabase `auth.uid`) — can deadlock when + // it's fired mid-stream during `Row` deserialization (the typeinfo reply is + // queued behind the query's `DataRow`s, but `query_typed` won't drain them + // until `get_type` returns → deadlock once the row data fills the channel + // buffer). On a transaction-mode pooler the same interleave additionally + // orphans the statement across backend reassignment (`42P05` on PgBouncer, + // or a hang on Supavisor). Pinning the backend with an explicit + // transaction, clearing stale statements, pre-resolving column types, then + // running the #149-unnamed data fetch on a connection that is *not* + // returned to the pool closes the pooler case. See `exec_query_pooled_txn`. + // + // Direct (non-pooler) result-set queries have the same interleave but no + // reassignment hazard, so they pre-resolve column types via a plain + // `prepare` on the shared cached client inside `exec_query_on_client` + // (#166) — cheaper than the one-shot path (preserves pool reuse) and safe + // (no backend reassignment to collide with). // // Non-result-set statements (DDL, writes) and the batch path // (`run_batch_in_session`, which owns its own transaction) stay on the @@ -684,6 +694,48 @@ async fn exec_query_on_client( }; let manual_limit = if is_paginated { None } else { limit }; + // Pre-resolve result column types on a *direct* connection (no pooler) + // before the data fetch (#166). tokio-postgres's `query_typed` resolves + // non-builtin column types (`get_type` → the internal named + // `typeinfo_statement`) *inside* its `RowDescription` loop, mid-stream, + // over the same channel delivering the query's `DataRow`s. The typeinfo + // reply is queued behind the pending rows, but `query_typed` won't read + // the rows until `get_type` returns → a deadlock once the row data fills + // the bounded `responses` channel + socket buffer (hence the size + // threshold — small results pass, large ones hang). This is not + // pooler-specific; it deadlocks on any connection. + // + // `prepare` runs Parse+Describe+Sync with no Execute/no DataRows, so its + // `get_type` interleave has an empty channel and completes cleanly, + // warming `CachedTypeInfo.types` on the shared `InnerClient`. The + // subsequent `query_typed` then hits that cache (`get_type`'s + // `client.type_(oid)` returns early) → no `typeinfo_statement` mid-drain + // → no deadlock, regardless of result size. This is equivalent to rc.8's + // behavior (rc.8 used the named `query()` path which resolved types in + // its prepare's Describe phase; this uses a separate `prepare` + the + // unnamed `query_typed`, but the outcome — types resolved before the + // data fetch, no mid-stream interleave — is the same), which worked. + // + // Gated to direct connections: on a transaction-mode pooler a plain + // `prepare`'s named statement collides across backend reassignment (the + // `s0`→`s1` shift that killed the removed pre-warm, commit ca33b98), so + // poolers keep the #164 pinned one-shot path instead. The pre-resolve is + // non-fatal on failure: a prepare error is swallowed (`.ok()`) and the + // `query_typed` below runs anyway — for builtin types `get_type` is always + // a `Type::from_oid` cache hit (no `typeinfo_statement`, no hang), and a + // direct prepare failure on a valid result-set query is rare. The + // `Statement` is kept alive (not dropped immediately) so its `.columns()` + // can be reused by the empty-rows branch below instead of preparing a + // second time. (The warmed type cache persists on the shared `InnerClient` + // regardless of the `Statement`'s lifetime — `Statement::Drop` sends a + // server `Close` but does not clear `CachedTypeInfo.types` — so holding + // it alive is for `.columns()` reuse, not cache persistence.) + let prepared = if !is_transaction_pooler { + pg_client.prepare(&final_query).await.ok() + } else { + None + }; + // Execute query // Unnamed-statement protocol (`query_typed`) — pooler-safe under // transaction-mode poolers (PgBouncer); see `client`'s module note @@ -699,31 +751,20 @@ async fn exec_query_on_client( .map_err(|e| client::format_query_error(&e, is_transaction_pooler))?; if rows.is_empty() { - // Get columns from the statement if possible. `prepare`'s own - // `Parse + Describe + Sync` round-trip is pooler-safe for built-in - // column types (the metadata returns before the `ReadyForQuery` - // that lets a transaction-mode pooler reassign), and the - // `Statement`'s `Drop` sends a fire-and-forget `Close` whose - // response is harmlessly discarded (`let _ =` in - // `StatementInner::drop`). But for user-defined types (custom - // enums/composites), `prepare` internally calls `get_type`, which - // triggers tokio-postgres's cached `typeinfo_statement` — a named - // statement prepared and executed across separate Syncs, the same - // pooler-unsafe pattern this PR eliminates elsewhere. That path is - // a tokio-postgres 0.7 limitation (see the module note in - // `client.rs`). - // - // On a transaction-mode pooler connection, skip `prepare()` - // entirely and return `columns: []` — the host handles empty - // columns gracefully, and avoiding `prepare()` eliminates the - // plugin's own named-statement trigger (#157, tabularis#1097). - // The remaining trigger (tokio-postgres's internal - // `typeinfo_statement` during `Row` deserialization on the - // non-empty-rows path) is handled by the error-message rewrite - // above + `max_prepared_statements` on the pooler side. On direct - // connections, `prepare()` is still used (it's safe there and - // gives better column discovery for empty result sets). - let columns: Vec = if !is_transaction_pooler { + // Get columns from the statement if possible. On a direct connection + // the pre-resolve above already prepared `final_query`, so reuse its + // `.columns()` instead of preparing a second time. On a transaction- + // mode pooler, `prepare()` is skipped (its named statement would + // collide across backend reassignment) and `columns: []` is returned + // — the host handles empty columns gracefully (#157, tabularis#1097). + let columns: Vec = if let Some(stmt) = prepared.as_ref() { + stmt.columns() + .iter() + .map(|c| c.name().to_string()) + .collect() + } else if !is_transaction_pooler { + // Pre-resolve didn't run or failed; try once more for column + // discovery (the pre-#166 behavior for direct empty result sets). if let Ok(stmt) = pg_client.prepare(&final_query).await { stmt.columns() .iter()