diff --git a/docs/server-reference.md b/docs/server-reference.md index 5b418c1b1..2d4902996 100644 --- a/docs/server-reference.md +++ b/docs/server-reference.md @@ -2486,9 +2486,11 @@ how many request workers are busy. ([#1368](https://github.com/durable-workflow/server/issues/1368)). A release that holds a held poll's budget slot frees it within about 5 seconds of reset plus 5 seconds of release ping, well within the 30-second - transition queue deadline. Writes are not bounded this way: a request - larger than the socket's send buffer can still wait on a peer that stopped - reading until the operating system gives up on it. + transition queue deadline. Socket flushes for statement writes and release + commands share the same bound (45 seconds for statements, 5 seconds for + release), so a large send to a peer that has stopped reading also fails + within the bound and discards the connection + ([#1385](https://github.com/durable-workflow/server/issues/1385)). A healthy server always replies sooner: PostgreSQL ends every statement on these connections after 30 seconds (`statement_timeout`, first-start migrations included), and MySQL and MariaDB refuse lock waits after 5 diff --git a/rust/src/runtime/mysql_stall_tests.rs b/rust/src/runtime/mysql_stall_tests.rs index fe0825cb8..446c8d75d 100644 --- a/rust/src/runtime/mysql_stall_tests.rs +++ b/rust/src/runtime/mysql_stall_tests.rs @@ -525,3 +525,52 @@ async fn qualification_a_release_on_a_silent_peer_ends_within_its_reply_bound() assert!(super::super::backend::RELEASE_REPLY_BOUND <= acquire); assert!(super::super::backend::RELEASE_REPLY_BOUND < super::super::store::TRANSITION_QUEUE_DEADLINE); } + +/// Server #1385, non-reading peer during a large write: the proxy stops reading +/// from the client, and a payload larger than the loopback socket buffers +/// stalls in `flush`. The send fails within the statement bound with `TimedOut` +/// and the connection is discarded. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires disposable MySQL/MariaDB; run qualification_ explicitly"] +async fn qualification_a_large_write_to_a_non_reading_peer_fails_within_its_bound() { + let (pool, gate, proxy) = silent_peer_pool(SHORT_REPLIES).await; + let qualified = tokio::time::timeout(Duration::from_secs(30), async { + let mut connection = pool.acquire().await.unwrap(); + let silent = session_id(&mut connection).await; + // Prepare the statement before stalling so the stalled send goes + // straight into flushing the large parameter. + let warm: i64 = sqlx::query_scalar("SELECT OCTET_LENGTH(?)") + .bind(vec![b'x'; 1]) + .fetch_one(&mut *connection) + .await + .unwrap(); + assert_eq!(warm, 1); + gate.hold_upstream.store(true, Ordering::SeqCst); + let payload = vec![b'x'; 24 * 1024 * 1024]; + let started = Instant::now(); + let outcome = sqlx::query_scalar::<_, i64>("SELECT OCTET_LENGTH(?)") + .bind(payload) + .fetch_one(&mut *connection) + .await; + let waited = started.elapsed(); + assert!( + matches!(&outcome, Err(sqlx::Error::Io(error)) if error.kind() == std::io::ErrorKind::TimedOut && error.to_string().contains("did not accept a write")), + "a non-reading peer fails the write flush: {outcome:?}" + ); + assert!( + waited >= SHORT_REPLIES.statement - Duration::from_millis(100) + && waited < SHORT_REPLIES.statement + Duration::from_secs(2), + "within the statement bound: {waited:?}" + ); + let returned = Instant::now(); + connection.return_to_pool().await; + assert!(returned.elapsed() < Duration::from_secs(1), "a connection out of step is discarded at once"); + gate.release(); + let mut replacement = tokio::time::timeout(Duration::from_secs(10), pool.acquire()).await + .expect("the stalled connection's slot returns").unwrap(); + assert_ne!(session_id(&mut replacement).await, silent, "the stalled connection was discarded"); + }) + .await; + close_silent_peer_pool(pool, gate, proxy).await; + qualified.expect("bounded large-write qualification"); +} diff --git a/rust/src/runtime/postgres.rs b/rust/src/runtime/postgres.rs index 99ce1cbcd..8dabe3bc8 100644 --- a/rust/src/runtime/postgres.rs +++ b/rust/src/runtime/postgres.rs @@ -1348,6 +1348,56 @@ mod tests { qualified.expect("bounded release silent-peer qualification"); } + /// Server #1385, non-reading peer during a large write: the proxy stops + /// reading from the client, and a payload larger than the loopback socket + /// buffers stalls in `flush`. The send fails within the statement bound + /// with `TimedOut` and the connection is discarded. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + #[ignore = "requires disposable PostgreSQL; run qualification_ explicitly"] + async fn qualification_a_large_write_to_a_non_reading_peer_fails_within_its_bound() { + use std::sync::atomic::Ordering; + let db = Database::new().await; + let peer = silent_peer_pool(&db, SHORT_REPLIES).await; + let (pool, gate) = (&peer.0, &peer.1); + let qualified = tokio::time::timeout(Duration::from_secs(30), async { + let mut connection = pool.acquire().await.unwrap(); + let silent = backend_pid(&mut connection).await; + let warm: i32 = sqlx::query_scalar("SELECT octet_length($1)") + .bind(vec![b'x'; 1]) + .fetch_one(&mut *connection) + .await + .unwrap(); + assert_eq!(warm, 1); + gate.hold_upstream.store(true, Ordering::SeqCst); + let payload = vec![b'x'; 24 * 1024 * 1024]; + let started = tokio::time::Instant::now(); + let outcome = sqlx::query_scalar::<_, i32>("SELECT octet_length($1)") + .bind(payload) + .fetch_one(&mut *connection) + .await; + let waited = started.elapsed(); + assert!( + matches!(&outcome, Err(sqlx::Error::Io(error)) if error.kind() == std::io::ErrorKind::TimedOut && error.to_string().contains("did not accept a write")), + "a non-reading peer fails the write flush: {outcome:?}" + ); + assert!( + waited >= SHORT_REPLIES.statement - Duration::from_millis(100) + && waited < SHORT_REPLIES.statement + Duration::from_secs(2), + "within the statement bound: {waited:?}" + ); + let returned = tokio::time::Instant::now(); + connection.return_to_pool().await; + assert!(returned.elapsed() < Duration::from_secs(1), "a connection out of step is discarded at once"); + gate.release(); + let mut replacement = tokio::time::timeout(Duration::from_secs(10), pool.acquire()).await + .expect("the stalled connection's slot returns").unwrap(); + assert_ne!(backend_pid(&mut replacement).await, silent, "the stalled connection was discarded"); + }) + .await; + close_silent_peer_pool(peer, db).await; + qualified.expect("bounded large-write qualification"); + } + fn refused(result: Result, expected: &str) { match result { Err(super::super::RuntimeError::Refused { reason, .. }) => assert_eq!(reason, expected), diff --git a/rust/src/runtime/test_reply_gate.rs b/rust/src/runtime/test_reply_gate.rs index 716cc807c..8c8d574bc 100644 --- a/rust/src/runtime/test_reply_gate.rs +++ b/rust/src/runtime/test_reply_gate.rs @@ -11,6 +11,7 @@ use tokio::{ #[derive(Default)] pub(crate) struct ReplyGate { pub(crate) hold: AtomicBool, + pub(crate) hold_upstream: AtomicBool, pub(crate) blocked: Notify, released: Notify, } @@ -18,6 +19,7 @@ pub(crate) struct ReplyGate { impl ReplyGate { pub(crate) fn release(&self) { self.hold.store(false, Ordering::SeqCst); + self.hold_upstream.store(false, Ordering::SeqCst); self.released.notify_waiters(); } } @@ -50,7 +52,22 @@ pub(crate) async fn forward(listener: TcpListener, upstream: String, gate: Arc, std::io::Result<()>) = tokio::join!(downstream, upstream); diff --git a/rust/vendor/sqlx-mysql/DURABLE-PATCH.md b/rust/vendor/sqlx-mysql/DURABLE-PATCH.md index ea5340384..8c49be8c2 100644 --- a/rust/vendor/sqlx-mysql/DURABLE-PATCH.md +++ b/rust/vendor/sqlx-mysql/DURABLE-PATCH.md @@ -199,12 +199,15 @@ fails at once with the same I/O `TimedOut` error, so the pool discards the connection even if the replies turn up later. With neither set, reads are unchanged. Native Server sets 45 seconds for statements and 5 seconds for the session reset and release ping, and lifts it for the namespace delete and -per-run retention prune, which have no row bound. Writes are not bounded: a -send larger than the socket buffer can still wait on a peer that stopped -reading. - -`runtime::mysql::stall_tests::qualification_a_statement_in_flight_on_a_silent_peer_fails_within_its_reply_bound` -and `qualification_a_release_on_a_silent_peer_ends_within_its_reply_bound` +per-run retention prune, which have no row bound. Socket flushes +(`MySqlStream::flush`, also used by `flush_queued`, `wait_until_ready`, and +`send_packet`) share the same bound (`reply_deadline` / `reply_timeout`) so a +large write to a peer that stopped reading also times out, sets `reply_failed`, +and causes the pool to discard the connection (Server #1385). + +`runtime::mysql::stall_tests::qualification_a_statement_in_flight_on_a_silent_peer_fails_within_its_reply_bound`, +`qualification_a_release_on_a_silent_peer_ends_within_its_reply_bound`, and +`qualification_a_large_write_to_a_non_reading_peer_fails_within_its_bound` hold every reply and require the statement, and the return to the pool, to end within a shortened bound and the connection to be replaced. Remove this change only when a reviewed published driver lets a caller bound each read, diff --git a/rust/vendor/sqlx-mysql/src/connection/stream.rs b/rust/vendor/sqlx-mysql/src/connection/stream.rs index cbfd14fc5..f1c5cda71 100755 --- a/rust/vendor/sqlx-mysql/src/connection/stream.rs +++ b/rust/vendor/sqlx-mysql/src/connection/stream.rs @@ -96,12 +96,67 @@ impl MySqlStream { /// path before the next command leaves queued closes to share its write. pub(crate) async fn flush_queued(&mut self) -> Result<(), Error> { if !self.socket.write_buffer().is_empty() { - self.socket.flush().await?; + self.flush().await?; } self.queued_unanswered = false; Ok(()) } + /// Flush buffered writes to the database, bounded by `reply_deadline` and + /// `reply_timeout` when set (Durable Workflow Server #1385). A flush that + /// stalls on a non-reading peer sets `reply_failed` so the connection is + /// discarded. + pub(crate) async fn flush(&mut self) -> Result<(), Error> { + if self.reply_failed { + return Err(unanswered_reply()); + } + let now = std::time::Instant::now(); + let deadline = match (self.reply_deadline, self.reply_timeout) { + (None, None) => return Ok(self.socket.flush().await?), + (Some(deadline), None) => deadline, + (None, Some(timeout)) => now + timeout, + (Some(deadline), Some(timeout)) => deadline.min(now + timeout), + }; + let remaining = deadline.saturating_duration_since(now); + let flushed = if remaining.is_zero() { + None + } else { + sqlx_core::rt::timeout(remaining, self.socket.flush()).await.ok() + }; + let Some(result) = flushed else { + self.reply_failed = true; + return Err(write_timed_out()); + }; + Ok(result?) + } + + /// Shut down the socket, failing immediately if a prior read or write + /// already timed out and otherwise honoring the same bound (Durable + /// Workflow Server #1385). + pub(crate) async fn shutdown(&mut self) -> Result<(), Error> { + if self.reply_failed { + return Err(unanswered_reply()); + } + let now = std::time::Instant::now(); + let deadline = match (self.reply_deadline, self.reply_timeout) { + (None, None) => return Ok(self.socket.shutdown().await?), + (Some(deadline), None) => deadline, + (None, Some(timeout)) => now + timeout, + (Some(deadline), Some(timeout)) => deadline.min(now + timeout), + }; + let remaining = deadline.saturating_duration_since(now); + let closed = if remaining.is_zero() { + None + } else { + sqlx_core::rt::timeout(remaining, self.socket.shutdown()).await.ok() + }; + let Some(result) = closed else { + self.reply_failed = true; + return Err(write_timed_out()); + }; + Ok(result?) + } + pub(crate) fn record_status(&mut self, status: Status) { self.status = status; self.status_known = true; @@ -111,7 +166,7 @@ impl MySqlStream { // Queued commands without a reply wait for the next command; nothing // pending needs them to be sent first. if !self.socket.write_buffer().is_empty() && !self.queued_unanswered { - self.socket.flush().await?; + self.flush().await?; } while !self.waiting.is_empty() { @@ -345,3 +400,13 @@ pub(crate) fn unanswered_reply() -> Error { "the database sent no reply within the connection's reply bound", )) } + +/// A write flush stalled past the connection's bound on a peer that stopped +/// reading (Durable Workflow Server #1385). The session is out of step and +/// discarded. +fn write_timed_out() -> Error { + Error::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "the database did not accept a write within the connection's bound", + )) +} diff --git a/rust/vendor/sqlx-postgres/DURABLE-PATCH.md b/rust/vendor/sqlx-postgres/DURABLE-PATCH.md index bab449bf7..60c8e4ce3 100644 --- a/rust/vendor/sqlx-postgres/DURABLE-PATCH.md +++ b/rust/vendor/sqlx-postgres/DURABLE-PATCH.md @@ -107,12 +107,15 @@ runs past either sets `reply_failed`, and every later read fails at once with the same I/O `TimedOut` error, so the pool discards the connection. The read stays cancel-safe. With neither set, reads are unchanged. Native Server sets 45 seconds for statements, which `statement_timeout` (30 s) ends sooner on a -healthy server, and 5 seconds for the release ping. Writes are not bounded: -a send larger than the socket buffer can still wait on a peer that stopped -reading. - -`runtime::postgres::tests::qualification_a_statement_in_flight_on_a_silent_peer_fails_within_its_reply_bound` -and `qualification_a_release_on_a_silent_peer_ends_within_its_reply_bound` +healthy server, and 5 seconds for the release ping. Socket flushes +(`PgStream::flush`, used by `send` and every executor/connection flush) share +the same bound (`reply_deadline` / `reply_timeout`) so a large write to a peer +that stopped reading also times out, sets `reply_failed`, and causes the pool +to discard the connection (Server #1385). + +`runtime::postgres::tests::qualification_a_statement_in_flight_on_a_silent_peer_fails_within_its_reply_bound`, +`qualification_a_release_on_a_silent_peer_ends_within_its_reply_bound`, and +`qualification_a_large_write_to_a_non_reading_peer_fails_within_its_bound` hold every reply and require the statement, and the return to the pool, to end within a shortened bound and the connection to be replaced. Remove this change only when a reviewed published driver lets a caller bound each read, diff --git a/rust/vendor/sqlx-postgres/src/connection/stream.rs b/rust/vendor/sqlx-postgres/src/connection/stream.rs index 509be30c4..52f95ebf9 100755 --- a/rust/vendor/sqlx-postgres/src/connection/stream.rs +++ b/rust/vendor/sqlx-postgres/src/connection/stream.rs @@ -81,6 +81,61 @@ impl PgStream { self.write(EncodeMessage(message)) } + /// Flush buffered writes to the database, bounded by `reply_deadline` and + /// `reply_timeout` when set (Durable Workflow Server #1385). A flush that + /// stalls on a non-reading peer sets `reply_failed` so the connection is + /// discarded. + pub(crate) async fn flush(&mut self) -> Result<(), Error> { + if self.reply_failed { + return Err(unanswered_reply()); + } + let now = std::time::Instant::now(); + let deadline = match (self.reply_deadline, self.reply_timeout) { + (None, None) => return Ok(self.inner.flush().await?), + (Some(deadline), None) => deadline, + (None, Some(timeout)) => now + timeout, + (Some(deadline), Some(timeout)) => deadline.min(now + timeout), + }; + let remaining = deadline.saturating_duration_since(now); + let flushed = if remaining.is_zero() { + None + } else { + sqlx_core::rt::timeout(remaining, self.inner.flush()).await.ok() + }; + let Some(result) = flushed else { + self.reply_failed = true; + return Err(write_timed_out()); + }; + Ok(result?) + } + + /// Shut down the socket, failing immediately if a prior read or write + /// already timed out and otherwise honoring the same bound (Durable + /// Workflow Server #1385). + pub(crate) async fn shutdown(&mut self) -> Result<(), Error> { + if self.reply_failed { + return Err(unanswered_reply()); + } + let now = std::time::Instant::now(); + let deadline = match (self.reply_deadline, self.reply_timeout) { + (None, None) => return Ok(self.inner.shutdown().await?), + (Some(deadline), None) => deadline, + (None, Some(timeout)) => now + timeout, + (Some(deadline), Some(timeout)) => deadline.min(now + timeout), + }; + let remaining = deadline.saturating_duration_since(now); + let closed = if remaining.is_zero() { + None + } else { + sqlx_core::rt::timeout(remaining, self.inner.shutdown()).await.ok() + }; + let Some(result) = closed else { + self.reply_failed = true; + return Err(write_timed_out()); + }; + Ok(result?) + } + pub(crate) async fn send(&mut self, message: T) -> Result<(), Error> where T: FrontendMessage, @@ -336,3 +391,13 @@ fn unanswered_reply() -> Error { "the database sent no reply within the connection's reply bound", )) } + +/// A write flush stalled past the connection's bound on a peer that stopped +/// reading (Durable Workflow Server #1385). The session is out of step and +/// discarded. +fn write_timed_out() -> Error { + Error::Io(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "the database did not accept a write within the connection's bound", + )) +}