diff --git a/docs/rust-server-port.md b/docs/rust-server-port.md index 5a4b0e6c6..70d97dc55 100644 --- a/docs/rust-server-port.md +++ b/docs/rust-server-port.md @@ -491,12 +491,15 @@ contract fixture before its correction. instead: poll probes share the rest of the node's pool, leaving the reserve to health, readiness and admin requests. Unset, all three leave native's behavior unchanged. Whatever the setting, held polls' admission, replay, - probe, readiness and claim work takes its connections from a budget of the - request pool size minus one (at least one), and the maintenance loop has - its own connection, so neither occupies the request pool's last - connection. Other work, listed in the server reference, stays outside the - budget ([#1204](https://github.com/durable-workflow/server/issues/1204), - [#1355](https://github.com/durable-workflow/server/issues/1355)). + probe, readiness and claim work takes its connections from a budget: reads + take at most the request pool size minus two (two read slots on the + request pool of four) and the transaction holding the transition queue one + more. The maintenance loop has its own connection, so neither occupies the + request pool's last connection. Other work, listed in the server + reference, stays outside the budget + ([#1204](https://github.com/durable-workflow/server/issues/1204), + [#1355](https://github.com/durable-workflow/server/issues/1355), + [#1372](https://github.com/durable-workflow/server/issues/1372)). The per-namespace variants stay ignored ([#982](https://github.com/durable-workflow/server/issues/982), [server reference](server-reference.md#native-long-poll-capacity)). diff --git a/docs/server-reference.md b/docs/server-reference.md index 3d18db5a2..b5fbcb6c5 100644 --- a/docs/server-reference.md +++ b/docs/server-reference.md @@ -2415,20 +2415,23 @@ how many request workers are busy. with `timeout_seconds: 0` never needs a slot. A slot is released when the poll answers, fails or its client disconnects. - `DW_WORKER_LONG_POLL_RESERVED_HTTP_WORKERS` reserves database connections. - A native node opens four database connections on MySQL, PostgreSQL and file - SQLite: a request pool of three, which health, readiness, admin and every + A native node opens five database connections on MySQL, PostgreSQL and file + SQLite: a request pool of four, which health, readiness, admin and every other request share, and one connection of its own for the maintenance loop (timers, schedules, repair, retention and the task-offer key window), so maintenance never borrows a request connection - ([#1355](https://github.com/durable-workflow/server/issues/1355)). With a + ([#1355](https://github.com/durable-workflow/server/issues/1355), + [#1372](https://github.com/durable-workflow/server/issues/1372)). With a positive value, every poll probe takes one of `request pool size - reserved` probe permits (at least one) and returns it before waiting, so polls never - occupy the reserved connections. Unset or zero, probes take no permit. + occupy the reserved connections: `2`, the PHP default, gives two permits, + `3` gives one. Unset or zero, probes take no permit. - Whatever the setting, a node-wide budget covers this held-poll work, so it never occupies the request pool's last connection, which producers and registrations keep. Its reads take at most the request pool size minus two - connections (at least one); the one transaction holding the transition - queue takes one more, so it never waits behind those reads: + connections (at least one), so two read slots on the request pool of four; + the one transaction holding the transition queue takes one more, so it + never waits behind those reads: - a held workflow or activity poll's admission and replay reads, its probes' lock-free reads (one connection per probe, returned before it claims or waits), its claim transactions and, for a workflow poll, its @@ -2879,7 +2882,8 @@ every operator-facing variable the server honors. | `DW_POLLING_CACHE_PATH` | `storage/.../server-polling/` | Writable local coordination and wait-lock directory, also required with Redis or database polling caches. | | `DW_WAKE_SIGNAL_TTL_SECONDS` | `max(DW_WORKER_POLL_TIMEOUT + 5, 60)` | TTL for per-queue wake signals. | | `DW_WORKER_LONG_POLL_MAX_CONCURRENT` | (unset; derived for PHP CLI server) | Optional cap for concurrent held workflow/activity worker long-poll waits on this server node. Query-task polls use a separate wait budget so live workflow queries are not starved by idle workflow/activity waits. Native honors it as a node-wide cap with the same `429 long_poll_capacity_exhausted` refusal; unset, native waits are unbounded (see [Native long-poll capacity](#native-long-poll-capacity)). | -| `DW_WORKER_LONG_POLL_RESERVED_HTTP_WORKERS` | `2` | PHP CLI server workers reserved for health and control-plane requests when deriving the workflow/activity long-poll wait cap. Native has no request-worker pool; it reads this as the number of its request-pool database connections that long-poll probes leave free. Unset, native reserves none for it; the held-poll work listed under native long-poll capacity still leaves the request pool's last connection free. | +| `DW_WORKER_LONG_POLL_RESERVED_HTTP_WORKERS` | `2` | PHP CLI server workers reserved for health and control-plane requests when deriving the workflow/activity long-poll wait cap. Native has no request-worker pool; it reads this as the number of its request-pool database connections (four) that long-poll probes leave free, so `2` leaves two probe permits. Unset, native reserves none for it; the held-poll work listed under native long-poll capacity still leaves the request pool's last connection free. | +| `DW_NATIVE_DB_STATEMENT_CACHE_CAPACITY` | `192` | Native only. Server-side prepared statements each MySQL or PostgreSQL request connection keeps (0 to 4083; SQLx's `statement-cache-capacity` `DB_URL` parameter sets the same value and must agree). The maintenance connection keeps at most 48 (none at `0`). A node holds at most `4 × capacity + min(capacity, 48)`, so on MySQL keep `nodes × (4 × capacity + min(capacity, 48)) + other clients' statements ≤ max_prepared_stmt_count` (16382 by default): 20 nodes at the default. A request connection's hot path uses about 166 statements on the PHP SDK workload ([#1174](https://github.com/durable-workflow/server/issues/1174)) and about 126 on the in-process workload ([#1372](https://github.com/durable-workflow/server/issues/1372)). | | `DW_MAX_TASKS_PER_POLL` | `1` | Maximum tasks returned per poll. | | `DW_SQLITE_CLAIM_LOCK_TTL_SECONDS` | `10` | Seconds the SQLite quickstart backend holds the cache-backed worker poll claim gate before the lock expires. | | `DW_SQLITE_CLAIM_LOCK_WAIT_SECONDS` | `5` | Seconds SQLite worker poll claims wait for the cache-backed claim gate before returning backend lock pressure. | diff --git a/rust/README.md b/rust/README.md index 9dc6d3b8d..e2e870d4a 100644 --- a/rust/README.md +++ b/rust/README.md @@ -250,34 +250,51 @@ datum decoding or qualifying ingress. ## Prepared-statement cache -Each connection of the MySQL and PostgreSQL runtime pools (4 connections per -node) keeps up to `DW_NATIVE_DB_STATEMENT_CACHE_CAPACITY` server-side prepared -statements, default **200**. SQLx's `statement-cache-capacity` `DB_URL` -parameter sets the same value; if both are set they must agree. Values are -whole numbers from `0` (prepare and close every statement) to `4095`; anything -else, or two different values, stops startup. SQLite is -unaffected. +Each request connection of the MySQL and PostgreSQL runtime pools (a request +pool of 4 per node) keeps up to `DW_NATIVE_DB_STATEMENT_CACHE_CAPACITY` +server-side prepared statements, default **192**; the node's fifth +connection, the maintenance loop's, keeps at most 48 (fewer if the capacity is +smaller, none at `0`). SQLx's `statement-cache-capacity` `DB_URL` parameter +sets the same value; if both are set they must agree. Values are whole numbers +from `0` (prepare and close every statement) to `4083`; anything else, or two +different values, stops startup. SQLite is unaffected. SQLx's own default of 100 is smaller than the hot path. On the #1078 workload (200 workflows of five 20 ms activities, six PHP workers, MySQL 8.0) each pool -connection uses about 160 distinct statements. At 100 the cache evicted them, -so every workflow prepared about 12 statements again and closed about 11 +connection uses about 160 to 166 distinct statements. At 100 the cache evicted +them, so every workflow prepared about 12 statements again and closed about 11 (Server #1174). At 200 the same workload prepares 0.2 statements per workflow and closes none. +Server #1372 added the fifth connection. The maintenance loop uses few +statements, so its connection keeps a small cache and the request connections +keep 192, still above the #1174 working set. On the same shape of workload +driven in process (200 workflows of five 20 ms activities and a signal, six +workers, MariaDB 10.11; `tests/execution/hot_path_cache.rs`) each request +connection uses 123 to 126 distinct statements and the maintenance connection +about 8: + +| Capacity | Prepares per workflow | Closes per workflow | Hit rate | +|---|---|---|---| +| 200 | 2.50 | 0 | 99.71 % | +| 160 | 2.52 | 0 | 99.70 % | +| 128 | 2.51 | 0.26 | 99.71 % | +| 100 | 17.42 | 15.70 | 97.96 % | + MySQL counts every prepared statement of every client toward the server-wide `max_prepared_stmt_count` (default 16382). When a client reaches it, further prepares fail with error 1461. A native node holds at most -`4 × capacity` statements, so keep +`4 × capacity + min(capacity, 48)` statements, so keep ```text -nodes × 4 × DW_NATIVE_DB_STATEMENT_CACHE_CAPACITY + other clients' statements ≤ max_prepared_stmt_count +nodes × (4 × DW_NATIVE_DB_STATEMENT_CACHE_CAPACITY + min(DW_NATIVE_DB_STATEMENT_CACHE_CAPACITY, 48)) + + other clients' statements ≤ max_prepared_stmt_count ``` -At the default that is 800 per node and up to 20 nodes on a default MySQL -server. The hot path above fills about 650 per node. For a larger cluster, +At the default that is 816 per node and up to 20 nodes on a default MySQL +server. The hot path above fills about 510 per node. For a larger cluster, raise `max_prepared_stmt_count` or lower the capacity. `Prepared_stmt_count` -in `SHOW GLOBAL STATUS` reports current use. The upper bound of 4095 keeps one +in `SHOW GLOBAL STATUS` reports current use. The upper bound of 4083 keeps one node within the default limit. PostgreSQL has no server-wide limit; each cached statement holds memory in its own backend. @@ -405,7 +422,8 @@ across restarts. This opt-in does not authorize use as a production replacement. The first slice uses Axum/Tokio for HTTP and SQLx for SQLite transactions, with only the required features enabled and no build-time database or SQL macro -generation. Four connections and `BEGIN IMMEDIATE` serialize durable state +generation. Five connections (a request pool of four and the maintenance +loop's) and `BEGIN IMMEDIATE` serialize durable state changes; SQLite runs on SQLx's connection workers. HTTP uses two Tokio executor threads. WAL with full synchronous writes retains acknowledged state. Namespaces within one runtime share a FIFO transition queue before pool diff --git a/rust/src/runtime/backend.rs b/rust/src/runtime/backend.rs index 42f4b34ee..9789de675 100644 --- a/rust/src/runtime/backend.rs +++ b/rust/src/runtime/backend.rs @@ -239,6 +239,14 @@ pub(super) trait Backend: Database { /// `statement_timeout` ends every statement there within 30 s. MySQL /// drops it, so a healthy server is never cut off mid-delete. fn lift_statement_reply_bound(_connection: &mut Self::Connection) {} + /// The maintenance connection's connect options, from the request pool's: + /// a statement cache of at most `statement_cache::MAINTENANCE` entries + /// (Server #1372). SQLite keeps no server-side statements. + fn maintenance_connect_options( + options: ::Options, + ) -> ::Options { + options + } const HISTORY_SEQUENCE_MAX: i64 = i64::MAX; const HISTORY_ADVANCE_RETURNS_ROW: bool = true; const HISTORY_ADVANCE_SQL: &str = "UPDATE workflow_runs SET last_history_sequence=last_history_sequence+1 WHERE id=$1 AND last_history_sequence>=0 AND last_history_sequence<$2 RETURNING last_history_sequence"; @@ -633,6 +641,12 @@ impl Encode<'_, Postgres> for PostgresDocument { } impl Backend for Postgres { + fn maintenance_connect_options( + options: ::Options, + ) -> ::Options { + let capacity = crate::statement_cache::maintenance(options.get_statement_cache_capacity()); + options.statement_cache_capacity(capacity) + } const COMMIT_HANDOFF: bool = true; const HISTORY_SEQUENCE_MAX: i64 = i32::MAX as i64; const TASK_CANDIDATES_SQL: &str = super::postgres::TASK_CANDIDATES_SQL; @@ -765,6 +779,12 @@ impl Backend for MySql { fn lift_statement_reply_bound(connection: &mut Self::Connection) { connection.set_reply_timeout(None); } + fn maintenance_connect_options( + options: ::Options, + ) -> ::Options { + let capacity = crate::statement_cache::maintenance(options.get_statement_cache_capacity()); + options.statement_cache_capacity(capacity) + } const COMMIT_HANDOFF: bool = true; const HISTORY_SEQUENCE_MAX: i64 = u32::MAX as i64; const HISTORY_ADVANCE_RETURNS_ROW: bool = false; @@ -1249,3 +1269,23 @@ async fn mysql_ownership_lock(tx: &mut Transaction<'_, MySql>) -> Result<()> { .bind(mysql::MARIADB_VERSION).bind(mysql::MYSQL_VERSION).fetch_one(&mut **tx).await?; Ok(()) } + +#[cfg(test)] +mod maintenance_cache_tests { + use super::Backend; + + /// Server #1372: the maintenance connection keeps at most + /// `statement_cache::MAINTENANCE` statements, and none when the + /// configured capacity turns the cache off. + #[test] + fn the_maintenance_connection_keeps_a_small_cache_or_none() { + use crate::statement_cache::{DEFAULT, MAINTENANCE, MAX}; + use sqlx::{mysql::MySqlConnectOptions, postgres::PgConnectOptions}; + for (configured, kept) in [(DEFAULT, MAINTENANCE), (MAX, MAINTENANCE), (20, 20), (0, 0)] { + let mysql = sqlx::MySql::maintenance_connect_options(MySqlConnectOptions::new().statement_cache_capacity(configured)); + assert_eq!(mysql.get_statement_cache_capacity(), kept, "{configured}"); + let postgres = sqlx::Postgres::maintenance_connect_options(PgConnectOptions::new().statement_cache_capacity(configured)); + assert_eq!(postgres.get_statement_cache_capacity(), kept, "{configured}"); + } + } +} diff --git a/rust/src/runtime/execution.rs b/rust/src/runtime/execution.rs index e8e17f9a0..7e3483472 100644 --- a/rust/src/runtime/execution.rs +++ b/rust/src/runtime/execution.rs @@ -32,6 +32,9 @@ mod transition_codec_tests; #[cfg(test)] #[path = "continuation_atomic_tests.rs"] pub(super) mod continuation_atomic_tests; +#[cfg(test)] +#[path = "poll_wake_tests.rs"] +mod poll_wake_tests; #[derive(Clone)] pub struct Runtime { diff --git a/rust/src/runtime/mod.rs b/rust/src/runtime/mod.rs index 36374a250..954a638c4 100644 --- a/rust/src/runtime/mod.rs +++ b/rust/src/runtime/mod.rs @@ -132,6 +132,7 @@ mod test_reply_gate; mod poll_sweeps; mod plain_input; mod poll_readiness; +mod poll_wakes; pub mod postgres; mod previews; mod prometheus_metrics; diff --git a/rust/src/runtime/mysql.rs b/rust/src/runtime/mysql.rs index 7943876f0..46d81baf4 100644 --- a/rust/src/runtime/mysql.rs +++ b/rust/src/runtime/mysql.rs @@ -2689,6 +2689,10 @@ mod pool_tests; #[path = "mysql_stall_tests.rs"] mod stall_tests; +#[cfg(test)] +#[path = "mysql_held_poll_bench.rs"] +mod held_poll_bench; + #[cfg(test)] mod tests { diff --git a/rust/src/runtime/mysql_held_poll_bench.rs b/rust/src/runtime/mysql_held_poll_bench.rs new file mode 100644 index 000000000..973caea26 --- /dev/null +++ b/rust/src/runtime/mysql_held_poll_bench.rs @@ -0,0 +1,150 @@ +//! Held-poll benchmark (Server #1372). `polls` held workflow polls across +//! `max(polls / 8, 1)` worker queues re-poll continuously with 2 s waits while +//! four producers start workflows round-robin across those queues, for 15 s. +//! It reports start throughput and latency, read-slot waits (and typed pool +//! timeouts), leased and empty poll answer times, and dispatch latency: from +//! a start's return to the poll that leased its task. +//! +//! Run against a disposable MySQL or MariaDB: +//! `DW_TEST_MYSQL_URL=... cargo test --lib runtime::mysql::held_poll_bench -- --ignored --nocapture --test-threads=1` +#![cfg(test)] +use super::*; +use super::super::{QueryTaskConfig, probe_connections::probe_stats, store::Store}; +use serde_json::json; +use sqlx::{ConnectOptions, MySql, migrate::MigrateDatabase}; +use std::{collections::HashMap, str::FromStr, sync::{Arc, Mutex}}; +use tokio::time::Instant; + +const SECONDS: u64 = 15; + +fn percentile(values: &mut [f64], p: f64) -> f64 { + if values.is_empty() { + return f64::NAN; + } + values.sort_by(|a, b| a.partial_cmp(b).unwrap()); + values[((values.len() as f64 - 1.0) * p) as usize] +} + +#[derive(Default)] +struct Polls { + leased: Vec, + dispatch: Vec, + empty: Vec, + errors: HashMap, +} + +async fn held_polls(polls: usize) { + use crate::codec::{Value as Payload, ValueCodec}; + let database = format!("dw_bench_{}", ulid::Ulid::new().to_string().to_lowercase()); + let direct = MySqlConnectOptions::from_str(&std::env::var("DW_TEST_MYSQL_URL").unwrap()).unwrap().database(&database); + let url = direct.to_url_lossy().to_string(); + MySql::create_database(&url).await.unwrap(); + let store = Arc::new(Store::new(MySqlStorage::open(direct).await.unwrap().into_pool()).with_maintenance_pool()); + let queues = (polls / 8).max(1); + for n in 0..polls { + store.register(json!({"worker_id":format!("bench-{n}"),"task_queue":format!("q-{}", n % queues),"runtime":"php", + "supported_workflow_types":["bench"],"supported_activity_types":[]}), &QueryTaskConfig::default(), Some("1.20")).await.unwrap(); + } + probe_stats::reset(); + let started_at: Arc>> = Arc::default(); + let results: Arc> = Arc::default(); + let end = Instant::now() + Duration::from_secs(SECONDS); + let mut tasks = Vec::new(); + for n in 0..polls { + let (store, results, started_at) = (store.clone(), results.clone(), started_at.clone()); + tasks.push(tokio::spawn(async move { + let body = json!({"worker_id":format!("bench-{n}"),"task_queue":format!("q-{}", n % queues),"timeout_seconds":2}); + while Instant::now() < end { + let begun = Instant::now(); + let answer = store.poll(body.clone(), "workflow", "1.20").await; + let took = begun.elapsed().as_secs_f64() * 1000.0; + let failed = { + let mut results = results.lock().unwrap(); + match answer { + Ok(answer) if answer["poll_status"] == "leased" => { + results.leased.push(took); + let started = answer["task"]["workflow_id"].as_str().and_then(|id| started_at.lock().unwrap().get(id).copied()); + if let Some(started) = started { + results.dispatch.push(started.elapsed().as_secs_f64() * 1000.0); + } + false + } + Ok(_) => { + results.empty.push(took); + false + } + Err(error) => { + *results.errors.entry(format!("{error:?}").chars().take(60).collect()).or_default() += 1; + true + } + } + }; + if failed { + tokio::time::sleep(Duration::from_millis(200)).await; + } + } + })); + } + let starts: Arc>> = Arc::default(); + let start_errors: Arc>> = Arc::default(); + for producer in 0..4 { + let (store, starts, start_errors, started_at) = (store.clone(), starts.clone(), start_errors.clone(), started_at.clone()); + tasks.push(tokio::spawn(async move { + let input = json!({"codec":"avro","blob":ValueCodec::new().unwrap().encode(&Payload::Array(vec![])).unwrap()}); + let mut n = 0; + while Instant::now() < end { + n += 1; + let id = format!("w-{producer}-{n}"); + let begun = Instant::now(); + let started = store.start(json!({"workflow_id":id,"workflow_type":"bench", + "task_queue":format!("q-{}", (producer + n * 4) % queues),"input":input.clone()}), + super::super::memos::initial(json!({})).unwrap(), None, None).await; + match started { + Ok(_) => { + starts.lock().unwrap().push(begun.elapsed().as_secs_f64() * 1000.0); + started_at.lock().unwrap().insert(id, Instant::now()); + } + Err(error) => *start_errors.lock().unwrap().entry(format!("{error:?}").chars().take(60).collect()).or_default() += 1, + } + } + })); + } + for task in tasks { + task.await.unwrap(); + } + let mut starts = std::mem::take(&mut *starts.lock().unwrap()); + let (mut waits, pool_timeouts) = probe_stats::take(); + let mut results = std::mem::take(&mut *results.lock().unwrap()); + eprintln!( + "BENCH polls={polls} queues={queues} starts/s={:.1} start_p50={:.0} start_p99={:.0} start_errors={:?} \ + probe_n={} probe_p50={:.1} probe_p99={:.1} probe_max={:.0} probe_pool_timeouts={pool_timeouts} \ + leased_n={} leased_p50={:.0} leased_p99={:.0} dispatch_p50={:.0} dispatch_p99={:.0} \ + empty_n={} empty_p50={:.0} empty_p99={:.0} poll_errors={:?}", + starts.len() as f64 / SECONDS as f64, percentile(&mut starts, 0.5), percentile(&mut starts, 0.99), + start_errors.lock().unwrap(), + waits.len(), percentile(&mut waits, 0.5), percentile(&mut waits, 0.99), percentile(&mut waits, 1.0), + results.leased.len(), percentile(&mut results.leased, 0.5), percentile(&mut results.leased, 0.99), + percentile(&mut results.dispatch, 0.5), percentile(&mut results.dispatch, 0.99), + results.empty.len(), percentile(&mut results.empty, 0.5), percentile(&mut results.empty, 0.99), results.errors, + ); + store.close().await; + MySql::drop_database(&url).await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "benchmark; requires disposable MySQL/MariaDB"] +async fn bench_8_held_polls() { + held_polls(8).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "benchmark; requires disposable MySQL/MariaDB"] +async fn bench_64_held_polls() { + held_polls(64).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "benchmark; requires disposable MySQL/MariaDB"] +async fn bench_256_held_polls() { + held_polls(256).await +} diff --git a/rust/src/runtime/poll_readiness.rs b/rust/src/runtime/poll_readiness.rs index 6c0265829..00fbfe840 100644 --- a/rust/src/runtime/poll_readiness.rs +++ b/rust/src/runtime/poll_readiness.rs @@ -7,31 +7,69 @@ //! A same-node commit wakes it to read at once; timed reads observe other //! server processes. A false positive costs one locked claim that finds //! nothing, and a commit racing a read is seen on the next one. -use std::time::Duration; -use tokio::{sync::futures::Notified, time::Instant}; +use std::{future::Future, time::Duration}; +use tokio::time::Instant; /// Paces a held poll's timed reads, which are how it observes another server -/// process. The first read comes 50 ms after a probe, and each later one waits -/// twice as long, up to 250 ms. A same-node wake reads at once and starts again -/// from 50 ms. No wait runs past the poll's deadline. +/// process. The first read comes 50 ms after a probe, and each later one that +/// finds nothing waits twice as long, up to a ceiling that grows with the +/// number of held polls waiting on this node: 250 ms for up to 31 of them, +/// then 8 ms per waiting poll, at most 2 s (Server #1372). No pause is shorter +/// than a quarter of the ceiling, so a short poll does not spend its life in +/// the fast first steps. Many idle polls then read a few hundred times a +/// second between them instead of several times a second each, which had +/// filled the read budget and slowed the polls that had work and the +/// producers. A same-node wake reads at once, so a poll whose queue gets a +/// task on this node still claims it promptly; work committed by another +/// server process is seen within the ceiling. No wait runs past the poll's +/// deadline. pub(super) struct ReadPace { next: Duration, } impl ReadPace { const FIRST: Duration = Duration::from_millis(50); + /// The ceiling with few waiting polls. const LONGEST: Duration = Duration::from_millis(250); + /// How much each waiting poll adds to the ceiling. + const PER_WAITING_POLL: Duration = Duration::from_millis(8); + /// The ceiling with many waiting polls. + const SLOWEST: Duration = Duration::from_secs(2); pub(super) fn new() -> Self { Self { next: Self::FIRST } } + /// The longest pause between timed reads while `waiting` held polls wait. + pub(super) fn ceiling(waiting: usize) -> Duration { + Self::PER_WAITING_POLL + .saturating_mul(u32::try_from(waiting).unwrap_or(u32::MAX)) + .clamp(Self::LONGEST, Self::SLOWEST) + } + /// Returns at a same-node wake or when the next timed read is due. - pub(super) async fn wait(&mut self, wake: Notified<'_>, deadline: Instant) { - let pause = self.next.min(deadline.saturating_duration_since(Instant::now())); + pub(super) async fn wait( + &mut self, wake: impl Future, deadline: Instant, wakes: &super::poll_wakes::PollWakes, + ) { + let _waiting = wakes.waiting(); + let ceiling = Self::ceiling(wakes.waiting_now()); + let pause = self.next.max(ceiling / 4).min(ceiling).min(deadline.saturating_duration_since(Instant::now())); tokio::select! { - _ = wake => self.next = Self::FIRST, - _ = tokio::time::sleep(pause) => self.next = (self.next * 2).min(Self::LONGEST), + () = wake => self.next = Self::FIRST, + () = tokio::time::sleep(pause) => self.next = (self.next * 2).min(ceiling), + } + } +} + +#[cfg(test)] +mod tests { + use super::ReadPace; + use std::time::Duration; + + #[test] + fn the_timed_read_ceiling_grows_with_waiting_polls_within_bounds() { + for (waiting, ceiling) in [(0, 250), (8, 250), (31, 250), (64, 512), (128, 1024), (250, 2000), (256, 2000), (100_000, 2000)] { + assert_eq!(ReadPace::ceiling(waiting), Duration::from_millis(ceiling), "{waiting}"); } } } diff --git a/rust/src/runtime/poll_wake_tests.rs b/rust/src/runtime/poll_wake_tests.rs new file mode 100644 index 000000000..de3b55f2f --- /dev/null +++ b/rust/src/runtime/poll_wake_tests.rs @@ -0,0 +1,91 @@ +//! Which held polls each hot commit wakes (Server #1372). +use super::{Runtime, Storage}; +use std::time::Duration; +use tokio::time::timeout; + +/// Server #1372: each hot commit wakes the held polls of the queue it +/// made ready, and not those of another queue: a start, a workflow task +/// completion that schedules an activity on another queue (and the run's +/// own queue, whose other tasks it unfences), an activity completion and a +/// signal. +#[tokio::test] +async fn hot_commits_wake_the_queues_they_make_ready() { + use crate::codec::{Value as Payload, ValueCodec}; + use axum::{body::{Body, to_bytes}, http::{Request, StatusCode}}; + use serde_json::json; + use tower::ServiceExt; + let envelope = |value: Payload| json!({"codec":"avro","blob":ValueCodec::new().unwrap().encode(&value).unwrap()}); + let directory = tempfile::tempdir().unwrap(); + let runtime = Runtime::open(directory.path().join("runtime.sqlite").to_str().unwrap(), "test-token".into()).await.unwrap(); + for (worker, queue) in [("wakes-workflows", "wakes-wq"), ("wakes-activities", "wakes-aq")] { + runtime.register_unversioned(json!({"worker_id":worker,"task_queue":queue,"runtime":"php", + "supported_workflow_types":["echo"],"supported_activity_types":["act"], + "workflow_command_contracts":{"echo":{"signals":["note"],"signal_contracts":[{"name":"note","parameters":[{"name":"args", + "position":0,"type":null,"required":false,"variadic":true,"default_available":false,"default":null,"allows_null":true}]}]}}})) + .await.unwrap(); + } + let Storage::Sqlite(store) = runtime.storage.as_ref() else { unreachable!() }; + let wakes = store.poll_wakes.clone(); + let (workflows, activities, elsewhere) = + (wakes.subscribe("default", "wakes-wq"), wakes.subscribe("default", "wakes-aq"), wakes.subscribe("default", "wakes-elsewhere")); + // Each check registers its waiters before the commit it observes. + macro_rules! wakes_only { + ($commit:expr, [$($queue:expr),*], $label:expr) => {{ + let (w, a, e) = (Box::pin(workflows.notify.clone().notified_owned()), Box::pin(activities.notify.clone().notified_owned()), + Box::pin(elsewhere.notify.clone().notified_owned())); + let mut expected = std::collections::BTreeSet::new(); + $(expected.insert($queue);)* + $commit; + let observed: std::collections::BTreeSet<&str> = [ + ("wakes-wq", timeout(Duration::from_millis(50), w).await.is_ok()), + ("wakes-aq", timeout(Duration::from_millis(50), a).await.is_ok()), + ("wakes-elsewhere", timeout(Duration::from_millis(50), e).await.is_ok()), + ].into_iter().filter(|(_, woken)| *woken).map(|(queue, _)| queue).collect(); + assert_eq!(observed, expected, $label); + }}; + } + wakes_only!(runtime.start(json!({"workflow_id":"wakes","workflow_type":"echo","task_queue":"wakes-wq", + "input":envelope(Payload::Array(vec![]))}), None).await.unwrap(), ["wakes-wq"], "a start"); + let task = runtime.poll(json!({"worker_id":"wakes-workflows","task_queue":"wakes-wq","timeout_seconds":0}), "workflow", "1.20") + .await.unwrap()["task"].clone(); + wakes_only!(runtime.complete_workflow(task["task_id"].as_str().unwrap(), json!({"lease_owner":"wakes-workflows", + "workflow_task_attempt":task["workflow_task_attempt"],"commands":[{"type":"schedule_activity","activity_type":"act", + "queue":"wakes-aq","arguments":envelope(Payload::Array(vec![]))}]}), None, Some("1.20")).await.unwrap(), + ["wakes-wq", "wakes-aq"], "a workflow task completion"); + let activity = runtime.poll(json!({"worker_id":"wakes-activities","task_queue":"wakes-aq","timeout_seconds":0}), "activity", "1.20") + .await.unwrap()["task"].clone(); + let app = crate::runtime::router(runtime.clone()); + let request = |path: String, body: serde_json::Value| { + let app = app.clone(); + async move { + let response = app.oneshot(Request::builder().method("POST").uri(path) + .header("authorization", "Bearer test-token").header("x-namespace", "default") + .header("x-durable-workflow-control-plane-version", "2").header("x-durable-workflow-protocol-version", "1.20") + .header("content-type", "application/json").body(Body::from(body.to_string())).unwrap()).await.unwrap(); + let status = response.status(); + let bytes = to_bytes(response.into_body(), 1 << 20).await.unwrap(); + (status, String::from_utf8_lossy(&bytes).into_owned()) + } + }; + wakes_only!({ + let (status, body) = request(format!("/api/worker/activity-tasks/{}/complete", activity["task_id"].as_str().unwrap()), + json!({"lease_owner":"wakes-activities","activity_attempt_id":activity["activity_attempt_id"],"result":envelope(Payload::Long(7))})).await; + assert_eq!(status, StatusCode::OK, "{body}"); + }, ["wakes-wq"], "an activity completion"); + // The run now has a ready workflow task; take it and leave the run + // waiting, so the signal is what makes it ready again. + let task = runtime.poll(json!({"worker_id":"wakes-workflows","task_queue":"wakes-wq","timeout_seconds":0}), "workflow", "1.20") + .await.unwrap()["task"].clone(); + runtime.complete_workflow(task["task_id"].as_str().unwrap(), json!({"lease_owner":"wakes-workflows", + "workflow_task_attempt":task["workflow_task_attempt"],"commands":[{"type":"start_timer","delay_seconds":3600}]}), None, Some("1.20")) + .await.unwrap(); + wakes_only!({ + let (status, body) = request("/api/workflows/wakes/signal/note".into(), json!({"input":envelope(Payload::Array(vec![Payload::Long(1)]))})).await; + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + }, ["wakes-wq"], "a signal"); + let task = runtime.poll(json!({"worker_id":"wakes-workflows","task_queue":"wakes-wq","timeout_seconds":0}), "workflow", "1.20") + .await.unwrap()["task"].clone(); + assert!(!task.is_null(), "the signal made the run's workflow task ready"); + drop((workflows, activities, elsewhere)); + runtime.close().await; +} diff --git a/rust/src/runtime/poll_wakes.rs b/rust/src/runtime/poll_wakes.rs new file mode 100644 index 000000000..0dd7b33ea --- /dev/null +++ b/rust/src/runtime/poll_wakes.rs @@ -0,0 +1,210 @@ +//! In-process wakes for held worker polls, per namespace and task queue +//! (Server #1372). +//! +//! A commit used to wake every held poll on the node through one +//! `Notify`, and each woken poll read the database: with many held polls on +//! many queues, almost every one of those reads found nothing, and they +//! queued behind each other for the read budget. A transaction that creates +//! a ready task (`Store::create_task_dispatched`) now records its namespace +//! and queue, and its commit wakes only the held workflow and activity polls +//! of those queues. The hottest commits (starts, signals and task +//! completions) no longer wake every poll; they wake the queues they made +//! ready and the waiters that are not held worker polls ([`PollWakes::others`]: +//! query-task polls and update, query and validation result waits). Every +//! other commit still wakes everyone through `Store::wake`. +//! +//! A missed wake costs latency, never a task: a held poll still reads on its +//! own timed schedule ([`super::poll_readiness::ReadPace`]), which is also +//! how it sees work another server process committed. +use std::{ + collections::{BTreeSet, HashMap}, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, +}; +use tokio::sync::Notify; + +/// A queue's key: namespace and task queue. +pub(super) type QueueKey = (String, String); + +#[derive(Default)] +pub(super) struct PollWakes { + queues: Mutex>, + /// Waiters that are not held worker polls, which the hottest commits + /// wake instead of `Store::wake`. + pub(super) others: Notify, + /// Held polls now waiting between reads, node-wide. + waiting: AtomicUsize, + /// When this node last checked each queue for abandoned workflow task + /// leases on a held poll's later probe. + recovery_checks: Mutex>, +} + +/// How often this node checks one queue for abandoned workflow task leases on +/// held polls' later probes. A lease is abandoned only once its owner's +/// registration is stale (no heartbeat for `worker_stale_after_seconds`, +/// 30 s by default), so a check a second later finds the same leases; every +/// poll's first probe still checks. +pub(super) const RECOVERY_CHECK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1); + +#[derive(Default)] +struct QueueWaiters { + notify: Arc, + count: usize, +} + +impl PollWakes { + /// Subscribes a held poll to its queue's wakes until the returned value + /// is dropped. + pub(super) fn subscribe(&self, namespace: &str, queue: &str) -> QueueWait<'_> { + let key = (namespace.to_owned(), queue.to_owned()); + let mut queues = self.queues.lock().unwrap(); + let waiters = queues.entry(key.clone()).or_default(); + waiters.count += 1; + QueueWait { wakes: self, notify: waiters.notify.clone(), key } + } + + /// Wakes the held polls of `queues` and the other waiters, after a + /// commit that made those queues ready. + pub(super) fn committed<'a>(&self, queues: impl IntoIterator) { + self.wake_queues(queues); + self.others.notify_waiters(); + } + + /// Wakes the held polls of `queues` only. + pub(super) fn wake_queues<'a>(&self, queues: impl IntoIterator) { + let waiting = self.queues.lock().unwrap(); + if waiting.is_empty() { + return; + } + for key in queues { + if let Some(waiters) = waiting.get(key) { + waiters.notify.notify_waiters(); + } + } + } + + /// Whether a held poll's later probe should check `queue` for abandoned + /// workflow task leases (Server #1372): at most once per + /// [`RECOVERY_CHECK_INTERVAL`] per queue on this node. Each of them used + /// to check on every probe of every poll, and those reads were about + /// half of all held-poll reads with many idle polls. + pub(super) fn recovery_due(&self, namespace: &str, queue: &str) -> bool { + let now = std::time::Instant::now(); + let mut checks = self.recovery_checks.lock().unwrap(); + let key = (namespace.to_owned(), queue.to_owned()); + if checks.get(&key).is_some_and(|last| now.duration_since(*last) < RECOVERY_CHECK_INTERVAL) { + return false; + } + if checks.len() > 4096 { + checks.retain(|_, last| now.duration_since(*last) < RECOVERY_CHECK_INTERVAL); + } + checks.insert(key, now); + true + } + + /// Counts a held poll as waiting until the returned guard is dropped. + pub(super) fn waiting(&self) -> Waiting<'_> { + self.waiting.fetch_add(1, Ordering::Relaxed); + Waiting(self) + } + + /// Held polls now waiting between reads. + pub(super) fn waiting_now(&self) -> usize { + self.waiting.load(Ordering::Relaxed) + } +} + +pub(super) struct QueueWait<'a> { + wakes: &'a PollWakes, + key: QueueKey, + pub(super) notify: Arc, +} + +impl Drop for QueueWait<'_> { + fn drop(&mut self) { + let mut queues = self.wakes.queues.lock().unwrap(); + let waiters = queues.get_mut(&self.key).expect("subscribed queue"); + waiters.count -= 1; + if waiters.count == 0 { + queues.remove(&self.key); + } + } +} + +pub(super) struct Waiting<'a>(&'a PollWakes); + +impl Drop for Waiting<'_> { + fn drop(&mut self) { + self.0.waiting.fetch_sub(1, Ordering::Relaxed); + } +} + +/// Resolves when either wake resolves. Both were registered when created, so +/// neither misses a wake that comes before this is first polled. +pub(super) async fn any(first: impl std::future::Future, second: impl std::future::Future) { + tokio::select! { + () = first => {} + () = second => {} + } +} + +/// The queues a transaction made ready, woken when it commits. +pub(super) type ReadyQueues = BTreeSet; + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + use tokio::time::timeout; + + #[tokio::test] + async fn a_commit_wakes_only_the_polls_of_the_queues_it_made_ready() { + let wakes = PollWakes::default(); + let orders = wakes.subscribe("default", "orders"); + let same = wakes.subscribe("default", "orders"); + let other_queue = wakes.subscribe("default", "billing"); + let other_namespace = wakes.subscribe("tenant", "orders"); + let (orders_woken, same_woken) = (orders.notify.notified(), same.notify.notified()); + let (queue_woken, namespace_woken) = (other_queue.notify.notified(), other_namespace.notify.notified()); + let others_woken = wakes.others.notified(); + + wakes.committed([&("default".to_owned(), "orders".to_owned())]); + + timeout(Duration::ZERO, orders_woken).await.unwrap(); + timeout(Duration::ZERO, same_woken).await.unwrap(); + timeout(Duration::ZERO, others_woken).await.unwrap(); + assert!(timeout(Duration::from_millis(20), queue_woken).await.is_err()); + assert!(timeout(Duration::from_millis(20), namespace_woken).await.is_err()); + + drop((orders, same, other_queue, other_namespace)); + assert!(wakes.queues.lock().unwrap().is_empty(), "unsubscribed queues leave no entry"); + } + + #[test] + fn a_queue_is_checked_for_abandoned_leases_at_most_once_an_interval() { + let wakes = PollWakes::default(); + assert!(wakes.recovery_due("default", "orders")); + assert!(!wakes.recovery_due("default", "orders"), "the same queue within the interval"); + assert!(wakes.recovery_due("default", "billing"), "another queue"); + assert!(wakes.recovery_due("tenant", "orders"), "another namespace"); + wakes.recovery_checks.lock().unwrap().insert( + ("default".to_owned(), "orders".to_owned()), + std::time::Instant::now() - RECOVERY_CHECK_INTERVAL, + ); + assert!(wakes.recovery_due("default", "orders"), "once the interval has passed"); + } + + #[test] + fn waiting_polls_are_counted_while_they_wait() { + let wakes = PollWakes::default(); + let first = wakes.waiting(); + let second = wakes.waiting(); + assert_eq!(wakes.waiting_now(), 2); + drop(first); + assert_eq!(wakes.waiting_now(), 1); + drop(second); + assert_eq!(wakes.waiting_now(), 0); + } +} diff --git a/rust/src/runtime/probe_connections.rs b/rust/src/runtime/probe_connections.rs index 98064bf07..3d46bb852 100644 --- a/rust/src/runtime/probe_connections.rs +++ b/rust/src/runtime/probe_connections.rs @@ -116,6 +116,19 @@ store_methods! { /// already free is taken even after `answer_by`. async fn budgeted_connection_by( &self, budget: &Arc, answer_by: Option, + ) -> Result>> { + #[cfg(test)] + let started = std::time::Instant::now(); + let acquired = self.budgeted_connection_untimed(budget, answer_by).await; + #[cfg(test)] + if Arc::ptr_eq(budget, &self.probe_slots) { + probe_stats::record(started.elapsed(), acquired.is_err()); + } + acquired + } + + async fn budgeted_connection_untimed( + &self, budget: &Arc, answer_by: Option, ) -> Result>> { let deadline = tokio::time::Instant::now() + self.pool.options().get_acquire_timeout(); let slot = match answer_by.filter(|answer_by| *answer_by < deadline) { @@ -135,6 +148,32 @@ store_methods! { } } +/// Read-slot waits, for the held-poll benchmark +/// (`runtime::mysql::held_poll_bench`). +#[cfg(test)] +pub(super) mod probe_stats { + use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}}; + static WAITS: Mutex> = Mutex::new(Vec::new()); + static FAILURES: AtomicUsize = AtomicUsize::new(0); + + pub(super) fn record(waited: std::time::Duration, failed: bool) { + WAITS.lock().unwrap().push(waited.as_secs_f64() * 1000.0); + if failed { + FAILURES.fetch_add(1, Ordering::Relaxed); + } + } + + pub(in crate::runtime) fn reset() { + WAITS.lock().unwrap().clear(); + FAILURES.store(0, Ordering::Relaxed); + } + + /// The read-slot waits in milliseconds, and how many failed. + pub(in crate::runtime) fn take() -> (Vec, usize) { + (std::mem::take(&mut *WAITS.lock().unwrap()), FAILURES.load(Ordering::Relaxed)) + } +} + #[cfg(test)] mod tests { use super::super::{QueryTaskConfig, store::Store}; diff --git a/rust/src/runtime/queries.rs b/rust/src/runtime/queries.rs index 7aed07abf..f1df81fc4 100644 --- a/rust/src/runtime/queries.rs +++ b/rust/src/runtime/queries.rs @@ -862,7 +862,7 @@ where // Periodic probes observe results committed by another server process. let mut last = json!({"status":"pending"}); loop { - let wake = self.wake.notified(); + let wake = super::poll_wakes::any(self.wake.notified(), self.poll_wakes.others.notified()); let remaining = (deadline - authority::now()).to_std().unwrap_or_default(); let read = Self::query(DB::QUERY_CACHE_GET) .bind(&key) @@ -1048,7 +1048,7 @@ where let mut wait_slot = None; loop { let probe = self.poll_capacity.probe().await; - let wake = self.wake.notified(); + let wake = super::poll_wakes::any(self.wake.notified(), self.poll_wakes.others.notified()); // A later probe that cannot get a read slot by the poll's // deadline answers as at its deadline (Server #1355). let first_probe = std::mem::take(&mut first); @@ -1109,7 +1109,7 @@ where self.poll_capacity.hold(&mut wait_slot, super::poll_capacity::Pool::QueryTask, &self.namespace, text(body, "task_queue")?, "query_task")?; drop(probe); - pace.wait(wake, deadline).await; + pace.wait(wake, deadline, &self.poll_wakes).await; } } diff --git a/rust/src/runtime/store.rs b/rust/src/runtime/store.rs index 0bda5bc12..b4cb7ea55 100644 --- a/rust/src/runtime/store.rs +++ b/rust/src/runtime/store.rs @@ -209,6 +209,8 @@ pub(super) struct Store { transitions: Arc>, pub(super) wake: Arc, history_wakes: Arc, + /// Held worker polls' per-queue wakes (Server #1372). + pub(super) poll_wakes: Arc, pub(super) namespace: Arc, pub(super) memo_codec: Arc, pub(super) memo_size_limit: Option, @@ -408,6 +410,7 @@ where transitions: Arc::default(), wake: Arc::new(Notify::new()), history_wakes: Arc::default(), + poll_wakes: Arc::default(), namespace: "default".into(), memo_codec: Arc::new(Semaphore::new(1)), memo_size_limit: Some(262_144), @@ -454,6 +457,7 @@ where transitions: self.transitions.clone(), wake: self.wake.clone(), history_wakes: self.history_wakes.clone(), + poll_wakes: self.poll_wakes.clone(), namespace: namespace.into(), memo_codec: self.memo_codec.clone(), memo_size_limit: self.memo_size_limit, @@ -539,13 +543,15 @@ where /// Give the maintenance loop its own connection (Server #1355): one /// connection with the request pool's options, hooks and connect /// options, opened when the loop first needs it. The node still opens - /// at most `statement_cache::POOL_CONNECTIONS` connections. + /// at most `statement_cache::POOL_CONNECTIONS` connections. Its statement + /// cache keeps at most `statement_cache::MAINTENANCE` entries + /// (Server #1372). pub(super) fn with_maintenance_pool(mut self) -> Self { self.maintenance_pool = Some( self.pool.options().clone() .max_connections(crate::statement_cache::MAINTENANCE_CONNECTIONS) .min_connections(0) - .connect_lazy_with((*self.pool.connect_options()).clone()), + .connect_lazy_with(DB::maintenance_connect_options((*self.pool.connect_options()).clone())), ); self } @@ -605,6 +611,7 @@ where .await .map(|inner| { Transaction::new(inner, self.history_budget, Some(queued), Some(self.history_wakes.clone())) + .with_poll_wakes(self.poll_wakes.clone()) }) } /// A background transition (Server #1355): its turn on the transition @@ -632,7 +639,8 @@ where queued: tokio::sync::OwnedMutexGuard<()>, ) -> Result> { let inner = DB::begin_on(connection).await?; - Ok(Transaction::new(inner, self.history_budget, Some(queued), Some(self.history_wakes.clone()))) + Ok(Transaction::new(inner, self.history_budget, Some(queued), Some(self.history_wakes.clone())) + .with_poll_wakes(self.poll_wakes.clone())) } /// [`begin_read`](Self::begin_read) on a connection the caller holds. @@ -755,7 +763,9 @@ where ) .await?; tx.commit().await?; - self.wake.notify_waiters(); + // The commit woke the held polls of the queues it made ready; wake + // the other waiters, not every held poll (Server #1372). + self.poll_wakes.others.notify_waiters(); Ok(started) } @@ -1411,7 +1421,9 @@ where // A refusal commits its durable rejection record. tx.commit().await?; let mut response = admitted?; - self.wake.notify_waiters(); + // The commit woke the held polls of the queues it made ready; wake + // the other waiters, not every held poll (Server #1372). + self.poll_wakes.others.notify_waiters(); if let Some(key) = key { response["request_id"] = json!(key); response["retained"] = json!(false); @@ -2678,6 +2690,9 @@ where let mut pace = super::poll_readiness::ReadPace::new(); let worker_id = text(&body, "worker_id")?; let mut wait_slot = None; + // Woken by commits that make its queue ready, and by everything + // that still wakes every poll (Server #1372). + let queue_wait = self.poll_wakes.subscribe(self.namespace.as_ref(), text(&body, "task_queue")?); loop { // Each probe's database work takes a probe permit, so polls // leave the reserved connections free (Server #982). @@ -2692,7 +2707,7 @@ where return Err(super::RuntimeError::Protocol { status: StatusCode::SERVICE_UNAVAILABLE, response }); } // Register the notification before probing. - let wake = self.wake.notified(); + let wake = super::poll_wakes::any(self.wake.notified(), queue_wait.notify.notified()); let first_probe = std::mem::take(&mut first); let (current, mut claimed) = match &poll_request { Some(request) if first_probe => { @@ -2750,6 +2765,7 @@ where if current && kind == "workflow" && matches!(claimed, Ok(None)) + && (first_probe || self.poll_wakes.recovery_due(self.namespace.as_ref(), text(&body, "task_queue")?)) && self.recover_abandoned_workflow_leases(text(&body, "task_queue")?).await? { claimed = self.claim(&body, kind, protocol_version, page, poll_request.as_ref(), fence.as_ref(), claim_until).await; @@ -2800,7 +2816,7 @@ where if let Some(id) = poll_pause_id(kind, &body, poll_request.as_ref()) { super::poll_pauses::stop_at(id, super::poll_pauses::PollPoint::Waiting).await; } - pace.wait(wake, deadline).await; + pace.wait(wake, deadline, &self.poll_wakes).await; } } @@ -4937,9 +4953,14 @@ where let cached_through = tail.as_ref().map(super::continuation_tail::Tail::cached_through); Self::record_sticky_cache(&mut tx, self.namespace.as_ref(), &run_id, task_id, &body, &run_status, metrics, cached_through).await?; } + // Completing this workflow task releases the same-run fence on the + // run's other workflow tasks (Server #1282), so its commit also wakes + // the run's queue; the commit wakes the queues it made ready, and the + // other waiters are woken here, not every held poll (Server #1372). + tx.ready_queues.insert((self.namespace.to_string(), DB::string(&run, "queue")?)); let transaction = if deferred { Some(tx) } else { tx.commit().await?; - self.wake.notify_waiters(); + self.poll_wakes.others.notify_waiters(); None }; let mut response = json!({"task_id": task_id, "run_id": run_id, "run_status": run_status, "workflow_task_attempt": body["workflow_task_attempt"], "outcome": "completed", "recorded": true, "reason": null, "created_task_ids": created}); @@ -5449,7 +5470,9 @@ where let mut response = self.complete_activity_in(&mut tx, task_id, body, external.as_ref(), result, workflow_poll, prefix).await?; tx.commit().await?; super::carried_polls::refresh_workflow_clock(&mut response); - self.wake.notify_waiters(); + // The commit woke the held polls of the queues it made ready; wake + // the other waiters, not every held poll (Server #1372). + self.poll_wakes.others.notify_waiters(); Ok(response) } @@ -6187,6 +6210,7 @@ where .bind(tags.compatibility.as_deref()) .bind(DB::optional_time(matches!(kind, "workflow" | "activity").then_some(created))) .execute(&mut **tx).await?; + tx.ready_queues.insert((namespace.clone(), queue.to_owned())); Ok(task_id) } diff --git a/rust/src/runtime/task_offer_dispatch.rs b/rust/src/runtime/task_offer_dispatch.rs index d4b75ce43..a8589651c 100644 --- a/rust/src/runtime/task_offer_dispatch.rs +++ b/rust/src/runtime/task_offer_dispatch.rs @@ -206,7 +206,7 @@ store_methods! { response: super::storage_admission::refusal(&pressure, super::storage_admission::Admission::Poll, Some(scope.request_id)), }); } - let wake = self.wake.notified(); + let wake = super::poll_wakes::any(self.wake.notified(), self.poll_wakes.others.notified()); let window = windows.current().ok_or_else(unavailable)?; match self.issue_task_offer(&claim, keys, &window).await { Ok(Some(offer)) => return Ok(Delivery::Offer(Some(offer))), @@ -219,7 +219,7 @@ store_methods! { } self.poll_capacity.hold(&mut slot, pool, &self.namespace, scope.queue, kind)?; drop(probe); - pace.wait(wake, deadline).await; + pace.wait(wake, deadline, &self.poll_wakes).await; } } diff --git a/rust/src/runtime/transaction.rs b/rust/src/runtime/transaction.rs index b90aa6eba..6b8ab5670 100644 --- a/rust/src/runtime/transaction.rs +++ b/rust/src/runtime/transaction.rs @@ -92,6 +92,10 @@ pub(super) struct Transaction<'a, DB: Backend> { /// carried claim fenced, under the same transition lock. pub(super) fresh_lease_owner: Option, history_wakes: Option>, + /// The queues this transaction created ready tasks on, and the wakes of + /// their held polls (Server #1372). + pub(super) ready_queues: super::poll_wakes::ReadyQueues, + poll_wakes: Option>, // An implicit failure drops the database transaction before this guard. _queue_guard: Option>, #[cfg(test)] @@ -120,12 +124,21 @@ impl<'a, DB: Backend> Transaction<'a, DB> { remembered_events: None, fresh_lease_owner: None, history_wakes, + ready_queues: Default::default(), + poll_wakes: None, _queue_guard: queue_guard, #[cfg(test)] commit_gate: None, } } + /// Wake the held polls of the queues this transaction creates ready + /// tasks on when it commits (Server #1372). + pub(super) fn with_poll_wakes(mut self, wakes: Arc) -> Self { + self.poll_wakes = Some(wakes); + self + } + /// Cache only immutable task tags from an authoritative row this /// transaction already read. A malformed tag is decoded at the original /// task-creation boundary if that path needs it, not on unrelated reads. @@ -300,6 +313,9 @@ where if !changed_runs.is_empty() && let Some(wakes) = self.history_wakes { wakes.committed(changed_runs.keys()); } + if !self.ready_queues.is_empty() && let Some(wakes) = self.poll_wakes { + wakes.wake_queues(&self.ready_queues); + } Ok(()) } } diff --git a/rust/src/runtime/update_validation.rs b/rust/src/runtime/update_validation.rs index b56502931..4433a34b4 100644 --- a/rust/src/runtime/update_validation.rs +++ b/rust/src/runtime/update_validation.rs @@ -373,7 +373,7 @@ where self.wake.notify_waiters(); let deadline = tokio::time::Instant::now() + Duration::from_secs(timeouts().0 as u64); loop { - let wake = self.wake.notified(); + let wake = super::poll_wakes::any(self.wake.notified(), self.poll_wakes.others.notified()); let status = Self::query("SELECT status FROM workflow_update_validation_tasks WHERE id=$1") .bind(&task_id) .fetch_one(&self.pool) @@ -1066,7 +1066,7 @@ where let mut wait_slot = None; loop { let probe = self.poll_capacity.probe().await; - let wake = self.wake.notified(); + let wake = super::poll_wakes::any(self.wake.notified(), self.poll_wakes.others.notified()); if (std::mem::take(&mut first) || self.validation_waiting(task_queue).await?) && let Some(task_id) = self.claim_update_validation(worker_id, task_queue).await? { @@ -1079,7 +1079,7 @@ where self.poll_capacity.hold(&mut wait_slot, super::poll_capacity::Pool::QueryTask, &self.namespace, task_queue, "update_validation_task")?; drop(probe); - pace.wait(wake, deadline).await; + pace.wait(wake, deadline, &self.poll_wakes).await; } } @@ -1186,9 +1186,12 @@ where let mut pace = super::poll_readiness::ReadPace::new(); let mut first = true; let mut wait_slot = None; + // Woken by commits that make its queue ready, and by everything + // that still wakes every poll (Server #1372). + let queue_wait = self.poll_wakes.subscribe(self.namespace.as_ref(), &task_queue); loop { let probe = self.poll_capacity.probe().await; - let wake = self.wake.notified(); + let wake = super::poll_wakes::any(self.wake.notified(), queue_wait.notify.notified()); let first_probe = std::mem::take(&mut first); let current = match &fence { _ if first_probe && request.is_some() => true, @@ -1235,7 +1238,7 @@ where self.poll_capacity.hold(&mut wait_slot, super::poll_capacity::Pool::Worker, &self.namespace, &task_queue, "workflow_task")?; drop(probe); - pace.wait(wake, deadline).await; + pace.wait(wake, deadline, &self.poll_wakes).await; } } diff --git a/rust/src/runtime/updates.rs b/rust/src/runtime/updates.rs index 63fcad3ee..eda11ba59 100644 --- a/rust/src/runtime/updates.rs +++ b/rust/src/runtime/updates.rs @@ -825,7 +825,7 @@ where let deadline = tokio::time::Instant::now() + Duration::from_secs(wait_seconds as u64); loop { - let wake = self.wake.notified(); + let wake = super::poll_wakes::any(self.wake.notified(), self.poll_wakes.others.notified()); let update = Self::query(UPDATE_ROW) .bind(update_id) .fetch_one(&self.pool) diff --git a/rust/src/statement_cache.rs b/rust/src/statement_cache.rs index 44cd422ae..724f72ee9 100644 --- a/rust/src/statement_cache.rs +++ b/rust/src/statement_cache.rs @@ -3,36 +3,68 @@ //! //! SQLx keeps a least-recently-used cache of server-side prepared statements //! on each connection. Its default of 100 entries is smaller than the native -//! hot path: the #1078 workload uses about 160 distinct statements on every +//! hot path: the #1078 workload used about 160 distinct statements on every //! pool connection, so the cache evicted and prepared about 12 statements -//! (plus 11 closes) per workflow. 200 entries hold that working set. +//! (plus 11 closes) per workflow, and 200 entries held that working set. +//! +//! A node now opens five connections (Server #1372): a request pool of four +//! and the maintenance connection. The maintenance loop uses few statements +//! (about 8 on that workload), so its connection keeps at most +//! [`MAINTENANCE`], and the request connections keep the configured capacity, +//! by default 192: still above the #1174 working set (166), and the most +//! that keeps 20 nodes within MySQL's default limit beside a 48-entry +//! maintenance cache. On the in-process shape of the #1078 workload (200 +//! workflows of five sequential activities and a signal, six workers) each +//! request connection uses 123 to 126 distinct statements; 128 entries start +//! to close statements, and SQLx's 100 prepares 17 again per workflow. //! //! On MySQL, cached statements count toward the server-wide //! `max_prepared_stmt_count` (default 16382), shared by every client of the -//! server. A native node holds at most `POOL_CONNECTIONS × capacity` of them, -//! so a cluster stays within the limit while -//! `nodes × POOL_CONNECTIONS × capacity + other clients ≤ max_prepared_stmt_count`. +//! server. A native node holds at most +//! `REQUEST_CONNECTIONS × capacity + min(capacity, MAINTENANCE)` of them, so a +//! cluster stays within the limit while +//! `nodes × (4 × capacity + min(capacity, 48)) + other clients ≤ max_prepared_stmt_count`. //! The upper bound below keeps a single node within the default limit. /// Environment variable that sets the capacity. pub const ENV: &str = "DW_NATIVE_DB_STATEMENT_CACHE_CAPACITY"; /// SQLx's `DB_URL` parameter for the same capacity. pub const URL_PARAMETER: &str = "statement-cache-capacity"; -/// Capacity when neither `ENV` nor `URL_PARAMETER` is set. -pub const DEFAULT: usize = 200; +/// Capacity of each request connection when neither `ENV` nor +/// `URL_PARAMETER` is set. +pub const DEFAULT: usize = 192; /// Connections a native node opens to its MySQL or PostgreSQL database: its -/// request pool plus its maintenance pool (Server #1355). -pub const POOL_CONNECTIONS: u32 = 4; +/// request pool plus its maintenance pool (Server #1355). The request pool of +/// four gives held polls two read slots and the transition queue's holder a +/// slot of its own, and still leaves producers the last connection +/// (Server #1372). +pub const POOL_CONNECTIONS: u32 = 5; /// The maintenance loop's own pool (timers, schedules, repair, retention and /// offer-window refresh), so it never borrows a request connection. pub const MAINTENANCE_CONNECTIONS: u32 = 1; /// The request pool: everything else, including held polls. pub const REQUEST_CONNECTIONS: u32 = POOL_CONNECTIONS - MAINTENANCE_CONNECTIONS; +/// The most statements the maintenance connection keeps: the configured +/// capacity when that is smaller ([`maintenance`]). +pub const MAINTENANCE: usize = 48; /// MySQL's default `max_prepared_stmt_count`. pub const MYSQL_DEFAULT_MAX_PREPARED_STMT_COUNT: usize = 16_382; /// Largest accepted capacity: one node's full pool stays within MySQL's /// default `max_prepared_stmt_count`. -pub const MAX: usize = MYSQL_DEFAULT_MAX_PREPARED_STMT_COUNT / POOL_CONNECTIONS as usize; +pub const MAX: usize = (MYSQL_DEFAULT_MAX_PREPARED_STMT_COUNT - MAINTENANCE_CONNECTIONS as usize * MAINTENANCE) + / REQUEST_CONNECTIONS as usize; + +/// The maintenance connection's capacity for a configured `capacity`: zero +/// still turns the cache off. +pub fn maintenance(capacity: usize) -> usize { + capacity.min(MAINTENANCE) +} + +/// Statements one node holds at most with `capacity` per request connection. +pub const fn node_statements(capacity: usize) -> usize { + let maintenance = if capacity < MAINTENANCE { capacity } else { MAINTENANCE }; + REQUEST_CONNECTIONS as usize * capacity + MAINTENANCE_CONNECTIONS as usize * maintenance +} pub const INVALID: &str = "invalid DW_NATIVE_DB_STATEMENT_CACHE_CAPACITY"; pub const INVALID_URL: &str = "invalid DB_URL statement-cache-capacity"; @@ -40,10 +72,14 @@ pub const CONFLICT: &str = "DB_URL statement-cache-capacity conflicts with DW_NA /// Distinct statements per pool connection on the #1078 workload (Server #1174). const MEASURED_WORKING_SET: usize = 166; +/// Distinct statements on the maintenance connection on the #1372 workload. +const MEASURED_MAINTENANCE_WORKING_SET: usize = 8; const _: () = assert!(DEFAULT >= MEASURED_WORKING_SET); -const _: () = assert!(MAX * POOL_CONNECTIONS as usize <= MYSQL_DEFAULT_MAX_PREPARED_STMT_COUNT); +const _: () = assert!(MAINTENANCE >= 4 * MEASURED_MAINTENANCE_WORKING_SET); +const _: () = assert!(node_statements(MAX) <= MYSQL_DEFAULT_MAX_PREPARED_STMT_COUNT); +const _: () = assert!(node_statements(MAX + 1) > MYSQL_DEFAULT_MAX_PREPARED_STMT_COUNT); // 20 nodes at the default fit within MySQL's default limit. -const _: () = assert!(20 * DEFAULT * POOL_CONNECTIONS as usize <= MYSQL_DEFAULT_MAX_PREPARED_STMT_COUNT); +const _: () = assert!(20 * node_statements(DEFAULT) <= MYSQL_DEFAULT_MAX_PREPARED_STMT_COUNT); fn parse(value: &str) -> Option { if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) { @@ -85,7 +121,10 @@ mod tests { fn unset_capacity_uses_the_default() { assert_eq!(capacity(None, None), Ok(DEFAULT)); assert_eq!(capacity(Some(""), Some("mysql://db/app?charset=utf8mb4")), Ok(DEFAULT)); - assert_eq!(MAX, 4095); + assert_eq!(MAX, 4083); + assert_eq!(maintenance(DEFAULT), MAINTENANCE); + assert_eq!(maintenance(0), 0); + assert_eq!(maintenance(20), 20); // The environment audit knows the name; it is not an unknown DW_ variable. assert!(crate::config_audit::NATIVE_HONORED.iter().any(|setting| setting.name == ENV)); } @@ -94,26 +133,33 @@ mod tests { fn environment_or_url_sets_the_capacity() { assert_eq!(capacity(Some("400"), None), Ok(400)); assert_eq!(capacity(Some(" 0 "), None), Ok(0)); - assert_eq!(capacity(Some("4095"), None), Ok(4095)); + assert_eq!(capacity(Some("4083"), None), Ok(4083)); assert_eq!(capacity(None, Some("mysql://u:p@db/app?statement-cache-capacity=150")), Ok(150)); assert_eq!( capacity(Some("150"), Some("postgres://db/app?sslmode=prefer&statement-cache-capacity=150#x")), Ok(150) ); - assert_eq!(capacity(None, Some("mysql://db/app#statement-cache-capacity=7")), Ok(200)); + assert_eq!(capacity(None, Some("mysql://db/app#statement-cache-capacity=7")), Ok(DEFAULT)); } #[test] fn invalid_or_conflicting_capacities_are_refused_without_the_url() { - for value in ["-1", "+5", "1e3", "abc", "4096", "18446744073709551616"] { + for value in ["-1", "+5", "1e3", "abc", "4084", "18446744073709551616"] { assert_eq!(capacity(Some(value), None), Err(INVALID), "{value}"); } let secret = "mysql://user:secret@db/app?statement-cache-capacity="; - for value in ["", "x", "4096"] { + for value in ["", "x", "4084"] { let error = capacity(None, Some(&format!("{secret}{value}"))).unwrap_err(); assert_eq!(error, INVALID_URL); assert!(!error.contains("secret")); } assert_eq!(capacity(Some("300"), Some("mysql://db/app?statement-cache-capacity=200")), Err(CONFLICT)); } + + #[test] + fn a_node_holds_four_request_caches_and_a_small_maintenance_cache() { + assert_eq!(node_statements(DEFAULT), 4 * 192 + 48); + assert_eq!(node_statements(20), 5 * 20); + assert_eq!(node_statements(0), 0); + } } diff --git a/rust/tests/execution.rs b/rust/tests/execution.rs index 0400d35a1..5d0bf435f 100644 --- a/rust/tests/execution.rs +++ b/rust/tests/execution.rs @@ -18,6 +18,8 @@ use std::str::FromStr; #[path = "execution/schedules.rs"] mod schedules; +#[path = "execution/hot_path_cache.rs"] +mod hot_path_cache; #[path = "execution/visibility.rs"] mod visibility; diff --git a/rust/tests/execution/hot_path_cache.rs b/rust/tests/execution/hot_path_cache.rs new file mode 100644 index 000000000..beae7813e --- /dev/null +++ b/rust/tests/execution/hot_path_cache.rs @@ -0,0 +1,139 @@ +//! Statement-cache measurement (Server #1372): the #1171 workload shape, +//! 200 workflows of five sequential 20 ms activities plus one signal each, +//! on six workers that long-poll and heartbeat, at the capacity in +//! `DW_BENCH_CACHE` (default: the runtime's). It reports the server's +//! prepare, execute and close counters per workflow and, when the server's +//! `performance_schema` is on, each connection's cached statements. +//! +//! Run against a disposable MySQL or MariaDB: +//! `DW_EXECUTION_MYSQL_URL=... DW_BENCH_CACHE=192 cargo test --test execution hot_path_cache -- --ignored --nocapture` +use super::*; +use sqlx::Connection; +use std::{ + collections::HashMap, + sync::{Arc, atomic::{AtomicUsize, Ordering}}, + time::Duration, +}; + +async fn statement_counters(connection: &mut sqlx::MySqlConnection) -> HashMap { + let rows = sqlx::raw_sql("SHOW GLOBAL STATUS LIKE 'Com_stmt_%'").fetch_all(&mut *connection).await.unwrap(); + rows.iter() + .map(|row| (sqlx::Row::get::(row, 0), sqlx::Row::get::(row, 1).parse().unwrap())) + .collect() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "benchmark; requires DW_EXECUTION_MYSQL_URL"] +async fn hot_path_cache_measurement() { + const ACTIVITIES: usize = 5; + let workflows: usize = std::env::var("DW_BENCH_WORKFLOWS").ok().and_then(|value| value.parse().ok()).unwrap_or(200); + let database = TestDatabase::new().await; + let TestDatabase::MySql { options, .. } = &database else { panic!("the measurement needs DW_EXECUTION_MYSQL_URL") }; + let mut options = options.as_ref().clone(); + let capacity = std::env::var("DW_BENCH_CACHE").ok().and_then(|value| value.parse().ok()) + .unwrap_or(durable_workflow_server::statement_cache::DEFAULT); + options = options.statement_cache_capacity(capacity); + let runtime = Runtime::open_mysql(options.clone(), "test-token".into()).await.unwrap(); + let app = router(runtime.clone()); + let signal_contract = json!({"echo":{"signals":["payload"],"signal_contracts":[{"name":"payload","parameters":[{"name":"args", + "position":0,"type":null,"required":false,"variadic":true,"default_available":false,"default":null,"allows_null":true}]}]}}); + for n in 0..6 { + let (code, body) = request(&app, "POST", "/api/worker/register", json!({"worker_id":format!("w{n}"),"task_queue":"test", + "runtime":"php","supported_workflow_types":["echo"],"supported_activity_types":["act"], + "workflow_command_contracts":signal_contract})).await; + assert_eq!(code, StatusCode::CREATED, "{body}"); + } + let mut counters = sqlx::MySqlConnection::connect_with(&options.clone().database("")).await.unwrap(); + let before = statement_counters(&mut counters).await; + let began = std::time::Instant::now(); + let done = Arc::new(AtomicUsize::new(0)); + let mut tasks = Vec::new(); + for producer in 0..2 { + let app = app.clone(); + tasks.push(tokio::spawn(async move { + for n in 0..workflows / 2 { + let id = format!("wf-{producer}-{n}"); + let (code, body) = request(&app, "POST", "/api/workflows", json!({"workflow_id":id,"workflow_type":"echo", + "task_queue":"test","input":envelope(Payload::Array(vec![Payload::Long(1)]))})).await; + assert_eq!(code, StatusCode::CREATED, "{body}"); + let (code, body) = request(&app, "POST", &format!("/api/workflows/{id}/signal/payload"), + json!({"input":envelope(Payload::Array(vec![Payload::Long(2)]))})).await; + assert_eq!(code, StatusCode::ACCEPTED, "{body}"); + } + })); + } + for n in 0..6 { + let worker = format!("w{n}"); + let (app_heartbeat, worker_heartbeat, done_heartbeat) = (app.clone(), worker.clone(), done.clone()); + // As an SDK does: a registration not seen for 30 s is stale. + tasks.push(tokio::spawn(async move { + while done_heartbeat.load(Ordering::SeqCst) < workflows { + let (code, body) = request(&app_heartbeat, "POST", "/api/worker/heartbeat", json!({"worker_id":worker_heartbeat})).await; + assert_eq!(code, StatusCode::OK, "{body}"); + tokio::time::sleep(Duration::from_secs(5)).await; + } + })); + for kind in ["workflow", "activity"] { + let (app, worker, done) = (app.clone(), worker.clone(), done.clone()); + tasks.push(tokio::spawn(async move { + while done.load(Ordering::SeqCst) < workflows { + let (code, body) = request(&app, "POST", &format!("/api/worker/{kind}-tasks/poll"), + json!({"worker_id":worker,"task_queue":"test","timeout_seconds":1})).await; + assert_eq!(code, StatusCode::OK, "{body}"); + let task = &body["task"]; + if task.is_null() { + continue; + } + let id = task["task_id"].as_str().unwrap(); + if kind == "activity" { + tokio::time::sleep(Duration::from_millis(20)).await; + let (code, body) = request(&app, "POST", &format!("/api/worker/activity-tasks/{id}/complete"), + json!({"lease_owner":worker,"activity_attempt_id":task["activity_attempt_id"],"result":envelope(Payload::Long(7))})).await; + assert_eq!(code, StatusCode::OK, "{body}"); + continue; + } + let events = task["history_events"].as_array().cloned().unwrap_or_default(); + let count = |name: &str| events.iter().filter(|event| event["event_type"] == name).count(); + let (scheduled, completed) = (count("ActivityScheduled"), count("ActivityCompleted")); + let commands = if scheduled > completed { + // A signal woke the workflow while its activity runs. + json!([{"type":"record_side_effect","result":envelope(Payload::Null)}]) + } else if completed < ACTIVITIES { + json!([{"type":"schedule_activity","activity_type":"act","arguments":envelope(Payload::Array(vec![]))}]) + } else { + json!([{"type":"complete_workflow","result":envelope(Payload::Long(9))}]) + }; + let finishing = completed >= ACTIVITIES && scheduled == completed; + let (code, body) = finish_task(&app, task, commands).await; + assert!(code.is_success(), "{code} {body}"); + if finishing { + done.fetch_add(1, Ordering::SeqCst); + } + } + })); + } + } + tokio::time::timeout(Duration::from_secs(600), async { + for task in tasks { + task.await.unwrap(); + } + }) + .await + .expect("bounded workload"); + let elapsed = began.elapsed().as_secs_f64(); + let after = statement_counters(&mut counters).await; + let delta = |name: &str| after.get(name).copied().unwrap_or(0) - before.get(name).copied().unwrap_or(0); + let (prepared, executed, closed) = (delta("Com_stmt_prepare"), delta("Com_stmt_execute"), delta("Com_stmt_close")); + // Each cached connection's statements, when performance_schema is on. + let cached: Vec = sqlx::query_scalar( + "SELECT COUNT(*) FROM performance_schema.prepared_statements_instances GROUP BY OWNER_THREAD_ID ORDER BY COUNT(*)") + .fetch_all(&mut counters).await.unwrap_or_default(); + eprintln!( + "CACHE capacity={capacity} workflows={workflows} elapsed={elapsed:.1}s prepare={prepared} execute={executed} close={closed} \ + prepares_per_workflow={:.2} closes_per_workflow={:.2} hit_rate={:.4} cached_per_connection={cached:?}", + prepared as f64 / workflows as f64, closed as f64 / workflows as f64, + 1.0 - prepared as f64 / executed.max(1) as f64, + ); + drop(counters); + runtime.close().await; +} diff --git a/rust/vendor/sqlx-mysql/DURABLE-PATCH.md b/rust/vendor/sqlx-mysql/DURABLE-PATCH.md index ea5340384..91802b341 100644 --- a/rust/vendor/sqlx-mysql/DURABLE-PATCH.md +++ b/rust/vendor/sqlx-mysql/DURABLE-PATCH.md @@ -1,6 +1,6 @@ # SQLx MySQL driver patches -This directory contains the official `sqlx-mysql` 0.9.0 crate with six scoped +This directory contains the official `sqlx-mysql` 0.9.0 crate with seven scoped patches. Its published archive has SHA-256 `90b8020fe17c5f2c245bfa2505d7ef59c5604839527c740266ad2214acebea27` and VCS @@ -209,3 +209,11 @@ 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, or when the server bounds silent peers another way. + +## The statement cache capacity can be read + +`get_statement_cache_capacity` (`src/options/mod.rs`) returns the capacity the +connect options carry. Native Server reads it to give its maintenance +connection a smaller cache than its request connections (Server #1372), and +still none when the operator turned the cache off. Remove it only when a +published release has the same getter. diff --git a/rust/vendor/sqlx-mysql/src/options/mod.rs b/rust/vendor/sqlx-mysql/src/options/mod.rs index 421bfb700..d65475804 100755 --- a/rust/vendor/sqlx-mysql/src/options/mod.rs +++ b/rust/vendor/sqlx-mysql/src/options/mod.rs @@ -297,6 +297,12 @@ impl MySqlConnectOptions { self } + /// The capacity of the prepared-statement cache (Durable Workflow + /// Server #1372: its maintenance connection keeps a smaller one). + pub fn get_statement_cache_capacity(&self) -> usize { + self.statement_cache_capacity + } + /// Sets the character set for the connection. /// /// The default character set is `utf8mb4`. This is supported from MySQL 5.5.3. diff --git a/rust/vendor/sqlx-postgres/DURABLE-PATCH.md b/rust/vendor/sqlx-postgres/DURABLE-PATCH.md index bab449bf7..dca49245a 100644 --- a/rust/vendor/sqlx-postgres/DURABLE-PATCH.md +++ b/rust/vendor/sqlx-postgres/DURABLE-PATCH.md @@ -1,7 +1,8 @@ # SQLx PostgreSQL driver patch This directory contains the official `sqlx-postgres` 0.9.0 crate with one -backported driver correction, one native tagging patch and two reply bounds. Its published +backported driver correction, one native tagging patch, two reply bounds and a +capacity getter. Its published archive has SHA-256 `87a2bdd6e83f6b3ea525ca9fee568030508b58355a43d0b2c1674d5f79dcd65e` (the `Cargo.lock` checksum it replaces) and VCS commit @@ -117,3 +118,11 @@ 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, or when the server bounds silent peers another way. + +## The statement cache capacity can be read + +`get_statement_cache_capacity` (`src/options/mod.rs`) returns the capacity the +connect options carry. Native Server reads it to give its maintenance +connection a smaller cache than its request connections (Server #1372), and +still none when the operator turned the cache off. Remove it only when a +published release has the same getter. diff --git a/rust/vendor/sqlx-postgres/src/options/mod.rs b/rust/vendor/sqlx-postgres/src/options/mod.rs index 21e6628ca..df56e71d2 100755 --- a/rust/vendor/sqlx-postgres/src/options/mod.rs +++ b/rust/vendor/sqlx-postgres/src/options/mod.rs @@ -354,6 +354,12 @@ impl PgConnectOptions { self } + /// The capacity of the prepared-statement cache (Durable Workflow + /// Server #1372: its maintenance connection keeps a smaller one). + pub fn get_statement_cache_capacity(&self) -> usize { + self.statement_cache_capacity + } + /// Sets the application name. Defaults to None /// /// # Example