@@ -76,6 +76,7 @@ def __init__(
7676
7777 # Guard to ensure model is loaded once per client lifecycle
7878 self ._model_loaded = False
79+ self ._model_load_lock = asyncio .Lock ()
7980
8081 async def start (self , request_id : str = "default" ):
8182 """Start the trickle client."""
@@ -183,21 +184,26 @@ def set_target_fps(self, target_fps: Optional[float]):
183184
184185 async def _ensure_model_loaded (self ):
185186 """Load the model once on the same event loop before processing begins."""
186- if not self ._model_loaded :
187- # Transition to LOADING while model warms up, if state is available
188- try :
189- if getattr (self .frame_processor , "state" , None ) is not None :
190- self .frame_processor .state .set_state (PipelineState .LOADING )
191- await self .frame_processor .load_model ()
192- # Mark startup complete; this moves LOADING → IDLE per state machine
193- if getattr (self .frame_processor , "state" , None ) is not None :
194- self .frame_processor .state .set_startup_complete ()
195- self ._model_loaded = True
196- except Exception as e :
197- # Reflect error in state if available, then propagate
198- if getattr (self .frame_processor , "state" , None ) is not None :
199- self .frame_processor .state .set_error (str (e ))
200- raise
187+ # Transition to LOADING while model warms up, if state is available
188+ try :
189+ if getattr (self .frame_processor , "state" , None ) is not None :
190+ self .frame_processor .state .set_state (PipelineState .LOADING )
191+
192+ # Use the thread-safe wrapper
193+ await self .frame_processor .ensure_model_loaded ()
194+
195+ # Mark startup complete; this moves LOADING → IDLE per state machine
196+ if getattr (self .frame_processor , "state" , None ) is not None :
197+ self .frame_processor .state .set_startup_complete ()
198+
199+ # Update our local flag for consistency
200+ self ._model_loaded = True
201+
202+ except Exception as e :
203+ # Reflect error in state if available, then propagate
204+ if getattr (self .frame_processor , "state" , None ) is not None :
205+ self .frame_processor .state .set_error (str (e ))
206+ raise
201207
202208 async def _on_protocol_error (self , error_type : str , exception : Optional [Exception ] = None ):
203209 """Handle protocol errors and shutdown events."""
0 commit comments