modelexpress-server 0.7.0

High-performance gRPC server for model serving and management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! In-memory P2P metadata backend for tests and local dev. Not persistent, single
//! process. Mirrors the Redis backend's key layout (`(source_id, worker_id)` ->
//! `rank -> record`, plus a per-worker reported rank), but is not behaviorally
//! identical: `remove_worker` drops a source once its last worker is gone, where Redis
//! leaves the orphaned source index behind. So `list_sources` here won't report empty
//! sources.

use std::collections::{BTreeMap, HashMap};
use std::sync::{Mutex, PoisonError};

use async_trait::async_trait;
use modelexpress_common::grpc::p2p::{SourceIdentity, SourceStatus, WorkerMetadata};

use crate::p2p::backend::{
    MetadataBackend, MetadataResult, ModelMetadataRecord, SourceInstanceInfo, WorkerRecord,
};

#[derive(Default)]
struct WorkerEntry {
    ranks: BTreeMap<u32, WorkerRecord>,
    // the rank list_workers reports for this worker
    index_rank: u32,
}

#[derive(Default)]
struct SourceEntry {
    model_name: String,
    extra_parameters: HashMap<String, String>,
    identity: Option<SourceIdentity>,
    workers: HashMap<String, WorkerEntry>,
}

#[derive(Default)]
pub struct InMemoryMetadataBackend {
    sources: Mutex<HashMap<String, SourceEntry>>,
}

impl InMemoryMetadataBackend {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, SourceEntry>> {
        // poisoned just means someone panicked mid-write; the map is still usable
        self.sources.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

#[async_trait]
impl MetadataBackend for InMemoryMetadataBackend {
    async fn connect(&self) -> MetadataResult<()> {
        Ok(())
    }

    async fn publish_metadata(
        &self,
        identity: &SourceIdentity,
        worker_id: &str,
        worker: WorkerMetadata,
        _pod_name: &str,
        _pod_uid: &str,
        _pod_namespace: &str,
    ) -> MetadataResult<()> {
        let source_id = crate::p2p::source_identity::compute_mx_source_id(identity);
        let record = WorkerRecord::from(worker);
        let rank = record.worker_rank;

        let mut sources = self.lock();
        let source = sources.entry(source_id).or_default();
        source.model_name = identity.model_name.clone();
        source.extra_parameters = identity.extra_parameters.clone();
        source.identity = Some(identity.clone());
        let entry = source.workers.entry(worker_id.to_string()).or_default();
        entry.ranks.insert(rank, record);
        entry.index_rank = rank;
        Ok(())
    }

    async fn get_metadata(
        &self,
        source_id: &str,
        worker_id: &str,
    ) -> MetadataResult<Option<ModelMetadataRecord>> {
        let sources = self.lock();
        let Some(source) = sources.get(source_id) else {
            return Ok(None);
        };
        let Some(entry) = source.workers.get(worker_id) else {
            return Ok(None);
        };
        if entry.ranks.is_empty() {
            return Ok(None);
        }
        Ok(Some(ModelMetadataRecord {
            source_id: source_id.to_string(),
            worker_id: worker_id.to_string(),
            model_name: source.model_name.clone(),
            workers: entry.ranks.values().cloned().collect(),
            published_at: 0,
            identity: source.identity.clone(),
        }))
    }

    async fn list_workers(
        &self,
        source_id: Option<String>,
        status_filter: Option<SourceStatus>,
    ) -> MetadataResult<Vec<SourceInstanceInfo>> {
        let sources = self.lock();
        let mut result = Vec::new();
        for (sid, source) in sources.iter() {
            if let Some(filter) = &source_id
                && sid != filter
            {
                continue;
            }
            for (worker_id, entry) in &source.workers {
                if let Some(status) = status_filter
                    && !entry.ranks.values().any(|r| r.status == status as i32)
                {
                    continue;
                }
                let reported = entry
                    .ranks
                    .get(&entry.index_rank)
                    .or_else(|| entry.ranks.values().next());
                let (status, updated_at, accelerator, source_load, topology) = reported
                    .map_or_else(
                        || (0, 0, String::new(), None, HashMap::new()),
                        |r| {
                            (
                                r.status,
                                r.updated_at,
                                r.accelerator.clone(),
                                r.source_load,
                                r.topology.clone(),
                            )
                        },
                    );
                result.push(SourceInstanceInfo {
                    source_id: sid.clone(),
                    worker_id: worker_id.clone(),
                    model_name: source.model_name.clone(),
                    worker_rank: entry.index_rank,
                    status,
                    updated_at,
                    accelerator,
                    source_load,
                    topology,
                    training_step: super::parse_training_step(&source.extra_parameters),
                    layout_signature: super::parse_layout_signature(&source.extra_parameters),
                });
            }
        }
        Ok(result)
    }

    async fn remove_metadata(&self, source_id: &str) -> MetadataResult<()> {
        self.lock().remove(source_id);
        Ok(())
    }

    async fn remove_worker(&self, source_id: &str, worker_id: &str) -> MetadataResult<()> {
        // drop the source once its last worker is gone, so empties don't pile up
        let mut sources = self.lock();
        if let Some(source) = sources.get_mut(source_id) {
            source.workers.remove(worker_id);
            if source.workers.is_empty() {
                sources.remove(source_id);
            }
        }
        Ok(())
    }

    async fn list_sources(&self) -> MetadataResult<Vec<(String, String)>> {
        Ok(self
            .lock()
            .iter()
            .map(|(sid, source)| (sid.clone(), source.model_name.clone()))
            .collect())
    }

    async fn update_status(
        &self,
        source_id: &str,
        worker_id: &str,
        worker_rank: u32,
        status: SourceStatus,
        updated_at: i64,
        source_load: Option<f32>,
    ) -> MetadataResult<()> {
        let mut sources = self.lock();
        let record = sources
            .get_mut(source_id)
            .and_then(|source| source.workers.get_mut(worker_id))
            .and_then(|entry| entry.ranks.get_mut(&worker_rank));
        match record {
            Some(record) => {
                record.status = status as i32;
                record.updated_at = updated_at;
                record.source_load = source_load;
                Ok(())
            }
            None => Err(format!(
                "update_status: rank {worker_rank} not found in source '{source_id}' worker '{worker_id}'"
            )
            .into()),
        }
    }
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
    use super::*;
    use crate::p2p::source_identity::compute_mx_source_id;
    use modelexpress_common::grpc::p2p::MxSourceType;

    fn identity(model: &str) -> SourceIdentity {
        SourceIdentity {
            mx_version: "0.7.0".to_string(),
            mx_source_type: MxSourceType::Weights as i32,
            model_name: model.to_string(),
            backend_framework: 1,
            tensor_parallel_size: 1,
            pipeline_parallel_size: 1,
            expert_parallel_size: 0,
            dtype: "bfloat16".to_string(),
            quantization: String::new(),
            extra_parameters: Default::default(),
            revision: String::new(),
            ..Default::default()
        }
    }

    fn worker(rank: u32, status: SourceStatus) -> WorkerMetadata {
        WorkerMetadata {
            worker_rank: rank,
            backend_metadata: None,
            status: status as i32,
            updated_at: 0,
            accelerator: "cuda".to_string(),
            ..Default::default()
        }
    }

    // store/fetch works, and the source goes away with its last worker
    #[tokio::test]
    async fn publish_get_remove_roundtrip() {
        let backend = InMemoryMetadataBackend::new();
        let id = identity("m");
        let source_id = compute_mx_source_id(&id);

        backend
            .publish_metadata(&id, "w1", worker(0, SourceStatus::Ready), "", "", "")
            .await
            .expect("publish");
        let record = backend
            .get_metadata(&source_id, "w1")
            .await
            .expect("get")
            .expect("present");
        assert_eq!(record.model_name, "m");
        assert_eq!(record.workers.len(), 1);

        backend
            .remove_worker(&source_id, "w1")
            .await
            .expect("remove");
        assert!(
            backend
                .get_metadata(&source_id, "w1")
                .await
                .expect("get")
                .is_none()
        );
        assert!(backend.list_sources().await.expect("list").is_empty());
    }

    // multiple ranks under one worker_id come back sorted by rank
    #[tokio::test]
    async fn get_metadata_returns_ranks_sorted() {
        let backend = InMemoryMetadataBackend::new();
        let id = identity("m");
        let source_id = compute_mx_source_id(&id);

        for rank in [2, 0, 1] {
            backend
                .publish_metadata(&id, "w1", worker(rank, SourceStatus::Ready), "", "", "")
                .await
                .expect("publish");
        }

        let record = backend
            .get_metadata(&source_id, "w1")
            .await
            .expect("get")
            .expect("present");
        let ranks: Vec<u32> = record.workers.iter().map(|w| w.worker_rank).collect();
        assert_eq!(ranks, [0, 1, 2], "ranks sorted ascending");
    }

    // a worker is listed when ANY of its ranks matches the status filter
    #[tokio::test]
    async fn list_workers_status_filter_matches_any_rank() {
        let backend = InMemoryMetadataBackend::new();
        let id = identity("m");

        backend
            .publish_metadata(&id, "w1", worker(0, SourceStatus::Initializing), "", "", "")
            .await
            .expect("publish r0");
        backend
            .publish_metadata(&id, "w1", worker(1, SourceStatus::Ready), "", "", "")
            .await
            .expect("publish r1");

        assert_eq!(
            backend
                .list_workers(None, Some(SourceStatus::Ready))
                .await
                .expect("ready")
                .len(),
            1,
            "Ready matches rank 1"
        );
        assert_eq!(
            backend
                .list_workers(None, Some(SourceStatus::Initializing))
                .await
                .expect("init")
                .len(),
            1,
            "Initializing matches rank 0"
        );
        assert!(
            backend
                .list_workers(None, Some(SourceStatus::Stale))
                .await
                .expect("stale")
                .is_empty(),
            "no rank is Stale"
        );
    }

    // list_workers reports the last-published (index) rank and its status
    #[tokio::test]
    async fn list_workers_reports_index_rank() {
        let backend = InMemoryMetadataBackend::new();
        let mut id = identity("m");
        id.extra_parameters
            .insert("training_step".to_string(), "42".to_string());
        let source_id = compute_mx_source_id(&id);

        backend
            .publish_metadata(&id, "w1", worker(0, SourceStatus::Initializing), "", "", "")
            .await
            .expect("publish r0");
        backend
            .publish_metadata(&id, "w1", worker(3, SourceStatus::Ready), "", "", "")
            .await
            .expect("publish r3");

        let listed = backend
            .list_workers(Some(source_id), None)
            .await
            .expect("list");
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].worker_rank, 3, "reports the last-published rank");
        assert_eq!(listed[0].status, SourceStatus::Ready as i32);
        assert_eq!(
            listed[0].accelerator, "cuda",
            "carries the runtime accelerator"
        );
        assert_eq!(listed[0].training_step, Some(42));
    }

    // update_status patches an existing rank and errors on a missing rank or worker
    #[tokio::test]
    async fn update_status_patches_then_errors_on_missing() {
        let backend = InMemoryMetadataBackend::new();
        let id = identity("m");
        let source_id = compute_mx_source_id(&id);

        backend
            .publish_metadata(&id, "w1", worker(0, SourceStatus::Initializing), "", "", "")
            .await
            .expect("publish");
        backend
            .update_status(&source_id, "w1", 0, SourceStatus::Ready, 123, Some(0.0))
            .await
            .expect("patch existing rank");

        let record = backend
            .get_metadata(&source_id, "w1")
            .await
            .expect("get")
            .expect("present");
        assert_eq!(record.workers[0].status, SourceStatus::Ready as i32);
        assert_eq!(record.workers[0].updated_at, 123);

        assert!(
            backend
                .update_status(&source_id, "w1", 99, SourceStatus::Ready, 1, Some(0.0))
                .await
                .is_err(),
            "unknown rank errors"
        );
        assert!(
            backend
                .update_status(&source_id, "ghost", 0, SourceStatus::Ready, 1, Some(0.0))
                .await
                .is_err(),
            "unknown worker errors"
        );
    }

    // a source survives while it has any worker, and is dropped with its last one
    #[tokio::test]
    async fn remove_worker_drops_source_only_when_empty() {
        let backend = InMemoryMetadataBackend::new();
        let id = identity("m");
        let source_id = compute_mx_source_id(&id);

        backend
            .publish_metadata(&id, "w1", worker(0, SourceStatus::Ready), "", "", "")
            .await
            .expect("publish w1");
        backend
            .publish_metadata(&id, "w2", worker(0, SourceStatus::Ready), "", "", "")
            .await
            .expect("publish w2");

        backend
            .remove_worker(&source_id, "w1")
            .await
            .expect("remove w1");
        assert_eq!(
            backend.list_sources().await.expect("list").len(),
            1,
            "source stays while w2 remains"
        );
        assert!(
            backend
                .get_metadata(&source_id, "w2")
                .await
                .expect("get")
                .is_some()
        );

        backend
            .remove_worker(&source_id, "w2")
            .await
            .expect("remove w2");
        assert!(
            backend.list_sources().await.expect("list").is_empty(),
            "source dropped with its last worker"
        );
    }

    // source_load is Option: a worker that has never heartbeated lists as None
    // (no reading), and a heartbeat's Some(x) is what list_workers surfaces.
    // None and 0.0 are different answers on the wire and must stay so here.
    #[tokio::test]
    async fn source_load_round_trips_as_option() {
        let backend = InMemoryMetadataBackend::new();
        let id = identity("m");
        let source_id = compute_mx_source_id(&id);
        backend
            .publish_metadata(&id, "w1", worker(0, SourceStatus::Ready), "", "", "")
            .await
            .expect("publish");

        let before = backend
            .list_workers(Some(source_id.clone()), None)
            .await
            .expect("list");
        assert_eq!(before.len(), 1);
        assert_eq!(before[0].source_load, None);

        backend
            .update_status(&source_id, "w1", 0, SourceStatus::Ready, 7, Some(0.42))
            .await
            .expect("update_status");
        let after = backend
            .list_workers(Some(source_id), None)
            .await
            .expect("list");
        assert_eq!(after[0].source_load, Some(0.42));
        assert_eq!(after[0].updated_at, 7);
    }
}