From 5a4e2731c7b1956592e5f149ae42f00574f94aeb Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 6 Dec 2026 07:43:16 +0000 Subject: [PATCH 1/2] fix(db): bound snapshot capture checkout by its write deadline Capture transactions now require a BoundedWriteDeadline minted only by Db::with_conn_before, so permit waits and connection checkout share the deadline pinned for the transaction. Guild snapshot capture was still checking out through Db::with_conn after that deadline was captured. Co-authored-by: JATMN --- src/db.rs | 49 ++++++++++++++++++++++++- src/db/bot_actions.rs | 14 +++---- src/db/guild_data/snapshots.rs | 10 +++-- src/db/guild_data/tests/snapshots.rs | 55 ++++++++++++++++++++++++++++ src/db/tests/remote_stream.rs | 8 ++-- src/db_compat.rs | 17 ++++++++- 6 files changed, 135 insertions(+), 18 deletions(-) diff --git a/src/db.rs b/src/db.rs index c404c669..da0cb637 100644 --- a/src/db.rs +++ b/src/db.rs @@ -30,6 +30,32 @@ use crate::types::{ CommandDef, GLOBAL_SCOPE, GuildSettings, GuildSettingsOverride, RuleDef, resolve_settings, }; +mod bounded_write { + use tokio::time::Instant; + + /// Proof that [`super::Db::with_conn_before`] bounded connection checkout by this deadline. + /// + /// [`crate::db_compat::Connection::transaction_capture_before`] accepts only this proof. + /// Pass [`crate::db_compat::DbRuntime::capture_write_deadline`] to `with_conn_before`. + /// `Db::with_conn` does not mint it, so a capture transaction cannot skip the deadline + /// while it waits for a pool permit or a connection. + #[derive(Clone, Copy)] + pub struct BoundedWriteDeadline { + deadline: Option, + } + + impl BoundedWriteDeadline { + pub(super) fn mint(deadline: Option) -> Self { + Self { deadline } + } + + pub(crate) fn instant(self) -> Option { + self.deadline + } + } +} +pub(crate) use bounded_write::BoundedWriteDeadline; + mod primary_outage; use primary_outage::{Admission, PrimaryBackoff, PrimaryOutageGate, PrimaryOutageReported}; @@ -1600,10 +1626,29 @@ impl Db { F: FnOnce(&mut Connection) -> Result + Send + 'static, T: Send + 'static, { - self.with_conn_before(None, f).await + self.with_conn_deadline(None, f).await + } + + /// Runs `f` after bounding permit waits and connection checkout by `write_deadline`. + /// + /// The closure receives a [`BoundedWriteDeadline`]. Capture transactions accept + /// only that proof, so `DbRuntime::capture_write_deadline` must be passed here + /// instead of into `Db::with_conn`. + pub(crate) async fn with_conn_before( + &self, + write_deadline: Option, + f: F, + ) -> Result + where + F: FnOnce(&mut Connection, BoundedWriteDeadline) -> Result + Send + 'static, + T: Send + 'static, + { + let bounded = bounded_write::BoundedWriteDeadline::mint(write_deadline); + self.with_conn_deadline(write_deadline, move |conn| f(conn, bounded)) + .await } - async fn with_conn_before( + async fn with_conn_deadline( &self, write_deadline: Option, f: F, diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs index 931e3cc4..bb28d634 100644 --- a/src/db/bot_actions.rs +++ b/src/db/bot_actions.rs @@ -473,12 +473,12 @@ pub async fn claim_advised_bot_action(db: &Db, now: i64) -> Result Result, + write_deadline: super::BoundedWriteDeadline, #[cfg(test)] after_due_read: Option, ) -> Result> { let mut tx = if promote { conn.transaction_capture_before(write_deadline, false)? } else { - conn.transaction_primary_snapshot_before(write_deadline)? + conn.transaction_primary_snapshot_before(write_deadline.instant())? }; let due: bool = tx.query_row(&poll_due_sql(), params![now], |r| Ok(r.get(0)?))?; if !due { @@ -539,7 +539,7 @@ fn claim_advised_bot_action_conn( tx } else { tx.finish_read()?; - conn.transaction_immediate_before(write_deadline)? + conn.transaction_immediate_before(write_deadline.instant())? }; claim_bot_action_tx(tx, now) } diff --git a/src/db/guild_data/snapshots.rs b/src/db/guild_data/snapshots.rs index c3196e33..3fb14a37 100644 --- a/src/db/guild_data/snapshots.rs +++ b/src/db/guild_data/snapshots.rs @@ -514,16 +514,18 @@ impl GuildDataStore { let first = operation.clone(); match self .db - .with_conn(move |conn| first(conn.transaction_capture_before(deadline, false)?)) + .with_conn_before(deadline, move |conn, bounded| { + first(conn.transaction_capture_before(bounded, false)?) + }) .await { Err(error) if crate::db_compat::is_database_busy(&error) => { - // The failed transaction was rolled back before with_conn + // The failed transaction was rolled back before checkout // returned. Re-read everything under the existing writer path // once, instead of repeatedly trying to promote stale reads. self.db - .with_conn(move |conn| { - operation(conn.transaction_capture_before(deadline, true)?) + .with_conn_before(deadline, move |conn, bounded| { + operation(conn.transaction_capture_before(bounded, true)?) }) .await } diff --git a/src/db/guild_data/tests/snapshots.rs b/src/db/guild_data/tests/snapshots.rs index 2e9344fd..cd2ff96f 100644 --- a/src/db/guild_data/tests/snapshots.rs +++ b/src/db/guild_data/tests/snapshots.rs @@ -1404,3 +1404,58 @@ async fn remote_capture_keeps_the_pooled_write_deadline_through_commit_and_retry fixture.assert_committed_within_lifetime(0); } } + +#[tokio::test(start_paused = true)] +async fn remote_capture_permit_wait_uses_the_captured_write_deadline() { + let (f, _, local, scope) = ready().await; + let (fixture, _) = HranaFixture::modeled_latency_database( + &f.store_path, + Duration::ZERO, + Duration::from_secs(5), + Default::default(), + ) + .await; + let write_limit = Duration::from_millis(100); + let remote = GuildDataStore { + db: fixture.db_with_operation_timeout(write_limit), + expected: local.expected.clone(), + core: None, + }; + let clock = crate::db_compat::ManualClock::new(); + remote + .db + .runtime + .install_manual_clock(Some(std::sync::Arc::clone(&clock))); + let _held = std::sync::Arc::clone(&remote.db.permits) + .try_acquire_many_owned(2) + .unwrap(); + let capture = remote.observe_snapshot(scope, observation(41, Some("queued"), None, 1)); + tokio::pin!(capture); + + tokio::select! { + biased; + result = &mut capture => panic!("capture returned before checkout queued: {result:?}"), + () = std::future::ready(()) => {} + } + clock.advance(write_limit - Duration::from_millis(1)); + tokio::select! { + biased; + result = &mut capture => panic!("checkout returned before the write deadline: {result:?}"), + () = std::future::ready(()) => {} + } + clock.advance(Duration::from_millis(1)); + let error = tokio::select! { + biased; + result = &mut capture => result.expect_err("capture succeeded at the deadline"), + () = std::future::ready(()) => panic!("capture still waiting at the captured write deadline"), + }; + + assert_eq!( + crate::db_compat::local_database_timeout_operation(&error), + Some(crate::db::WAIT_FOR_CONNECTION), + "{error:#}" + ); + assert_eq!(remote.db.connections.outage.failure_count(), 0); + assert!(fixture.take_statements().is_empty(), "capture started SQL"); + assert_eq!(remote.db.permits.available_permits(), 0); +} diff --git a/src/db/tests/remote_stream.rs b/src/db/tests/remote_stream.rs index ef126902..c64da020 100644 --- a/src/db/tests/remote_stream.rs +++ b/src/db/tests/remote_stream.rs @@ -2003,8 +2003,8 @@ async fn capture_promotes_after_the_read_deadline_within_the_write_budget() { let deadline = remote.connections.runtime.capture_write_deadline(); remote - .with_conn(move |conn| { - let mut tx = conn.transaction_capture_before(deadline, false)?; + .with_conn_before(deadline, move |conn, bounded| { + let mut tx = conn.transaction_capture_before(bounded, false)?; let _: i64 = tx.query_row("SELECT 1", (), |row| Ok(row.get(0)?))?; // The final read succeeded before the interactive deadline. clock.advance(crate::db_compat::INTERACTIVE_READ_BUDGET + Duration::from_millis(500)); @@ -2041,8 +2041,8 @@ async fn expired_capture_cannot_prepare_growth_or_reclaim_receipts() { let clock = Arc::clone(&clock); let deadline = remote.runtime.capture_write_deadline(); let error = remote - .with_conn(move |conn| { - let mut tx = conn.transaction_capture_before(deadline, false)?; + .with_conn_before(deadline, move |conn, bounded| { + let mut tx = conn.transaction_capture_before(bounded, false)?; let _: i64 = tx.query_row("SELECT 1", (), |row| Ok(row.get(0)?))?; // Preflight returned successfully, then the budget expired // before the first required write. diff --git a/src/db_compat.rs b/src/db_compat.rs index b0bd1ab5..b16fe0f5 100644 --- a/src/db_compat.rs +++ b/src/db_compat.rs @@ -1956,8 +1956,23 @@ impl Connection { /// Snapshot capture reads before acquiring the writer lock. A concurrent /// writer can invalidate promotion; the capture owner must restart the /// entire operation on a proven busy error, never reuse the read results. + /// + /// Requires a [`crate::db::BoundedWriteDeadline`] from + /// [`crate::db::Db::with_conn_before`] so connection checkout, permit waits, and + /// recovery probes share the same pinned write deadline. Pass + /// [`DbRuntime::capture_write_deadline`] to that checkout; a raw instant cannot + /// open this transaction. #[track_caller] pub(crate) fn transaction_capture_before( + &self, + write_deadline: crate::db::BoundedWriteDeadline, + immediate: bool, + ) -> Result { + self.transaction_capture_with_deadline(write_deadline.instant(), immediate) + } + + #[track_caller] + fn transaction_capture_with_deadline( &self, write_deadline: Option, immediate: bool, @@ -4109,7 +4124,7 @@ mod tests { .unwrap(); let writer = Connection::open(&path).unwrap(); let mut capture = reader - .transaction_capture_before(reader.runtime.capture_write_deadline(), false) + .transaction_capture_with_deadline(reader.runtime.capture_write_deadline(), false) .unwrap(); let before: i64 = capture .query_row("SELECT value FROM counter", (), |r| Ok(r.get(0)?)) From fcd249a5276f7f5f3b03eba92643872074a36f72 Mon Sep 17 00:00:00 2001 From: jatmn Date: Sun, 6 Dec 2026 07:50:21 -0800 Subject: [PATCH 2/2] fix(db): bind capture to its deadline-aware checkout --- src/db.rs | 68 ++++++++++++++++------------------ src/db/bot_actions.rs | 16 ++++---- src/db/guild_data/snapshots.rs | 8 ++-- src/db/tests/remote_stream.rs | 25 +++++++++++-- src/db_compat.rs | 35 +++++++++-------- 5 files changed, 81 insertions(+), 71 deletions(-) diff --git a/src/db.rs b/src/db.rs index da0cb637..441be9cc 100644 --- a/src/db.rs +++ b/src/db.rs @@ -31,30 +31,45 @@ use crate::types::{ }; mod bounded_write { + use super::{Connection, Db, Result}; use tokio::time::Instant; - /// Proof that [`super::Db::with_conn_before`] bounded connection checkout by this deadline. - /// - /// [`crate::db_compat::Connection::transaction_capture_before`] accepts only this proof. - /// Pass [`crate::db_compat::DbRuntime::capture_write_deadline`] to `with_conn_before`. - /// `Db::with_conn` does not mint it, so a capture transaction cannot skip the deadline - /// while it waits for a pool permit or a connection. - #[derive(Clone, Copy)] - pub struct BoundedWriteDeadline { - deadline: Option, - } - - impl BoundedWriteDeadline { - pub(super) fn mint(deadline: Option) -> Self { - Self { deadline } + /// Borrows the connection checked out by [`Db::with_conn_before`] with its deadline. + pub(crate) struct BoundedConnection<'conn> { + connection: &'conn Connection, + write_deadline: Option, + } + + impl BoundedConnection<'_> { + pub(crate) fn connection_and_deadline(&self) -> (&Connection, Option) { + (self.connection, self.write_deadline) } + } - pub(crate) fn instant(self) -> Option { - self.deadline + impl Db { + /// Applies the pinned write deadline to pool waits, checkout, and the connection + /// passed to `f`. Use [`crate::db_compat::DbRuntime::capture_write_deadline`] + /// to pin the deadline before the first checkout attempt. + pub(crate) async fn with_conn_before( + &self, + write_deadline: Option, + f: F, + ) -> Result + where + F: FnOnce(BoundedConnection<'_>) -> Result + Send + 'static, + T: Send + 'static, + { + self.with_conn_deadline(write_deadline, move |connection| { + f(BoundedConnection { + connection, + write_deadline, + }) + }) + .await } } } -pub(crate) use bounded_write::BoundedWriteDeadline; +pub(crate) use bounded_write::BoundedConnection; mod primary_outage; use primary_outage::{Admission, PrimaryBackoff, PrimaryOutageGate, PrimaryOutageReported}; @@ -1629,25 +1644,6 @@ impl Db { self.with_conn_deadline(None, f).await } - /// Runs `f` after bounding permit waits and connection checkout by `write_deadline`. - /// - /// The closure receives a [`BoundedWriteDeadline`]. Capture transactions accept - /// only that proof, so `DbRuntime::capture_write_deadline` must be passed here - /// instead of into `Db::with_conn`. - pub(crate) async fn with_conn_before( - &self, - write_deadline: Option, - f: F, - ) -> Result - where - F: FnOnce(&mut Connection, BoundedWriteDeadline) -> Result + Send + 'static, - T: Send + 'static, - { - let bounded = bounded_write::BoundedWriteDeadline::mint(write_deadline); - self.with_conn_deadline(write_deadline, move |conn| f(conn, bounded)) - .await - } - async fn with_conn_deadline( &self, write_deadline: Option, diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs index bb28d634..71424629 100644 --- a/src/db/bot_actions.rs +++ b/src/db/bot_actions.rs @@ -473,12 +473,11 @@ pub async fn claim_advised_bot_action(db: &Db, now: i64) -> Result Result Result, now: i64, promote: bool, - write_deadline: super::BoundedWriteDeadline, #[cfg(test)] after_due_read: Option, ) -> Result> { + let (connection, deadline) = conn.connection_and_deadline(); let mut tx = if promote { - conn.transaction_capture_before(write_deadline, false)? + conn.transaction_capture(false)? } else { - conn.transaction_primary_snapshot_before(write_deadline.instant())? + connection.transaction_primary_snapshot_before(deadline)? }; let due: bool = tx.query_row(&poll_due_sql(), params![now], |r| Ok(r.get(0)?))?; if !due { @@ -539,7 +537,7 @@ fn claim_advised_bot_action_conn( tx } else { tx.finish_read()?; - conn.transaction_immediate_before(write_deadline.instant())? + connection.transaction_immediate_before(deadline)? }; claim_bot_action_tx(tx, now) } diff --git a/src/db/guild_data/snapshots.rs b/src/db/guild_data/snapshots.rs index 3fb14a37..908d81a1 100644 --- a/src/db/guild_data/snapshots.rs +++ b/src/db/guild_data/snapshots.rs @@ -514,8 +514,8 @@ impl GuildDataStore { let first = operation.clone(); match self .db - .with_conn_before(deadline, move |conn, bounded| { - first(conn.transaction_capture_before(bounded, false)?) + .with_conn_before(deadline, move |conn| { + first(conn.transaction_capture(false)?) }) .await { @@ -524,8 +524,8 @@ impl GuildDataStore { // returned. Re-read everything under the existing writer path // once, instead of repeatedly trying to promote stale reads. self.db - .with_conn_before(deadline, move |conn, bounded| { - operation(conn.transaction_capture_before(bounded, true)?) + .with_conn_before(deadline, move |conn| { + operation(conn.transaction_capture(true)?) }) .await } diff --git a/src/db/tests/remote_stream.rs b/src/db/tests/remote_stream.rs index c64da020..07dbe1e2 100644 --- a/src/db/tests/remote_stream.rs +++ b/src/db/tests/remote_stream.rs @@ -1993,6 +1993,23 @@ async fn slow_advised_due_check_leaves_time_to_prepare_the_claim() { super::cleanup_db(&path); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn remote_capture_requires_a_checkout_write_deadline() { + let fixture = HranaFixture::start().await; + let remote = fixture.db_with_operation_timeout(Duration::from_secs(5)); + + let error = remote + .with_conn_before(None, |conn| conn.transaction_capture(false)?.finish_read()) + .await + .unwrap_err(); + + assert_eq!( + error.to_string(), + "remote capture requires a checkout write deadline" + ); + assert!(fixture.take_statements().is_empty(), "capture started SQL"); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn capture_promotes_after_the_read_deadline_within_the_write_budget() { let path = super::tmp_db_path("remote_capture_promotion"); @@ -2003,8 +2020,8 @@ async fn capture_promotes_after_the_read_deadline_within_the_write_budget() { let deadline = remote.connections.runtime.capture_write_deadline(); remote - .with_conn_before(deadline, move |conn, bounded| { - let mut tx = conn.transaction_capture_before(bounded, false)?; + .with_conn_before(deadline, move |conn| { + let mut tx = conn.transaction_capture(false)?; let _: i64 = tx.query_row("SELECT 1", (), |row| Ok(row.get(0)?))?; // The final read succeeded before the interactive deadline. clock.advance(crate::db_compat::INTERACTIVE_READ_BUDGET + Duration::from_millis(500)); @@ -2041,8 +2058,8 @@ async fn expired_capture_cannot_prepare_growth_or_reclaim_receipts() { let clock = Arc::clone(&clock); let deadline = remote.runtime.capture_write_deadline(); let error = remote - .with_conn_before(deadline, move |conn, bounded| { - let mut tx = conn.transaction_capture_before(bounded, false)?; + .with_conn_before(deadline, move |conn| { + let mut tx = conn.transaction_capture(false)?; let _: i64 = tx.query_row("SELECT 1", (), |row| Ok(row.get(0)?))?; // Preflight returned successfully, then the budget expired // before the first required write. diff --git a/src/db_compat.rs b/src/db_compat.rs index b16fe0f5..0febcd28 100644 --- a/src/db_compat.rs +++ b/src/db_compat.rs @@ -1953,24 +1953,6 @@ impl Connection { Ok(transaction) } - /// Snapshot capture reads before acquiring the writer lock. A concurrent - /// writer can invalidate promotion; the capture owner must restart the - /// entire operation on a proven busy error, never reuse the read results. - /// - /// Requires a [`crate::db::BoundedWriteDeadline`] from - /// [`crate::db::Db::with_conn_before`] so connection checkout, permit waits, and - /// recovery probes share the same pinned write deadline. Pass - /// [`DbRuntime::capture_write_deadline`] to that checkout; a raw instant cannot - /// open this transaction. - #[track_caller] - pub(crate) fn transaction_capture_before( - &self, - write_deadline: crate::db::BoundedWriteDeadline, - immediate: bool, - ) -> Result { - self.transaction_capture_with_deadline(write_deadline.instant(), immediate) - } - #[track_caller] fn transaction_capture_with_deadline( &self, @@ -2175,6 +2157,23 @@ impl Connection { } } +impl crate::db::BoundedConnection<'_> { + /// Opens capture on the connection supplied by [`crate::db::Db::with_conn_before`]. + /// + /// Deferred capture reads before acquiring the writer lock. A concurrent + /// writer can invalidate promotion. On a proven busy error, the capture + /// owner restarts the entire operation using the original write deadline. + #[track_caller] + pub(crate) fn transaction_capture(&self, immediate: bool) -> Result { + let (connection, write_deadline) = self.connection_and_deadline(); + anyhow::ensure!( + write_deadline.is_some() || !connection.runtime.is_remote(), + "remote capture requires a checkout write deadline" + ); + connection.transaction_capture_with_deadline(write_deadline, immediate) + } +} + impl SqlExecutor for Connection { fn execute(&self, sql: &str, params: impl IntoParams + Send) -> Result { require_read_sql(sql)?;