modelexpress-server 0.8.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
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Kubernetes CRD types for ModelMetadata.
//!
//! These types define the ModelMetadata CustomResourceDefinition used as an
//! alternative to Redis for storing P2P metadata.

use kube::CustomResource;
use modelexpress_common::grpc::p2p::MxSourceType;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// ModelMetadata spec - the desired state
#[derive(CustomResource, Clone, Debug, Deserialize, Serialize, JsonSchema)]
#[kube(
    group = "modelexpress.nvidia.com",
    version = "v1alpha1",
    kind = "ModelMetadata",
    plural = "modelmetadatas",
    shortname = "mxmeta",
    shortname = "mm",
    namespaced,
    status = "ModelMetadataStatus",
    doc = "ModelExpress P2P worker coordination metadata",
    printcolumn = r#"{"name":"Model","type":"string","description":"Model name","jsonPath":".spec.modelName"}"#,
    printcolumn = r#"{"name":"Type","type":"string","description":"Source type","jsonPath":".spec.sourceType"}"#,
    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#
)]
pub struct ModelMetadataSpec {
    /// Full model name (e.g., deepseek-ai/DeepSeek-V3)
    #[serde(rename = "modelName")]
    pub model_name: String,

    /// Source type from SourceIdentity (e.g., weights, torch_compile_cache).
    #[serde(rename = "sourceType", default = "default_source_type")]
    pub source_type: String,
}

fn default_source_type() -> String {
    "unknown".to_string()
}

impl ModelMetadataSpec {
    /// Convert an `MxSourceType` proto enum value (i32) to the CRD source type string.
    pub fn source_type_name_from_proto(mx_source_type: i32) -> String {
        match MxSourceType::try_from(mx_source_type) {
            Ok(MxSourceType::Weights) => "weights",
            Ok(MxSourceType::Lora) => "lora",
            Ok(MxSourceType::CudaGraph) => "cuda_graph",
            Ok(MxSourceType::TorchCompileCache) => "torch_compile_cache",
            Ok(MxSourceType::TritonCache) => "triton_cache",
            Ok(MxSourceType::DeepGemmCache) => "deep_gemm_cache",
            Ok(MxSourceType::TilelangCache) => "tilelang_cache",
            Ok(MxSourceType::CuteDslCache) => "cute_dsl_cache",
            Ok(MxSourceType::FlashinferCache) => "flashinfer_cache",
            Ok(MxSourceType::TvmFfiCache) => "tvm_ffi_cache",
            Err(_) => "unknown",
        }
        .to_string()
    }
}

/// ModelMetadata status - the observed state
#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct ModelMetadataStatus {
    /// Single worker NIXL metadata and readiness state (one CR per worker)
    #[serde(default)]
    pub worker: Option<WorkerStatus>,

    /// Conditions for ModelMetadata lifecycle
    #[serde(default)]
    pub conditions: Vec<Condition>,

    /// Generation observed by the controller
    #[serde(rename = "observedGeneration", default)]
    pub observed_generation: i64,

    /// Timestamp when first worker published
    #[serde(rename = "publishedAt", default)]
    #[schemars(with = "Option<chrono::DateTime<chrono::Utc>>")]
    pub published_at: Option<String>,
}

/// Per-worker status
#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct WorkerStatus {
    /// Worker rank (0-indexed)
    #[serde(rename = "workerRank")]
    pub worker_rank: i32,

    /// Backend type discriminator ("nixl", "transfer_engine", "none")
    #[serde(rename = "backendType", default)]
    #[schemars(with = "Option<BackendTypeSchema>")]
    pub backend_type: Option<String>,

    /// Base64-encoded NIXL agent metadata blob
    #[serde(rename = "nixlMetadata", default)]
    pub nixl_metadata: String,

    /// Mooncake TransferEngine session ID
    #[serde(rename = "transferEngineSessionId", default)]
    pub transfer_engine_session_id: Option<String>,

    /// Number of tensors registered by this worker
    #[serde(rename = "tensorCount", default)]
    pub tensor_count: i32,

    /// Name of ConfigMap containing tensor descriptors
    #[serde(rename = "tensorConfigMap", default)]
    pub tensor_config_map: Option<String>,

    /// Worker lifecycle status (Initializing, Ready, Stale)
    #[serde(default = "default_worker_status")]
    #[schemars(with = "WorkerLifecycleSchema")]
    pub status: String,

    /// Timestamp of last status update (RFC3339)
    #[serde(rename = "updatedAt", default)]
    #[schemars(with = "Option<chrono::DateTime<chrono::Utc>>")]
    pub updated_at: Option<String>,

    /// P2P: NIXL listen thread endpoint (host:port)
    #[serde(rename = "metadataEndpoint", default)]
    pub metadata_endpoint: String,

    /// P2P: NIXL agent name
    #[serde(rename = "agentName", default)]
    pub agent_name: String,

    /// P2P: Worker gRPC endpoint for tensor manifest (host:port)
    #[serde(rename = "workerGrpcEndpoint", default)]
    pub worker_grpc_endpoint: String,

    /// Runtime accelerator family for compatibility filtering.
    #[serde(default)]
    pub accelerator: String,

    /// Source-published busyness in [0, 1] (default: RDMA NIC utilization).
    ///
    /// `None` must serialize as an explicit `null`, not be skipped: both status
    /// writes go out as a JSON merge patch, where an omitted key means "leave
    /// unchanged" and `null` means "delete". Skipping it would let the field go
    /// `None -> Some` but never back, so a worker the reaper marks Stale with no
    /// reading would keep advertising its last load. The CRD schema declares the
    /// field `nullable` so the API server accepts the null.
    #[serde(default, rename = "sourceLoad")]
    pub source_load: Option<f32>,

    /// Datacenter topology domain values keyed by level.
    #[serde(default)]
    pub topology: std::collections::HashMap<String, String>,

    /// Small discovery summary for file-backed artifact sources.
    #[serde(rename = "artifactSource", default)]
    pub artifact_source: Option<ArtifactSourceStatus>,
}

/// Bounded artifact discovery summary stored in ModelMetadata status.
#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema, PartialEq)]
pub struct ArtifactSourceStatus {
    /// Digest of the canonical sealed artifact manifest.
    #[serde(rename = "artifactId")]
    pub artifact_id: String,

    /// Total artifact bytes across all manifest files. Kubernetes OpenAPI
    /// exposes this as int64; the backend converts to/from the proto uint64.
    #[serde(rename = "totalSize")]
    #[schemars(range(min = 0))]
    pub total_size: i64,

    /// Number of files in the sealed artifact manifest.
    #[serde(rename = "fileCount")]
    #[schemars(with = "i64", range(min = 0, max = 4294967295u32))]
    pub file_count: u32,

    /// Number of transfer chunks in the sealed artifact manifest.
    #[serde(rename = "chunkCount")]
    #[schemars(with = "i64", range(min = 0, max = 4294967295u32))]
    pub chunk_count: u32,

    /// Distributed node rank that owns this node-scoped artifact.
    #[serde(rename = "nodeRank", default)]
    #[schemars(with = "i64", range(min = 0, max = 4294967295u32))]
    pub node_rank: u32,
}

impl WorkerStatus {
    /// Convert a `SourceStatus` proto enum value (i32) to the CRD status string.
    pub fn status_name_from_proto(status: i32) -> String {
        match status {
            0 => "Unknown",
            1 => "Initializing",
            2 => "Ready",
            3 => "Stale",
            _ => "Unknown",
        }
        .to_string()
    }

    /// Convert a CRD status string back to the `SourceStatus` proto enum value (i32).
    pub fn status_proto_from_name(name: &str) -> i32 {
        match name {
            "Initializing" => 1,
            "Ready" => 2,
            "Stale" => 3,
            _ => 0,
        }
    }
}

/// Standard Kubernetes condition
#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct Condition {
    /// Condition type
    #[serde(rename = "type")]
    #[schemars(with = "ConditionTypeSchema")]
    pub type_: String,

    /// Status: True, False, Unknown
    #[schemars(with = "ConditionStatusSchema")]
    pub status: String,

    /// Machine-readable reason for condition
    #[serde(default)]
    pub reason: Option<String>,

    /// Human-readable message
    #[serde(default)]
    pub message: Option<String>,

    /// Timestamp of last transition
    #[serde(rename = "lastTransitionTime", default)]
    #[schemars(with = "Option<chrono::DateTime<chrono::Utc>>")]
    pub last_transition_time: Option<String>,
}

fn default_worker_status() -> String {
    "Unknown".to_string()
}

#[derive(JsonSchema)]
#[allow(dead_code)]
#[schemars(rename_all = "snake_case")]
enum BackendTypeSchema {
    Nixl,
    TransferEngine,
    None,
}

#[derive(JsonSchema)]
#[allow(dead_code)]
enum WorkerLifecycleSchema {
    Unknown,
    Initializing,
    Ready,
    Stale,
}

#[derive(JsonSchema)]
#[allow(dead_code)]
enum ConditionStatusSchema {
    True,
    False,
    Unknown,
}

#[derive(JsonSchema)]
#[allow(dead_code)]
enum ConditionTypeSchema {
    Ready,
}

impl ModelMetadataStatus {
    /// Insert or update a condition by type. If a condition with the same type
    /// already exists, it is updated in place; `lastTransitionTime` is only
    /// changed when `status` actually transitions.
    pub fn set_condition(&mut self, type_: &str, status: &str, reason: &str, message: &str) {
        let now = chrono::Utc::now().to_rfc3339();
        if let Some(existing) = self.conditions.iter_mut().find(|c| c.type_ == type_) {
            if existing.status != status {
                existing.last_transition_time = Some(now);
            }
            existing.status = status.to_string();
            existing.reason = Some(reason.to_string());
            existing.message = Some(message.to_string());
        } else {
            self.conditions.push(Condition {
                type_: type_.to_string(),
                status: status.to_string(),
                reason: Some(reason.to_string()),
                message: Some(message.to_string()),
                last_transition_time: Some(now),
            });
        }
    }

    /// Update the `Ready` condition based on the worker's proto status value.
    /// Ready=True only when the worker status is `SOURCE_STATUS_READY` (2).
    pub fn update_ready_condition(&mut self, worker_proto_status: i32) {
        let is_ready = worker_proto_status == 2; // SOURCE_STATUS_READY
        if is_ready {
            self.set_condition("Ready", "True", "WorkerReady", "Worker is ready");
        } else {
            let status_name = WorkerStatus::status_name_from_proto(worker_proto_status);
            self.set_condition(
                "Ready",
                "False",
                &format!("Worker{}", status_name),
                "Worker is not ready",
            );
        }
    }
}

/// Tensor descriptor stored in ConfigMap
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TensorDescriptorJson {
    pub name: String,
    /// Serialized as string to avoid precision loss
    pub addr: String,
    /// Serialized as string to avoid precision loss
    pub size: String,
    pub device_id: u32,
    pub dtype: String,
}

/// Sanitize model name to be a valid Kubernetes resource name
/// e.g., "deepseek-ai/DeepSeek-V3" -> "deepseek-ai-deepseek-v3"
pub fn sanitize_model_name(model_name: &str) -> String {
    model_name
        .to_lowercase()
        .replace(['/', '_'], "-")
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '.')
        .collect::<String>()
        .trim_matches('-')
        .to_string()
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn test_source_type_name_from_proto() {
        assert_eq!(ModelMetadataSpec::source_type_name_from_proto(0), "weights");
        assert_eq!(
            ModelMetadataSpec::source_type_name_from_proto(3),
            "torch_compile_cache"
        );
        assert_eq!(
            ModelMetadataSpec::source_type_name_from_proto(5),
            "deep_gemm_cache"
        );
        assert_eq!(
            ModelMetadataSpec::source_type_name_from_proto(6),
            "tilelang_cache"
        );
        assert_eq!(
            ModelMetadataSpec::source_type_name_from_proto(7),
            "cute_dsl_cache"
        );
        assert_eq!(
            ModelMetadataSpec::source_type_name_from_proto(8),
            "flashinfer_cache"
        );
        assert_eq!(
            ModelMetadataSpec::source_type_name_from_proto(9),
            "tvm_ffi_cache"
        );
        assert_eq!(
            ModelMetadataSpec::source_type_name_from_proto(99),
            "unknown"
        );
    }

    #[test]
    fn test_model_metadata_spec_defaults_missing_source_type() {
        let spec: ModelMetadataSpec =
            serde_json::from_str(r#"{"modelName":"Qwen/Qwen2.5-0.5B-Instruct"}"#)
                .expect("spec should deserialize without sourceType");

        assert_eq!(spec.model_name, "Qwen/Qwen2.5-0.5B-Instruct");
        assert_eq!(spec.source_type, "unknown");
    }

    #[test]
    fn test_status_roundtrip() {
        for (proto, name) in [
            (0, "Unknown"),
            (1, "Initializing"),
            (2, "Ready"),
            (3, "Stale"),
        ] {
            assert_eq!(WorkerStatus::status_name_from_proto(proto), name);
            assert_eq!(WorkerStatus::status_proto_from_name(name), proto);
        }
    }

    /// Regression test: proto status 0 (SOURCE_STATUS_UNKNOWN) must survive a
    /// write-to-CRD -> read-from-CRD roundtrip. Before the fix, status_proto_from_name
    /// returned None for "Unknown", causing get_metadata to hard-error on any worker
    /// that hadn't received an explicit UpdateStatus call after PublishMetadata.
    #[test]
    fn test_status_unknown_roundtrip() {
        let written = WorkerStatus::status_name_from_proto(0);
        assert_eq!(written, "Unknown");
        let read_back = WorkerStatus::status_proto_from_name(&written);
        assert_eq!(
            read_back, 0,
            "Unknown status must roundtrip to proto value 0"
        );
    }

    #[test]
    fn test_status_name_from_proto_unknown() {
        assert_eq!(WorkerStatus::status_name_from_proto(99), "Unknown");
        assert_eq!(WorkerStatus::status_name_from_proto(4), "Unknown");
    }

    #[test]
    fn test_status_proto_from_name_unknown() {
        assert_eq!(WorkerStatus::status_proto_from_name("Unknown"), 0);
        assert_eq!(WorkerStatus::status_proto_from_name(""), 0);
        assert_eq!(WorkerStatus::status_proto_from_name("ready"), 0);
    }

    #[test]
    fn test_worker_status_defaults_missing_status() {
        let worker: WorkerStatus = serde_json::from_str(r#"{"workerRank":0}"#)
            .expect("worker should deserialize without status");

        assert_eq!(worker.status, "Unknown");
    }

    #[test]
    fn test_sanitize_model_name() {
        assert_eq!(
            sanitize_model_name("deepseek-ai/DeepSeek-V3"),
            "deepseek-ai-deepseek-v3"
        );
        assert_eq!(
            sanitize_model_name("meta-llama/Llama-3.1-70B"),
            "meta-llama-llama-3.1-70b"
        );
        assert_eq!(sanitize_model_name("simple-model"), "simple-model");
    }

    #[test]
    fn test_sanitize_model_name_special_chars() {
        assert_eq!(sanitize_model_name("Llama@3.1+8B"), "llama3.18b");
        assert_eq!(sanitize_model_name("model with spaces"), "modelwithspaces");
        assert_eq!(
            sanitize_model_name("org_name/model_v2"),
            "org-name-model-v2"
        );
    }

    #[test]
    fn test_sanitize_model_name_edge_cases() {
        assert_eq!(sanitize_model_name(""), "");
        assert_eq!(sanitize_model_name("///"), "");
        assert_eq!(sanitize_model_name("---"), "");
        assert_eq!(sanitize_model_name("-model-"), "model");
    }

    #[test]
    fn test_tensor_descriptor_json_roundtrip() {
        let original = TensorDescriptorJson {
            name: "model.layers.0.weight".to_string(),
            addr: "139948187451390".to_string(),
            size: "134217728".to_string(),
            device_id: 0,
            dtype: "bfloat16".to_string(),
        };

        let json = serde_json::to_string(&original).expect("serialize");
        let parsed: TensorDescriptorJson = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(parsed.name, original.name);
        assert_eq!(parsed.addr, original.addr);
        assert_eq!(parsed.size, original.size);
        assert_eq!(parsed.device_id, original.device_id);
        assert_eq!(parsed.dtype, original.dtype);

        let addr: u64 = parsed.addr.parse().expect("addr should parse as u64");
        assert_eq!(addr, 139948187451390);
        let size: u64 = parsed.size.parse().expect("size should parse as u64");
        assert_eq!(size, 134217728);
    }

    #[test]
    fn test_tensor_descriptor_json_large_values() {
        let desc = TensorDescriptorJson {
            name: "test".to_string(),
            addr: u64::MAX.to_string(),
            size: u64::MAX.to_string(),
            device_id: 7,
            dtype: "float16".to_string(),
        };

        let json = serde_json::to_string(&desc).expect("serialize");
        let parsed: TensorDescriptorJson = serde_json::from_str(&json).expect("deserialize");

        let addr: u64 = parsed.addr.parse().expect("max u64 addr should parse");
        assert_eq!(addr, u64::MAX);
    }

    #[test]
    fn test_set_condition_inserts_new() {
        let mut status = ModelMetadataStatus::default();
        assert!(status.conditions.is_empty());

        status.set_condition("Ready", "True", "WorkerPublished", "Published");

        assert_eq!(status.conditions.len(), 1);
        let cond = &status.conditions[0];
        assert_eq!(cond.type_, "Ready");
        assert_eq!(cond.status, "True");
        assert_eq!(cond.reason.as_deref(), Some("WorkerPublished"));
        assert_eq!(cond.message.as_deref(), Some("Published"));
        assert!(cond.last_transition_time.is_some());
    }

    #[test]
    fn test_set_condition_updates_existing() {
        let mut status = ModelMetadataStatus::default();
        status.set_condition("Ready", "True", "WorkerPublished", "Published");
        let original_time = status.conditions[0].last_transition_time.clone();

        status.set_condition("Ready", "False", "WorkerStale", "Worker is stale");

        assert_eq!(status.conditions.len(), 1);
        let cond = &status.conditions[0];
        assert_eq!(cond.status, "False");
        assert_eq!(cond.reason.as_deref(), Some("WorkerStale"));
        assert_ne!(
            cond.last_transition_time, original_time,
            "lastTransitionTime must change on status transition"
        );
    }

    #[test]
    fn test_set_condition_same_status_preserves_transition_time() {
        let mut status = ModelMetadataStatus::default();
        status.set_condition("Ready", "True", "WorkerPublished", "Published");
        let original_time = status.conditions[0].last_transition_time.clone();

        status.set_condition("Ready", "True", "StillReady", "Still ready");

        assert_eq!(status.conditions.len(), 1);
        assert_eq!(status.conditions[0].reason.as_deref(), Some("StillReady"));
        assert_eq!(
            status.conditions[0].last_transition_time, original_time,
            "lastTransitionTime must not change when status stays the same"
        );
    }

    #[test]
    fn test_update_ready_condition_ready() {
        let mut status = ModelMetadataStatus::default();
        status.update_ready_condition(2); // SOURCE_STATUS_READY

        assert_eq!(status.conditions.len(), 1);
        let cond = &status.conditions[0];
        assert_eq!(cond.type_, "Ready");
        assert_eq!(cond.status, "True");
        assert_eq!(cond.reason.as_deref(), Some("WorkerReady"));
    }

    #[test]
    fn test_update_ready_condition_not_ready_states() {
        for (proto, expected_reason) in [
            (0, "WorkerUnknown"),
            (1, "WorkerInitializing"),
            (3, "WorkerStale"),
        ] {
            let mut status = ModelMetadataStatus::default();
            status.update_ready_condition(proto);

            assert_eq!(status.conditions.len(), 1);
            let cond = &status.conditions[0];
            assert_eq!(cond.type_, "Ready");
            assert_eq!(cond.status, "False");
            assert_eq!(
                cond.reason.as_deref(),
                Some(expected_reason),
                "proto status {} should produce reason {}",
                proto,
                expected_reason
            );
        }
    }

    #[test]
    fn test_update_ready_condition_transition() {
        let mut status = ModelMetadataStatus::default();

        status.update_ready_condition(1); // Initializing
        assert_eq!(status.conditions[0].status, "False");
        let time_false = status.conditions[0].last_transition_time.clone();

        status.update_ready_condition(2); // Ready
        assert_eq!(status.conditions[0].status, "True");
        assert_ne!(
            status.conditions[0].last_transition_time, time_false,
            "lastTransitionTime must change on False->True transition"
        );

        status.update_ready_condition(3); // Stale
        assert_eq!(status.conditions[0].status, "False");
        assert_eq!(status.conditions[0].reason.as_deref(), Some("WorkerStale"));
    }

    // Both status writes are JSON merge patches, where an omitted key means
    // "leave unchanged" and null means "delete". A None reading must therefore
    // reach the wire as an explicit null, or the reaper's Stale mark can never
    // clear the last load a worker published.
    #[test]
    fn test_worker_status_none_source_load_serializes_as_null() {
        let mut worker = WorkerStatus::default();
        assert_eq!(worker.source_load, None);
        let out = serde_json::to_value(&worker).expect("serialize");
        assert!(
            out.get("sourceLoad")
                .is_some_and(serde_json::Value::is_null),
            "None must serialize as an explicit null, got {out}"
        );

        worker.source_load = Some(0.42);
        let out = serde_json::to_value(&worker).expect("serialize");
        assert_eq!(out["sourceLoad"].as_f64().map(|v| v as f32), Some(0.42));

        // And an explicit null on the way back in reads as None, not 0.0.
        let back: WorkerStatus =
            serde_json::from_value(serde_json::json!({"workerRank": 0, "sourceLoad": null}))
                .expect("deserialize");
        assert_eq!(back.source_load, None);
    }
}