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

//! Metrics decorator for [`RegistryBackend`].
//!
//! Wraps any backend and records [`crate::metrics::backend`] families around
//! every call, leaving the Redis, Kubernetes and in-memory implementations
//! untouched. A backend added later is instrumented because it is wrapped at
//! construction, not because someone remembered to add timing code to it.
//!
//! Every method is forwarded explicitly. The trait has no default bodies today;
//! if one is added it must still be overridden here, because a default body
//! would run on the decorator, call back through the decorator's other methods,
//! and so bypass any specialised override in the concrete backend while
//! counting the call twice under two op names. That failure compiles and turns
//! no test red.

use async_trait::async_trait;
use std::sync::Arc;

use crate::metrics::backend::{BackendMetrics, Store};
use crate::metrics::registry::{ClaimResult, LeaseResult, RegistryMetrics, StatusLabel};
use crate::registry::backend::{ClaimOutcome, ModelRecord, RegistryBackend, RegistryResult};
use modelexpress_common::models::{ModelProvider, ModelStatus};

/// A [`RegistryBackend`] that records timing and outcome for each operation.
pub struct InstrumentedRegistryBackend {
    inner: Arc<dyn RegistryBackend>,
    metrics: BackendMetrics,
    lifecycle: RegistryMetrics,
}

impl InstrumentedRegistryBackend {
    /// Wrap `inner`, returning it as a trait object so call sites are unchanged.
    #[must_use]
    pub fn wrap(
        inner: Arc<dyn RegistryBackend>,
        metrics: BackendMetrics,
        lifecycle: RegistryMetrics,
    ) -> Arc<dyn RegistryBackend> {
        Arc::new(Self {
            inner,
            metrics,
            lifecycle,
        })
    }
}

#[async_trait]
impl RegistryBackend for InstrumentedRegistryBackend {
    async fn connect(&self) -> RegistryResult<()> {
        self.metrics
            .time(Store::Registry, "connect", self.inner.connect())
            .await
    }

    async fn get_status(&self, model_name: &str) -> RegistryResult<Option<ModelStatus>> {
        self.metrics
            .time(
                Store::Registry,
                "get_status",
                self.inner.get_status(model_name),
            )
            .await
    }

    async fn get_model_record(&self, model_name: &str) -> RegistryResult<Option<ModelRecord>> {
        self.metrics
            .time(
                Store::Registry,
                "get_model_record",
                self.inner.get_model_record(model_name),
            )
            .await
    }

    async fn set_status(
        &self,
        model_name: &str,
        provider: ModelProvider,
        status: ModelStatus,
        message: Option<String>,
    ) -> RegistryResult<()> {
        self.metrics
            .time(
                Store::Registry,
                "set_status",
                self.inner.set_status(model_name, provider, status, message),
            )
            .await
    }

    async fn touch_model(&self, model_name: &str) -> RegistryResult<()> {
        self.metrics
            .time(
                Store::Registry,
                "touch_model",
                self.inner.touch_model(model_name),
            )
            .await
    }

    async fn delete_model(&self, model_name: &str) -> RegistryResult<()> {
        self.metrics
            .time(
                Store::Registry,
                "delete_model",
                self.inner.delete_model(model_name),
            )
            .await
    }

    async fn get_models_by_last_used(
        &self,
        limit: Option<u32>,
    ) -> RegistryResult<Vec<ModelRecord>> {
        self.metrics
            .time(
                Store::Registry,
                "get_models_by_last_used",
                self.inner.get_models_by_last_used(limit),
            )
            .await
    }

    async fn get_status_counts(&self) -> RegistryResult<(u32, u32, u32)> {
        self.metrics
            .time(
                Store::Registry,
                "get_status_counts",
                self.inner.get_status_counts(),
            )
            .await
    }

    async fn try_claim_for_download(
        &self,
        model_name: &str,
        provider: ModelProvider,
        claim_id: &str,
        lease_duration: std::time::Duration,
    ) -> RegistryResult<ClaimOutcome> {
        let outcome = self
            .metrics
            .time(
                Store::Registry,
                "try_claim_for_download",
                self.inner
                    .try_claim_for_download(model_name, provider, claim_id, lease_duration),
            )
            .await;
        self.lifecycle.record_claim(match &outcome {
            Ok(ClaimOutcome::Claimed) => ClaimResult::Claimed,
            Ok(ClaimOutcome::TookOver) => ClaimResult::Takeover,
            Ok(ClaimOutcome::AlreadyExists(_)) => ClaimResult::AlreadyExists,
            Err(_) => ClaimResult::Error,
        });
        outcome
    }

    async fn try_reset_error_for_retry(
        &self,
        model_name: &str,
        provider: ModelProvider,
        claim_id: &str,
        lease_duration: std::time::Duration,
    ) -> RegistryResult<bool> {
        let reset = self
            .metrics
            .time(
                Store::Registry,
                "try_reset_error_for_retry",
                self.inner.try_reset_error_for_retry(
                    model_name,
                    provider,
                    claim_id,
                    lease_duration,
                ),
            )
            .await;
        // Only the winner sees `true`, so this counts retries actually started
        // rather than replicas that observed the error.
        if matches!(reset, Ok(true)) {
            self.lifecycle
                .record_transition(StatusLabel::Error, StatusLabel::Downloading);
        }
        reset
    }

    async fn refresh_download_claim(
        &self,
        model_name: &str,
        provider: ModelProvider,
        claim_id: &str,
        lease_duration: std::time::Duration,
    ) -> RegistryResult<bool> {
        let renewed = self
            .metrics
            .time(
                Store::Registry,
                "refresh_download_claim",
                self.inner
                    .refresh_download_claim(model_name, provider, claim_id, lease_duration),
            )
            .await;
        self.lifecycle.record_lease_refresh(match &renewed {
            Ok(true) => LeaseResult::Renewed,
            Ok(false) => LeaseResult::Lost,
            Err(_) => LeaseResult::Error,
        });
        renewed
    }

    async fn finish_download_claim(
        &self,
        model_name: &str,
        provider: ModelProvider,
        claim_id: &str,
        status: ModelStatus,
        message: Option<String>,
    ) -> RegistryResult<bool> {
        let finished = self
            .metrics
            .time(
                Store::Registry,
                "finish_download_claim",
                self.inner
                    .finish_download_claim(model_name, provider, claim_id, status, message),
            )
            .await;
        // `false` means a stale owner was fenced after its lease was taken over:
        // the entry did not leave `downloading` on this call, and counting it
        // would make the in-flight derivation go negative.
        if matches!(finished, Ok(true)) {
            self.lifecycle
                .record_transition(StatusLabel::Downloading, status.into());
        }
        finished
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metrics::{encode_text, new_registry};
    use crate::registry::backend::MockRegistryBackend;

    #[tokio::test]
    async fn a_successful_op_is_recorded_as_ok() {
        let mut mock = MockRegistryBackend::new();
        mock.expect_get_status()
            .times(1)
            .returning(|_| Ok(Some(ModelStatus::DOWNLOADED)));

        let mut registry = new_registry();
        let metrics = BackendMetrics::register(&mut registry);
        let backend = InstrumentedRegistryBackend::wrap(
            Arc::new(mock),
            metrics,
            RegistryMetrics::register(&mut new_registry()),
        );

        let status = backend.get_status("google-t5/t5-small").await;
        assert_eq!(status.ok().flatten(), Some(ModelStatus::DOWNLOADED));

        let encoded = encode_text(&registry).unwrap_or_else(|_| String::from("<encode failed>"));
        assert!(
            encoded.contains(
                r#"mx_backend_ops_total{store="registry",op="get_status",result="ok"} 1"#
            ),
            "{encoded}"
        );
    }

    #[tokio::test]
    async fn a_backend_failure_is_recorded_as_an_error() {
        let mut mock = MockRegistryBackend::new();
        mock.expect_connect()
            .times(1)
            .returning(|| Err("redis is down".into()));

        let mut registry = new_registry();
        let metrics = BackendMetrics::register(&mut registry);
        let backend = InstrumentedRegistryBackend::wrap(
            Arc::new(mock),
            metrics,
            RegistryMetrics::register(&mut new_registry()),
        );

        assert!(backend.connect().await.is_err());

        let encoded = encode_text(&registry).unwrap_or_else(|_| String::from("<encode failed>"));
        assert!(
            encoded.contains(
                r#"mx_backend_ops_total{store="registry",op="connect",result="error"} 1"#
            ),
            "{encoded}"
        );
    }

    /// Twelve near-identical forwarding bodies invite a copy-pasted op literal, so
    /// pin that each method reports under its own name and none under another's.
    #[tokio::test]
    async fn every_method_reports_under_its_own_op_name() {
        let lease = std::time::Duration::from_secs(30);
        let mut mock = MockRegistryBackend::new();
        mock.expect_connect().times(1).returning(|| Ok(()));
        mock.expect_get_status().times(1).returning(|_| Ok(None));
        mock.expect_get_model_record()
            .times(1)
            .returning(|_| Ok(None));
        mock.expect_set_status()
            .times(1)
            .returning(|_, _, _, _| Ok(()));
        mock.expect_touch_model().times(1).returning(|_| Ok(()));
        mock.expect_delete_model().times(1).returning(|_| Ok(()));
        mock.expect_get_models_by_last_used()
            .times(1)
            .returning(|_| Ok(Vec::new()));
        mock.expect_get_status_counts()
            .times(1)
            .returning(|| Ok((0, 0, 0)));
        mock.expect_try_claim_for_download()
            .times(1)
            .returning(|_, _, _, _| Ok(ClaimOutcome::Claimed));
        mock.expect_try_reset_error_for_retry()
            .times(1)
            .returning(|_, _, _, _| Ok(false));
        mock.expect_refresh_download_claim()
            .times(1)
            .returning(|_, _, _, _| Ok(true));
        mock.expect_finish_download_claim()
            .times(1)
            .returning(|_, _, _, _, _| Ok(true));

        let mut registry = new_registry();
        let metrics = BackendMetrics::register(&mut registry);
        let backend = InstrumentedRegistryBackend::wrap(
            Arc::new(mock),
            metrics,
            RegistryMetrics::register(&mut new_registry()),
        );

        let model = "google-t5/t5-small";
        let _ = backend.connect().await;
        let _ = backend.get_status(model).await;
        let _ = backend.get_model_record(model).await;
        let _ = backend
            .set_status(
                model,
                ModelProvider::HuggingFace,
                ModelStatus::DOWNLOADED,
                None,
            )
            .await;
        let _ = backend.touch_model(model).await;
        let _ = backend.delete_model(model).await;
        let _ = backend.get_models_by_last_used(Some(10)).await;
        let _ = backend.get_status_counts().await;
        let _ = backend
            .try_claim_for_download(model, ModelProvider::HuggingFace, "claim-1", lease)
            .await;
        let _ = backend
            .try_reset_error_for_retry(model, ModelProvider::HuggingFace, "claim-1", lease)
            .await;
        let _ = backend
            .refresh_download_claim(model, ModelProvider::HuggingFace, "claim-1", lease)
            .await;
        let _ = backend
            .finish_download_claim(
                model,
                ModelProvider::HuggingFace,
                "claim-1",
                ModelStatus::DOWNLOADED,
                None,
            )
            .await;

        let encoded = encode_text(&registry).unwrap_or_else(|_| String::from("<encode failed>"));
        for op in [
            "connect",
            "get_status",
            "get_model_record",
            "set_status",
            "touch_model",
            "delete_model",
            "get_models_by_last_used",
            "get_status_counts",
            "try_claim_for_download",
            "try_reset_error_for_retry",
            "refresh_download_claim",
            "finish_download_claim",
        ] {
            let expected =
                format!(r#"mx_backend_ops_total{{store="registry",op="{op}",result="ok"}} 1"#);
            assert!(encoded.contains(&expected), "missing {op}: {encoded}");
        }
    }

    // --- download lifecycle ---------------------------------------------------
    //
    // The three tests above hand `RegistryMetrics::register` a throwaway
    // `new_registry()` that is dropped on the spot. That is harmless for them --
    // they only assert on `mx_backend_ops_total` -- but it means the lifecycle
    // families are never encoded, so nothing below can be written that way. All
    // four PR-673 lifecycle counters reach Prometheus only through this
    // decorator, so these register both families on the one registry the
    // assertions actually read.

    const MODEL: &str = "google-t5/t5-small";
    const CLAIM: &str = "claim-1";

    fn lease() -> std::time::Duration {
        std::time::Duration::from_secs(30)
    }

    /// Wrap `mock` with both metric families on a single registry, returned so
    /// the caller can encode it.
    fn instrumented(
        mock: MockRegistryBackend,
    ) -> (
        Arc<dyn RegistryBackend>,
        prometheus_client::registry::Registry,
    ) {
        let mut prom = new_registry();
        let backend = InstrumentedRegistryBackend::wrap(
            Arc::new(mock),
            BackendMetrics::register(&mut prom),
            RegistryMetrics::register(&mut prom),
        );
        (backend, prom)
    }

    fn scrape(prom: &prometheus_client::registry::Registry) -> String {
        encode_text(prom).unwrap_or_else(|_| String::from("<encode failed>"))
    }

    /// Sum the transition series the way the documented flow query does, so the
    /// assertion is the derivation operators read rather than one series.
    ///
    /// Deliberately a local copy of the helper in [`crate::metrics::registry`]:
    /// that one proves the counter's arithmetic given hand-written labels, this
    /// one proves the decorator feeds it the right ones.
    /// True when no transition was counted.
    ///
    /// Not `!encoded.contains(...)`: the transition family is pre-created at
    /// zero for every label pair (see [`crate::metrics::registry`]), so a
    /// booked transition and an unbooked one both have a series and only the
    /// value distinguishes them. Asserting absence would pass whether or not
    /// the decorator behaved.
    fn no_transition_booked(encoded: &str) -> bool {
        !encoded.lines().any(|line| {
            line.starts_with("mx_registry_status_transitions_total{") && !line.ends_with(" 0")
        })
    }

    fn in_flight(encoded: &str) -> i64 {
        let mut arrivals: i64 = 0;
        let mut departures: i64 = 0;
        for line in encoded.lines() {
            let Some((labels, value)) = line
                .strip_prefix("mx_registry_status_transitions_total{")
                .and_then(|rest| rest.split_once("} "))
            else {
                continue;
            };
            let count: i64 = value.trim().parse().unwrap_or_default();
            if labels.contains(r#"to="downloading""#) {
                arrivals = arrivals.saturating_add(count);
            }
            if labels.contains(r#"from="downloading""#) {
                departures = departures.saturating_add(count);
            }
        }
        arrivals.saturating_sub(departures)
    }

    /// Every `ClaimOutcome` must land on its own `result` label, and only the two
    /// owning outcomes may imply a transition.
    ///
    /// A takeover reported as a fresh claim is the regression `ClaimOutcome::TookOver`
    /// was introduced to prevent: a re-pull of hundreds of gigabytes reads as a
    /// first fetch. A backend error counted as a claim is worse still -- it books
    /// an arrival that never departs.
    #[tokio::test]
    async fn each_claim_outcome_reaches_its_own_result_label() {
        let mut mock = MockRegistryBackend::new();
        let call = std::sync::atomic::AtomicUsize::new(0);
        mock.expect_try_claim_for_download()
            .times(4)
            .returning(move |_, _, _, _| {
                match call.fetch_add(1, std::sync::atomic::Ordering::SeqCst) {
                    0 => Ok(ClaimOutcome::Claimed),
                    1 => Ok(ClaimOutcome::TookOver),
                    2 => Ok(ClaimOutcome::AlreadyExists(ModelStatus::DOWNLOADING)),
                    _ => Err("redis is down".into()),
                }
            });

        let (backend, prom) = instrumented(mock);
        for _ in 0..4 {
            let _ = backend
                .try_claim_for_download(MODEL, ModelProvider::HuggingFace, CLAIM, lease())
                .await;
        }

        let encoded = scrape(&prom);
        for result in ["claimed", "takeover", "already_exists", "error"] {
            let expected = format!(r#"mx_download_claims_total{{result="{result}"}} 1"#);
            assert!(encoded.contains(&expected), "missing {expected}: {encoded}");
        }
        // The two owning outcomes differ only in where they came from: a fresh
        // claim creates the record, a takeover finds it already `DOWNLOADING`.
        assert!(
            encoded.contains(
                r#"mx_registry_status_transitions_total{from="absent",to="downloading"} 1"#
            ),
            "a fresh claim did not book absent -> downloading: {encoded}"
        );
        assert!(
            encoded.contains(
                r#"mx_registry_status_transitions_total{from="downloading",to="downloading"} 1"#
            ),
            "a takeover did not book downloading -> downloading: {encoded}"
        );
        // A waiter and a failed call changed nothing, so the level is one
        // download, not three.
        assert_eq!(
            in_flight(&encoded),
            1,
            "waiters and errors must not move the level: {encoded}"
        );
    }

    /// One download, taken over mid-flight, then finished -- driven through the
    /// backend rather than by handing the counter its own labels.
    ///
    /// This is the module doc's invariant end to end: a takeover is an arrival
    /// and a departure that cancel, so the only thing left at the end is the
    /// finish. Booking the takeover as `absent -> downloading` drifts the level
    /// up by one per takeover and it never comes back down.
    #[tokio::test]
    async fn a_claim_taken_over_then_finished_leaves_nothing_in_flight() {
        let mut mock = MockRegistryBackend::new();
        let call = std::sync::atomic::AtomicUsize::new(0);
        mock.expect_try_claim_for_download()
            .times(2)
            .returning(move |_, _, _, _| {
                if call.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 {
                    Ok(ClaimOutcome::Claimed)
                } else {
                    Ok(ClaimOutcome::TookOver)
                }
            });
        mock.expect_finish_download_claim()
            .times(1)
            .returning(|_, _, _, _, _| Ok(true));

        let (backend, prom) = instrumented(mock);

        let _ = backend
            .try_claim_for_download(MODEL, ModelProvider::HuggingFace, CLAIM, lease())
            .await;
        assert_eq!(in_flight(&scrape(&prom)), 1, "one download in flight");

        // Ownership moves; the download itself is still the same one.
        let _ = backend
            .try_claim_for_download(MODEL, ModelProvider::HuggingFace, "claim-2", lease())
            .await;
        assert_eq!(
            in_flight(&scrape(&prom)),
            1,
            "a takeover is not a second download"
        );

        let _ = backend
            .finish_download_claim(
                MODEL,
                ModelProvider::HuggingFace,
                "claim-2",
                ModelStatus::DOWNLOADED,
                None,
            )
            .await;
        let encoded = scrape(&prom);
        assert_eq!(in_flight(&encoded), 0, "the download finished: {encoded}");
    }

    /// Only the replica that wins the compare-and-set spawns the retry, so only
    /// it may book the arrival.
    #[tokio::test]
    async fn a_won_retry_reset_records_the_arrival_from_error() {
        let mut mock = MockRegistryBackend::new();
        mock.expect_try_reset_error_for_retry()
            .times(1)
            .returning(|_, _, _, _| Ok(true));

        let (backend, prom) = instrumented(mock);
        let _ = backend
            .try_reset_error_for_retry(MODEL, ModelProvider::HuggingFace, CLAIM, lease())
            .await;

        let encoded = scrape(&prom);
        // Direction matters as much as the fact of recording: reversed, a retry
        // being started reads as a download failing.
        assert!(
            encoded.contains(
                r#"mx_registry_status_transitions_total{from="error",to="downloading"} 1"#
            ),
            "a won retry did not book error -> downloading: {encoded}"
        );
        assert_eq!(in_flight(&encoded), 1, "the retry is in flight: {encoded}");
    }

    /// The losers of the compare-and-set must record nothing.
    ///
    /// Under a thundering herd on a failed model every waiting replica calls
    /// this and sees `false`; counting those would inflate the in-flight level by
    /// the replica count, with no matching departures to bring it back.
    #[tokio::test]
    async fn a_lost_retry_reset_records_no_arrival() {
        let mut mock = MockRegistryBackend::new();
        mock.expect_try_reset_error_for_retry()
            .times(1)
            .returning(|_, _, _, _| Ok(false));

        let (backend, prom) = instrumented(mock);
        let _ = backend
            .try_reset_error_for_retry(MODEL, ModelProvider::HuggingFace, CLAIM, lease())
            .await;

        let encoded = scrape(&prom);
        assert!(
            no_transition_booked(&encoded),
            "a replica that lost the retry race booked a transition: {encoded}"
        );
    }

    /// `result="lost"` is the leading indicator of a duplicate download, so it
    /// must not be collapsed into `renewed` -- the panel would read flat-green
    /// during exactly the incident it was built for.
    #[tokio::test]
    async fn each_lease_heartbeat_outcome_reaches_its_own_result_label() {
        let mut mock = MockRegistryBackend::new();
        let call = std::sync::atomic::AtomicUsize::new(0);
        mock.expect_refresh_download_claim()
            .times(3)
            .returning(move |_, _, _, _| {
                match call.fetch_add(1, std::sync::atomic::Ordering::SeqCst) {
                    0 => Ok(true),
                    1 => Ok(false),
                    _ => Err("redis is down".into()),
                }
            });

        let (backend, prom) = instrumented(mock);
        for _ in 0..3 {
            let _ = backend
                .refresh_download_claim(MODEL, ModelProvider::HuggingFace, CLAIM, lease())
                .await;
        }

        let encoded = scrape(&prom);
        for result in ["renewed", "lost", "error"] {
            let expected = format!(r#"mx_download_lease_refresh_total{{result="{result}"}} 1"#);
            assert!(encoded.contains(&expected), "missing {expected}: {encoded}");
        }
    }

    /// The departure carries the status the download actually finished with.
    ///
    /// `ERROR` is exercised alongside `DOWNLOADED` because a hardcoded `to` label
    /// looks correct for the success case while reporting every failed download
    /// as a successful one.
    #[tokio::test]
    async fn a_finished_download_departs_to_its_terminal_status() {
        let mut mock = MockRegistryBackend::new();
        mock.expect_finish_download_claim()
            .times(2)
            .returning(|_, _, _, _, _| Ok(true));

        let (backend, prom) = instrumented(mock);
        for status in [ModelStatus::ERROR, ModelStatus::DOWNLOADED] {
            let _ = backend
                .finish_download_claim(MODEL, ModelProvider::HuggingFace, CLAIM, status, None)
                .await;
        }

        let encoded = scrape(&prom);
        for to in ["error", "downloaded"] {
            let expected = format!(
                r#"mx_registry_status_transitions_total{{from="downloading",to="{to}"}} 1"#
            );
            assert!(encoded.contains(&expected), "missing {expected}: {encoded}");
        }
    }

    /// `Ok(false)` means a stale owner was fenced after its lease was taken over.
    ///
    /// The entry did not leave `DOWNLOADING` on this call -- the new owner will
    /// book its own departure later -- so counting this one makes the in-flight
    /// derivation go negative.
    #[tokio::test]
    async fn a_fenced_stale_owner_records_no_departure() {
        let mut mock = MockRegistryBackend::new();
        mock.expect_finish_download_claim()
            .times(1)
            .returning(|_, _, _, _, _| Ok(false));

        let (backend, prom) = instrumented(mock);
        let _ = backend
            .finish_download_claim(
                MODEL,
                ModelProvider::HuggingFace,
                CLAIM,
                ModelStatus::DOWNLOADED,
                None,
            )
            .await;

        let encoded = scrape(&prom);
        assert!(
            no_transition_booked(&encoded),
            "a fenced stale owner booked a departure it did not make: {encoded}"
        );
    }
}