@@ -13,7 +13,7 @@ use metrics::counter;
1313use openshell_core:: proto:: {
1414 ConfigBootstrap , ProviderEnvironmentSnapshot , Sandbox , SandboxConfigSnapshot ,
1515} ;
16- use tokio:: sync:: Semaphore ;
16+ use tokio:: sync:: { OwnedSemaphorePermit , Semaphore } ;
1717use tonic:: { Code , Status } ;
1818use 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 ) ]
199192pub 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 {
211205impl 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 ) ]
316348enum 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+
400463async 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+
512587fn 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