hf2q 0.1.31

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
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
//! What the engines of this process have committed of the host's memory, and
//! how a load is admitted against it.
//!
//! # The bounds of an admission
//!
//! A load that selects memory-carrying routes (a DFlash2 drafter, prepared
//! planes, retained scratch) may take them only within
//! (`dflash2_policy::memory_verdict`):
//!
//! ```text
//! present = available now - charged engines - model file - KV budget - reserve
//! budget  = physical      - charged engines - model file - KV budget - reserve
//! ```
//!
//! and it takes the smaller. *Charged engines* is every commitment in this
//! ledger: an engine's whole claim (model file, KV budget, drafter, planes,
//! scratch), allocated or not. *Available now* is what the host reports
//! free, inactive or purgeable at the decision.
//!
//! Canonical main experts have disjoint ownership phases: raw+prepared before
//! KV/drafter/cache provisioning, then source-free weights with boot KV/drafter
//! load, then weights with the unchanged KV promise and execution scratch.
//! Admission reserves their maximum. Only checked producer completion and
//! source-registration retirement let `promote_canonical` replace that startup
//! charge with the actual retained bound. The file floor, other weights and MTP
//! are never credited away; kernel page reclamation is still governed by the
//! unchanged host-present bound below.
//!
//! Why every term is in the present bound. What is available now is still
//! owed, later, to everything that has been promised memory and has not
//! taken it: the incoming model's file and its KV budget, and the part of
//! each charged engine's commitment that it has not allocated yet (a KV
//! cache it has not filled, planes it prepares on first use, scratch).
//! Scheduler admission later honors those promises without asking the host
//! again, so the load must leave room for all of them now. The ledger knows
//! what each engine was promised, not how much of it the engine has
//! materialized, so the whole of every commitment is subtracted. The part an
//! engine has already allocated is then counted twice (it is also missing
//! from what is available), which errs on the safe side and by at most the
//! engines' resident size; no estimate of that size is attempted.
//!
//! What is available now also excludes, by itself, everything anybody holds
//! at the decision whatever the ledger says: memory of a torn-down engine
//! that the kernel has not reclaimed yet, buffers a command still running
//! holds, the allocator's cache, and every other process. On an idle host
//! the two bounds are equal; otherwise the present bound is the smaller, so
//! other programs' memory lowers what a load may take. The budget remains as
//! the bound that does not depend on a reading. Neither covers another
//! process that grows after the decision; the reserve is the only margin for
//! that.
//!
//! # Why an admission cannot race
//!
//! - **Against another admission.** The decision and its reservation are
//!   one transaction ([`Ledger::admit`]): the commitment is reserved only if
//!   the charged total has not grown since the decision read it, else the
//!   decision is made again. Two loads, through one pool or through
//!   independent ones, are never both decided against the same total. The
//!   later of two loads sees the earlier one charged in full from the
//!   moment it was admitted, before it has allocated anything.
//! - **Against a teardown.** A reservation stays charged until its engine's
//!   teardown has completed, so a decision that overlaps a teardown counts
//!   the engine in full. An admission also waits for every teardown that is
//!   in progress before it decides ([`TeardownMarker`]), so that it reads
//!   the host's available memory after the engine has let go and not in the
//!   middle. A teardown that does not end does not block loads for good: the
//!   wait is bounded, and the engine stays charged.
//! - **Against a running engine that allocates.** Those allocations are
//!   inside the engine's charge, and the whole charge is withheld from both
//!   bounds before the engine makes them.
//!
//! # Who releases a reservation
//!
//! A reservation is owned by whoever owns the model's buffers. While a load
//! is in progress that is the loading thread; `Engine::spawn*` then gives it
//! to the worker thread with the model, and it is released by the worker's
//! teardown alone (`WorkerTeardown` in `serve::api::engine_supervisor`):
//! after the model is dropped, the thread's GPU caches are dropped, the
//! thread has terminated and every queue the model's threads encoded on is
//! settled (`inference::device_settle`). Dropping the last `Engine` handle
//! does not release it: an evicted engine whose worker is still tearing
//! down, or is wedged inside Metal, still holds its memory and is still
//! charged, and a teardown that fails leaves it charged for good
//! ([`Reservation::strand`]). The loading thread keeps a claim of its own
//! ([`LoadingClaim`]) until it has given back what it held for the model:
//! the commitment leaves the ledger only when the worker's teardown and the
//! loading thread's cleanup have both succeeded, in whichever order they
//! end. An entry that has left the ledger is never put back.
//!
//! The kernel returns the pages of released buffers on its own, some time
//! after user space has let go. The ledger does not claim to know when: the
//! present bound is what keeps those bytes from being handed out, because
//! they are not in what the host reports available.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, LazyLock, Mutex};
use std::time::Duration;

/// What one engine holds resident, by component.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct Commitment {
    /// The GGUF's weights.
    pub(crate) model_file_bytes: u64,
    /// The configured aggregate KV budget; zero when none is configured.
    pub(crate) kv_budget_bytes: u64,
    /// The DFlash2 drafter checkpoint.
    pub(crate) drafter_bytes: u64,
    /// Prepared planes of the fast routes.
    pub(crate) plane_bytes: u64,
    /// Scratch the fast routes retain between steps.
    pub(crate) scratch_bytes: u64,
    /// Header-bound phase plan; replaced only by checked source-free promotion.
    pub(crate) canonical: CanonicalCommitment,
}

/// Main expert conversion is disjoint from KV/drafter/cache materialization.
/// These are allocation ownership bounds, not a claim of physical reclamation.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct CanonicalCommitment {
    pub(crate) raw_bytes: u64,
    pub(crate) prepared_bytes: u64,
    /// Header upper bound retained for startup diagnostics after promotion.
    pub(crate) startup_prepared_bytes: u64,
    /// Main expert planes already included in `Commitment::plane_bytes`.
    pub(crate) routed_prepared_bytes: u64,
    pub(crate) boot_kv_bytes: u64,
    pub(crate) drafter_load_bytes: u64,
    pub(crate) drafter_run_bytes: u64,
}

impl Commitment {
    /// Peak of the disjoint raw preparation and source-free retained phases.
    pub(crate) fn total(&self) -> u64 {
        if self.canonical.startup_prepared_bytes == 0 {
            return self.raw_total();
        }
        self.startup_total().max(self.retained_total())
    }

    fn raw_total(&self) -> u64 {
        [
            self.model_file_bytes,
            self.kv_budget_bytes,
            self.drafter_bytes,
            self.plane_bytes,
            self.scratch_bytes,
        ]
        .into_iter()
        .fold(0, u64::saturating_add)
    }

    pub(crate) fn startup_total(&self) -> u64 {
        self.model_file_bytes.saturating_add(self.canonical.startup_prepared_bytes)
    }

    pub(crate) fn retained_total(&self) -> u64 {
        let canonical = self.canonical;
        if canonical.startup_prepared_bytes == 0 {
            return self.raw_total();
        }
        // Retire only the converted source allocation. Preserve the file
        // floor and all non-main products, including the separate MTP domain.
        let weights = self.model_file_bytes.max(
            self.model_file_bytes.saturating_sub(canonical.raw_bytes)
                .saturating_add(canonical.prepared_bytes),
        );
        let other_planes = self.plane_bytes.saturating_sub(canonical.routed_prepared_bytes);
        let load = canonical.boot_kv_bytes.saturating_add(canonical.drafter_load_bytes);
        let run = self.kv_budget_bytes.max(canonical.boot_kv_bytes).saturating_add(self.scratch_bytes)
            .saturating_add(canonical.drafter_run_bytes);
        weights.saturating_add(other_planes).saturating_add(load.max(run))
    }
}

struct Entry {
    /// The model the engine was loaded from, for diagnostics.
    model: PathBuf,
    commitment: Commitment,
    /// No retained-state credit until the producer has completed and its
    /// source registrations have actually been retired.
    canonical_promoted: bool,
    /// The thread that owns the model has begun to tear it down.
    tearing_down: bool,
    /// The reservation's owner has let go of it.
    owner_released: bool,
    /// The loading thread has not said yet whether it could give back what
    /// it held for the model ([`LoadingClaim`]).
    loading_claim: bool,
    /// The commitment is never released: a teardown or a loading cleanup
    /// failed.
    stranded: bool,
}

impl Entry {
    fn charged_bytes(&self) -> u64 {
        if self.canonical_promoted {
            self.commitment.retained_total()
        } else {
            self.commitment.total()
        }
    }
}

#[derive(Default)]
struct Entries {
    next_id: u64,
    reserved: BTreeMap<u64, Entry>,
    /// Reservations whose teardown is in progress.
    tearing_down: usize,
    /// Admissions waiting for those teardowns.
    #[cfg(test)]
    admissions_waiting: usize,
}

impl Entries {
    fn total(&self) -> u64 {
        self.reserved
            .values()
            .map(Entry::charged_bytes)
            .fold(0, u64::saturating_add)
    }

    fn insert(&mut self, model: &Path, commitment: Commitment) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        self.reserved.insert(
            id,
            Entry {
                model: model.to_path_buf(),
                commitment,
                canonical_promoted: false,
                tearing_down: false,
                owner_released: false,
                loading_claim: false,
                stranded: false,
            },
        );
        id
    }

    /// The teardown of `id`, if one was in progress, is over. Returns
    /// whether one was.
    fn end_teardown(&mut self, id: u64) -> bool {
        let was_tearing_down = self
            .reserved
            .get_mut(&id)
            .is_some_and(|entry| std::mem::take(&mut entry.tearing_down));
        if was_tearing_down {
            self.tearing_down -= 1;
        }
        was_tearing_down
    }

    /// Remove the entry of `id` if everyone who held it has let go of it
    /// cleanly: its owner released it, the loading thread has concluded, and
    /// neither stranded it. An entry is removed here and nowhere else, and a
    /// removed entry is never put back.
    fn release_if_unheld(&mut self, id: u64) {
        let unheld = self
            .reserved
            .get(&id)
            .is_some_and(|entry| entry.owner_released && !entry.loading_claim && !entry.stranded);
        if unheld {
            self.reserved.remove(&id);
        }
    }

    /// Strand the entry of `id` and say so.
    fn strand(&mut self, id: u64, reason: &str) {
        let Some(entry) = self.reserved.get_mut(&id) else {
            return;
        };
        if !std::mem::replace(&mut entry.stranded, true) {
            tracing::error!(
                model = %entry.model.display(),
                bytes = entry.charged_bytes(),
                reason,
                "engine memory stays reserved until the process restarts"
            );
        }
    }
}

/// How long an admission waits for teardowns in progress before it decides
/// with their engines still charged.
const ADMISSION_TEARDOWN_WAIT: Duration = Duration::from_secs(30);

/// The commitments of the engines of this process.
pub(crate) struct Ledger {
    entries: Mutex<Entries>,
    teardown_ended: Condvar,
    teardown_wait: Duration,
}

impl Ledger {
    pub(crate) fn new() -> Arc<Self> {
        Self::with_teardown_wait(ADMISSION_TEARDOWN_WAIT)
    }

    /// A ledger whose admissions wait at most `teardown_wait` for teardowns
    /// in progress.
    pub(crate) fn with_teardown_wait(teardown_wait: Duration) -> Arc<Self> {
        Arc::new(Self {
            entries: Mutex::default(),
            teardown_ended: Condvar::new(),
            teardown_wait,
        })
    }

    fn entries(&self) -> std::sync::MutexGuard<'_, Entries> {
        // The guarded state is plain bookkeeping, valid after any panic.
        self.entries
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Sum of every reservation's commitment.
    #[cfg(test)]
    pub(crate) fn total(&self) -> u64 {
        self.entries().total()
    }

    /// Inject a resident commitment for ledger tests. Production loads must
    /// enter through `admit`; no unconditional reservation bypass is exposed.
    #[cfg(test)]
    pub(crate) fn reserve(self: &Arc<Self>, model: &Path, commitment: Commitment) -> Reservation {
        Reservation {
            id: self.entries().insert(model, commitment),
            ledger: Arc::clone(self),
        }
    }

    /// Wait for the teardowns in progress to end, for at most the ledger's
    /// bound, and return the charged total.
    fn total_after_teardowns(&self, model: &Path) -> u64 {
        // Mutated only by the test-only count of waiting admissions.
        #[cfg_attr(not(test), allow(unused_mut))]
        let mut entries = self.entries();
        if entries.tearing_down > 0 {
            tracing::info!(
                model = %model.display(),
                teardowns = entries.tearing_down,
                "load waits for engine teardowns in progress"
            );
        }
        #[cfg(test)]
        {
            entries.admissions_waiting += 1;
        }
        #[cfg_attr(not(test), allow(unused_mut))]
        let (mut entries, waited) = self
            .teardown_ended
            .wait_timeout_while(entries, self.teardown_wait, |entries| {
                entries.tearing_down > 0
            })
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        #[cfg(test)]
        {
            entries.admissions_waiting -= 1;
        }
        if waited.timed_out() {
            tracing::warn!(
                model = %model.display(),
                teardowns = entries.tearing_down,
                waited_s = self.teardown_wait.as_secs(),
                "engine teardowns did not end; the load is decided with their engines charged"
            );
        }
        entries.total()
    }

    /// Decide a load against what is charged and reserve what it decided,
    /// as one transaction, after the teardowns in progress have ended.
    ///
    /// `decide` receives the charged total and returns its decision with
    /// the commitment that decision needs. The commitment is reserved only
    /// if the charged total has not grown since `decide` read it; if
    /// another load reserved in between, `decide` runs again against the new
    /// total. A total that shrank leaves the decision valid, only more
    /// cautious than it had to be. `decide` runs without the ledger locked,
    /// so a slow decision (one that downloads a drafter) blocks no other
    /// load and no release.
    pub(crate) fn admit<T, E>(
        self: &Arc<Self>,
        model: &Path,
        mut decide: impl FnMut(u64) -> Result<(T, Commitment), E>,
    ) -> Result<(T, Reservation), E> {
        let mut resident = self.total_after_teardowns(model);
        loop {
            let (decision, commitment) = decide(resident)?;
            let mut entries = self.entries();
            let now = entries.total();
            if now <= resident {
                let id = entries.insert(model, commitment);
                drop(entries);
                return Ok((
                    decision,
                    Reservation {
                        ledger: Arc::clone(self),
                        id,
                    },
                ));
            }
            resident = now;
        }
    }

    /// Admissions that are waiting for a teardown to end.
    #[cfg(test)]
    pub(crate) fn admissions_waiting(&self) -> usize {
        self.entries().admissions_waiting
    }
}

/// One engine's commitment; released when dropped.
pub(crate) struct Reservation {
    ledger: Arc<Ledger>,
    id: u64,
}

impl Reservation {
    /// What the thread that owns the engine's model uses to say that its
    /// teardown has begun.
    pub(crate) fn teardown_marker(&self) -> TeardownMarker {
        TeardownMarker {
            ledger: Arc::clone(&self.ledger),
            id: self.id,
        }
    }

    /// The loading thread's own claim on the commitment, taken before the
    /// reservation can move on with the model. While it is outstanding the
    /// commitment stays charged, whoever else lets go of it.
    pub(crate) fn loading_claim(&self) -> LoadingClaim {
        if let Some(entry) = self.ledger.entries().reserved.get_mut(&self.id) {
            entry.loading_claim = true;
        }
        LoadingClaim {
            ledger: Arc::clone(&self.ledger),
            id: self.id,
            concluded: false,
        }
    }

    /// Accept only the completed producer's actual metadata, before KV,
    /// drafter or GPU-cache provisioning. A mismatch leaves the full startup
    /// charge intact; callers fail the load rather than borrowing early credit.
    pub(crate) fn promote_canonical(
        &self,
        raw_bytes: u64,
        prepared_bytes: u64,
    ) -> anyhow::Result<Commitment> {
        let mut entries = self.ledger.entries();
        let entry = entries.reserved.get_mut(&self.id)
            .ok_or_else(|| anyhow::anyhow!("canonical reservation no longer exists"))?;
        anyhow::ensure!(
            !entry.stranded && !entry.owner_released && !entry.tearing_down,
            "canonical reservation is not owned by an active load"
        );
        anyhow::ensure!(!entry.canonical_promoted, "canonical reservation already promoted");
        let planned = entry.commitment;
        let expected = planned.canonical;
        anyhow::ensure!(
            raw_bytes <= expected.raw_bytes
                && prepared_bytes <= expected.prepared_bytes
                && prepared_bytes >= raw_bytes
                && prepared_bytes - raw_bytes
                    <= expected.prepared_bytes.saturating_sub(expected.raw_bytes)
                && (raw_bytes != 0 || prepared_bytes == 0),
            "completed canonical expert bytes exceed the admitted header bound"
        );
        let mut completed = planned;
        completed.canonical.raw_bytes = raw_bytes;
        completed.canonical.prepared_bytes = prepared_bytes;
        anyhow::ensure!(
            completed.retained_total() <= planned.total(),
            "completed canonical retained ownership exceeds the startup reservation"
        );
        entry.commitment = completed;
        entry.canonical_promoted = true;
        Ok(completed)
    }

    /// Keep the commitment charged for the rest of the process: the teardown
    /// of the engine it stands for failed, so its memory cannot be taken to
    /// be free. `reason` is logged with the model.
    pub(crate) fn strand(self, reason: &str) {
        self.ledger.entries().strand(self.id, reason);
        // Dropping it ends the teardown; a stranded entry is not removed.
    }
}

impl Drop for Reservation {
    fn drop(&mut self) {
        let mut entries = self.ledger.entries();
        let ended = entries.end_teardown(self.id);
        if let Some(entry) = entries.reserved.get_mut(&self.id) {
            entry.owner_released = true;
        }
        entries.release_if_unheld(self.id);
        drop(entries);
        if ended {
            self.ledger.teardown_ended.notify_all();
        }
    }
}

impl std::fmt::Debug for Reservation {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Reservation")
            .field("id", &self.id)
            .finish()
    }
}

/// The loading thread's claim on an engine's commitment
/// ([`Reservation::loading_claim`]).
///
/// The loading thread held the model while it loaded and provisioned it, and
/// may still hold memory for it (a GPU cache it primed, a queue it encoded
/// on) after the reservation has moved on to the worker with the model.
/// The worker can be torn down before the loading thread has cleaned up: a
/// warmup that fails joins the worker's teardown first. So the commitment is
/// released only when both have let go cleanly, in either order, and the
/// entry stays in the ledger, charged, until then.
pub(crate) struct LoadingClaim {
    ledger: Arc<Ledger>,
    id: u64,
    concluded: bool,
}

impl LoadingClaim {
    /// The loading thread is done with the model. `settled` says whether it
    /// could give back what it held for it; if it could not, the commitment
    /// is stranded.
    pub(crate) fn conclude(mut self, settled: anyhow::Result<()>) {
        self.finish(settled);
    }

    fn finish(&mut self, settled: anyhow::Result<()>) {
        if std::mem::replace(&mut self.concluded, true) {
            return;
        }
        let mut entries = self.ledger.entries();
        if let Err(error) = settled {
            entries.strand(
                self.id,
                &format!(
                    "the loading thread could not give back what it held for the model: \
                     {error:#}"
                ),
            );
        }
        if let Some(entry) = entries.reserved.get_mut(&self.id) {
            entry.loading_claim = false;
        }
        entries.release_if_unheld(self.id);
    }
}

impl Drop for LoadingClaim {
    fn drop(&mut self) {
        // A loading thread that ends without concluding (it panicked) has
        // not shown that it gave anything back.
        self.finish(Err(anyhow::anyhow!(
            "the loading thread ended without concluding the load"
        )));
    }
}

/// What the loading thread does with an engine's commitment once the load
/// has ended, given whether the thread could give back what it held for the
/// model itself (`settled`).
///
/// `reservation` is still here when the load failed before a worker owned
/// the model; the model is dropped, and the reservation is released with the
/// claim. When the reservation has moved on with the model, the worker
/// releases it in its own time, before or after this. In both cases the
/// commitment leaves the ledger only once the reservation is released and
/// the claim has concluded with `Ok`.
pub(crate) fn conclude_load(
    reservation: Option<Reservation>,
    claim: LoadingClaim,
    settled: anyhow::Result<()>,
) {
    claim.conclude(settled);
    drop(reservation);
}

/// Marks the start of an engine's teardown. From [`Self::begin`] until the
/// reservation is released or stranded, new admissions wait
/// ([`Ledger::admit`]).
pub(crate) struct TeardownMarker {
    ledger: Arc<Ledger>,
    id: u64,
}

impl TeardownMarker {
    /// The thread that owns the model has stopped serving and is giving the
    /// model's memory back.
    pub(crate) fn begin(self) {
        let mut entries = self.ledger.entries();
        if let Some(entry) = entries.reserved.get_mut(&self.id) {
            if !std::mem::replace(&mut entry.tearing_down, true) {
                entries.tearing_down += 1;
            }
        }
    }
}

/// The process's physical footprint: what the kernel charges the process
/// for, GPU buffers included.
pub(crate) fn process_footprint_bytes() -> anyhow::Result<u64> {
    // SAFETY: `rusage_info_v4` is plain data, and `proc_pid_rusage` fills
    // the buffer of the flavor it is asked for.
    let mut info = unsafe { std::mem::zeroed::<libc::rusage_info_v4>() };
    let rc = unsafe {
        libc::proc_pid_rusage(
            libc::getpid(),
            libc::RUSAGE_INFO_V4,
            (&mut info as *mut libc::rusage_info_v4).cast(),
        )
    };
    anyhow::ensure!(
        rc == 0,
        "proc_pid_rusage failed: {}",
        std::io::Error::last_os_error()
    );
    Ok(info.ri_phys_footprint)
}

/// How often the footprint is read while the kernel reclaims.
const RECLAIM_POLL: Duration = Duration::from_millis(5);
/// The footprint counts as quiet when it has not fallen for this many polls
/// in a row (100 ms).
const RECLAIM_QUIET_POLLS: u32 = 20;
/// A fall smaller than this between the start of a quiet stretch and a poll
/// is not a reclaim in progress.
const RECLAIM_TOLERANCE_BYTES: u64 = 64 << 20;
/// Polls after which the wait gives up (10 s).
const RECLAIM_LIMIT_POLLS: u32 = 2_000;

/// Give the kernel time to return the memory of buffers this process
/// released, before the loads that waited for a teardown read what the host
/// has available.
///
/// Releasing a Metal buffer is not the end of it: the kernel reclaims the
/// pages afterwards, on its own, and gives no handle to wait on. Measured on
/// the Qwen3.6 gate artifact, 15 to 28 GiB of a 40 GiB engine were still
/// charged to the process when every thread of the engine had terminated
/// and its queues were settled, and were gone 0.1 to 1 s later. This watches
/// the process footprint until [`RECLAIM_QUIET_POLLS`] consecutive polls are
/// none more than [`RECLAIM_TOLERANCE_BYTES`] below the first of them, and
/// reports whether it saw that within [`RECLAIM_LIMIT_POLLS`] polls.
///
/// It is a courtesy, not a proof, and nothing relies on it for safety. The
/// footprint is the whole process's: it cannot say that one engine's bytes
/// are back. A load that reads the host's available memory too early is
/// admitted to less than it could have had; what keeps it from being
/// admitted to more is the present bound of the admission (module
/// documentation).
pub(crate) fn await_kernel_reclaim() -> anyhow::Result<()> {
    quiet_footprint(process_footprint_bytes, std::thread::sleep)
}

fn quiet_footprint(
    mut footprint: impl FnMut() -> anyhow::Result<u64>,
    mut pause: impl FnMut(Duration),
) -> anyhow::Result<()> {
    let mut reference = footprint()?;
    let mut quiet = 0;
    for _ in 0..RECLAIM_LIMIT_POLLS {
        pause(RECLAIM_POLL);
        let now = footprint()?;
        if now.saturating_add(RECLAIM_TOLERANCE_BYTES) < reference {
            reference = now;
            quiet = 0;
        } else {
            quiet += 1;
            if quiet == RECLAIM_QUIET_POLLS {
                return Ok(());
            }
        }
    }
    anyhow::bail!(
        "the process footprint was still falling after {} s",
        (RECLAIM_POLL * RECLAIM_LIMIT_POLLS).as_secs()
    )
}

static PROCESS: LazyLock<Arc<Ledger>> = LazyLock::new(Ledger::new);

/// The ledger of this process.
pub(crate) fn process() -> &'static Arc<Ledger> {
    &PROCESS
}

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

    const GIB: u64 = 1 << 30;

    fn commitment(model_gib: u64, planes_gib: u64) -> Commitment {
        Commitment {
            model_file_bytes: model_gib * GIB,
            kv_budget_bytes: 4 * GIB,
            drafter_bytes: GIB,
            plane_bytes: planes_gib * GIB,
            scratch_bytes: 0,
            canonical: CanonicalCommitment::default(),
        }
    }

    #[test]
    fn a_reservation_is_counted_until_it_is_dropped() {
        let ledger = Ledger::new();
        assert_eq!(ledger.total(), 0);
        let first = ledger.reserve(Path::new("/a.gguf"), commitment(16, 10));
        let second = ledger.reserve(Path::new("/b.gguf"), commitment(20, 0));
        assert_eq!(ledger.total(), (16 + 4 + 1 + 10 + 20 + 4 + 1) * GIB);
        // A load that fails, or an engine that is unloaded, drops its
        // reservation.
        drop(first);
        assert_eq!(ledger.total(), (20 + 4 + 1) * GIB);
        drop(second);
        assert_eq!(ledger.total(), 0);
    }

    #[test]
    fn a_decision_is_made_against_the_resident_total_and_reserved() {
        let ledger = Ledger::new();
        let _first = ledger.reserve(Path::new("/a.gguf"), commitment(16, 10));
        let (seen, reservation) = ledger
            .admit(Path::new("/b.gguf"), |resident| {
                Ok::<_, ()>((resident, commitment(20, 0)))
            })
            .expect("admitted");
        assert_eq!(seen, (16 + 4 + 1 + 10) * GIB);
        assert_eq!(ledger.total(), (16 + 4 + 1 + 10 + 20 + 4 + 1) * GIB);
        drop(reservation);
        assert_eq!(ledger.total(), (16 + 4 + 1 + 10) * GIB);
    }

    #[test]
    fn a_refused_decision_reserves_nothing() {
        let ledger = Ledger::new();
        let refused = ledger.admit(Path::new("/a.gguf"), |_| {
            Err::<((), Commitment), _>("required route does not fit")
        });
        assert_eq!(refused.err(), Some("required route does not fit"));
        assert_eq!(ledger.total(), 0);
    }

    #[test]
    fn a_reservation_that_lands_during_a_decision_makes_it_decide_again() {
        let ledger = Ledger::new();
        let mut other = None;
        let mut seen = Vec::new();
        let (planes, _reservation) = ledger
            .admit(Path::new("/a.gguf"), |resident| {
                seen.push(resident);
                // Another load, through another pool, reserves while this
                // one is still deciding against the total it read.
                if other.is_none() {
                    other = Some(ledger.reserve(Path::new("/b.gguf"), commitment(20, 10)));
                }
                // The decision a memory rule makes: planes only on a host
                // nothing else is resident on.
                let planes = if resident == 0 { 10 } else { 0 };
                Ok::<_, ()>((planes, commitment(16, planes)))
            })
            .expect("admitted");
        assert_eq!(seen, vec![0, (20 + 4 + 1 + 10) * GIB]);
        assert_eq!(planes, 0, "the stale decision was not reserved");
        assert_eq!(ledger.total(), (20 + 4 + 1 + 10 + 16 + 4 + 1) * GIB);
    }

    #[test]
    fn a_release_during_a_decision_does_not_repeat_it() {
        let ledger = Ledger::new();
        let mut other = Some(ledger.reserve(Path::new("/b.gguf"), commitment(20, 10)));
        let mut decisions = 0;
        let _reservation = ledger
            .admit(Path::new("/a.gguf"), |_| {
                decisions += 1;
                other.take();
                Ok::<_, ()>(((), commitment(16, 0)))
            })
            .expect("admitted");
        assert_eq!(decisions, 1);
        assert_eq!(ledger.total(), (16 + 4 + 1) * GIB);
    }

    #[test]
    fn concurrent_loads_never_both_take_what_fits_once() {
        // Each load takes the planes only if they fit beside what is
        // resident. They fit once. Whatever the interleaving, exactly one
        // load gets them.
        const LOADS: usize = 8;
        const BOUND: u64 = 40 * GIB;
        for _ in 0..50 {
            let ledger = Ledger::new();
            let start = Arc::new(std::sync::Barrier::new(LOADS));
            let loads: Vec<_> = (0..LOADS)
                .map(|_| {
                    let (ledger, start) = (Arc::clone(&ledger), Arc::clone(&start));
                    std::thread::spawn(move || {
                        start.wait();
                        ledger
                            .admit(Path::new("/a.gguf"), |resident| {
                                let planes = Commitment {
                                    plane_bytes: 30 * GIB,
                                    ..Commitment::default()
                                };
                                let fits = resident.saturating_add(planes.total()) <= BOUND;
                                std::thread::yield_now();
                                Ok::<_, ()>((
                                    fits,
                                    if fits { planes } else { Commitment::default() },
                                ))
                            })
                            .expect("admitted")
                    })
                })
                .collect();
            let admitted: Vec<_> = loads
                .into_iter()
                .map(|load| load.join().expect("load thread"))
                .collect();
            assert_eq!(admitted.iter().filter(|(fits, _)| *fits).count(), 1);
            assert_eq!(ledger.total(), 30 * GIB);
        }
    }

    #[test]
    fn a_reservation_is_counted_while_another_thread_owns_it() {
        // The worker thread owns its engine's reservation: the ledger
        // counts it until that thread lets go, whoever else is gone.
        let ledger = Ledger::new();
        let reservation = ledger.reserve(Path::new("/a.gguf"), commitment(16, 10));
        let (release, released) = std::sync::mpsc::channel::<()>();
        let worker = std::thread::spawn(move || {
            let _held = reservation;
            let _ = released.recv();
        });
        assert_eq!(ledger.total(), (16 + 4 + 1 + 10) * GIB);
        drop(release);
        worker.join().expect("worker");
        assert_eq!(ledger.total(), 0);
    }

    #[test]
    fn a_stranded_reservation_is_counted_for_good() {
        let ledger = Ledger::new();
        let failed = ledger.reserve(Path::new("/a.gguf"), commitment(16, 10));
        let live = ledger.reserve(Path::new("/b.gguf"), commitment(20, 0));
        failed.strand("its teardown failed");
        drop(live);
        assert_eq!(ledger.total(), (16 + 4 + 1 + 10) * GIB);
    }

    /// Runs [`quiet_footprint`] over a scripted footprint (the last value repeats)
    /// and returns its result with the number of polls it made.
    fn settled(script: &[u64]) -> (anyhow::Result<()>, usize) {
        let mut reads = 0;
        let mut pauses = 0;
        let result = quiet_footprint(
            || {
                let value = script[reads.min(script.len() - 1)];
                reads += 1;
                Ok(value)
            },
            |pause| {
                assert_eq!(pause, RECLAIM_POLL);
                pauses += 1;
            },
        );
        (result, pauses)
    }

    #[test]
    fn the_reclaim_wait_ends_when_the_footprint_has_stopped_falling() {
        let quiet = RECLAIM_QUIET_POLLS as usize;
        // Nothing to reclaim: one quiet stretch.
        let (result, polls) = settled(&[40 * GIB]);
        assert!(result.is_ok());
        assert_eq!(polls, quiet);
        // The kernel is still reclaiming: 28 GiB, then 26, 7, 0.2 and flat.
        // The quiet stretch starts at the last fall.
        let falling = [28 * GIB, 26 * GIB, 7 * GIB, GIB / 5];
        let (result, polls) = settled(&falling);
        assert!(result.is_ok());
        assert_eq!(polls, falling.len() - 1 + quiet);
        // A fall that resumes inside a quiet stretch restarts it.
        let mut resumed = vec![28 * GIB; quiet];
        resumed.push(GIB);
        let (result, polls) = settled(&resumed);
        assert!(result.is_ok());
        assert_eq!(polls, resumed.len() - 1 + quiet);
        // A footprint that rises (another engine serving) is not a reclaim.
        let (result, polls) = settled(&[GIB, 2 * GIB, 3 * GIB]);
        assert!(result.is_ok());
        assert_eq!(polls, quiet);
        // Neither is a fall within the tolerance.
        let (result, polls) = settled(&[GIB, GIB - RECLAIM_TOLERANCE_BYTES]);
        assert!(result.is_ok());
        assert_eq!(polls, quiet);
    }

    #[test]
    fn a_footprint_that_never_stops_falling_fails_the_wait() {
        let mut reads = 0_u64;
        let mut polls = 0;
        let result = quiet_footprint(
            || {
                reads += 1;
                Ok(u64::MAX - reads * 2 * RECLAIM_TOLERANCE_BYTES)
            },
            |_| polls += 1,
        );
        assert!(result.unwrap_err().to_string().contains("still falling"));
        assert_eq!(polls, RECLAIM_LIMIT_POLLS);
        // A footprint that cannot be read fails it at once.
        let unreadable = quiet_footprint(|| anyhow::bail!("no rusage"), |_| {});
        assert!(unreadable.is_err());
    }

    #[test]
    fn the_process_footprint_is_readable() {
        assert!(process_footprint_bytes().expect("footprint") > 0);
    }

    fn settle_failed() -> anyhow::Result<()> {
        Err(anyhow::anyhow!("a command queue could not be settled"))
    }

    /// An admission made now: the charged total it sees, without waiting.
    fn charged_now(ledger: &Arc<Ledger>) -> u64 {
        let asked = std::time::Instant::now();
        let (resident, _reservation) = ledger
            .admit(Path::new("/next.gguf"), |resident| {
                Ok::<_, ()>((resident, Commitment::default()))
            })
            .expect("admitted");
        assert!(
            asked.elapsed() < ADMISSION_TEARDOWN_WAIT / 3,
            "the admission waited for a teardown that had ended"
        );
        assert_eq!(ledger.admissions_waiting(), 0);
        resident
    }

    #[test]
    fn a_load_that_failed_before_a_worker_existed_concludes_by_its_cleanup() {
        let ledger = Ledger::new();
        let one = commitment(16, 10).total();
        // The loading thread gave everything back: the reservation goes.
        let reservation = ledger.reserve(Path::new("/a.gguf"), commitment(16, 10));
        let claim = reservation.loading_claim();
        conclude_load(Some(reservation), claim, Ok(()));
        assert_eq!(ledger.total(), 0);
        // It could not: stranded, so a retry is admitted against it.
        let reservation = ledger.reserve(Path::new("/a.gguf"), commitment(16, 10));
        let claim = reservation.loading_claim();
        conclude_load(Some(reservation), claim, settle_failed());
        assert_eq!(ledger.total(), one);
        assert_eq!(charged_now(&ledger), one);
    }

    #[test]
    fn a_worker_released_first_does_not_free_what_the_loading_thread_has_not_concluded() {
        // The order a failed warmup takes: the worker is stopped and its
        // teardown joined, and only then does the loading thread clean up.
        let ledger = Ledger::new();
        let one = commitment(16, 10).total();
        let load = || {
            let reservation = ledger.reserve(Path::new("/a.gguf"), commitment(16, 10));
            let claim = reservation.loading_claim();
            (reservation, claim)
        };
        let worker_teardown = |reservation: Reservation| {
            reservation.teardown_marker().begin();
            drop(reservation);
        };

        // The loading cleanup fails afterwards: the commitment the worker
        // let go of is still there to strand. It was never out of the
        // ledger, and it stays for good.
        let (reservation, claim) = load();
        worker_teardown(reservation);
        assert_eq!(
            ledger.total(),
            one,
            "the worker's release alone frees nothing"
        );
        // The teardown is over, so an admission is decided at once, and
        // against the commitment.
        assert_eq!(charged_now(&ledger), one);
        conclude_load(None, claim, settle_failed());
        assert_eq!(ledger.total(), one);
        assert_eq!(charged_now(&ledger), one);

        // The loading cleanup succeeds afterwards: released then, not
        // before.
        let (reservation, claim) = load();
        worker_teardown(reservation);
        assert_eq!(ledger.total(), 2 * one);
        assert_eq!(charged_now(&ledger), 2 * one);
        conclude_load(None, claim, Ok(()));
        assert_eq!(ledger.total(), one, "only the stranded one is left");
        assert_eq!(charged_now(&ledger), one);
    }

    #[test]
    fn a_loading_thread_that_concludes_first_leaves_the_release_to_the_worker() {
        let ledger = Ledger::new();
        let one = commitment(16, 10).total();
        // Cleanup succeeded: the worker's teardown releases, when it ends.
        let reservation = ledger.reserve(Path::new("/a.gguf"), commitment(16, 10));
        conclude_load(None, reservation.loading_claim(), Ok(()));
        assert_eq!(ledger.total(), one);
        drop(reservation);
        assert_eq!(ledger.total(), 0);
        // Cleanup failed: the worker's teardown, however clean, releases
        // nothing, and does not leave admissions waiting.
        let reservation = ledger.reserve(Path::new("/a.gguf"), commitment(16, 10));
        conclude_load(None, reservation.loading_claim(), settle_failed());
        reservation.teardown_marker().begin();
        drop(reservation);
        assert_eq!(ledger.total(), one);
        assert_eq!(charged_now(&ledger), one);
        // A worker whose own teardown failed strands it whatever the loading
        // thread concludes.
        let reservation = ledger.reserve(Path::new("/b.gguf"), commitment(20, 0));
        let claim = reservation.loading_claim();
        reservation.strand("its queues could not be settled");
        conclude_load(None, claim, Ok(()));
        assert_eq!(ledger.total(), one + commitment(20, 0).total());
    }

    #[test]
    fn a_loading_thread_that_never_concludes_strands_the_commitment() {
        let ledger = Ledger::new();
        let reservation = ledger.reserve(Path::new("/a.gguf"), commitment(16, 10));
        // The loading thread panics between the handoff and its cleanup.
        drop(reservation.loading_claim());
        drop(reservation);
        assert_eq!(ledger.total(), commitment(16, 10).total());
    }

    fn canonical_commitment() -> Commitment {
        Commitment {
            model_file_bytes: 100,
            kv_budget_bytes: 40,
            drafter_bytes: 10,
            plane_bytes: 90,
            scratch_bytes: 20,
            canonical: CanonicalCommitment {
                raw_bytes: 80,
                prepared_bytes: 82,
                startup_prepared_bytes: 82,
                routed_prepared_bytes: 82,
                boot_kv_bytes: 12,
                drafter_load_bytes: 30,
                drafter_run_bytes: 10,
            },
        }
    }

    #[test]
    fn canonical_phase_peak_is_maximum_not_raw_prepared_kv_sum() {
        let mut commitment = canonical_commitment();
        assert_eq!(commitment.startup_total(), 182);
        assert_eq!(commitment.retained_total(), 180);
        assert_eq!(commitment.total(), 182);
        commitment.kv_budget_bytes = 80;
        assert_eq!(commitment.retained_total(), 220);
        assert_eq!(commitment.total(), 220);
        commitment.canonical.boot_kv_bytes = 90;
        assert_eq!(commitment.total(), 230, "boot KV and drafter load coexist");
        commitment.canonical.drafter_run_bytes = 100;
        assert_eq!(commitment.total(), 320, "boot allocations remain live during run");
    }

    #[test]
    fn canonical_promotion_changes_only_its_instance_after_checked_metadata() {
        let ledger = Ledger::new();
        let first = ledger.reserve(Path::new("/a.gguf"), canonical_commitment());
        let second = ledger.reserve(Path::new("/b.gguf"), canonical_commitment());
        assert_eq!(ledger.total(), 364, "both startup peaks remain charged");
        first.promote_canonical(80, 82).unwrap();
        assert_eq!(ledger.total(), 362);
        assert_eq!(charged_now(&ledger), 362, "aggregate admission sees the transition");
        second.promote_canonical(40, 41).unwrap();
        assert_eq!(ledger.total(), 359, "a partial affine overlay converts only plain triplets");
        drop(first);
        assert_eq!(ledger.total(), 179);
        drop(second);
        assert_eq!(ledger.total(), 0);
    }

    #[test]
    fn failed_or_stranded_canonical_promotion_never_releases_startup_charge() {
        let ledger = Ledger::new();
        let failed = ledger.reserve(Path::new("/a.gguf"), canonical_commitment());
        assert!(failed.promote_canonical(81, 83).is_err());
        assert_eq!(ledger.total(), 182);
        failed.strand("producer completion/source retirement failed");
        assert_eq!(charged_now(&ledger), 182);

        let completed = ledger.reserve(Path::new("/b.gguf"), canonical_commitment());
        let claim = completed.loading_claim();
        completed.promote_canonical(80, 82).unwrap();
        completed.strand("worker cleanup failed after source-free promotion");
        conclude_load(None, claim, Ok(()));
        assert_eq!(ledger.total(), 362, "failed cleanup keeps the actual retained ownership charged");
    }

    #[test]
    fn unsupported_overlay_keeps_raw_accounting_after_zero_conversion_completion() {
        let ledger = Ledger::new();
        let mut planned = canonical_commitment();
        planned.plane_bytes = 0;
        planned.canonical.routed_prepared_bytes = 0;
        let held = ledger.reserve(Path::new("/affine.gguf"), planned);
        assert_eq!(ledger.total(), 182, "header preparation upper bound is charged until completion");
        let completed = held.promote_canonical(0, 0).unwrap();
        assert_eq!(completed.retained_total(), 170, "unsupported raw ownership keeps the old component sum");
        assert_eq!(ledger.total(), 170);
    }

    #[test]
    fn zero_and_subset_conversion_preserve_load_dominated_phase_plan() {
        let ledger = Ledger::new();
        let mut planned = canonical_commitment();
        planned.plane_bytes = 0;
        planned.canonical.routed_prepared_bytes = 0;
        planned.canonical.drafter_load_bytes = 160;
        planned.drafter_bytes = 140;
        assert_eq!(planned.total(), 274);
        for (raw, prepared, retained) in [(0, 0, 272), (40, 41, 273), (80, 82, 274)] {
            let reservation = ledger.reserve(Path::new("/load-dominated.gguf"), planned);
            assert_eq!(ledger.total(), 274);
            let completed = reservation.promote_canonical(raw, prepared).unwrap();
            assert_eq!(completed.retained_total(), retained);
            assert_eq!(ledger.total(), retained);
            drop(reservation);
            assert_eq!(ledger.total(), 0);
        }
        let reservation = ledger.reserve(Path::new("/unplanned-growth.gguf"), planned);
        assert!(reservation.promote_canonical(80, 83).is_err());
        assert_eq!(ledger.total(), 274, "growth is refused, not clamped to the startup bound");
    }

    #[test]
    fn zero_conversion_preserves_raw_components_and_the_file_floor() {
        let raw = commitment(16, 10);
        assert_eq!(raw.total(), raw.retained_total());
        let ledger = Ledger::new();
        let held = ledger.reserve(Path::new("/unsupported.gguf"), raw);
        assert_eq!(held.promote_canonical(0, 0).unwrap(), raw);
        assert_eq!(ledger.total(), raw.total());
        let mut smaller_planes = canonical_commitment();
        smaller_planes.canonical.prepared_bytes = 80;
        assert_eq!(smaller_planes.retained_total(), 178, "the model-file floor is unchanged");
    }

    #[test]
    fn a_commitment_sums_its_components_without_wrapping() {
        let all = Commitment {
            model_file_bytes: 1,
            kv_budget_bytes: 2,
            drafter_bytes: 3,
            plane_bytes: 4,
            scratch_bytes: 5,
            canonical: CanonicalCommitment::default(),
        };
        assert_eq!(all.total(), 15);
        let huge = Commitment {
            model_file_bytes: u64::MAX,
            ..all
        };
        assert_eq!(huge.total(), u64::MAX);
    }
}