//! The attach loop of the backend worker: wait for the engine to load the model, serve requests and control //! messages while it is there, and attach again when it is lost. #[allow(unused_imports)] use super::*; /// How a stretch of serving ended. pub(super) enum Flow { /// The service is shutting down. Stop, /// The engine is gone; attach again. Reattach, } /// The worker and everything its loops share. pub(super) struct AttachLoop { engine: Engine, config: BackendWorkerConfig, status: Arc>, shutdown: watch::Receiver, requests: mpsc::Receiver, control: mpsc::Receiver, /// `Load` requests that arrived while the engine was away. waiting: Vec, attached_before: bool, requests_closed: bool, control_closed: bool, } /// The HTTP status of a refusal by the engine. fn error_status(code: api::ErrorCode) -> u16 { match code { api::ErrorCode::InvalidRequest => 400, api::ErrorCode::UnsupportedModel => 501, api::ErrorCode::ResourceExhausted => 409, api::ErrorCode::BackendUnavailable => 503, api::ErrorCode::Internal => 500, } } /// Fail a request that cannot be served; nothing is replayed. async fn refuse_request(command: GenerationCommand, message: &str) { command.request.obs.error(message); command.request.obs.finalize(); send_failure(command.result, message.to_owned()).await; } /// Whether the request is still wanted: the caller has not gone, and a queued ticket (if any) is claimed. fn claim_request(command: &mut GenerationCommand) -> bool { !(command.result.is_closed() || command.queue.take().is_some_and(|ticket| !ticket.claim())) } impl AttachLoop { pub(super) fn new( engine: Engine, config: BackendWorkerConfig, status: Arc>, shutdown: watch::Receiver, inbox: WorkerInbox, ) -> Self { Self { engine, config, status, shutdown, requests: inbox.requests, control: inbox.control, waiting: Vec::new(), attached_before: false, requests_closed: false, control_closed: false, } } pub(super) async fn run(&mut self) { loop { let state = if self.attached_before { WorkerState::Restarting } else { WorkerState::Starting }; update(&self.status, state, None).await; // Fail what queued up while the engine was away; nothing is replayed. while let Ok(command) = self.requests.try_recv() { refuse_request(command, "worker is restarting; request was not replayed").await; } let Some(loaded) = self.attach().await else { return; }; self.become_ready().await; if let Flow::Stop = self.serve(&loaded).await { return; } } } /// Ask the engine for the model until it answers with the one that was asked for; `None` when shut down. async fn attach(&mut self) -> Option { loop { if let Some(loaded) = self.try_load().await { return Some(loaded); } if !self.wait_before_retry().await { return None; } } } async fn try_load(&self) -> Option { let model = self.config.model.clone(); let runtime = self.config.runtime.clone(); match on_engine(&self.engine, move |backend| backend.load(model, runtime)).await { Ok(Ok(loaded)) if loaded .validate_for_load(&self.config.model, &self.config.runtime) .is_ok() => { return Some(loaded); } Ok(Ok(_)) => { crate::elog!("the engine returned a load result that does not match the request") } Ok(Err(error)) => leleka_obs::info( "api", "engine_wait", &[("reason", error.to_string().as_str().into())], ), Err(error) => leleka_obs::info( "api", "engine_wait", &[("reason", error.to_string().as_str().into())], ), } None } /// Wait out the retry delay, answering what arrives; `false` when the service shuts down meanwhile. async fn wait_before_retry(&mut self) -> bool { let retry = tokio::time::sleep(self.config.attach_retry); tokio::pin!(retry); loop { tokio::select! { biased; _ = self.shutdown.changed() => { update(&self.status, WorkerState::Stopping, None).await; return false; } _ = &mut retry => return true, message = self.control.recv(), if !self.control_closed => self.on_control_detached(message), command = self.requests.recv(), if !self.requests_closed => { self.on_request_detached(command).await; } } } } fn on_control_detached(&mut self, message: Option) { match message { Some(Control::Load { reply }) => self.waiting.push(reply), Some(Control::Reconfigure { reply, .. }) => crate::worker::reconfigure_unavailable( reply, "the worker is not attached to the engine", ), Some(Control::Unload { reply, .. }) => { let _ = reply.send(leleka_serving_policy::idle::Outcome::NotLoaded); } None => self.control_closed = true, } } async fn on_request_detached(&mut self, command: Option) { match command { Some(command) => { let message = "worker is not attached to the engine; request was not replayed"; refuse_request(command, message).await } None => self.requests_closed = true, } } /// The engine has the model: report ready and answer the `Load` requests that waited. async fn become_ready(&mut self) { self.attached_before = true; crate::request_log::note_engine_attached(); self.publish_ready_status().await; self.answer_waiting_loads(); } /// The status of a worker whose engine holds the model. async fn publish_ready_status(&self) { update( &self.status, WorkerState::Ready, Some(self.config.max_context), ) .await; self.status.write().await.output_cap = Some(self.config.max_output_tokens); self.status.write().await.text_level_engine = true; self.status.write().await.last_activity = Some(Instant::now()); } fn answer_waiting_loads(&mut self) { for reply in self.waiting.drain(..) { let _ = reply.send(Ok(())); } } /// Serve until the service shuts down or the engine is lost. async fn serve(&mut self, loaded: &api::LoadedModel) -> Flow { let mut health = tokio::time::interval(self.config.health_interval); health.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); health.reset(); loop { tokio::select! { biased; _ = self.shutdown.changed() => { self.report_stopping().await; return Flow::Stop; } _ = health.tick() => { if let Some(flow) = self.on_health_tick().await { return flow; } } message = self.control.recv(), if !self.control_closed => self.on_control(message).await, command = self.requests.recv(), if !self.requests_closed => { if let Some(flow) = self.on_request(command, loaded).await { return flow; } } } } } /// An idle worker asks the engine whether the model is still loaded, so readiness drops when it is not. async fn on_health_tick(&self) -> Option { if !self.engine_reports_model().await { let reason = "the runtime no longer reports the model as loaded"; self.report_engine_lost(reason).await; return Some(Flow::Reattach); } refresh_prefix_view(&self.engine, &self.config).await; None } /// Ask the engine whether the configured model is still loaded. async fn engine_reports_model(&self) -> bool { let wanted = self.config.model.clone(); let present = on_engine(&self.engine, move |backend| { backend.capabilities().supports(&wanted) }) .await; present == Ok(true) } /// The service is shutting down: report it. async fn report_stopping(&self) { update(&self.status, WorkerState::Stopping, None).await; } /// The engine is gone: record why and fail the worker. async fn report_engine_lost(&self, reason: &str) { crate::request_log::note_engine_lost(reason); update(&self.status, WorkerState::Failed, None).await; } async fn on_control(&mut self, message: Option) { match message { Some(Control::Load { reply }) => { let _ = reply.send(Ok(())); } Some(Control::Reconfigure { settings, reply }) => { self.reconfigure(settings, reply).await } Some(Control::Unload { reply, .. }) => { // The runtime's lifecycle belongs to its operator (leleka-cli), not to HTTP. let _ = reply.send(leleka_serving_policy::idle::Outcome::Unsupported); } None => self.control_closed = true, } } async fn reconfigure( &self, settings: String, reply: tokio::sync::oneshot::Sender>, ) { // Requests that arrive meanwhile wait in the queue: the engine reopens its serve stack in tens of seconds. let answer = match on_engine(&self.engine, move |backend| backend.reconfigure(&settings)).await { Ok(Ok(effective)) => Ok(effective), Ok(Err(error)) => Err((error_status(error.code), error.message)), Err(message) => Err((500, message)), }; let _ = reply.send(answer); refresh_prefix_view(&self.engine, &self.config).await; } /// One queued request; `Some` ends the serving stretch. async fn on_request( &mut self, command: Option, loaded: &api::LoadedModel, ) -> Option { let Some(mut command) = command else { self.requests_closed = true; return None; }; if !claim_request(&mut command) { return None; } self.serve_claimed(command, loaded).await } /// Serve a request nobody has abandoned and decide how the serving stretch goes on. async fn serve_claimed( &mut self, mut command: GenerationCommand, loaded: &api::LoadedModel, ) -> Option { self.status.write().await.last_activity = Some(command.request.obs.now()); let _activity = command.activity.take(); let ctx = Context { engine: &self.engine, config: &self.config, status: &self.status, }; let served = serve_one(ctx, &mut self.shutdown, &mut command, loaded).await; self.after_request(served, &command).await } async fn after_request(&self, served: Served, command: &GenerationCommand) -> Option { match served { Served::Done => { self.finish_request(command).await; None } Served::Shutdown => { self.report_stopping().await; Some(Flow::Stop) } Served::Lost(reason) => { self.report_engine_lost(&reason).await; Some(Flow::Reattach) } } } /// A served request leaves the worker idle: stamp the activity and refresh the prefix view. async fn finish_request(&self, command: &GenerationCommand) { self.status.write().await.last_activity = Some(command.request.obs.now()); refresh_prefix_view(&self.engine, &self.config).await; } }