Skip to content

Commit 43f4c94

Browse files
committed
fix(server): bound configuration delivery workers
Signed-off-by: Piotr Mlocek <pmlocek@nvidia.com>
1 parent d33c96a commit 43f4c94

3 files changed

Lines changed: 173 additions & 49 deletions

File tree

‎architecture/gateway.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -622,11 +622,13 @@ refresh bootstrap material; sandboxes receive minted access tokens instead.
622622

623623
Committed configuration mutations publish component and scope identifiers,
624624
never configuration payloads, to a bounded coalescing scheduler. The scheduler
625-
builds the latest full snapshot for each affected active sandbox. An async
626-
router owns session lookup, message sizing, sequence allocation, and enqueue.
627-
Its local implementation uses the process-local supervisor registry. A future
628-
HA implementation can resolve the gateway that owns a session and forward the
629-
same typed message without changing mutation handlers.
625+
admits a fixed number of delivery workers and builds the latest full snapshot
626+
for each affected active sandbox. Fleet fanout waits for worker capacity before
627+
admitting another recipient. An async router owns session lookup, message
628+
sizing, sequence allocation, and enqueue. Its local implementation uses the
629+
process-local supervisor registry. A future HA implementation can resolve the
630+
gateway that owns a session and forward the same typed message without changing
631+
mutation handlers.
630632

631633
Polling remains authoritative during the first rollout stage. Snapshot build,
632634
fanout, or enqueue failure cannot fail a mutation that already committed.

‎architecture/sandbox.md‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -509,14 +509,15 @@ unavailable delivery. The gateway serializes construction per sandbox and
509509
component, and coalesces repeated mutations into the latest full snapshot. An
510510
enqueue result means only that the local stream queue accepted the message. A
511511
bounded scope fanout scheduler coalesces repeated workspace and global changes,
512-
and a semaphore sized from the database pool bounds how many snapshots build
513-
at once so a fleet-wide change cannot saturate the store or credential
514-
backends. Snapshot construction has a deadline that starts once a build holds a
515-
permit, and the gateway rejects encoded stream messages that approach the
516-
transport decoder limit. A later migration will apply these payloads directly
517-
and acknowledge their exact revisions before removing supervisor polling. At
518-
that point, the gateway will require a valid bootstrap before marking a session
519-
ready.
512+
and semaphores sized from the database pool bound delivery workers and snapshot
513+
builds. Fanout waits for worker capacity before admitting each recipient, so a
514+
fleet-wide change cannot create a fleet-sized task backlog or saturate the store
515+
and credential backends. Snapshot construction has a deadline that starts once
516+
a build holds a permit, and the gateway rejects encoded stream messages that
517+
approach the transport decoder limit. A later migration will apply these
518+
payloads directly and acknowledge their exact revisions before removing
519+
supervisor polling. At that point, the gateway will require a valid bootstrap
520+
before marking a session ready.
520521

521522
## Policy Revision Acknowledgement
522523

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

Lines changed: 157 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use metrics::counter;
1313
use openshell_core::proto::{
1414
ConfigBootstrap, ProviderEnvironmentSnapshot, Sandbox, SandboxConfigSnapshot,
1515
};
16-
use tokio::sync::Semaphore;
16+
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
1717
use tonic::{Code, Status};
1818
use tracing::warn;
1919

@@ -143,13 +143,6 @@ impl ConfigComponents {
143143
.into_iter()
144144
.filter_map(|(selected, component)| selected.then_some(component))
145145
}
146-
147-
fn only(component: ConfigComponentKind) -> Self {
148-
Self {
149-
sandbox_config: component == ConfigComponentKind::SandboxConfig,
150-
provider_environment: component == ConfigComponentKind::ProviderEnvironment,
151-
}
152-
}
153146
}
154147

155148
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -185,20 +178,21 @@ struct FanoutKey {
185178
component: ConfigComponentKind,
186179
}
187180

188-
/// Coalesces publications and runs one worker per sandbox and component.
181+
/// Coalesces publications and bounds workers per sandbox and component.
189182
///
190183
/// The map entry is also the worker lease. Its boolean is set when another
191184
/// mutation arrives during a build or route operation. The worker then rebuilds
192185
/// the current full snapshot once, regardless of how many mutations arrived.
193186
///
194-
/// Workers are spawned eagerly so coalescing stays exact, but snapshot
195-
/// construction itself is bounded by `build_permits`. A fleet-wide change
196-
/// therefore queues on the semaphore instead of saturating the database pool
197-
/// and credential backends all at once.
187+
/// Each pending map entry owns a delivery permit for its worker. Direct
188+
/// publications fail fast when all permits are held. Fanout workers wait for a
189+
/// permit before admitting the next recipient, which bounds both spawned tasks
190+
/// and pending keys while still walking the full recipient list.
198191
#[derive(Debug)]
199192
pub struct ConfigDeliveryQueue {
200193
pending: Mutex<HashMap<DeliveryKey, bool>>,
201194
fanout_pending: Mutex<HashMap<FanoutKey, bool>>,
195+
delivery_permits: Arc<Semaphore>,
202196
build_permits: Semaphore,
203197
}
204198

@@ -211,10 +205,12 @@ impl Default for ConfigDeliveryQueue {
211205
impl ConfigDeliveryQueue {
212206
#[must_use]
213207
pub fn new(max_concurrent_builds: usize) -> Self {
208+
let max_concurrent_builds = max_concurrent_builds.max(1);
214209
Self {
215210
pending: Mutex::default(),
216211
fanout_pending: Mutex::default(),
217-
build_permits: Semaphore::new(max_concurrent_builds.max(1)),
212+
delivery_permits: Arc::new(Semaphore::new(max_concurrent_builds)),
213+
build_permits: Semaphore::new(max_concurrent_builds),
218214
}
219215
}
220216

@@ -249,16 +245,45 @@ impl ConfigDeliveryQueue {
249245
tokio::time::timeout(CONFIG_SNAPSHOT_BUILD_TIMEOUT, build).await
250246
}
251247

252-
fn enqueue(&self, key: DeliveryKey) -> bool {
248+
fn enqueue(&self, key: DeliveryKey) -> DeliveryEnqueue {
249+
let mut pending = self.pending.lock().unwrap();
250+
match pending.entry(key) {
251+
Entry::Occupied(mut entry) => {
252+
*entry.get_mut() = true;
253+
DeliveryEnqueue::Coalesced
254+
}
255+
Entry::Vacant(entry) => {
256+
let Ok(permit) = Arc::clone(&self.delivery_permits).try_acquire_owned() else {
257+
return DeliveryEnqueue::Full;
258+
};
259+
entry.insert(true);
260+
DeliveryEnqueue::StartWorker(permit)
261+
}
262+
}
263+
}
264+
265+
async fn enqueue_from_fanout(&self, key: DeliveryKey) -> DeliveryEnqueue {
266+
{
267+
let mut pending = self.pending.lock().unwrap();
268+
if let Entry::Occupied(mut entry) = pending.entry(key.clone()) {
269+
*entry.get_mut() = true;
270+
return DeliveryEnqueue::Coalesced;
271+
}
272+
}
273+
274+
let permit = Arc::clone(&self.delivery_permits)
275+
.acquire_owned()
276+
.await
277+
.expect("delivery worker semaphore is never closed");
253278
let mut pending = self.pending.lock().unwrap();
254279
match pending.entry(key) {
255280
Entry::Occupied(mut entry) => {
256281
*entry.get_mut() = true;
257-
false
282+
DeliveryEnqueue::Coalesced
258283
}
259284
Entry::Vacant(entry) => {
260285
entry.insert(true);
261-
true
286+
DeliveryEnqueue::StartWorker(permit)
262287
}
263288
}
264289
}
@@ -312,6 +337,13 @@ impl ConfigDeliveryQueue {
312337
}
313338
}
314339

340+
#[derive(Debug)]
341+
enum DeliveryEnqueue {
342+
StartWorker(OwnedSemaphorePermit),
343+
Coalesced,
344+
Full,
345+
}
346+
315347
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
316348
enum FanoutEnqueue {
317349
StartWorker,
@@ -382,21 +414,52 @@ fn enqueue_sandbox(state: &Arc<ServerState>, sandbox_id: &str, components: Confi
382414
sandbox_id: sandbox_id.to_string(),
383415
component,
384416
};
385-
if state.config_delivery_queue.enqueue(key.clone()) {
386-
let state = Arc::clone(state);
387-
tokio::spawn(async move {
388-
loop {
389-
state.config_delivery_queue.take(&key);
390-
publish_sandbox_component_now(&state, &key).await;
391-
if !state.config_delivery_queue.finish_pass(&key) {
392-
break;
393-
}
394-
}
395-
});
417+
match state.config_delivery_queue.enqueue(key.clone()) {
418+
DeliveryEnqueue::StartWorker(permit) => {
419+
spawn_delivery_worker(state, key, permit);
420+
}
421+
DeliveryEnqueue::Coalesced => {}
422+
DeliveryEnqueue::Full => {
423+
record_delivery_worker_full(sandbox_id, component.name());
424+
}
396425
}
397426
}
398427
}
399428

429+
fn spawn_delivery_worker(state: &Arc<ServerState>, key: DeliveryKey, permit: OwnedSemaphorePermit) {
430+
let state = Arc::clone(state);
431+
tokio::spawn(async move {
432+
let _permit = permit;
433+
loop {
434+
state.config_delivery_queue.take(&key);
435+
publish_sandbox_component_now(&state, &key).await;
436+
if !state.config_delivery_queue.finish_pass(&key) {
437+
break;
438+
}
439+
}
440+
});
441+
}
442+
443+
async fn enqueue_sandbox_from_fanout(
444+
state: &Arc<ServerState>,
445+
sandbox_id: &str,
446+
component: ConfigComponentKind,
447+
) {
448+
let key = DeliveryKey {
449+
sandbox_id: sandbox_id.to_string(),
450+
component,
451+
};
452+
match state
453+
.config_delivery_queue
454+
.enqueue_from_fanout(key.clone())
455+
.await
456+
{
457+
DeliveryEnqueue::StartWorker(permit) => spawn_delivery_worker(state, key, permit),
458+
DeliveryEnqueue::Coalesced => {}
459+
DeliveryEnqueue::Full => unreachable!("fanout waits for delivery worker capacity"),
460+
}
461+
}
462+
400463
async fn publish_sandbox_component_now(state: &Arc<ServerState>, key: &DeliveryKey) {
401464
let component = key.component.name();
402465
let build = async {
@@ -505,10 +568,22 @@ async fn publish_fanout_now(state: &Arc<ServerState>, key: &FanoutKey) {
505568
continue;
506569
}
507570
}
508-
enqueue_sandbox(state, &sandbox_id, ConfigComponents::only(key.component));
571+
enqueue_sandbox_from_fanout(state, &sandbox_id, key.component).await;
509572
}
510573
}
511574

575+
fn record_delivery_worker_full(sandbox_id: &str, component: &'static str) {
576+
counter!(
577+
"openshell_supervisor_config_delivery_workers_total",
578+
"outcome" => "queue_full",
579+
)
580+
.increment(1);
581+
warn!(
582+
sandbox_id,
583+
component, "supervisor configuration delivery worker queue is full"
584+
);
585+
}
586+
512587
fn record_delivery(component: &'static str, disposition: DeliveryDisposition) {
513588
let outcome = match disposition {
514589
DeliveryDisposition::Enqueued => "enqueued",
@@ -558,13 +633,22 @@ mod tests {
558633
fn queue_coalesces_repeated_component_changes_while_worker_is_active() {
559634
let queue = ConfigDeliveryQueue::default();
560635
let key = key("sb-1", ConfigComponentKind::SandboxConfig);
561-
assert!(queue.enqueue(key.clone()));
636+
let DeliveryEnqueue::StartWorker(permit) = queue.enqueue(key.clone()) else {
637+
panic!("first publication must start a worker");
638+
};
562639
queue.take(&key);
563-
assert!(!queue.enqueue(key.clone()));
564-
assert!(!queue.enqueue(key.clone()));
640+
assert!(matches!(
641+
queue.enqueue(key.clone()),
642+
DeliveryEnqueue::Coalesced
643+
));
644+
assert!(matches!(
645+
queue.enqueue(key.clone()),
646+
DeliveryEnqueue::Coalesced
647+
));
565648
assert!(queue.finish_pass(&key));
566649
queue.take(&key);
567650
assert!(!queue.finish_pass(&key));
651+
drop(permit);
568652
}
569653

570654
#[test]
@@ -651,10 +735,47 @@ mod tests {
651735

652736
#[test]
653737
fn queue_runs_components_and_sandboxes_independently() {
654-
let queue = ConfigDeliveryQueue::default();
655-
assert!(queue.enqueue(key("sb-1", ConfigComponentKind::SandboxConfig)));
656-
assert!(queue.enqueue(key("sb-1", ConfigComponentKind::ProviderEnvironment)));
657-
assert!(queue.enqueue(key("sb-2", ConfigComponentKind::SandboxConfig)));
738+
let queue = ConfigDeliveryQueue::new(3);
739+
assert!(matches!(
740+
queue.enqueue(key("sb-1", ConfigComponentKind::SandboxConfig)),
741+
DeliveryEnqueue::StartWorker(_)
742+
));
743+
assert!(matches!(
744+
queue.enqueue(key("sb-1", ConfigComponentKind::ProviderEnvironment)),
745+
DeliveryEnqueue::StartWorker(_)
746+
));
747+
assert!(matches!(
748+
queue.enqueue(key("sb-2", ConfigComponentKind::SandboxConfig)),
749+
DeliveryEnqueue::StartWorker(_)
750+
));
751+
}
752+
753+
#[tokio::test]
754+
async fn fleet_fanout_waits_without_creating_unbounded_delivery_workers() {
755+
const ROUTED_SANDBOXES: usize = 10_000;
756+
let queue = Arc::new(ConfigDeliveryQueue::new(1));
757+
let first = key("sandbox-0", ConfigComponentKind::SandboxConfig);
758+
let DeliveryEnqueue::StartWorker(_blocked_worker) = queue.enqueue(first) else {
759+
panic!("first publication must start a worker");
760+
};
761+
762+
let sandbox_ids = (1..ROUTED_SANDBOXES)
763+
.map(|index| format!("sandbox-{index}"))
764+
.collect::<Vec<_>>();
765+
let fanout = async {
766+
for sandbox_id in sandbox_ids {
767+
for component in ConfigComponents::ALL.selected() {
768+
let _ = queue.enqueue_from_fanout(key(&sandbox_id, component)).await;
769+
}
770+
}
771+
};
772+
tokio::pin!(fanout);
773+
tokio::select! {
774+
() = &mut fanout => panic!("fanout must wait for worker capacity"),
775+
() = tokio::task::yield_now() => {}
776+
}
777+
778+
assert_eq!(queue.pending.lock().unwrap().len(), 1);
658779
}
659780

660781
#[test]

0 commit comments

Comments
 (0)