From 22d96d94ef043292803b6d5c929652abd69612dd Mon Sep 17 00:00:00 2001 From: Helen Tian Date: Mon, 9 Nov 2026 17:40:31 +1100 Subject: [PATCH] [buzz] Recover database pool capacity after stalled connections (#9267) > **The pin is a temporary workaround for this week's public release. The SQLx fix is still unmerged.** > > 1. We considered a maintained fork, but repository permissions blocked it. > 2. We will move to an official SQLx release once it includes the required fixes and is verified with Buzz. Revisit the fork if needed. ## Bug https://linear.app/squareup/issue/BUZZ-656/relay-writer-pool-connections-stranded-after-a-burst-bb-public-2026-11 A short database interruption can leave the relay unable to handle database requests after traffic returns to normal. All connection slots can remain occupied even though no request is using them and PostgreSQL is idle. New requests then time out waiting for a slot. ## Cause SQLx, our database library, returns connections to the pool in a background task. If a socket stays open but stops answering, the final health check has no timeout. That task keeps its slot, and idle-connection cleanup cannot reclaim it ([#4349](https://github.com/transact-rs/sqlx/issues/4349)). ## Fix Pin SQLx to [`c3735abf`](https://github.com/transact-rs/sqlx/commit/c3735abf034689bb1fab9d7bf9f040e492de28cf) from [PR #4407](https://github.com/transact-rs/sqlx/pull/4407). After five seconds, it stops a stalled return operation, discards the connection, and frees the slot so new requests can open a replacement. Preserve the existing [transaction rollback (#4394)](https://github.com/transact-rs/sqlx/pull/4394) and [SQLite compatibility (#4402)](https://github.com/transact-rs/sqlx/pull/4402) fixes. Give the reader's own check four seconds so it can record its timeout before the outer deadline. ## Critical risk **This fix depends on a SQLx patch that has not been merged.** Its five-second limit affects every pool using this revision, so it can also discard slow but healthy connections and cause more reconnections. The local reproduction proves recovery from the injected failure; it does not establish production behavior. **Prevent accidental replacement:** require SQLx `=0.9.0`, disable Renovate updates for all seven crates, and fail required CI if the approved revision, lockfile source, or update restriction changes. These guards prevent version drift; they do not remove the runtime risk of the patch. An upgrade must explicitly update the policy after verifying all required fixes. ## Before and after evidence With real PostgreSQL 17.6 on macOS arm64, a proxy silenced 100 existing connections while allowing new connections. All borrowers dropped their connections; PostgreSQL showed 100 idle sessions. | Observation | Before | After | | --- | --- | --- | | Pool slots still occupied | 100 after 10 seconds | 0 after 5.008 seconds | | New work | Next checkout timed out | All 100 replacement connections served `SELECT 1` |
Captured before and after output **Before** ```text REPRO burst: 100 dropped borrowers, all release pings held: size=100 idle=0 active=100 REPRO burst DB sessions: [("idle", "ClientRead", 100)] REPRO burst after 10.000680583s: size=100 idle=0 active=100 REPRO burst: later checkout timed out despite PostgreSQL being healthy ``` **After** ```text REPRO burst: 100 dropped borrowers, all release pings held: size=100 idle=0 active=100 REPRO burst DB sessions: [("idle", "ClientRead", 100)] REPRO burst after 5.008456917s: size=0 idle=0 active=0 REPRO burst: all 100 replacement slots serve SELECT 1 while old sessions stay silent ``` Before evidence used Buzz `96af488d968a1ae9d961c2132bea27822735f8da` with SQLx `f1e94ec3`. After evidence used Buzz `4bfe60197e8c390a8701053228cd50c5391f37d3` with the SQLx pin committed in `f253760085e24358728fa4f4fef059ccf892157f`. These are local fault-injection results: they establish the stranded-slot mechanism and recovery, not what originally interrupted production database traffic.
--------- Signed-off-by: Helen Tian Co-authored-by: OpenAI Codex --- .github/workflows/ci.yml | 4 + Cargo.lock | 14 +- Cargo.toml | 29 ++- crates/buzz-db/src/runtime/mod.rs | 24 +- crates/buzz-db/src/runtime/tests.rs | 3 + .../tests/pool_release_postgres_tests.rs | 210 ++++++++++++++++++ crates/buzz-db/src/test_support.rs | 28 +++ renovate.json | 6 + scripts/check-sqlx-pin.py | 60 +++++ scripts/test-sqlx-pin.py | 124 +++++++++++ 10 files changed, 469 insertions(+), 33 deletions(-) create mode 100644 crates/buzz-db/src/runtime/tests/pool_release_postgres_tests.rs create mode 100644 scripts/check-sqlx-pin.py create mode 100644 scripts/test-sqlx-pin.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4191f3891f..d951aba328 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -144,6 +144,10 @@ jobs: run: | scripts/test-rust-cache-contract.sh scripts/test-rust-cache-contract-regressions.sh + - name: SQLx dependency pin + run: | + python3 scripts/check-sqlx-pin.py + python3 scripts/test-sqlx-pin.py - name: CI required-context isolation contract run: scripts/test-ci-required-context-isolation.sh - name: CI path selection regression tests diff --git a/Cargo.lock b/Cargo.lock index 665b0448d9..4742c3d53b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9921,7 +9921,7 @@ dependencies = [ [[package]] name = "sqlx" version = "0.9.0" -source = "git+https://github.com/launchbadge/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "sqlx-core", "sqlx-macros", @@ -9933,7 +9933,7 @@ dependencies = [ [[package]] name = "sqlx-core" version = "0.9.0" -source = "git+https://github.com/launchbadge/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "base64 0.22.1", "bytes", @@ -9970,7 +9970,7 @@ dependencies = [ [[package]] name = "sqlx-macros" version = "0.9.0" -source = "git+https://github.com/launchbadge/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "proc-macro2", "quote", @@ -9982,7 +9982,7 @@ dependencies = [ [[package]] name = "sqlx-macros-core" version = "0.9.0" -source = "git+https://github.com/launchbadge/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "cfg-if 1.0.4", "dotenvy", @@ -10007,7 +10007,7 @@ dependencies = [ [[package]] name = "sqlx-mysql" version = "0.9.0" -source = "git+https://github.com/launchbadge/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "bitflags 2.13.0", "byteorder", @@ -10034,7 +10034,7 @@ dependencies = [ [[package]] name = "sqlx-postgres" version = "0.9.0" -source = "git+https://github.com/launchbadge/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "atoi", "base64 0.22.1", @@ -10070,7 +10070,7 @@ dependencies = [ [[package]] name = "sqlx-sqlite" version = "0.9.0" -source = "git+https://github.com/launchbadge/sqlx?rev=f1e94ec34dd5f11ad6488a3a8ac7988439a3f757#f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" +source = "git+https://github.com/launchbadge/sqlx?rev=c3735abf034689bb1fab9d7bf9f040e492de28cf#c3735abf034689bb1fab9d7bf9f040e492de28cf" dependencies = [ "atoi", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 235efe04dc..340fe02234 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,7 +57,7 @@ tower = { version = "0.5", features = ["timeout", "util", "limit"] } tower-http = { version = "0.6", features = ["trace", "cors", "compression-gzip", "limit", "timeout", "fs"] } # Database -sqlx = { version = "0.9", features = [ +sqlx = { version = "=0.9.0", features = [ "runtime-tokio", "tls-rustls", "postgres", "uuid", "chrono", "json" ] } @@ -193,8 +193,13 @@ strip = true # allowlist for the auth token). Revert to crates.io once #449 lands upstream. [patch.crates-io] aws-creds = { git = "https://github.com/tlongwell-block/rust-s3", rev = "c9fce3620dd434c1f810101d672cf384268dbb0f" } -# SQLx: pin every crate to one unreleased upstream commit until 0.9.1 ships. -# The crates share types, so they must move together. It carries two fixes: +# SQLx: pin every crate together; these crates share types. This unreleased +# revision includes the whole-return deadline from the open upstream PR #4407 +# and retains the fixes below. Return to a released version once it includes +# all three fixes: +# - https://github.com/transact-rs/sqlx/pull/4407: bound the entire return to +# the pool, including the release hook and SQLx ping, to five seconds. Silent +# sockets must release their pool permits so new connections can replace them. # - https://github.com/transact-rs/sqlx/pull/4394: a `BEGIN` whose future is # dropped before Postgres answers no longer returns its pooled connection # still inside the transaction. 0.9.0 queues no `ROLLBACK` for it, so the @@ -203,10 +208,14 @@ aws-creds = { git = "https://github.com/tlongwell-block/rust-s3", rev = "c9fce36 # - https://github.com/transact-rs/sqlx/pull/4402: MeshLLM 0.76 uses # libsqlite3-sys 0.38, which 0.9.0's optional SQLite driver rejects; Cargo # resolves it even though Buzz only enables PostgreSQL. -sqlx = { git = "https://github.com/launchbadge/sqlx", rev = "f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" } -sqlx-core = { git = "https://github.com/launchbadge/sqlx", rev = "f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" } -sqlx-macros = { git = "https://github.com/launchbadge/sqlx", rev = "f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" } -sqlx-macros-core = { git = "https://github.com/launchbadge/sqlx", rev = "f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" } -sqlx-mysql = { git = "https://github.com/launchbadge/sqlx", rev = "f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" } -sqlx-postgres = { git = "https://github.com/launchbadge/sqlx", rev = "f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" } -sqlx-sqlite = { git = "https://github.com/launchbadge/sqlx", rev = "f1e94ec34dd5f11ad6488a3a8ac7988439a3f757" } +# The exact version prevents lockfile updates from selecting a newer unpatched +# release. Renovate updates are disabled for these crates; CI checks this pin +# with scripts/check-sqlx-pin.py. Update that policy only after verifying all +# three fixes in the replacement release. +sqlx = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } +sqlx-core = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } +sqlx-macros = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } +sqlx-macros-core = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } +sqlx-mysql = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } +sqlx-postgres = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } +sqlx-sqlite = { git = "https://github.com/launchbadge/sqlx", rev = "c3735abf034689bb1fab9d7bf9f040e492de28cf" } diff --git a/crates/buzz-db/src/runtime/mod.rs b/crates/buzz-db/src/runtime/mod.rs index f6f3461558..1c4eb4b673 100644 --- a/crates/buzz-db/src/runtime/mod.rs +++ b/crates/buzz-db/src/runtime/mod.rs @@ -1061,21 +1061,19 @@ impl Db { options.options([("default_transaction_isolation", "read committed")]) } - /// Upper bound on a reader connection's release check (see - /// [`Db::read_pool_options`]); matches sqlx's own close-on-drop bound. - const READER_RELEASE_TIMEOUT: Duration = Duration::from_secs(5); + /// Leave headroom inside SQLx's five-second whole-return deadline so this + /// check records the reason before SQLx cancels the release future. + const READER_RELEASE_TIMEOUT: Duration = Duration::from_secs(4); /// Reader pool options apart from connection lifetimes (see /// [`Db::connect_read_pool`]). /// /// Every checkout that goes back to the pool first passes a release - /// check bounded by [`Db::READER_RELEASE_TIMEOUT`]. sqlx's own release - /// ping has no timeout, so a socket whose reader stopped answering - /// without closing it (a failover, a partition) would otherwise hold its - /// slot until the kernel gives up on it; with every slot held that way, - /// the pool cannot dial the reader that replaced it. A check that times - /// out or errors closes the socket and frees the slot, and sqlx's floor - /// maintenance dials a replacement. + /// check bounded by [`Db::READER_RELEASE_TIMEOUT`]. A check that times + /// out or errors records the reason, closes the socket, and frees the + /// slot. SQLx bounds the whole return, including its subsequent ping, + /// so a reader that stops answering without closing cannot strand pool + /// capacity. Its floor maintenance dials a replacement. /// /// The check also closes, rather than returns, a connection still inside /// a transaction. sqlx rolls back a checkout dropped while its `BEGIN` @@ -1087,12 +1085,6 @@ impl Db { /// (see [`Db::proved_reader`]) and reader sessions default to `READ /// COMMITTED` (see [`Db::reader_connect_options`]), so an isolation level /// other than the session default means a transaction is still open. - /// - /// Residual window: after the check passes, sqlx sends its own release - /// ping, which has no timeout. A reader that goes silent in that one - /// round trip strands that one slot until the socket fails. That is - /// bounded by the releases in flight at that instant, and later checkouts - /// of silent connections go through the proof timeout and this check. pub(crate) fn read_pool_options(max_connections: u32) -> PgPoolOptions { PgPoolOptions::new() .max_connections(max_connections) diff --git a/crates/buzz-db/src/runtime/tests.rs b/crates/buzz-db/src/runtime/tests.rs index bab213081b..fcfc6610fb 100644 --- a/crates/buzz-db/src/runtime/tests.rs +++ b/crates/buzz-db/src/runtime/tests.rs @@ -4467,3 +4467,6 @@ async fn serving_write_guard_insert_indexes_mentions_in_event_transaction() { .await .expect("release serving-write lease")); } + +#[path = "tests/pool_release_postgres_tests.rs"] +mod pool_release_postgres_tests; diff --git a/crates/buzz-db/src/runtime/tests/pool_release_postgres_tests.rs b/crates/buzz-db/src/runtime/tests/pool_release_postgres_tests.rs new file mode 100644 index 0000000000..b6bceed5a0 --- /dev/null +++ b/crates/buzz-db/src/runtime/tests/pool_release_postgres_tests.rs @@ -0,0 +1,210 @@ +//! Pool capacity must recover when old database sockets silently stop answering. +use super::*; +use crate::test_support::PausingProxy; +use sqlx::{pool::PoolConnection, ConnectOptions, Postgres}; + +async fn writer_pool(max: u32, min: u32) -> (PgPool, PausingProxy, ScratchDb) { + let scratch = ScratchDb::create(&crate::test_support::database_url(), "release").await; + let options: sqlx::postgres::PgConnectOptions = scratch.url().parse().unwrap(); + let proxy = PausingProxy::spawn(options.get_host().to_owned(), options.get_port()).await; + let proxied = options + .host("127.0.0.1") + .port(proxy.port) + .to_url_lossy() + .to_string(); + let pool = Db::connect_writer_pool(&DbConfig { + database_url: proxied, + max_connections: max, + min_connections: min, + ..DbConfig::default() + }) + .await + .expect("production writer pool"); + (pool, proxy, scratch) +} + +async fn hold(pool: &PgPool, count: usize) -> Vec> { + let mut held = Vec::new(); + for _ in 0..count { + let mut conn = pool.acquire().await.expect("checkout"); + sqlx::query("SELECT 1").execute(&mut *conn).await.unwrap(); + held.push(conn); + } + held +} + +async fn await_capacity(pool: &PgPool, size: u32) { + let started = std::time::Instant::now(); + let result = tokio::time::timeout(Duration::from_secs(10), async { + loop { + if pool.size() == size && pool.num_idle() == size as usize { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await; + eprintln!( + "release recovery: elapsed={:?} size={} idle={} target={size}", + started.elapsed(), + pool.size(), + pool.num_idle() + ); + result.expect("released connections must stop consuming pool capacity"); +} + +async fn fresh_query(pool: &PgPool) { + let value: i32 = tokio::time::timeout( + Duration::from_secs(5), + sqlx::query_scalar("SELECT 1").fetch_one(pool), + ) + .await + .expect("fresh query deadline") + .expect("fresh connection works while old sessions remain stalled"); + assert_eq!(value, 1); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn dropped_writer_connections_reclaim_saturated_pool() { + let (pool, proxy, _scratch) = writer_pool(3, 0).await; + let held = hold(&pool, 3).await; + proxy.stall_established(); + drop(held); + proxy.wait_for_held_sessions(3).await; + await_capacity(&pool, 0).await; + drop(hold(&pool, 3).await); + pool.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn aborted_writer_queries_reclaim_saturated_pool() { + let (pool, proxy, _scratch) = writer_pool(3, 0).await; + let held = hold(&pool, 3).await; + proxy.stall_established(); + let tasks: Vec<_> = held + .into_iter() + .map(|mut conn| { + tokio::spawn(async move { sqlx::query("SELECT 1").execute(&mut *conn).await }) + }) + .collect(); + proxy.wait_for_held_sessions(3).await; + for task in &tasks { + task.abort(); + } + for task in tasks { + assert!(task.await.expect_err("query task aborted").is_cancelled()); + } + await_capacity(&pool, 0).await; + fresh_query(&pool).await; + pool.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn aborted_writer_begin_reclaims_slot_and_allows_committed_write() { + let (pool, proxy, scratch) = writer_pool(1, 0).await; + let observer = scratch.connect().await; + sqlx::query("CREATE TABLE release_probe (n int)") + .execute(&observer) + .await + .unwrap(); + let mut conn = pool.acquire().await.unwrap(); + proxy.stall_established(); + let task = tokio::spawn(async move { + let _tx = conn.begin().await.unwrap(); + }); + proxy.wait_for_held_sessions(1).await; + task.abort(); + assert!(task.await.expect_err("BEGIN task aborted").is_cancelled()); + await_capacity(&pool, 0).await; + sqlx::query("INSERT INTO release_probe VALUES (1)") + .execute(&pool) + .await + .unwrap(); + let committed: i32 = sqlx::query_scalar("SELECT n FROM release_probe") + .fetch_one(&observer) + .await + .expect("independent session sees commit"); + assert_eq!(committed, 1); + pool.close().await; + observer.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn transient_return_stall_reuses_healthy_writer_connection() { + let (pool, proxy, _scratch) = writer_pool(1, 0).await; + let mut conn = pool.acquire().await.unwrap(); + let before: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *conn) + .await + .unwrap(); + proxy.set_paused(true); + drop(conn); + proxy.wait_for_held_sessions(1).await; + proxy.resume_all(); + await_capacity(&pool, 1).await; + let after: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!( + before, after, + "a resumed return must reuse the healthy session" + ); + pool.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn silent_return_replenishes_writer_minimum() { + let (pool, proxy, _scratch) = writer_pool(1, 1).await; + let held = hold(&pool, 1).await; + let sessions = proxy.sessions(); + proxy.stall_established(); + drop(held); + proxy.wait_for_held_sessions(1).await; + await_capacity(&pool, 1).await; + assert!( + proxy.sessions() > sessions, + "minimum must use a new physical session" + ); + fresh_query(&pool).await; + pool.close().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn silence_after_release_hook_does_not_strand_sqlx_ping() { + let scratch = ScratchDb::create(&crate::test_support::database_url(), "release_hook").await; + let options: sqlx::postgres::PgConnectOptions = scratch.url().parse().unwrap(); + let proxy = std::sync::Arc::new( + PausingProxy::spawn(options.get_host().to_owned(), options.get_port()).await, + ); + let hook_proxy = proxy.clone(); + let first = std::sync::atomic::AtomicBool::new(true); + let pool = Db::read_pool_options(1) + .min_connections(0) + .after_release(move |conn, _| { + let proxy = hook_proxy.clone(); + let stall = first.swap(false, std::sync::atomic::Ordering::SeqCst); + Box::pin(async move { + let result = Db::reader_release_check(conn).await; + assert!(matches!(result, Ok(true)), "release hook must succeed"); + if stall { + proxy.stall_established(); + } + result + }) + }) + .connect_with(options.host("127.0.0.1").port(proxy.port)) + .await + .unwrap(); + drop(pool.acquire().await.unwrap()); + proxy.wait_for_held_sessions(1).await; + await_capacity(&pool, 0).await; + fresh_query(&pool).await; + pool.close().await; +} diff --git a/crates/buzz-db/src/test_support.rs b/crates/buzz-db/src/test_support.rs index 80d43afef7..9fc8d9fec7 100644 --- a/crates/buzz-db/src/test_support.rs +++ b/crates/buzz-db/src/test_support.rs @@ -521,6 +521,7 @@ pub(crate) struct PausingProxy { pub(crate) port: u16, hold: tokio::sync::watch::Sender, next_session: std::sync::Arc, + held_sessions: tokio::sync::watch::Sender>, } /// Which proxy sessions hold their bytes. @@ -549,6 +550,7 @@ impl PausingProxy { mut to: tokio::net::tcp::OwnedWriteHalf, mut hold: tokio::sync::watch::Receiver, session: u64, + held_sessions: tokio::sync::watch::Sender>, ) { let mut buf = [0u8; 8192]; loop { @@ -558,6 +560,9 @@ impl PausingProxy { if n == 0 { return; } + if hold.borrow().holds(session) { + held_sessions.send_if_modified(|sessions| sessions.insert(session)); + } if hold.wait_for(|hold| !hold.holds(session)).await.is_err() { return; } @@ -575,6 +580,8 @@ impl PausingProxy { let accept_hold = hold.subscribe(); let next_session = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); let accept_next = next_session.clone(); + let (held_sessions, _) = tokio::sync::watch::channel(Default::default()); + let accept_held_sessions = held_sessions.clone(); tokio::spawn(async move { while let Ok((client, _)) = listener.accept().await { let session = accept_next.fetch_add(1, Ordering::SeqCst); @@ -590,12 +597,14 @@ impl PausingProxy { server_write, accept_hold.clone(), session, + accept_held_sessions.clone(), )); tokio::spawn(pump( server_read, client_write, accept_hold.clone(), session, + accept_held_sessions.clone(), )); } }); @@ -603,9 +612,28 @@ impl PausingProxy { port, hold, next_session, + held_sessions, } } + /// Resume all previously stalled test-proxy sessions. + pub(crate) fn resume_all(&self) { + self.hold.send_replace(ProxyHold::default()); + } + + /// Wait until traffic from at least `count` distinct sessions has hit a hold. + pub(crate) async fn wait_for_held_sessions(&self, count: usize) { + tokio::time::timeout(std::time::Duration::from_secs(5), async { + self.held_sessions + .subscribe() + .wait_for(|sessions| sessions.len() >= count) + .await + .expect("proxy observations remain open"); + }) + .await + .expect("database traffic reached the proxy hold"); + } + pub(crate) fn set_paused(&self, paused: bool) { self.hold.send_modify(|hold| hold.all = paused); } diff --git a/renovate.json b/renovate.json index 91bd5fcc83..4e795e7614 100644 --- a/renovate.json +++ b/renovate.json @@ -50,6 +50,12 @@ "description": "tiptap 3.23.x breaks editor lifecycle under real relay latency — pin until upstream stabilizes.", "matchPackageNames": ["@tiptap/{/,}**"], "allowedVersions": "<3.23.0" + }, + { + "description": "Keep SQLx on the verified pool-return timeout patch until an official release retains it, cancelled-BEGIN rollback, and SQLite compatibility. Keep this rule last so later rules cannot re-enable updates.", + "matchManagers": ["cargo"], + "matchDepNames": ["sqlx", "sqlx-core", "sqlx-macros", "sqlx-macros-core", "sqlx-mysql", "sqlx-postgres", "sqlx-sqlite"], + "enabled": false } ] } diff --git a/scripts/check-sqlx-pin.py b/scripts/check-sqlx-pin.py new file mode 100644 index 0000000000..887c4e6a1c --- /dev/null +++ b/scripts/check-sqlx-pin.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Keep the SQLx recovery patch selected until an intentional upgrade (Python 3.11+).""" + +import json +import sys +import tomllib +from pathlib import Path + + +CRATES = [ + "sqlx", + "sqlx-core", + "sqlx-macros", + "sqlx-macros-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] +REVISION = "c3735abf034689bb1fab9d7bf9f040e492de28cf" +REPOSITORY = "https://github.com/launchbadge/sqlx" +VERSION = "0.9.0" + + +def check(root: Path) -> None: + manifest = tomllib.loads((root / "Cargo.toml").read_text()) + dependency = manifest["workspace"]["dependencies"]["sqlx"] + if dependency.get("version") != f"={VERSION}": + raise ValueError(f"SQLx must require exactly ={VERSION}; newer releases may omit the patch") + + patches = manifest.get("patch", {}).get("crates-io", {}) + for name in CRATES: + if patches.get(name) != {"git": REPOSITORY, "rev": REVISION}: + raise ValueError(f"{name}: preserve the reviewed SQLx Git patch") + + lock = tomllib.loads((root / "Cargo.lock").read_text()) + source = f"git+{REPOSITORY}?rev={REVISION}#{REVISION}" + for name in CRATES: + packages = [p for p in lock["package"] if p["name"] == name] + if ( + len(packages) != 1 + or packages[0].get("version") != VERSION + or packages[0].get("source") != source + ): + raise ValueError(f"{name}: Cargo.lock must contain exactly one package from the reviewed revision") + + rules = json.loads((root / "renovate.json").read_text()).get("packageRules", []) + # Renovate applies matching rules in order. The final rule must retain the + # disable, including when an earlier rule enables automerge for all crates. + required = {"matchManagers": ["cargo"], "matchDepNames": CRATES, "enabled": False} + if not rules or {k: v for k, v in rules[-1].items() if k != "description"} != required: + raise ValueError("The final Renovate rule must disable updates for all seven SQLx crates") + + +if __name__ == "__main__": + root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parents[1] + try: + check(root) + except (OSError, ValueError, KeyError, TypeError) as error: + sys.exit(f"SQLx pin check failed: {error}. Verify all required fixes before changing the pin policy.") + print("SQLx manifest, lockfile, and Renovate policy preserve the reviewed revision") diff --git a/scripts/test-sqlx-pin.py b/scripts/test-sqlx-pin.py new file mode 100644 index 0000000000..d7cd0d678f --- /dev/null +++ b/scripts/test-sqlx-pin.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Exercise the dependency guard through its real command and repository inputs.""" + +import json +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +INPUTS = {name: (ROOT / name).read_text() for name in ("Cargo.toml", "Cargo.lock", "renovate.json")} +REVISION = "c3735abf034689bb1fab9d7bf9f040e492de28cf" + + +def replace_once(text, old, new): + if old not in text: + raise AssertionError(f"missing mutation target: {old}") + return text.replace(old, new, 1) + + +def edit_rules(text, edit): + config = json.loads(text) + edit(config["packageRules"]) + return json.dumps(config) + + +class SqlxPinTests(unittest.TestCase): + def run_guard(self, filename=None, change=None): + with tempfile.TemporaryDirectory(prefix="buzz-sqlx-pin-") as directory: + root = Path(directory) + for name, text in INPUTS.items(): + (root / name).write_text(change(text) if name == filename else text) + return subprocess.run( + [sys.executable, str(ROOT / "scripts/check-sqlx-pin.py"), str(root)], + capture_output=True, + text=True, + check=False, + ) + + def test_current_repository_passes(self): + result = self.run_guard() + self.assertEqual(result.returncode, 0, result.stderr) + + def test_dependency_updates_cannot_silently_remove_the_fix(self): + cases = [ + ( + "version range", "Cargo.toml", + lambda s: replace_once(s, 'version = "=0.9.0"', 'version = "0.9"'), + "exactly", + ), + ( + "changed patch", "Cargo.toml", + lambda s: replace_once(s, REVISION, "0" * 40), "Git patch", + ), + ( + "missing patch", "Cargo.toml", + lambda s: re.sub(r'^sqlx-sqlite = .*\n', '', s, flags=re.M), "Git patch", + ), + ( + "changed lock revision", "Cargo.lock", + lambda s: replace_once(s, REVISION, "0" * 40), "Cargo.lock", + ), + ( + "registry replacement", "Cargo.lock", + lambda s: re.sub( + r'^source = "git\+https://github.com/launchbadge/sqlx[^\n]+', + 'source = "registry+https://github.com/rust-lang/crates.io-index"', + s, flags=re.M, + ), + "Cargo.lock", + ), + ( + "duplicate version", "Cargo.lock", + lambda s: s + '\n[[package]]\nname = "sqlx"\nversion = "0.9.1"\n', + "Cargo.lock", + ), + ( + "missing lock package", "Cargo.lock", + lambda s: re.sub( + r'\[\[package\]\]\nname = "sqlx-sqlite"\n.*?(?=\[\[package\]\]|\Z)', + '', s, flags=re.S, + ), + "Cargo.lock", + ), + ( + "removed Renovate rule", "renovate.json", + lambda s: edit_rules(s, lambda rules: rules.pop()), "Renovate", + ), + ( + "enabled Renovate", "renovate.json", + lambda s: edit_rules(s, lambda rules: rules[-1].update(enabled=True)), + "Renovate", + ), + ( + "omitted crate", "renovate.json", + lambda s: edit_rules(s, lambda rules: rules[-1]["matchDepNames"].pop()), + "Renovate", + ), + ( + "later override", "renovate.json", + lambda s: edit_rules(s, lambda rules: rules.append({ + "matchManagers": ["cargo"], "enabled": True, + })), + "Renovate", + ), + ( + "narrowed rule", "renovate.json", + lambda s: edit_rules(s, lambda rules: rules[-1].update(matchUpdateTypes=["major"])), + "Renovate", + ), + ] + for name, filename, change, diagnostic in cases: + with self.subTest(name=name): + self.assertNotEqual(change(INPUTS[filename]), INPUTS[filename]) + result = self.run_guard(filename, change) + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertIn(diagnostic, result.stderr) + + +if __name__ == "__main__": + unittest.main()