Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions docs/server-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
49 changes: 49 additions & 0 deletions rust/src/runtime/mysql_stall_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
50 changes: 50 additions & 0 deletions rust/src/runtime/postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PostgresStorage>, expected: &str) {
match result {
Err(super::super::RuntimeError::Refused { reason, .. }) => assert_eq!(reason, expected),
Expand Down
19 changes: 18 additions & 1 deletion rust/src/runtime/test_reply_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ use tokio::{
#[derive(Default)]
pub(crate) struct ReplyGate {
pub(crate) hold: AtomicBool,
pub(crate) hold_upstream: AtomicBool,
pub(crate) blocked: Notify,
released: Notify,
}

impl ReplyGate {
pub(crate) fn release(&self) {
self.hold.store(false, Ordering::SeqCst);
self.hold_upstream.store(false, Ordering::SeqCst);
self.released.notify_waiters();
}
}
Expand Down Expand Up @@ -50,7 +52,22 @@ pub(crate) async fn forward(listener: TcpListener, upstream: String, gate: Arc<R
client_write.shutdown().await
};
let upstream = async {
tokio::io::copy(&mut client_read, &mut server_write).await?;
let mut bytes = [0; 65536];
loop {
while gate.hold_upstream.load(Ordering::SeqCst) {
let release = gate.released.notified();
gate.blocked.notify_one();
if !gate.hold_upstream.load(Ordering::SeqCst) {
break;
}
release.await;
}
let count = client_read.read(&mut bytes).await?;
if count == 0 {
break;
}
server_write.write_all(&bytes[..count]).await?;
}
server_write.shutdown().await
};
let _: (std::io::Result<()>, std::io::Result<()>) = tokio::join!(downstream, upstream);
Expand Down
15 changes: 9 additions & 6 deletions rust/vendor/sqlx-mysql/DURABLE-PATCH.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
69 changes: 67 additions & 2 deletions rust/vendor/sqlx-mysql/src/connection/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,67 @@ impl<S: Socket> MySqlStream<S> {
/// 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;
Expand All @@ -111,7 +166,7 @@ impl<S: Socket> MySqlStream<S> {
// 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() {
Expand Down Expand Up @@ -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",
))
}
15 changes: 9 additions & 6 deletions rust/vendor/sqlx-postgres/DURABLE-PATCH.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
65 changes: 65 additions & 0 deletions rust/vendor/sqlx-postgres/src/connection/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(&mut self, message: T) -> Result<(), Error>
where
T: FrontendMessage,
Expand Down Expand Up @@ -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",
))
}