model_manager.rs 25.5 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
// SPDX-License-Identifier: Apache-2.0

4
5
use std::{
    collections::{HashMap, HashSet},
6
    sync::Arc,
7
8
};

9
use dashmap::{DashMap, mapref::entry::Entry};
10
use parking_lot::RwLock;
11
use tokio::sync::oneshot;
12

13
use super::worker_monitor::LoadThresholdConfig;
14
use super::{KvWorkerMonitor, RuntimeConfigWatch, runtime_config_watch};
15

16
use dynamo_runtime::{
17
    component::{Client, Endpoint, build_transport_type},
18
    discovery::DiscoverySpec,
19
20
21
    prelude::DistributedRuntimeProvider,
    protocols::EndpointId,
};
22
23

use crate::{
24
25
26
27
    kv_router::{
        KvRouter, KvRouterConfig, protocols::WorkerId, router_endpoint_id,
        scheduler::DefaultWorkerSelector,
    },
28
    local_model::runtime_config::DisaggregatedEndpoint,
29
    model_card::ModelDeploymentCard,
30
    model_type::ModelType,
31
32
33
34
35
    types::{
        generic::tensor::TensorStreamingEngine,
        openai::{
            chat_completions::OpenAIChatCompletionsStreamingEngine,
            completions::OpenAICompletionsStreamingEngine,
36
            embeddings::OpenAIEmbeddingsStreamingEngine, images::OpenAIImagesStreamingEngine,
37
            videos::OpenAIVideosStreamingEngine,
38
39
        },
    },
40
};
41

42
43
44
45
46
47
48
49
/// State for prefill router activation rendezvous
enum PrefillActivationState {
    /// Decode model registered, waiting for prefill endpoint
    DecodeWaiting(oneshot::Sender<Endpoint>),
    /// Prefill endpoint arrived, waiting for decode model to register
    PrefillReady(oneshot::Receiver<Endpoint>),
}

50
51
52
53
54
55
56
57
58
#[derive(Debug, thiserror::Error)]
pub enum ModelManagerError {
    #[error("Model not found: {0}")]
    ModelNotFound(String),

    #[error("Model already exists: {0}")]
    ModelAlreadyExists(String),
}

59
60
61
62
63
64
/// Central manager for model engines, routing, and configuration.
///
/// Manages model lifecycle including engines, KV routers, prefill coordination,
/// and per-model busy thresholds for load-based request rejection.
///
/// Note: Don't implement Clone for this, put it in an Arc instead.
65
66
67
68
69
pub struct ModelManager {
    // We read a lot and write rarely, so these three are RwLock
    completion_engines: RwLock<ModelEngines<OpenAICompletionsStreamingEngine>>,
    chat_completion_engines: RwLock<ModelEngines<OpenAIChatCompletionsStreamingEngine>>,
    embeddings_engines: RwLock<ModelEngines<OpenAIEmbeddingsStreamingEngine>>,
70
    images_engines: RwLock<ModelEngines<OpenAIImagesStreamingEngine>>,
71
    videos_engines: RwLock<ModelEngines<OpenAIVideosStreamingEngine>>,
72
    tensor_engines: RwLock<ModelEngines<TensorStreamingEngine>>,
73
74
    // Prefill models don't have engines - they're only tracked for discovery/lifecycle
    prefill_engines: RwLock<ModelEngines<()>>,
75

76
77
78
    cards: DashMap<String, ModelDeploymentCard>,
    kv_choosers: DashMap<EndpointId, Arc<KvRouter>>,
    prefill_router_activators: DashMap<String, PrefillActivationState>,
79

80
81
    // Per-model monitoring: worker_monitors for load-based rejection, runtime_configs for KvScheduler
    worker_monitors: DashMap<String, KvWorkerMonitor>,
82
    runtime_configs: DashMap<EndpointId, RuntimeConfigWatch>,
83
84
85
86
87
88
89
90
91
92
93
94
95
96
}

impl Default for ModelManager {
    fn default() -> Self {
        Self::new()
    }
}

impl ModelManager {
    pub fn new() -> Self {
        Self {
            completion_engines: RwLock::new(ModelEngines::default()),
            chat_completion_engines: RwLock::new(ModelEngines::default()),
            embeddings_engines: RwLock::new(ModelEngines::default()),
97
            images_engines: RwLock::new(ModelEngines::default()),
98
            videos_engines: RwLock::new(ModelEngines::default()),
99
            tensor_engines: RwLock::new(ModelEngines::default()),
100
            prefill_engines: RwLock::new(ModelEngines::default()),
101
102
103
            cards: DashMap::new(),
            kv_choosers: DashMap::new(),
            prefill_router_activators: DashMap::new(),
104
            worker_monitors: DashMap::new(),
105
            runtime_configs: DashMap::new(),
106
107
108
        }
    }

109
110
111
112
113
114
115
116
117
118
119
120
121
    pub fn is_valid_checksum(
        &self,
        model_type: ModelType,
        model_name: &str,
        candidate_checksum: &str,
    ) -> Option<bool> {
        let mut results = vec![];
        for unit in model_type.units() {
            let maybe_valid_checksum = match unit {
                ModelType::Chat => self.chat_completion_engines.read().checksum(model_name),
                ModelType::Completions => self.completion_engines.read().checksum(model_name),
                ModelType::Embedding => self.embeddings_engines.read().checksum(model_name),
                ModelType::TensorBased => self.tensor_engines.read().checksum(model_name),
122
                ModelType::Images => self.images_engines.read().checksum(model_name),
123
                ModelType::Videos => self.videos_engines.read().checksum(model_name),
124
                ModelType::Prefill => self.prefill_engines.read().checksum(model_name),
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
                _ => {
                    continue;
                }
            };
            if let Some(is_valid) = maybe_valid_checksum.map(|valid_checksum| {
                tracing::debug!(
                    model_name,
                    valid_checksum,
                    candidate_checksum,
                    "is_valid_checksum: check case"
                );
                valid_checksum == candidate_checksum
            }) {
                results.push(is_valid)
            }
        }
        if results.is_empty() {
            None
        } else {
            // The checksum is valid if it is correct for all the ModelType in the bitflag.
            Some(results.into_iter().all(|x| x))
        }
    }

149
    pub fn get_model_cards(&self) -> Vec<ModelDeploymentCard> {
150
        self.cards.iter().map(|r| r.value().clone()).collect()
151
152
    }

153
154
    /// Check if a decode model (chat or completions) is registered
    pub fn has_decode_model(&self, model: &str) -> bool {
155
156
        self.chat_completion_engines.read().contains(model)
            || self.completion_engines.read().contains(model)
157
158
159
160
161
162
163
164
165
166
167
    }

    /// Check if a prefill model is registered
    pub fn has_prefill_model(&self, model: &str) -> bool {
        self.prefill_engines.read().contains(model)
    }

    /// Check if any model (decode or prefill) is registered.
    /// Note: For registration skip-checks, use has_decode_model() or has_prefill_model() instead.
    pub fn has_model_any(&self, model: &str) -> bool {
        self.has_decode_model(model) || self.has_prefill_model(model)
168
169
    }

170
171
172
173
174
    pub fn model_display_names(&self) -> HashSet<String> {
        self.list_chat_completions_models()
            .into_iter()
            .chain(self.list_completions_models())
            .chain(self.list_embeddings_models())
175
            .chain(self.list_images_models())
176
177
            .chain(self.list_videos_models())
            .chain(self.list_tensor_models())
178
            .chain(self.list_prefill_models())
179
180
181
            .collect()
    }

182
    pub fn list_chat_completions_models(&self) -> Vec<String> {
183
        self.chat_completion_engines.read().list()
184
185
186
    }

    pub fn list_completions_models(&self) -> Vec<String> {
187
        self.completion_engines.read().list()
188
189
190
    }

    pub fn list_embeddings_models(&self) -> Vec<String> {
191
        self.embeddings_engines.read().list()
192
193
    }

194
195
196
197
    pub fn list_tensor_models(&self) -> Vec<String> {
        self.tensor_engines.read().list()
    }

198
199
200
201
    pub fn list_prefill_models(&self) -> Vec<String> {
        self.prefill_engines.read().list()
    }

202
203
204
205
    pub fn list_images_models(&self) -> Vec<String> {
        self.images_engines.read().list()
    }

206
207
208
209
    pub fn list_videos_models(&self) -> Vec<String> {
        self.videos_engines.read().list()
    }

210
211
212
    pub fn add_completions_model(
        &self,
        model: &str,
213
        card_checksum: &str,
214
215
        engine: OpenAICompletionsStreamingEngine,
    ) -> Result<(), ModelManagerError> {
216
        let mut clients = self.completion_engines.write();
217
        clients.add(model, card_checksum, engine)
218
219
220
221
222
    }

    pub fn add_chat_completions_model(
        &self,
        model: &str,
223
        card_checksum: &str,
224
225
        engine: OpenAIChatCompletionsStreamingEngine,
    ) -> Result<(), ModelManagerError> {
226
        let mut clients = self.chat_completion_engines.write();
227
        clients.add(model, card_checksum, engine)
228
229
230
231
232
    }

    pub fn add_embeddings_model(
        &self,
        model: &str,
233
        card_checksum: &str,
234
235
        engine: OpenAIEmbeddingsStreamingEngine,
    ) -> Result<(), ModelManagerError> {
236
        let mut clients = self.embeddings_engines.write();
237
        clients.add(model, card_checksum, engine)
238
239
    }

240
241
242
    pub fn add_tensor_model(
        &self,
        model: &str,
243
        card_checksum: &str,
244
245
246
        engine: TensorStreamingEngine,
    ) -> Result<(), ModelManagerError> {
        let mut clients = self.tensor_engines.write();
247
        clients.add(model, card_checksum, engine)
248
249
    }

250
251
252
253
254
255
256
257
258
259
    pub fn add_images_model(
        &self,
        model: &str,
        card_checksum: &str,
        engine: OpenAIImagesStreamingEngine,
    ) -> Result<(), ModelManagerError> {
        let mut clients = self.images_engines.write();
        clients.add(model, card_checksum, engine)
    }

260
261
262
263
264
265
266
267
268
269
    pub fn add_videos_model(
        &self,
        model: &str,
        card_checksum: &str,
        engine: OpenAIVideosStreamingEngine,
    ) -> Result<(), ModelManagerError> {
        let mut clients = self.videos_engines.write();
        clients.add(model, card_checksum, engine)
    }

270
271
272
273
274
275
    pub fn add_prefill_model(
        &self,
        model: &str,
        card_checksum: &str,
    ) -> Result<(), ModelManagerError> {
        let mut clients = self.prefill_engines.write();
276
        clients.add(model, card_checksum, ())
277
278
    }

279
    pub fn remove_completions_model(&self, model: &str) -> Result<(), ModelManagerError> {
280
        let mut clients = self.completion_engines.write();
281
282
283
284
        clients.remove(model)
    }

    pub fn remove_chat_completions_model(&self, model: &str) -> Result<(), ModelManagerError> {
285
        let mut clients = self.chat_completion_engines.write();
286
287
288
289
        clients.remove(model)
    }

    pub fn remove_embeddings_model(&self, model: &str) -> Result<(), ModelManagerError> {
290
        let mut clients = self.embeddings_engines.write();
291
292
293
        clients.remove(model)
    }

294
295
296
297
298
    pub fn remove_tensor_model(&self, model: &str) -> Result<(), ModelManagerError> {
        let mut clients = self.tensor_engines.write();
        clients.remove(model)
    }

299
300
301
302
303
    pub fn remove_images_model(&self, model: &str) -> Result<(), ModelManagerError> {
        let mut clients = self.images_engines.write();
        clients.remove(model)
    }

304
305
306
307
308
    pub fn remove_videos_model(&self, model: &str) -> Result<(), ModelManagerError> {
        let mut clients = self.videos_engines.write();
        clients.remove(model)
    }

309
310
311
312
313
    pub fn remove_prefill_model(&self, model: &str) -> Result<(), ModelManagerError> {
        let mut clients = self.prefill_engines.write();
        clients.remove(model)
    }

314
    pub fn get_embeddings_engine(
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
        &self,
        model: &str,
    ) -> Result<OpenAIEmbeddingsStreamingEngine, ModelManagerError> {
        self.embeddings_engines
            .read()
            .get(model)
            .cloned()
            .ok_or(ModelManagerError::ModelNotFound(model.to_string()))
    }

    pub fn get_completions_engine(
        &self,
        model: &str,
    ) -> Result<OpenAICompletionsStreamingEngine, ModelManagerError> {
        self.completion_engines
            .read()
            .get(model)
            .cloned()
            .ok_or(ModelManagerError::ModelNotFound(model.to_string()))
    }

    pub fn get_chat_completions_engine(
        &self,
        model: &str,
    ) -> Result<OpenAIChatCompletionsStreamingEngine, ModelManagerError> {
        self.chat_completion_engines
            .read()
            .get(model)
            .cloned()
            .ok_or(ModelManagerError::ModelNotFound(model.to_string()))
    }

347
348
349
350
351
352
353
354
355
356
357
    pub fn get_tensor_engine(
        &self,
        model: &str,
    ) -> Result<TensorStreamingEngine, ModelManagerError> {
        self.tensor_engines
            .read()
            .get(model)
            .cloned()
            .ok_or(ModelManagerError::ModelNotFound(model.to_string()))
    }

358
359
360
361
362
363
364
365
366
367
368
    pub fn get_images_engine(
        &self,
        model: &str,
    ) -> Result<OpenAIImagesStreamingEngine, ModelManagerError> {
        self.images_engines
            .read()
            .get(model)
            .cloned()
            .ok_or(ModelManagerError::ModelNotFound(model.to_string()))
    }

369
370
371
372
373
374
375
376
377
378
379
    pub fn get_videos_engine(
        &self,
        model: &str,
    ) -> Result<OpenAIVideosStreamingEngine, ModelManagerError> {
        self.videos_engines
            .read()
            .get(model)
            .cloned()
            .ok_or(ModelManagerError::ModelNotFound(model.to_string()))
    }

380
    /// Save a ModelDeploymentCard from an instance's key so we can fetch it later when the key is
381
382
    /// deleted.
    pub fn save_model_card(&self, key: &str, card: ModelDeploymentCard) -> anyhow::Result<()> {
383
        self.cards.insert(key.to_string(), card);
384
        Ok(())
385
386
    }

387
    /// Remove and return model card for this instance's key. We do this when the instance stops.
388
    pub fn remove_model_card(&self, key: &str) -> Option<ModelDeploymentCard> {
389
        self.cards.remove(key).map(|(_, v)| v)
390
391
392
393
    }

    pub async fn kv_chooser_for(
        &self,
394
        endpoint: &Endpoint,
395
        kv_cache_block_size: u32,
396
        kv_router_config: Option<KvRouterConfig>,
397
        worker_type: &'static str,
398
    ) -> anyhow::Result<Arc<KvRouter>> {
399
        let endpoint_id = endpoint.id();
400

401
        if let Some(kv_chooser) = self.get_kv_chooser(&endpoint_id) {
402
403
404
            // Check if the existing router has a different block size
            if kv_chooser.block_size() != kv_cache_block_size {
                tracing::warn!(
405
                    endpoint = %endpoint_id,
406
407
                    existing_block_size = %kv_chooser.block_size(),
                    requested_block_size = %kv_cache_block_size,
408
                    "KV Router block size mismatch! Endpoint is requesting a different kv_cache_block_size than the existing router. \
409
410
411
                     This will cause routing to fail silently. Consider using the same block size or restarting the router."
                );
            }
412
413
414
            return Ok(kv_chooser);
        }

415
        let client = endpoint.client().await?;
416
417
418
419
420

        // Register router via discovery mechanism
        let discovery = endpoint.component().drt().discovery();
        let instance_id = discovery.instance_id();

421
        // Build transport for router endpoint based on request plane mode
422
423
        // Use KV_ROUTER_COMPONENT as the component name to distinguish from the generate endpoint's component
        let router_endpoint_id = router_endpoint_id(endpoint.id().namespace);
424
        let transport = build_transport_type(endpoint, &router_endpoint_id, instance_id).await?;
425
426
427
428
429

        let discovery_spec = DiscoverySpec::Endpoint {
            namespace: router_endpoint_id.namespace.clone(),
            component: router_endpoint_id.component.clone(),
            endpoint: router_endpoint_id.name.clone(),
430
            transport,
431
432
433
434
        };

        discovery.register(discovery_spec).await?;

435
436
437
        // Get or create runtime config watcher for this endpoint
        let workers_with_configs = self.get_or_create_runtime_config_watcher(endpoint).await?;

438
        let selector = Box::new(DefaultWorkerSelector::new(kv_router_config));
439
        let chooser = KvRouter::new(
440
441
            endpoint.clone(),
            client,
442
            workers_with_configs,
443
444
            kv_cache_block_size,
            Some(selector),
445
            kv_router_config,
446
            instance_id,
447
            worker_type,
448
449
        )
        .await?;
450
        let new_kv_chooser = Arc::new(chooser);
451
        self.kv_choosers.insert(endpoint_id, new_kv_chooser.clone());
452
453
        Ok(new_kv_chooser)
    }
454

455
    fn get_kv_chooser(&self, id: &EndpointId) -> Option<Arc<KvRouter>> {
456
        self.kv_choosers.get(id).map(|r| r.value().clone())
457
458
459
460
461
462
463
464
465
    }

    /// Register a prefill router for a decode model. Returns a receiver that will be
    /// activated when the corresponding prefill model is discovered.
    /// Returns None if the decode model was already registered.
    pub fn register_prefill_router(
        &self,
        model_name: String,
    ) -> Option<oneshot::Receiver<Endpoint>> {
466
467
        match self.prefill_router_activators.remove(&model_name) {
            Some((_, PrefillActivationState::PrefillReady(rx))) => {
468
469
470
471
472
473
474
                // Prefill endpoint already arrived - rx will immediately resolve
                tracing::debug!(
                    model_name = %model_name,
                    "Prefill endpoint already available, returning receiver with endpoint"
                );
                Some(rx)
            }
475
            Some((key, PrefillActivationState::DecodeWaiting(tx))) => {
476
477
478
479
480
                // Decode already registered - this shouldn't happen, restore state and return None
                tracing::error!(
                    model_name = %model_name,
                    "Decode model already registered for this prefill router"
                );
481
482
                self.prefill_router_activators
                    .insert(key, PrefillActivationState::DecodeWaiting(tx));
483
484
485
486
487
                None
            }
            None => {
                // New registration: create tx/rx pair, store sender and return receiver
                let (tx, rx) = oneshot::channel();
488
                self.prefill_router_activators.insert(
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
                    model_name.clone(),
                    PrefillActivationState::DecodeWaiting(tx),
                );
                tracing::debug!(
                    model_name = %model_name,
                    "No prefill endpoint available yet, storing sender for future activation"
                );
                Some(rx)
            }
        }
    }

    /// Activate a prefill router by sending the endpoint through the oneshot channel.
    /// If no decode model has registered yet, stores the endpoint for future retrieval.
    pub fn activate_prefill_router(
        &self,
        model_name: &str,
        endpoint: Endpoint,
    ) -> anyhow::Result<()> {
508
509
        match self.prefill_router_activators.remove(model_name) {
            Some((_, PrefillActivationState::DecodeWaiting(sender))) => {
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
                // Decode model already registered
                sender.send(endpoint).map_err(|_| {
                    anyhow::anyhow!(
                        "Failed to send endpoint to prefill router activator for model: {}",
                        model_name
                    )
                })?;

                tracing::info!(
                    model_name = %model_name,
                    "Activated prefill router for already-registered decode model"
                );

                Ok(())
            }
525
            Some((_, PrefillActivationState::PrefillReady(_))) => {
526
527
528
529
530
531
532
533
534
535
536
537
                // Prefill already activated - this shouldn't happen
                anyhow::bail!("Prefill router for model {} already activated", model_name);
            }
            None => {
                // Decode model not registered yet - create pair and immediately send endpoint
                let (tx, rx) = oneshot::channel();

                tx.send(endpoint).map_err(|_| {
                    anyhow::anyhow!("Failed to send endpoint for prefill model: {}", model_name)
                })?;

                // Store the receiver for when decode model registers
538
                self.prefill_router_activators.insert(
539
540
541
542
543
544
545
546
547
548
549
550
                    model_name.to_string(),
                    PrefillActivationState::PrefillReady(rx),
                );

                tracing::info!(
                    model_name = %model_name,
                    "Stored prefill endpoint for future decode model registration"
                );

                Ok(())
            }
        }
551
552
    }

553
    pub fn get_model_tool_call_parser(&self, model: &str) -> Option<String> {
554
        self.cards
555
556
557
            .iter()
            .find(|r| r.value().display_name == model)
            .and_then(|r| r.value().runtime_config.tool_call_parser.clone())
558
    }
559
560
561
562
563
564
565
566
567

    /// Creates parsing options with tool call parser and reasoning parser for the specified model.
    /// Currently reasoning parser is not implemented (returns None).
    pub fn get_parsing_options(&self, model: &str) -> crate::protocols::openai::ParsingOptions {
        let tool_call_parser = self.get_model_tool_call_parser(model);
        let reasoning_parser = None; // TODO: Implement reasoning parser

        crate::protocols::openai::ParsingOptions::new(tool_call_parser, reasoning_parser)
    }
568

569
570
571
    /// Gets or sets the load threshold config for a model's worker monitor.
    /// Pass `Some(config)` to update, `None` to get. Returns `None` if no monitor exists.
    pub fn load_threshold_config(
572
573
        &self,
        model: &str,
574
575
576
577
578
        config: Option<&LoadThresholdConfig>,
    ) -> Option<LoadThresholdConfig> {
        let monitor = self.worker_monitors.get(model)?;
        if let Some(cfg) = config {
            monitor.set_load_threshold_config(cfg);
579
        }
580
        Some(monitor.load_threshold_config())
581
582
    }

583
584
585
586
587
    /// Gets an existing worker monitor for a model, if one exists.
    pub fn get_worker_monitor(&self, model: &str) -> Option<KvWorkerMonitor> {
        self.worker_monitors.get(model).map(|m| m.clone())
    }

588
    /// Gets or creates a worker monitor for a model. Updates thresholds if monitor exists.
589
590
591
    pub fn get_or_create_worker_monitor(
        &self,
        model: &str,
592
        client: Client,
593
        config: LoadThresholdConfig,
594
    ) -> KvWorkerMonitor {
595
596
597
        if let Some(existing) = self.worker_monitors.get(model) {
            existing.set_load_threshold_config(&config);
            return existing.clone();
598
        }
599
600
601
602
        let monitor = KvWorkerMonitor::new(client, config);
        self.worker_monitors
            .insert(model.to_string(), monitor.clone());
        monitor
603
604
    }

605
    /// Get or create a runtime config watcher for an endpoint.
606
607
    /// Spawns a background task that joins instance availability and config discovery.
    /// Returns a `watch::Receiver` with the latest `HashMap<WorkerId, ModelRuntimeConfig>`.
608
609
610
    pub async fn get_or_create_runtime_config_watcher(
        &self,
        endpoint: &Endpoint,
611
    ) -> anyhow::Result<RuntimeConfigWatch> {
612
613
614
615
616
617
618
        let endpoint_id = endpoint.id();

        // Fast path: return existing if present
        if let Some(existing) = self.runtime_configs.get(&endpoint_id) {
            return Ok(existing.clone());
        }

619
620
621
622
623
624
        // Slow path: create the watch (spawns a background task).
        // If another caller raced us, the entry() below picks up the winner;
        // the loser's background task stops once its receivers are dropped.
        let rx = runtime_config_watch(endpoint).await?;
        let result = match self.runtime_configs.entry(endpoint_id) {
            Entry::Occupied(e) => e.get().clone(),
625
            Entry::Vacant(e) => {
626
627
                e.insert(rx.clone());
                rx
628
629
630
            }
        };

631
        Ok(result)
632
633
634
635
636
637
638
639
640
    }

    /// Get disaggregated endpoint for a specific worker.
    /// Used by PrefillRouter for bootstrap info - works for ANY routing mode.
    pub fn get_disaggregated_endpoint(
        &self,
        endpoint_id: &EndpointId,
        worker_id: WorkerId,
    ) -> Option<DisaggregatedEndpoint> {
641
642
643
        let rx = self.runtime_configs.get(endpoint_id)?;
        let configs = rx.borrow();
        configs.get(&worker_id)?.disaggregated_endpoint.clone()
644
645
    }

646
647
    /// Lists all models with worker monitors configured.
    pub fn list_busy_thresholds(&self) -> Vec<(String, LoadThresholdConfig)> {
648
649
        self.worker_monitors
            .iter()
650
            .map(|entry| (entry.key().clone(), entry.value().load_threshold_config()))
651
652
            .collect()
    }
653
654
655
656
657
658
}

pub struct ModelEngines<E> {
    /// Optional default model name
    default: Option<String>,
    engines: HashMap<String, E>,
659
660
661
    /// Key: Model name, value: Checksum of the ModelDeploymentCard. New instances must have the
    /// same card.
    checksums: HashMap<String, String>,
662
663
664
665
666
667
668
}

impl<E> Default for ModelEngines<E> {
    fn default() -> Self {
        Self {
            default: None,
            engines: HashMap::new(),
669
            checksums: HashMap::new(),
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
        }
    }
}

impl<E> ModelEngines<E> {
    #[allow(dead_code)]
    fn set_default(&mut self, model: &str) {
        self.default = Some(model.to_string());
    }

    #[allow(dead_code)]
    fn clear_default(&mut self) {
        self.default = None;
    }

685
    fn add(&mut self, model: &str, checksum: &str, engine: E) -> Result<(), ModelManagerError> {
686
687
688
689
        if self.engines.contains_key(model) {
            return Err(ModelManagerError::ModelAlreadyExists(model.to_string()));
        }
        self.engines.insert(model.to_string(), engine);
690
691
        self.checksums
            .insert(model.to_string(), checksum.to_string());
692
693
694
695
696
697
698
        Ok(())
    }

    fn remove(&mut self, model: &str) -> Result<(), ModelManagerError> {
        if self.engines.remove(model).is_none() {
            return Err(ModelManagerError::ModelNotFound(model.to_string()));
        }
699
        let _ = self.checksums.remove(model);
700
701
702
703
704
705
706
707
708
709
710
711
712
713
        Ok(())
    }

    fn get(&self, model: &str) -> Option<&E> {
        self.engines.get(model)
    }

    fn contains(&self, model: &str) -> bool {
        self.engines.contains_key(model)
    }

    pub fn list(&self) -> Vec<String> {
        self.engines.keys().map(|k| k.to_owned()).collect()
    }
714
715
716
717
718
719

    /// Returns a newly allocated String for called convenience. All the places I use
    /// this I need a String.
    pub fn checksum(&self, model: &str) -> Option<String> {
        self.checksums.get(model).map(|s| s.to_string())
    }
720
}