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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! P2P Metadata Service implementation for storing and retrieving NIXL/RDMA metadata.
//!
//! Metadata is keyed by mx_source_id, a 16-char hex hash of SourceIdentity.
//! Clients send the full SourceIdentity; the server computes and returns the hash.

use crate::metrics::grpc::RpcOutcome;
use crate::p2p::backend::SourceInstanceInfo;
use crate::p2p::source_identity::{compute_mx_source_id, validate_identity};
use crate::p2p::state::P2pStateManager;
use modelexpress_common::grpc::p2p::{
    GetMetadataRequest, GetMetadataResponse, ListSourcesRequest, ListSourcesResponse,
    PublishMetadataRequest, PublishMetadataResponse, SourceInstanceRef, SourceStatus,
    UpdateStatusRequest, UpdateStatusResponse, WorkerMetadata, p2p_service_server::P2pService,
};
use std::sync::Arc;
use tonic::{Request, Response, Status};
use tracing::{debug, error, info};

/// Return `body` with the handler's own verdict attached.
///
/// Every handler in this file reports failure **in band**: `Ok` carrying
/// `success: false`, or an empty `instances` list, rather than `Err(Status)`.
/// That is deliberate and stays as it is -- clients depend on it -- but it means
/// the status code reads `Ok` straight through a backend outage, so nothing
/// outside the handler can tell an outage from an empty-but-healthy answer.
///
/// This publishes the real outcome into the response extensions, where
/// [`crate::metrics::grpc`] reads it. The tag is metrics-only: it does not touch
/// the response body or the status code, and losing it degrades the metric to
/// `outcome="ok"` rather than breaking the call.
#[allow(clippy::result_large_err)] // Returns the handlers' own tonic::Status result type.
fn tagged<T>(body: T, outcome: RpcOutcome) -> Result<Response<T>, Status> {
    let mut response = Response::new(body);
    response.extensions_mut().insert(outcome);
    Ok(response)
}

/// P2P Service implementation
pub struct P2pServiceImpl {
    state: Arc<P2pStateManager>,
}

impl P2pServiceImpl {
    /// Create a new P2P service
    pub fn new(state: Arc<P2pStateManager>) -> Self {
        Self { state }
    }
}

fn ready_source_is_fresh(
    info: &SourceInstanceInfo,
    now_ms: i64,
    heartbeat_timeout_ms: u64,
) -> bool {
    if info.updated_at <= 0 {
        return false;
    }

    let age_ms = now_ms.saturating_sub(info.updated_at).max(0) as u64;
    age_ms <= heartbeat_timeout_ms
}

fn worker_tensor_count(worker: &WorkerMetadata) -> usize {
    use modelexpress_common::grpc::p2p::worker_metadata::SourcePayload;

    match &worker.source_payload {
        Some(SourcePayload::TensorSource(tensor_source)) => tensor_source.tensors.len(),
        Some(SourcePayload::ArtifactSource(_)) => 0,
        _ => legacy_worker_tensor_count(worker),
    }
}

#[allow(deprecated)]
fn legacy_worker_tensor_count(worker: &WorkerMetadata) -> usize {
    worker.tensors.len()
}

#[tonic::async_trait]
impl P2pService for P2pServiceImpl {
    async fn publish_metadata(
        &self,
        request: Request<PublishMetadataRequest>,
    ) -> Result<Response<PublishMetadataResponse>, Status> {
        let req = request.into_inner();

        let identity = match req.identity {
            Some(id) => id,
            None => {
                return tagged(
                    PublishMetadataResponse {
                        success: false,
                        message: "identity is required".to_string(),
                        mx_source_id: String::new(),
                        worker_id: String::new(),
                    },
                    RpcOutcome::InvalidArgument,
                );
            }
        };

        if let Err(e) = validate_identity(&identity) {
            return tagged(
                PublishMetadataResponse {
                    success: false,
                    message: e,
                    mx_source_id: String::new(),
                    worker_id: String::new(),
                },
                RpcOutcome::InvalidArgument,
            );
        }

        if req.worker_id.is_empty() {
            return tagged(
                PublishMetadataResponse {
                    success: false,
                    message: "worker_id is required".to_string(),
                    mx_source_id: String::new(),
                    worker_id: String::new(),
                },
                RpcOutcome::InvalidArgument,
            );
        }

        let worker = match req.worker {
            Some(w) => w,
            None => {
                return tagged(
                    PublishMetadataResponse {
                        success: false,
                        message: "worker is required".to_string(),
                        mx_source_id: String::new(),
                        worker_id: String::new(),
                    },
                    RpcOutcome::InvalidArgument,
                );
            }
        };

        let source_id = compute_mx_source_id(&identity);
        let worker_id = req.worker_id.clone();
        let model_name = identity.model_name.clone();
        let worker_rank = worker.worker_rank;
        let tensor_count = worker_tensor_count(&worker);

        match self
            .state
            .publish_metadata(
                &identity,
                &worker_id,
                worker,
                &req.pod_name,
                &req.pod_uid,
                &req.pod_namespace,
            )
            .await
        {
            Ok(()) => {
                info!(
                    "PublishMetadata: model='{}' source_id={} worker_id={} worker_rank={} tensors={}",
                    model_name, source_id, worker_id, worker_rank, tensor_count
                );
                tagged(
                    PublishMetadataResponse {
                        success: true,
                        message: format!(
                            "Published metadata for '{}' (source_id={}, worker_id={}, worker_rank={}, {} tensors)",
                            model_name, source_id, worker_id, worker_rank, tensor_count
                        ),
                        mx_source_id: source_id,
                        worker_id,
                    },
                    RpcOutcome::Ok,
                )
            }
            Err(e) => {
                error!("Failed to publish metadata: {}", e);
                tagged(
                    PublishMetadataResponse {
                        success: false,
                        message: format!("Failed to publish metadata: {e}"),
                        mx_source_id: String::new(),
                        worker_id: String::new(),
                    },
                    RpcOutcome::BackendError,
                )
            }
        }
    }

    async fn list_sources(
        &self,
        request: Request<ListSourcesRequest>,
    ) -> Result<Response<ListSourcesResponse>, Status> {
        let req = request.into_inner();

        // Resolve optional source_id filter
        let source_id_filter: Option<String> = req.identity.as_ref().and_then(|id| {
            if id.model_name.is_empty() {
                None
            } else {
                Some(compute_mx_source_id(id))
            }
        });

        // Convert raw proto i32 to typed enum — None means no filter
        let status_filter = req
            .status_filter
            .and_then(|s| SourceStatus::try_from(s).ok());

        let workers: Vec<SourceInstanceInfo> = match self
            .state
            .list_workers_filtered(
                source_id_filter,
                status_filter,
                req.model_name_filter,
                req.worker_rank_filter,
                req.min_training_step,
                req.min_updated_at,
                req.limit.map(|value| value as usize),
            )
            .await
        {
            Ok(v) => v,
            Err(e) => {
                error!("Failed to list workers: {}", e);
                return tagged(
                    ListSourcesResponse {
                        instances: Vec::new(),
                    },
                    RpcOutcome::BackendError,
                );
            }
        };

        let workers = if status_filter == Some(SourceStatus::Ready) {
            let now_ms = chrono::Utc::now().timestamp_millis();
            let heartbeat_timeout_ms =
                modelexpress_common::envs::heartbeat_timeout_secs().saturating_mul(1000);
            workers
                .into_iter()
                .filter(|info| ready_source_is_fresh(info, now_ms, heartbeat_timeout_ms))
                .collect()
        } else {
            workers
        };

        let refs: Vec<SourceInstanceRef> = workers
            .into_iter()
            .map(|info| SourceInstanceRef {
                mx_source_id: info.source_id,
                worker_id: info.worker_id,
                model_name: info.model_name,
                worker_rank: info.worker_rank,
                accelerator: info.accelerator,
                updated_at: info.updated_at,
                training_step: info.training_step,
                layout_signature: info.layout_signature,
                source_load: info.source_load,
                topology: info.topology,
            })
            .collect();

        debug!("ListSources: returning {} instances", refs.len());

        tagged(ListSourcesResponse { instances: refs }, RpcOutcome::Ok)
    }

    async fn get_metadata(
        &self,
        request: Request<GetMetadataRequest>,
    ) -> Result<Response<GetMetadataResponse>, Status> {
        let req = request.into_inner();

        if req.mx_source_id.is_empty() || req.worker_id.is_empty() {
            return tagged(
                GetMetadataResponse {
                    found: false,
                    worker: None,
                    mx_source_id: String::new(),
                    worker_id: String::new(),
                    identity: None,
                },
                RpcOutcome::InvalidArgument,
            );
        }

        match self
            .state
            .get_metadata(&req.mx_source_id, &req.worker_id)
            .await
        {
            Ok(Some(record)) => {
                // Each worker_id maps to exactly one worker record; take the first.
                let identity = record.identity.clone();
                let worker = record.workers.into_iter().next().map(WorkerMetadata::from);
                let found = worker.is_some();
                info!(
                    "GetMetadata '{}' (source_id={}, worker_id={}): {} tensors, identity_present={}",
                    record.model_name,
                    req.mx_source_id,
                    req.worker_id,
                    worker.as_ref().map_or(0, worker_tensor_count),
                    identity.is_some(),
                );
                // A record with no workers is the same answer as no record at
                // all, so it carries the same outcome. Reporting it as Ok would
                // make an absent worker look like a successful lookup.
                let outcome = if found {
                    RpcOutcome::Ok
                } else {
                    RpcOutcome::NotFound
                };
                tagged(
                    GetMetadataResponse {
                        found,
                        worker,
                        mx_source_id: req.mx_source_id,
                        worker_id: req.worker_id,
                        identity,
                    },
                    outcome,
                )
            }
            Ok(None) => {
                info!(
                    "No metadata found for source_id={} worker_id={}",
                    req.mx_source_id, req.worker_id
                );
                tagged(
                    GetMetadataResponse {
                        found: false,
                        worker: None,
                        mx_source_id: req.mx_source_id,
                        worker_id: req.worker_id,
                        identity: None,
                    },
                    RpcOutcome::NotFound,
                )
            }
            Err(e) => {
                error!("Failed to get metadata: {}", e);
                tagged(
                    GetMetadataResponse {
                        found: false,
                        worker: None,
                        mx_source_id: String::new(),
                        worker_id: String::new(),
                        identity: None,
                    },
                    RpcOutcome::BackendError,
                )
            }
        }
    }

    async fn update_status(
        &self,
        request: Request<UpdateStatusRequest>,
    ) -> Result<Response<UpdateStatusResponse>, Status> {
        let req = request.into_inner();

        if req.mx_source_id.is_empty() {
            return tagged(
                UpdateStatusResponse {
                    success: false,
                    message: "mx_source_id is required".to_string(),
                },
                RpcOutcome::InvalidArgument,
            );
        }

        if req.worker_id.is_empty() {
            return tagged(
                UpdateStatusResponse {
                    success: false,
                    message: "worker_id is required".to_string(),
                },
                RpcOutcome::InvalidArgument,
            );
        }

        let status = match SourceStatus::try_from(req.status) {
            Ok(s) => s,
            Err(_) => {
                return tagged(
                    UpdateStatusResponse {
                        success: false,
                        message: format!("invalid status value: {}", req.status),
                    },
                    RpcOutcome::InvalidArgument,
                );
            }
        };

        // Publisher-asserted and public. A non-finite value would serialize as
        // JSON null in the status summary and make the rank unreadable, so it is
        // treated as "no reading" rather than rejected: rejecting the heartbeat
        // would trip the client's re-registration path over a telemetry glitch.
        let source_load = req
            .source_load
            .filter(|v| v.is_finite())
            .map(|v| v.clamp(0.0, 1.0));

        match self
            .state
            .update_worker_status(
                &req.mx_source_id,
                &req.worker_id,
                req.worker_rank,
                status,
                source_load,
            )
            .await
        {
            Ok(()) => tagged(
                UpdateStatusResponse {
                    success: true,
                    message: format!(
                        "Updated status for source '{}' worker_id '{}' rank {}",
                        req.mx_source_id, req.worker_id, req.worker_rank
                    ),
                },
                RpcOutcome::Ok,
            ),
            Err(e) => {
                error!("Failed to update status: {}", e);
                tagged(
                    UpdateStatusResponse {
                        success: false,
                        message: format!("Failed to update status: {e}"),
                    },
                    RpcOutcome::BackendError,
                )
            }
        }
    }
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
    use super::*;
    use crate::p2p::backend::{
        BackendMetadataRecord, MockMetadataBackend, ModelMetadataRecord, WorkerRecord,
    };
    use crate::p2p::state::P2pStateManager;
    use modelexpress_common::grpc::p2p::worker_metadata::SourcePayload;
    use modelexpress_common::grpc::p2p::{
        ArtifactSourceMetadata, MxSourceType, SourceIdentity, SourceStatus, TensorSourceMetadata,
    };
    use std::collections::HashMap;

    fn make_service(mock: MockMetadataBackend) -> P2pServiceImpl {
        P2pServiceImpl::new(Arc::new(P2pStateManager::with_backend(Arc::new(mock))))
    }

    fn empty_tensor_source() -> Option<SourcePayload> {
        Some(SourcePayload::TensorSource(TensorSourceMetadata {
            tensors: vec![],
        }))
    }

    fn test_identity() -> SourceIdentity {
        SourceIdentity {
            mx_version: "0.7.0".to_string(),
            mx_source_type: MxSourceType::Weights as i32,
            model_name: "my-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(),
            backend_framework_version: String::new(),
            torch_version: String::new(),
            cuda_version: String::new(),
            triton_version: String::new(),
            gpu_arch: String::new(),
            compile_config_digest: String::new(),
        }
    }

    fn test_artifact_identity() -> SourceIdentity {
        SourceIdentity {
            mx_source_type: MxSourceType::TorchCompileCache as i32,
            ..test_identity()
        }
    }

    // ── publish_metadata ────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_publish_metadata_missing_identity() {
        let svc = make_service(MockMetadataBackend::new());
        let resp = svc
            .publish_metadata(Request::new(PublishMetadataRequest {
                identity: None,
                worker: None,
                worker_id: "worker-uuid-1".to_string(),
                ..Default::default()
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.success);
        assert!(resp.mx_source_id.is_empty());
    }

    #[tokio::test]
    async fn test_publish_metadata_empty_model_name() {
        let svc = make_service(MockMetadataBackend::new());
        let mut id = test_identity();
        id.model_name = String::new();
        let resp = svc
            .publish_metadata(Request::new(PublishMetadataRequest {
                identity: Some(id),
                worker: None,
                worker_id: "worker-uuid-1".to_string(),
                ..Default::default()
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.success);
    }

    #[tokio::test]
    async fn test_publish_metadata_missing_worker_id() {
        let svc = make_service(MockMetadataBackend::new());
        let resp = svc
            .publish_metadata(Request::new(PublishMetadataRequest {
                identity: Some(test_identity()),
                worker: None,
                worker_id: String::new(),
                ..Default::default()
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.success);
        assert!(resp.message.contains("worker_id"));
    }

    #[tokio::test]
    async fn test_publish_metadata_success() {
        let mut mock = MockMetadataBackend::new();
        mock.expect_publish_metadata()
            .withf(|_, _, _, pod_name, pod_uid, pod_namespace| {
                pod_name == "vllm-worker-0" && pod_uid == "pod-uid-1" && pod_namespace == "default"
            })
            .once()
            .returning(|_, _, _, _, _, _| Ok(()));

        let svc = make_service(mock);
        let resp = svc
            .publish_metadata(Request::new(PublishMetadataRequest {
                identity: Some(test_identity()),
                worker: Some(WorkerMetadata {
                    worker_rank: 0,
                    backend_metadata: Some(
                        modelexpress_common::grpc::p2p::worker_metadata::BackendMetadata::NixlMetadata(vec![1, 2, 3]),
                    ),
                    source_payload: empty_tensor_source(),
                    status: SourceStatus::Initializing as i32,
                    updated_at: 0,
                    ..Default::default()
                }),
                worker_id: "worker-uuid-1".to_string(),
                pod_name: "vllm-worker-0".to_string(),
                pod_uid: "pod-uid-1".to_string(),
                pod_namespace: "default".to_string(),
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(resp.success);
        assert!(!resp.mx_source_id.is_empty());
        assert_eq!(resp.mx_source_id.len(), 16);
        assert_eq!(resp.worker_id, "worker-uuid-1");
    }

    #[tokio::test]
    async fn test_publish_metadata_backend_error() {
        let mut mock = MockMetadataBackend::new();
        mock.expect_publish_metadata()
            .once()
            .returning(|_, _, _, _, _, _| Err("storage unavailable".into()));

        let svc = make_service(mock);
        let resp = svc
            .publish_metadata(Request::new(PublishMetadataRequest {
                identity: Some(test_identity()),
                worker: Some(WorkerMetadata {
                    worker_rank: 0,
                    backend_metadata: None,
                    source_payload: empty_tensor_source(),
                    status: SourceStatus::Initializing as i32,
                    updated_at: 0,
                    ..Default::default()
                }),
                worker_id: "worker-uuid-1".to_string(),
                ..Default::default()
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.success);
        assert!(resp.message.contains("storage unavailable"));
    }

    // ── get_metadata ────────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_get_metadata_empty_source_id() {
        let svc = make_service(MockMetadataBackend::new());
        let resp = svc
            .get_metadata(Request::new(GetMetadataRequest {
                mx_source_id: String::new(),
                worker_id: "worker-uuid-1".to_string(),
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.found);
        assert!(resp.worker.is_none());
    }

    #[tokio::test]
    async fn test_get_metadata_found() {
        let expected_identity = test_identity();
        let returned_identity = expected_identity.clone();
        let mut mock = MockMetadataBackend::new();
        mock.expect_get_metadata()
            .once()
            .returning(move |source_id, worker_id| {
                Ok(Some(ModelMetadataRecord {
                    source_id: source_id.to_string(),
                    worker_id: worker_id.to_string(),
                    model_name: "my-model".to_string(),
                    workers: vec![WorkerRecord {
                        worker_rank: 0,
                        backend_metadata: BackendMetadataRecord::None,
                        tensors: vec![],
                        status: SourceStatus::Ready as i32,
                        updated_at: 1234567890000,
                        metadata_endpoint: String::new(),
                        agent_name: String::new(),
                        worker_grpc_endpoint: String::new(),
                        accelerator: String::new(),
                        source_load: None,
                        topology: Default::default(),
                        artifact_source: None,
                    }],
                    published_at: 1234567890,
                    identity: Some(returned_identity.clone()),
                }))
            });

        let svc = make_service(mock);
        let resp = svc
            .get_metadata(Request::new(GetMetadataRequest {
                mx_source_id: "abc123def456abcd".to_string(),
                worker_id: "worker-uuid-1".to_string(),
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(resp.found);
        assert!(resp.worker.is_some());
        assert_eq!(
            resp.worker.expect("worker should be present").status,
            SourceStatus::Ready as i32
        );
        assert_eq!(resp.mx_source_id, "abc123def456abcd");
        assert_eq!(resp.worker_id, "worker-uuid-1");
        assert_eq!(resp.identity, Some(expected_identity));
    }

    #[tokio::test]
    async fn test_get_metadata_not_found() {
        let mut mock = MockMetadataBackend::new();
        mock.expect_get_metadata().once().returning(|_, _| Ok(None));

        let svc = make_service(mock);
        let resp = svc
            .get_metadata(Request::new(GetMetadataRequest {
                mx_source_id: "abc123def456abcd".to_string(),
                worker_id: "worker-uuid-1".to_string(),
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.found);
        assert!(resp.worker.is_none());
        assert_eq!(resp.mx_source_id, "abc123def456abcd");
    }

    // ── update_status ───────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_update_status_invalid_status_value() {
        let svc = make_service(MockMetadataBackend::new());
        let resp = svc
            .update_status(Request::new(UpdateStatusRequest {
                mx_source_id: "abc123def456abcd".to_string(),
                worker_id: "worker-uuid-1".to_string(),
                worker_rank: 0,
                status: 99,
                source_load: None,
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.success);
        assert!(resp.message.contains("99"));
    }

    #[tokio::test]
    async fn test_update_status_empty_source_id() {
        let svc = make_service(MockMetadataBackend::new());
        let resp = svc
            .update_status(Request::new(UpdateStatusRequest {
                mx_source_id: String::new(),
                worker_id: "worker-uuid-1".to_string(),
                worker_rank: 0,
                status: SourceStatus::Ready as i32,
                source_load: None,
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.success);
    }

    #[tokio::test]
    async fn test_update_status_empty_worker_id() {
        let svc = make_service(MockMetadataBackend::new());
        let resp = svc
            .update_status(Request::new(UpdateStatusRequest {
                mx_source_id: "abc123def456abcd".to_string(),
                worker_id: String::new(),
                worker_rank: 0,
                status: SourceStatus::Ready as i32,
                source_load: None,
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.success);
    }

    #[tokio::test]
    async fn test_update_status_success() {
        let mut mock = MockMetadataBackend::new();
        mock.expect_update_status()
            // Assert the request's source_load reaches the backend unchanged.
            .withf(|_, _, _, _, _, source_load| {
                source_load.is_some_and(|v| (v - 0.42).abs() < f32::EPSILON)
            })
            .once()
            .returning(|_, _, _, _, _, _| Ok(()));

        let svc = make_service(mock);
        let resp = svc
            .update_status(Request::new(UpdateStatusRequest {
                mx_source_id: "abc123def456abcd".to_string(),
                worker_id: "worker-uuid-1".to_string(),
                worker_rank: 3,
                status: SourceStatus::Ready as i32,
                source_load: Some(0.42),
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(resp.success);
    }

    // ── publish_metadata (missing worker) ────────────────────────────────

    #[tokio::test]
    async fn test_publish_metadata_missing_worker() {
        let svc = make_service(MockMetadataBackend::new());
        let resp = svc
            .publish_metadata(Request::new(PublishMetadataRequest {
                identity: Some(test_identity()),
                worker: None,
                worker_id: "worker-uuid-1".to_string(),
                ..Default::default()
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.success);
        assert!(resp.message.contains("worker is required"));
    }

    // ── list_sources ────────────────────────────────────────────────────────

    #[tokio::test]
    async fn test_list_sources_returns_instances() {
        let now = chrono::Utc::now().timestamp_millis();
        let identity = test_identity();
        let expected_source_id = compute_mx_source_id(&identity);
        let mut mock = MockMetadataBackend::new();
        mock.expect_list_workers_filtered()
            .withf(
                move |source_id,
                      status_filter,
                      model_name_filter,
                      worker_rank_filter,
                      min_training_step,
                      min_updated_at,
                      limit| {
                    source_id.as_deref() == Some(expected_source_id.as_str())
                        && *status_filter == Some(SourceStatus::Ready)
                        && model_name_filter.as_deref() == Some("my-model")
                        && *worker_rank_filter == Some(1)
                        && *min_training_step == Some(40)
                        && *min_updated_at == Some(1_700_000_000_000)
                        && *limit == Some(2)
                },
            )
            .once()
            .returning(move |_, _, _, _, _, _, _| {
                Ok(vec![
                    SourceInstanceInfo {
                        source_id: "abc123def456abcd".to_string(),
                        worker_id: "w1".to_string(),
                        model_name: "my-model".to_string(),
                        worker_rank: 0,
                        status: SourceStatus::Ready as i32,
                        updated_at: now,
                        accelerator: "cuda".to_string(),
                        source_load: Some(0.25),
                        topology: HashMap::from([("rack".to_string(), "r3".to_string())]),
                        training_step: Some(42),
                        layout_signature: Some("layout-a".to_string()),
                    },
                    SourceInstanceInfo {
                        source_id: "abc123def456abcd".to_string(),
                        worker_id: "w2".to_string(),
                        model_name: "my-model".to_string(),
                        worker_rank: 1,
                        status: SourceStatus::Ready as i32,
                        updated_at: now,
                        accelerator: "cuda".to_string(),
                        source_load: Some(0.75),
                        topology: Default::default(),
                        training_step: Some(42),
                        layout_signature: Some("layout-a".to_string()),
                    },
                ])
            });

        let svc = make_service(mock);
        let resp = svc
            .list_sources(Request::new(ListSourcesRequest {
                identity: Some(identity),
                status_filter: Some(SourceStatus::Ready as i32),
                model_name_filter: Some("my-model".to_string()),
                worker_rank_filter: Some(1),
                min_training_step: Some(40),
                min_updated_at: Some(1_700_000_000_000),
                limit: Some(2),
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert_eq!(resp.instances.len(), 2);
        assert_eq!(resp.instances[0].worker_id, "w1");
        assert_eq!(resp.instances[0].worker_rank, 0);
        assert_eq!(resp.instances[0].source_load, Some(0.25));
        assert_eq!(
            resp.instances[0].topology.get("rack").map(String::as_str),
            Some("r3"),
            "topology surfaces onto the SourceInstanceRef"
        );
        assert_eq!(resp.instances[0].accelerator, "cuda");
        assert_eq!(resp.instances[0].updated_at, now);
        assert_eq!(resp.instances[0].training_step, Some(42));
        assert_eq!(
            resp.instances[0].layout_signature.as_deref(),
            Some("layout-a")
        );
        assert_eq!(resp.instances[1].worker_id, "w2");
        assert_eq!(resp.instances[1].worker_rank, 1);
        assert_eq!(resp.instances[1].source_load, Some(0.75));
    }

    #[tokio::test]
    async fn test_list_sources_filters_artifact_sources_by_worker_status() {
        let now = chrono::Utc::now().timestamp_millis();
        let identity = test_artifact_identity();
        let expected_source_id = compute_mx_source_id(&identity);
        let mut mock = MockMetadataBackend::new();
        mock.expect_list_workers_filtered()
            .withf(move |source_id, status_filter, _, _, _, _, _| {
                source_id.as_deref() == Some(expected_source_id.as_str())
                    && *status_filter == Some(SourceStatus::Ready)
            })
            .once()
            .returning(move |source_id, _, _, _, _, _, _| {
                Ok(vec![SourceInstanceInfo {
                    source_id: source_id.expect("source id"),
                    worker_id: "artifact-worker".to_string(),
                    model_name: "my-model".to_string(),
                    worker_rank: 0,
                    status: SourceStatus::Ready as i32,
                    updated_at: now,
                    accelerator: "cuda".to_string(),
                    source_load: None,
                    topology: Default::default(),
                    training_step: None,
                    layout_signature: None,
                }])
            });

        let svc = make_service(mock);
        let resp = svc
            .list_sources(Request::new(ListSourcesRequest {
                identity: Some(identity),
                status_filter: Some(SourceStatus::Ready as i32),
                ..Default::default()
            }))
            .await
            .expect("rpc")
            .into_inner();

        assert_eq!(resp.instances.len(), 1);
        assert_eq!(resp.instances[0].worker_id, "artifact-worker");
    }

    #[tokio::test]
    async fn test_list_sources_ready_filter_excludes_expired_heartbeats() {
        let now = chrono::Utc::now().timestamp_millis();
        let expired_updated_at =
            now - ((modelexpress_common::envs::heartbeat_timeout_secs() + 1) * 1000) as i64;

        let mut mock = MockMetadataBackend::new();
        mock.expect_list_workers_filtered()
            .once()
            .returning(move |_, _, _, _, _, _, _| {
                Ok(vec![
                    SourceInstanceInfo {
                        source_id: "abc123def456abcd".to_string(),
                        worker_id: "fresh-worker".to_string(),
                        model_name: "my-model".to_string(),
                        worker_rank: 0,
                        status: SourceStatus::Ready as i32,
                        updated_at: now,
                        accelerator: "cuda".to_string(),
                        source_load: None,
                        topology: Default::default(),
                        training_step: None,
                        layout_signature: None,
                    },
                    SourceInstanceInfo {
                        source_id: "abc123def456abcd".to_string(),
                        worker_id: "expired-worker".to_string(),
                        model_name: "my-model".to_string(),
                        worker_rank: 1,
                        status: SourceStatus::Ready as i32,
                        updated_at: expired_updated_at,
                        accelerator: "cuda".to_string(),
                        source_load: None,
                        topology: Default::default(),
                        training_step: None,
                        layout_signature: None,
                    },
                ])
            });

        let svc = make_service(mock);
        let resp = svc
            .list_sources(Request::new(ListSourcesRequest {
                identity: Some(test_identity()),
                status_filter: Some(SourceStatus::Ready as i32),
                ..Default::default()
            }))
            .await
            .expect("rpc")
            .into_inner();

        assert_eq!(resp.instances.len(), 1);
        assert_eq!(resp.instances[0].worker_id, "fresh-worker");
    }

    #[tokio::test]
    async fn test_get_metadata_preserves_artifact_source_status() {
        let mut mock = MockMetadataBackend::new();
        mock.expect_get_metadata()
            .once()
            .returning(|source_id, worker_id| {
                Ok(Some(ModelMetadataRecord {
                    source_id: source_id.to_string(),
                    worker_id: worker_id.to_string(),
                    model_name: "my-model".to_string(),
                    workers: vec![WorkerRecord {
                        worker_rank: 0,
                        backend_metadata: BackendMetadataRecord::None,
                        tensors: vec![],
                        status: SourceStatus::Ready as i32,
                        updated_at: 1234567890000,
                        metadata_endpoint: "10.0.0.1:5555".to_string(),
                        agent_name: "artifact-agent".to_string(),
                        worker_grpc_endpoint: "10.0.0.1:6555".to_string(),
                        accelerator: "cuda".to_string(),
                        source_load: None,
                        topology: Default::default(),
                        artifact_source: Some(
                            ArtifactSourceMetadata {
                                artifact_id: "sha256:artifact".to_string(),
                                total_size: 1024,
                                file_count: 1,
                                chunk_count: 2,
                                node_rank: 0,
                            }
                            .into(),
                        ),
                    }],
                    published_at: 1234567890,
                    identity: Some(test_artifact_identity()),
                }))
            });

        let svc = make_service(mock);
        let resp = svc
            .get_metadata(Request::new(GetMetadataRequest {
                mx_source_id: "artifact-source-id".to_string(),
                worker_id: "artifact-worker".to_string(),
            }))
            .await
            .expect("rpc")
            .into_inner();

        let worker = resp.worker.expect("worker should be present");
        assert_eq!(worker.status, SourceStatus::Ready as i32);
        assert!(matches!(
            worker.source_payload,
            Some(SourcePayload::ArtifactSource(ref artifact))
                if artifact.artifact_id == "sha256:artifact"
        ));
    }

    #[tokio::test]
    async fn test_list_sources_no_identity() {
        let mut mock = MockMetadataBackend::new();
        mock.expect_list_workers_filtered()
            .once()
            .returning(|_, _, _, _, _, _, _| Ok(vec![]));

        let svc = make_service(mock);
        let resp = svc
            .list_sources(Request::new(ListSourcesRequest {
                identity: None,
                status_filter: None,
                ..Default::default()
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(resp.instances.is_empty());
    }

    #[tokio::test]
    async fn test_list_sources_backend_error_returns_empty() {
        let mut mock = MockMetadataBackend::new();
        mock.expect_list_workers_filtered()
            .once()
            .returning(|_, _, _, _, _, _, _| Err("backend down".into()));

        let svc = make_service(mock);
        let response = svc
            .list_sources(Request::new(ListSourcesRequest {
                identity: Some(test_identity()),
                status_filter: None,
                ..Default::default()
            }))
            .await
            .expect("rpc");

        // The reason the tag exists: on the wire this is indistinguishable from
        // a healthy "no peers have published yet" -- same Ok, same empty list.
        // Only the handler knows it was an outage, so only the handler can say so.
        assert_eq!(
            response.extensions().get::<RpcOutcome>(),
            Some(&RpcOutcome::BackendError)
        );

        let resp = response.into_inner();
        assert!(resp.instances.is_empty());
    }

    #[tokio::test]
    async fn test_list_sources_empty_model_name_no_filter() {
        let mut mock = MockMetadataBackend::new();
        mock.expect_list_workers_filtered()
            .withf(|source_id, _, _, _, _, _, _| source_id.is_none())
            .once()
            .returning(|_, _, _, _, _, _, _| Ok(vec![]));

        let svc = make_service(mock);
        let mut id = test_identity();
        id.model_name = String::new();
        let resp = svc
            .list_sources(Request::new(ListSourcesRequest {
                identity: Some(id),
                status_filter: None,
                ..Default::default()
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(resp.instances.is_empty());
    }

    // ── get_metadata (additional) ───────────────────────────────────────────

    #[tokio::test]
    async fn test_get_metadata_empty_worker_id() {
        let svc = make_service(MockMetadataBackend::new());
        let resp = svc
            .get_metadata(Request::new(GetMetadataRequest {
                mx_source_id: "abc123def456abcd".to_string(),
                worker_id: String::new(),
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.found);
        assert!(resp.worker.is_none());
    }

    #[tokio::test]
    async fn test_get_metadata_backend_error() {
        let mut mock = MockMetadataBackend::new();
        mock.expect_get_metadata()
            .once()
            .returning(|_, _| Err("storage error".into()));

        let svc = make_service(mock);
        let resp = svc
            .get_metadata(Request::new(GetMetadataRequest {
                mx_source_id: "abc123def456abcd".to_string(),
                worker_id: "worker-uuid-1".to_string(),
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.found);
        assert!(resp.worker.is_none());
        assert!(resp.mx_source_id.is_empty());
    }

    #[tokio::test]
    async fn test_get_metadata_record_with_empty_workers() {
        let mut mock = MockMetadataBackend::new();
        mock.expect_get_metadata()
            .once()
            .returning(|source_id, worker_id| {
                Ok(Some(ModelMetadataRecord {
                    source_id: source_id.to_string(),
                    worker_id: worker_id.to_string(),
                    model_name: "my-model".to_string(),
                    workers: vec![],
                    published_at: 0,
                    identity: None,
                }))
            });

        let svc = make_service(mock);
        let response = svc
            .get_metadata(Request::new(GetMetadataRequest {
                mx_source_id: "abc123def456abcd".to_string(),
                worker_id: "worker-uuid-1".to_string(),
            }))
            .await
            .expect("rpc");

        // A record that exists but carries no workers is the same answer as no
        // record at all, and must not be reported as a successful lookup.
        assert_eq!(
            response.extensions().get::<RpcOutcome>(),
            Some(&RpcOutcome::NotFound)
        );

        let resp = response.into_inner();
        assert!(!resp.found);
        assert!(resp.worker.is_none());
    }

    // ── update_status (additional) ──────────────────────────────────────────

    #[tokio::test]
    async fn test_update_status_backend_error() {
        let mut mock = MockMetadataBackend::new();
        mock.expect_update_status()
            .once()
            .returning(|_, _, _, _, _, _| Err("write failed".into()));

        let svc = make_service(mock);
        let resp = svc
            .update_status(Request::new(UpdateStatusRequest {
                mx_source_id: "abc123def456abcd".to_string(),
                worker_id: "worker-uuid-1".to_string(),
                worker_rank: 0,
                status: SourceStatus::Ready as i32,
                source_load: None,
            }))
            .await
            .expect("rpc")
            .into_inner();
        assert!(!resp.success);
        assert!(resp.message.contains("write failed"));
    }
}