Skip to content

Commit 9d817de

Browse files
committed
feat(server): make the mutation lock pool size configurable
The mutation lock pool was fixed at 4 connections per replica. That number rests on one reconnect-burst bench rather than scale testing, so a gateway that serves many more sandboxes needs a way to raise it without a rebuild. Add --db-lock-max-connections, OPENSHELL_DB_LOCK_MAX_CONNECTIONS and the database_lock_max_connections gateway.toml key next to the data pool knob, resolved in the same order; Helm deployments set it through gatewayConfig. The default stays 4, zero is rejected, SQLite ignores it with a warning, and the gateway logs both pool sizes at startup. PostgreSQL now needs at least 2 data connections, because the SSH identity lock keeps one while it queries the pool. The connection sizing docs, the HA guide formula and the debug skill now count data plus lock connections. Part of #3528 Signed-off-by: Emilien Macchi <emacchi@redhat.com>
1 parent 231ef54 commit 9d817de

16 files changed

Lines changed: 396 additions & 97 deletions

File tree

‎crates/openshell-core/src/config.rs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,14 @@ pub struct Config {
253253
/// connection.
254254
pub database_max_connections: Option<u32>,
255255

256+
/// Connection ceiling for the `PostgreSQL` mutation lock pool.
257+
///
258+
/// `None` keeps the built-in default of 4. Each mutation guard holds one
259+
/// lock connection, so this bounds how many guarded mutations a replica
260+
/// runs or waits on in `PostgreSQL` at once. `SQLite` has no lock pool and
261+
/// ignores it.
262+
pub database_lock_max_connections: Option<u32>,
263+
256264
/// Explicit compute driver configured for the gateway.
257265
/// `None` enables runtime auto-detection.
258266
pub compute_driver: Option<String>,
@@ -903,6 +911,7 @@ impl Config {
903911
gateway_jwt: None,
904912
database_url: String::new(),
905913
database_max_connections: None,
914+
database_lock_max_connections: None,
906915
compute_driver: None,
907916
compute_driver_endpoints: BTreeMap::new(),
908917
credential_drivers: Vec::new(),
@@ -964,6 +973,18 @@ impl Config {
964973
self
965974
}
966975

976+
/// Create a new configuration with a mutation lock pool connection ceiling.
977+
///
978+
/// `None` keeps the built-in default.
979+
#[must_use]
980+
pub const fn with_database_lock_max_connections(
981+
mut self,
982+
max_connections: Option<u32>,
983+
) -> Self {
984+
self.database_lock_max_connections = max_connections;
985+
self
986+
}
987+
967988
/// Create a new configuration with an explicit compute driver.
968989
#[must_use]
969990
pub fn with_compute_driver(mut self, driver: impl ToString) -> Self {

‎crates/openshell-server/src/cli.rs‎

Lines changed: 91 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,15 +133,31 @@ struct RunArgs {
133133
///
134134
/// When unset, the gateway uses its backend default: 10 with Postgres,
135135
/// 5 with an on-disk `SQLite` database. An in-memory `SQLite` database is
136-
/// always a single connection. Each replica opens its own pool, so keep
137-
/// the total below what the database server itself admits.
136+
/// always a single connection. Postgres needs at least 2, because the SSH
137+
/// identity lock keeps one connection while it queries the pool, so the
138+
/// gateway rejects 1 there at startup. Each replica opens its own pool,
139+
/// plus a mutation lock pool on Postgres (`--db-lock-max-connections`), so
140+
/// keep the total below what the database server itself admits.
138141
#[arg(
139142
long,
140143
env = "OPENSHELL_DB_MAX_CONNECTIONS",
141144
value_parser = clap::value_parser!(u32).range(1..)
142145
)]
143146
db_max_connections: Option<u32>,
144147

148+
/// Connection ceiling for the Postgres mutation lock pool.
149+
///
150+
/// Each mutation guard holds one lock connection, so this bounds how many
151+
/// guarded mutations a replica runs or waits on in Postgres at once.
152+
/// When unset, the gateway uses 4. Each replica opens these on top of
153+
/// its database pool. `SQLite` has no lock pool and ignores it.
154+
#[arg(
155+
long,
156+
env = "OPENSHELL_DB_LOCK_MAX_CONNECTIONS",
157+
value_parser = clap::value_parser!(u32).range(1..)
158+
)]
159+
db_lock_max_connections: Option<u32>,
160+
145161
/// Compute driver configured for this gateway.
146162
///
147163
/// Accepts one registered driver name. When unset, the gateway runs
@@ -532,7 +548,8 @@ fn prepare_server_config_with_drivers(
532548

533549
config = config
534550
.with_database_url(db_url)
535-
.with_database_max_connections(args.db_max_connections);
551+
.with_database_max_connections(args.db_max_connections)
552+
.with_database_lock_max_connections(args.db_lock_max_connections);
536553
if let Some(driver) = &args.compute_driver {
537554
config = config.with_compute_driver(driver);
538555
}
@@ -1289,6 +1306,12 @@ fn merge_file_into_args(args: &mut RunArgs, file: &GatewayFileSection, matches:
12891306
{
12901307
args.db_max_connections = Some(max_connections);
12911308
}
1309+
if let Some(max_connections) = file.database_lock_max_connections
1310+
&& args.db_lock_max_connections.is_none()
1311+
&& arg_defaulted(matches, "db_lock_max_connections")
1312+
{
1313+
args.db_lock_max_connections = Some(max_connections);
1314+
}
12921315
}
12931316

12941317
fn validate_grpc_rate_limit_args(requests: Option<u64>, window_seconds: Option<u64>) -> Result<()> {
@@ -3221,6 +3244,71 @@ database_max_connections = 64
32213244
});
32223245
}
32233246

3247+
#[test]
3248+
fn file_db_lock_max_connections_populates_args_when_cli_omits() {
3249+
Environment::new()
3250+
.remove("OPENSHELL_DB_LOCK_MAX_CONNECTIONS")
3251+
.run(|| {
3252+
let (mut args, matches) =
3253+
parse_with_args(&["openshell-gateway", "--db-url", "sqlite::memory:"]);
3254+
assert_eq!(
3255+
args.db_lock_max_connections, None,
3256+
"default leaves the lock pool alone"
3257+
);
3258+
let file = config_file_from_toml(
3259+
r"
3260+
[openshell.gateway]
3261+
database_lock_max_connections = 8
3262+
",
3263+
);
3264+
merge_file_into_args(&mut args, &file.openshell.gateway, &matches);
3265+
3266+
assert_eq!(args.db_lock_max_connections, Some(8));
3267+
});
3268+
}
3269+
3270+
#[test]
3271+
fn env_db_lock_max_connections_overrides_file_value() {
3272+
Environment::new()
3273+
.set("OPENSHELL_DB_LOCK_MAX_CONNECTIONS", "16")
3274+
.run(|| {
3275+
let (mut args, matches) =
3276+
parse_with_args(&["openshell-gateway", "--db-url", "sqlite::memory:"]);
3277+
let file = config_file_from_toml(
3278+
r"
3279+
[openshell.gateway]
3280+
database_lock_max_connections = 8
3281+
",
3282+
);
3283+
merge_file_into_args(&mut args, &file.openshell.gateway, &matches);
3284+
3285+
assert_eq!(args.db_lock_max_connections, Some(16));
3286+
});
3287+
}
3288+
3289+
#[test]
3290+
fn db_lock_max_connections_rejects_a_zero_or_unparseable_ceiling() {
3291+
Environment::new()
3292+
.remove("OPENSHELL_DB_LOCK_MAX_CONNECTIONS")
3293+
.run(|| {
3294+
// A zero-sized lock pool would time out every guarded mutation.
3295+
for bad in ["0", "-5", "many"] {
3296+
assert!(
3297+
command()
3298+
.try_get_matches_from([
3299+
"openshell-gateway",
3300+
"--db-url",
3301+
"sqlite::memory:",
3302+
"--db-lock-max-connections",
3303+
bad,
3304+
])
3305+
.is_err(),
3306+
"input {bad:?} must be rejected"
3307+
);
3308+
}
3309+
});
3310+
}
3311+
32243312
#[test]
32253313
fn aux_listener_preserves_file_ip_against_public_bind() {
32263314
use std::net::SocketAddr;

‎crates/openshell-server/src/config_file.rs‎

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -105,14 +105,25 @@ pub struct GatewayFileSection {
105105
// ── Database ─────────────────────────────────────────────────────────
106106
/// Connection ceiling for the persistence pool. One shared pool serves
107107
/// every database-backed RPC, so this is also the gateway's ceiling on
108-
/// concurrent database work. On Postgres, total server connections are
109-
/// `database_max_connections × replica_count`, which must stay under the
110-
/// server's own `max_connections`. Omit to keep the backend default (10
111-
/// for Postgres, 5 for on-disk `SQLite`); an in-memory `SQLite` database
112-
/// is always a single connection.
108+
/// concurrent database work. On Postgres, each replica also opens up to
109+
/// `database_lock_max_connections` lock connections, so total server
110+
/// connections are `(database_max_connections +
111+
/// database_lock_max_connections) × replica_count`, plus rollout pods,
112+
/// which must stay under the server's own `max_connections`. Omit to keep
113+
/// the backend default (10 for Postgres, 5 for on-disk `SQLite`); an
114+
/// in-memory `SQLite` database is always a single connection. Postgres
115+
/// needs at least 2, because the SSH identity lock keeps one connection
116+
/// while it queries the pool.
113117
#[serde(default)]
114118
pub database_max_connections: Option<u32>,
115119

120+
/// Connection ceiling for the Postgres mutation lock pool. Each mutation
121+
/// guard holds one lock connection, so this bounds how many guarded
122+
/// mutations a replica runs or waits on in Postgres at once. Omit to keep
123+
/// the default of 4; `SQLite` has no lock pool and ignores it.
124+
#[serde(default)]
125+
pub database_lock_max_connections: Option<u32>,
126+
116127
// ── Drivers ──────────────────────────────────────────────────────────
117128
/// Explicit compute driver selection. `None` enables auto-detection.
118129
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -609,6 +620,13 @@ fn parse_and_validate(path: &Path, contents: &str) -> Result<ConfigFile, ConfigF
609620
message: "must be greater than zero; omit the key to use the built-in default",
610621
});
611622
}
623+
// A zero-sized lock pool would time out every guarded mutation.
624+
if file.openshell.gateway.database_lock_max_connections == Some(0) {
625+
return Err(ConfigFileError::InvalidValue {
626+
field: "openshell.gateway.database_lock_max_connections",
627+
message: "must be greater than zero; omit the key to use the built-in default",
628+
});
629+
}
612630
if file
613631
.openshell
614632
.gateway
@@ -1335,6 +1353,37 @@ database_max_connections = 0
13351353
));
13361354
}
13371355

1356+
#[test]
1357+
fn parses_database_lock_max_connections() {
1358+
let toml = r"
1359+
[openshell.gateway]
1360+
database_lock_max_connections = 8
1361+
";
1362+
let tmp = write_tmp(toml);
1363+
let file = load(tmp.path()).expect("a positive lock pool ceiling parses");
1364+
assert_eq!(
1365+
file.openshell.gateway.database_lock_max_connections,
1366+
Some(8)
1367+
);
1368+
}
1369+
1370+
#[test]
1371+
fn rejects_zero_database_lock_max_connections() {
1372+
let toml = r"
1373+
[openshell.gateway]
1374+
database_lock_max_connections = 0
1375+
";
1376+
let tmp = write_tmp(toml);
1377+
let err = load(tmp.path()).expect_err("a zero lock pool ceiling must be rejected");
1378+
assert!(matches!(
1379+
err,
1380+
ConfigFileError::InvalidValue {
1381+
field: "openshell.gateway.database_lock_max_connections",
1382+
..
1383+
}
1384+
));
1385+
}
1386+
13381387
#[test]
13391388
fn rejects_unknown_gateway_field() {
13401389
let toml = r"

‎crates/openshell-server/src/grpc/policy/endpoint_status.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,10 @@ use tonic::{Request, Response, Status};
3434
use tracing::warn;
3535

3636
const ENDPOINT_STARTUP_RECONCILIATION_PAGE_SIZE: u32 = 100;
37-
/// Sandboxes reconciled at once, matching the four-connection mutation lock
38-
/// pool.
37+
/// Sandboxes reconciled at once. On `PostgreSQL` each holds one mutation lock
38+
/// connection, so this matches the default lock pool size. With a smaller
39+
/// configured pool the extra reconciliations wait for a lock connection, and
40+
/// startup reconciliation does not fill a larger one.
3941
const ENDPOINT_STARTUP_RECONCILIATION_CONCURRENCY: usize = 4;
4042
/// Guarded attempts per sandbox before a concurrent write fails startup.
4143
const ENDPOINT_STARTUP_RECONCILIATION_ATTEMPTS: usize = 5;

‎crates/openshell-server/src/lib.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -609,7 +609,12 @@ pub(crate) async fn run_server(
609609
);
610610

611611
let store = Arc::new(
612-
Store::connect_with_pool_size(database_url, config.database_max_connections).await?,
612+
Store::connect_with_pool_sizes(
613+
database_url,
614+
config.database_max_connections,
615+
config.database_lock_max_connections,
616+
)
617+
.await?,
613618
);
614619
let credentials = credentials::CredentialRuntime::from_config_file_with_store(
615620
&config,

‎crates/openshell-server/src/persistence/mod.rs‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ impl Store {
388388
/// Connect to a persistence store based on the database URL, leaving pool
389389
/// sizing at the backend default.
390390
pub async fn connect(url: &str) -> CoreResult<Self> {
391-
Self::connect_with_pool_size(url, None).await
391+
Self::connect_with_pool_sizes(url, None, None).await
392392
}
393393

394394
/// Connect to a persistence store based on the database URL.
@@ -397,12 +397,26 @@ impl Store {
397397
/// its built-in default when `None`. The two backends have different
398398
/// defaults, and an in-memory `SQLite` database ignores the override
399399
/// entirely — it must be held by exactly one connection.
400-
pub async fn connect_with_pool_size(
400+
/// `lock_max_connections` sizes the `PostgreSQL` mutation lock pool the
401+
/// same way; `SQLite` has no lock pool and ignores it. A `PostgreSQL`
402+
/// data pool below 2 is rejected before any connection opens.
403+
pub async fn connect_with_pool_sizes(
401404
url: &str,
402405
max_connections: Option<u32>,
406+
lock_max_connections: Option<u32>,
403407
) -> CoreResult<Self> {
404408
if url.starts_with("postgres://") || url.starts_with("postgresql://") {
405-
let store = PostgresStore::connect(url, max_connections)
409+
if let Some(configured) = max_connections
410+
&& configured < postgres::MIN_MAX_CONNECTIONS
411+
{
412+
return Err(CoreError::config(format!(
413+
"database_max_connections (--db-max-connections, OPENSHELL_DB_MAX_CONNECTIONS) \
414+
is {configured}, but PostgreSQL needs at least {}: the SSH identity lock \
415+
keeps one data connection while it queries the pool",
416+
postgres::MIN_MAX_CONNECTIONS
417+
)));
418+
}
419+
let store = PostgresStore::connect(url, max_connections, lock_max_connections)
406420
.await
407421
.map_err(|e| CoreError::execution(e.to_string()))?;
408422
store
@@ -411,6 +425,11 @@ impl Store {
411425
.map_err(|e| CoreError::execution(e.to_string()))?;
412426
Ok(Self::Postgres(store))
413427
} else if url.starts_with("sqlite:") {
428+
if lock_max_connections.is_some() {
429+
tracing::warn!(
430+
"ignoring the configured mutation lock pool ceiling: SQLite has no lock pool"
431+
);
432+
}
414433
let store = SqliteStore::connect(url, max_connections)
415434
.await
416435
.map_err(|e| CoreError::execution(e.to_string()))?;

‎crates/openshell-server/src/persistence/mutation_lock.rs‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,17 +74,29 @@ pub const MUTATION_LOCK_TIMEOUT_SETTING: &str = "10s";
7474
/// Opening a lock connection can take this long, so a timeout with less time left is contention.
7575
pub const LOCK_CONNECTION_MIN_BUDGET: Duration = Duration::from_secs(1);
7676

77-
/// Size of the dedicated `PostgreSQL` lock pool.
77+
/// Default size of the dedicated `PostgreSQL` lock pool, used when
78+
/// `[openshell.gateway] database_lock_max_connections` is not set.
7879
///
7980
/// Lock connections come from their own pool so that guard holders can never
8081
/// starve the data pool their critical sections need. Each replica opens at
81-
/// most 10 data plus 4 lock connections. A cancelled acquisition frees its
82+
/// most `database_max_connections` data plus `database_lock_max_connections`
83+
/// lock connections, 10 plus 4 by default. A cancelled acquisition frees its
8284
/// slot at once, but its backend can stay until its `lock_timeout` while the
8385
/// pool opens a replacement, so size `max_connections` with headroom for
8486
/// rollouts as the high-availability guide describes
85-
/// (`(2 × replicas + surge) × 14`). Each guard holds
86-
/// one lock connection, so a replica sustains about 4 / c guarded operations
87-
/// per second, where c is how long one guard is held.
87+
/// (`(2 × replicas + surge) × (data + lock connections)`).
88+
///
89+
/// Each guard holds one lock connection, so a replica sustains about n / c
90+
/// guarded operations per second, where n is the lock pool size and c is how
91+
/// long one guard is held. The data pool's 10 is `SQLx`'s default, set
92+
/// explicitly when `PostgreSQL` support landed (5a15de63). The 4 is a
93+
/// judgment call: `bench_postgres_lock_pool_absorbs_a_12ms_reconnect_burst`
94+
/// (about 170 guarded operations per second on one replica, each held about
95+
/// 20 ms) keeps about 3.3 lock connections busy, so 4 leaves headroom while
96+
/// staying well under the data pool. Each extra slot costs
97+
/// `2 × replicas + surge` server connections during a rollout, so raise it
98+
/// for replicas whose guarded operations wait for a lock connection rather
99+
/// than by default.
88100
pub(super) const MUTATION_LOCK_POOL_MAX_CONNECTIONS: u32 = 4;
89101

90102
/// Domain separator hashed into every derived key.

0 commit comments

Comments
 (0)