Skip to content

Commit fc3a92d

Browse files
committed
fix(server): bound concurrent supervisor snapshot builds
Fleet-wide configuration changes spawned one snapshot build per connected sandbox and component with no concurrency limit, so a global setting or provider change issued every store query and credential-driver call at once. Gate builds behind a semaphore sized from the database pool and start the build deadline only once a permit is held. Signed-off-by: Piotr Mlocek <pmlocek@nvidia.com>
1 parent d0d8d02 commit fc3a92d

7 files changed

Lines changed: 184 additions & 18 deletions

File tree

‎architecture/sandbox.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -504,12 +504,15 @@ Polling remains the only path that changes runtime state and repairs dropped or
504504
unavailable delivery. The gateway serializes construction per sandbox and
505505
component, and coalesces repeated mutations into the latest full snapshot. An
506506
enqueue result means only that the local stream queue accepted the message. A
507-
bounded scope fanout scheduler coalesces repeated workspace and global changes.
508-
Snapshot construction has a deadline, and the gateway rejects encoded stream
509-
messages that approach the transport decoder limit. A
510-
later migration will apply these payloads directly and acknowledge their exact
511-
revisions before removing supervisor polling. At that point, the gateway will
512-
require a valid bootstrap before marking a session ready.
507+
bounded scope fanout scheduler coalesces repeated workspace and global changes,
508+
and a semaphore sized from the database pool bounds how many snapshots build
509+
at once so a fleet-wide change cannot saturate the store or credential
510+
backends. Snapshot construction has a deadline that starts once a build holds a
511+
permit, and the gateway rejects encoded stream messages that approach the
512+
transport decoder limit. A later migration will apply these payloads directly
513+
and acknowledge their exact revisions before removing supervisor polling. At
514+
that point, the gateway will require a valid bootstrap before marking a session
515+
ready.
513516

514517
## Policy Revision Acknowledgement
515518

‎crates/openshell-server/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@ protoc-bin-vendored = { workspace = true }
127127

128128
[dev-dependencies]
129129
base64 = { workspace = true }
130+
tokio = { workspace = true, features = ["test-util"] }
130131
hyper-rustls = { version = "0.27", default-features = false, features = ["native-tokio", "http1", "tls12", "logging", "aws-lc-rs"] }
131132
rcgen = { workspace = true }
132133
rsa = { version = "0.9", features = ["pem"] }

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

Lines changed: 155 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use metrics::counter;
1313
use openshell_core::proto::{
1414
ConfigBootstrap, ProviderEnvironmentSnapshot, Sandbox, SandboxConfigSnapshot,
1515
};
16+
use tokio::sync::Semaphore;
1617
use tonic::{Code, Status};
1718
use tracing::warn;
1819

@@ -26,6 +27,11 @@ use crate::supervisor_session::SupervisorSessionRegistry;
2627
pub const MAX_SUPERVISOR_CONFIG_MESSAGE_BYTES: usize = 3 * 1024 * 1024;
2728
const CONFIG_SNAPSHOT_BUILD_TIMEOUT: Duration = Duration::from_secs(45);
2829
const MAX_ACTIVE_FANOUT_WORKERS: usize = 64;
30+
/// Concurrent snapshot builds allowed per pooled database connection. Builds
31+
/// are short bursts of small queries, so a little oversubscription keeps the
32+
/// pool busy without stacking every waiter on the acquire timeout.
33+
const SNAPSHOT_BUILDS_PER_DB_CONNECTION: usize = 2;
34+
const MIN_CONCURRENT_SNAPSHOT_BUILDS: usize = 4;
2935

3036
/// One complete configuration component awaiting delivery to a supervisor.
3137
#[derive(Clone)]
@@ -181,13 +187,65 @@ struct FanoutKey {
181187
/// The map entry is also the worker lease. Its boolean is set when another
182188
/// mutation arrives during a build or route operation. The worker then rebuilds
183189
/// the current full snapshot once, regardless of how many mutations arrived.
184-
#[derive(Debug, Default)]
190+
///
191+
/// Workers are spawned eagerly so coalescing stays exact, but snapshot
192+
/// construction itself is bounded by `build_permits`. A fleet-wide change
193+
/// therefore queues on the semaphore instead of saturating the database pool
194+
/// and credential backends all at once.
195+
#[derive(Debug)]
185196
pub struct ConfigDeliveryQueue {
186197
pending: Mutex<HashMap<DeliveryKey, bool>>,
187198
fanout_pending: Mutex<HashMap<FanoutKey, bool>>,
199+
build_permits: Semaphore,
200+
}
201+
202+
impl Default for ConfigDeliveryQueue {
203+
fn default() -> Self {
204+
Self::new(MIN_CONCURRENT_SNAPSHOT_BUILDS)
205+
}
188206
}
189207

190208
impl ConfigDeliveryQueue {
209+
#[must_use]
210+
pub fn new(max_concurrent_builds: usize) -> Self {
211+
Self {
212+
pending: Mutex::default(),
213+
fanout_pending: Mutex::default(),
214+
build_permits: Semaphore::new(max_concurrent_builds.max(1)),
215+
}
216+
}
217+
218+
/// Size the build bound from the persistence pool that every build reads.
219+
#[must_use]
220+
pub fn for_db_connections(max_connections: u32) -> Self {
221+
let max_connections = usize::try_from(max_connections).unwrap_or(usize::MAX);
222+
Self::new(
223+
max_connections
224+
.saturating_mul(SNAPSHOT_BUILDS_PER_DB_CONNECTION)
225+
.max(MIN_CONCURRENT_SNAPSHOT_BUILDS),
226+
)
227+
}
228+
229+
#[cfg(test)]
230+
fn max_concurrent_builds(&self) -> usize {
231+
self.build_permits.available_permits()
232+
}
233+
234+
/// Run one snapshot build under the concurrency bound. The deadline starts
235+
/// only once a permit is held so queued builds do not spend their budget
236+
/// waiting.
237+
async fn run_bounded_build<T>(
238+
&self,
239+
build: impl Future<Output = T>,
240+
) -> Result<T, tokio::time::error::Elapsed> {
241+
let _permit = self
242+
.build_permits
243+
.acquire()
244+
.await
245+
.expect("snapshot build semaphore is never closed");
246+
tokio::time::timeout(CONFIG_SNAPSHOT_BUILD_TIMEOUT, build).await
247+
}
248+
191249
fn enqueue(&self, key: DeliveryKey) -> bool {
192250
let mut pending = self.pending.lock().unwrap();
193251
match pending.entry(key) {
@@ -337,16 +395,16 @@ fn enqueue_sandbox(state: &Arc<ServerState>, sandbox_id: &str, components: Confi
337395
}
338396

339397
async fn publish_sandbox_component_now(state: &Arc<ServerState>, key: &DeliveryKey) {
340-
let sandbox = match state.store.get_message::<Sandbox>(&key.sandbox_id).await {
341-
Ok(Some(sandbox)) => sandbox,
342-
Ok(None) => return,
343-
Err(_) => {
344-
record_build_failure(&key.sandbox_id, "sandbox", Code::Internal);
345-
return;
346-
}
347-
};
348398
let component = key.component.name();
349399
let build = async {
400+
let sandbox = state
401+
.store
402+
.get_message::<Sandbox>(&key.sandbox_id)
403+
.await
404+
.map_err(|error| Status::internal(format!("fetch sandbox failed: {error}")))?;
405+
let Some(sandbox) = sandbox else {
406+
return Ok(None);
407+
};
350408
match key.component {
351409
ConfigComponentKind::SandboxConfig => build_sandbox_config_snapshot(state, &sandbox)
352410
.await
@@ -357,9 +415,11 @@ async fn publish_sandbox_component_now(state: &Arc<ServerState>, key: &DeliveryK
357415
.map(SupervisorConfigMessage::ProviderEnvironment)
358416
}
359417
}
418+
.map(Some)
360419
};
361-
match tokio::time::timeout(CONFIG_SNAPSHOT_BUILD_TIMEOUT, build).await {
362-
Ok(Ok(message)) => {
420+
match state.config_delivery_queue.run_bounded_build(build).await {
421+
Ok(Ok(None)) => {}
422+
Ok(Ok(Some(message))) => {
363423
let disposition = state
364424
.supervisor_config_router()
365425
.deliver(&key.sandbox_id, message)
@@ -478,6 +538,8 @@ fn record_build_failure(sandbox_id: &str, component: &'static str, error_code: C
478538

479539
#[cfg(test)]
480540
mod tests {
541+
use std::sync::atomic::{AtomicUsize, Ordering};
542+
481543
use super::*;
482544
use crate::grpc::{OpenShellService, test_support::test_server_state};
483545
use openshell_core::proto::{
@@ -508,6 +570,88 @@ mod tests {
508570
assert!(!queue.finish_pass(&key));
509571
}
510572

573+
#[test]
574+
fn build_bound_is_sized_from_the_database_pool() {
575+
assert_eq!(
576+
ConfigDeliveryQueue::for_db_connections(10).max_concurrent_builds(),
577+
20
578+
);
579+
assert_eq!(
580+
ConfigDeliveryQueue::for_db_connections(1).max_concurrent_builds(),
581+
MIN_CONCURRENT_SNAPSHOT_BUILDS
582+
);
583+
assert_eq!(ConfigDeliveryQueue::new(0).max_concurrent_builds(), 1);
584+
}
585+
586+
#[tokio::test(start_paused = true)]
587+
async fn bounded_builds_never_exceed_the_permit_count() {
588+
const PERMITS: usize = 4;
589+
const BUILDS: usize = 40;
590+
let queue = Arc::new(ConfigDeliveryQueue::new(PERMITS));
591+
let active = Arc::new(AtomicUsize::new(0));
592+
let peak = Arc::new(AtomicUsize::new(0));
593+
594+
let workers = (0..BUILDS)
595+
.map(|_| {
596+
let queue = Arc::clone(&queue);
597+
let active = Arc::clone(&active);
598+
let peak = Arc::clone(&peak);
599+
tokio::spawn(async move {
600+
queue
601+
.run_bounded_build(async {
602+
let now = active.fetch_add(1, Ordering::SeqCst) + 1;
603+
peak.fetch_max(now, Ordering::SeqCst);
604+
tokio::time::sleep(Duration::from_millis(50)).await;
605+
active.fetch_sub(1, Ordering::SeqCst);
606+
})
607+
.await
608+
.expect("build must not time out");
609+
})
610+
})
611+
.collect::<Vec<_>>();
612+
for worker in workers {
613+
worker.await.unwrap();
614+
}
615+
616+
assert_eq!(peak.load(Ordering::SeqCst), PERMITS);
617+
assert_eq!(active.load(Ordering::SeqCst), 0);
618+
assert_eq!(queue.max_concurrent_builds(), PERMITS);
619+
}
620+
621+
#[tokio::test(start_paused = true)]
622+
async fn build_deadline_starts_after_a_permit_is_held() {
623+
let queue = Arc::new(ConfigDeliveryQueue::new(1));
624+
let almost_deadline = CONFIG_SNAPSHOT_BUILD_TIMEOUT
625+
.checked_sub(Duration::from_secs(1))
626+
.unwrap();
627+
let first = {
628+
let queue = Arc::clone(&queue);
629+
tokio::spawn(async move {
630+
queue
631+
.run_bounded_build(tokio::time::sleep(almost_deadline))
632+
.await
633+
})
634+
};
635+
tokio::task::yield_now().await;
636+
let second = queue.run_bounded_build(tokio::time::sleep(almost_deadline));
637+
638+
let (first, second) = tokio::join!(first, second);
639+
assert!(first.unwrap().is_ok());
640+
assert!(
641+
second.is_ok(),
642+
"waiting for a permit must not consume the build deadline"
643+
);
644+
645+
assert!(
646+
queue
647+
.run_bounded_build(tokio::time::sleep(
648+
CONFIG_SNAPSHOT_BUILD_TIMEOUT + Duration::from_secs(1),
649+
))
650+
.await
651+
.is_err()
652+
);
653+
}
654+
511655
#[test]
512656
fn queue_runs_components_and_sandboxes_independently() {
513657
let queue = ConfigDeliveryQueue::default();

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,8 @@ impl ServerState {
419419
let supervisor_config_router: Arc<dyn config_delivery::SupervisorConfigRouter> = Arc::new(
420420
config_delivery::LocalSupervisorConfigRouter::new(Arc::clone(&supervisor_sessions)),
421421
);
422+
let config_delivery_queue =
423+
config_delivery::ConfigDeliveryQueue::for_db_connections(store.max_connections());
422424
Self {
423425
config,
424426
store,
@@ -433,7 +435,7 @@ impl ServerState {
433435
settings_mutex: tokio::sync::Mutex::new(()),
434436
supervisor_sessions,
435437
gateway_shutting_down: AtomicBool::new(false),
436-
config_delivery_queue: config_delivery::ConfigDeliveryQueue::default(),
438+
config_delivery_queue,
437439
supervisor_config_router,
438440
extension_mint_limiter: auth::extension_mint_limit::ExtensionMintLimiter::default(),
439441
middleware_registry: Arc::new(MiddlewareRegistry::default()),

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,14 @@ impl Store {
271271
matches!(self, Self::Sqlite(_))
272272
}
273273

274+
/// Maximum number of pooled database connections for this backend.
275+
pub fn max_connections(&self) -> u32 {
276+
match self {
277+
Self::Postgres(store) => store.max_connections(),
278+
Self::Sqlite(store) => store.max_connections(),
279+
}
280+
}
281+
274282
/// Connect to a persistence store based on the database URL.
275283
pub async fn connect(url: &str) -> CoreResult<Self> {
276284
if url.starts_with("postgres://") || url.starts_with("postgresql://") {

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ impl PostgresStore {
4545
Ok(Self { pool })
4646
}
4747

48+
pub fn max_connections(&self) -> u32 {
49+
self.pool.options().get_max_connections()
50+
}
51+
4852
pub async fn migrate(&self) -> PersistenceResult<()> {
4953
POSTGRES_MIGRATOR
5054
.run(&self.pool)

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,10 @@ impl SqliteStore {
7777
self.close().await;
7878
}
7979

80+
pub fn max_connections(&self) -> u32 {
81+
self.pool.options().get_max_connections()
82+
}
83+
8084
pub async fn connect(url: &str) -> PersistenceResult<Self> {
8185
let is_in_memory = url.contains(":memory:") || url.contains("mode=memory");
8286
let max_connections = if is_in_memory { 1 } else { 5 };

0 commit comments

Comments
 (0)