@@ -13,6 +13,7 @@ use metrics::counter;
1313use openshell_core:: proto:: {
1414 ConfigBootstrap , ProviderEnvironmentSnapshot , Sandbox , SandboxConfigSnapshot ,
1515} ;
16+ use tokio:: sync:: Semaphore ;
1617use tonic:: { Code , Status } ;
1718use tracing:: warn;
1819
@@ -26,6 +27,11 @@ use crate::supervisor_session::SupervisorSessionRegistry;
2627pub const MAX_SUPERVISOR_CONFIG_MESSAGE_BYTES : usize = 3 * 1024 * 1024 ;
2728const CONFIG_SNAPSHOT_BUILD_TIMEOUT : Duration = Duration :: from_secs ( 45 ) ;
2829const 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 ) ]
185196pub 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
190208impl 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
339397async 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) ]
480540mod 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 ( ) ;
0 commit comments