overbrainer 0.8.1

Distill a large LLM into a smaller open-weights model: generate questions, collect answers, fine-tune, visualize.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
//! Views of the Runpod catalog: GPU types filtered and ordered cheapest first,
//! data centers with the stock of chosen GPU types, and the resolution of a
//! target's `auto` choices. Pure functions over what
//! [`RunpodClient`](super::RunpodClient) lists.

use std::cmp::Ordering;

use crate::config::ListOrAuto;

use super::RunpodTarget;
use super::types::{Availability, DataCenter, GpuType, NetworkVolume, Stock, Template};

/// What [`select_gpus`] keeps. The default keeps every Secure Cloud GPU type.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct GpuFilter {
    /// Least VRAM per GPU, in GB.
    pub min_vram_gb: Option<u32>,
    /// Highest Secure Cloud price of one GPU, in USD per hour; a GPU without a
    /// price is dropped when set.
    pub max_price: Option<f64>,
    /// Only GPU types offered in this data center; with `in_stock`, stock is
    /// judged there instead of overall.
    pub data_center: Option<String>,
    /// Only GPU types with some stock.
    pub in_stock: bool,
    /// Only GPU types whose Secure Cloud pod maximum covers this many GPUs.
    pub gpu_count: Option<u32>,
}

impl GpuFilter {
    /// Whether `gpu` passes every constraint.
    #[must_use]
    pub fn keeps(&self, gpu: &GpuType) -> bool {
        gpu.on_secure_cloud()
            && self.min_vram_gb.is_none_or(|min| gpu.memory >= min)
            && self
                .max_price
                .is_none_or(|max| gpu.secure_price().is_some_and(|price| price <= max))
            && self
                .gpu_count
                .is_none_or(|count| gpu.max_count.secure >= count)
            && self.stock_ok(gpu)
    }

    fn stock_ok(&self, gpu: &GpuType) -> bool {
        let stock = match &self.data_center {
            Some(center) => {
                if !gpu.data_centers.iter().any(|entry| &entry.id == center) {
                    return false;
                }
                gpu.stock_in(center)
            },
            None => gpu.availability,
        };
        !self.in_stock || stock.is_in_stock()
    }
}

/// Cheapest Secure Cloud price first (no price last), ties by more VRAM, then
/// by ID.
#[must_use]
pub fn by_price(a: &GpuType, b: &GpuType) -> Ordering {
    let price = match (a.secure_price(), b.secure_price()) {
        (Some(x), Some(y)) => x.total_cmp(&y),
        (Some(_), None) => Ordering::Less,
        (None, Some(_)) => Ordering::Greater,
        (None, None) => Ordering::Equal,
    };
    price
        .then_with(|| b.memory.cmp(&a.memory))
        .then_with(|| a.id.cmp(&b.id))
}

/// The GPU types `filter` keeps, cheapest first (see [`by_price`]).
#[must_use]
pub fn select_gpus(gpus: &[GpuType], filter: &GpuFilter) -> Vec<GpuType> {
    let mut kept: Vec<GpuType> = gpus
        .iter()
        .filter(|gpu| filter.keeps(gpu))
        .cloned()
        .collect();
    kept.sort_by(by_price);
    kept
}

/// The rows of `overbrainer pod gpus`, header first, for `gpus` already
/// filtered and sorted (see [`select_gpus`]); nothing when `gpus` is empty.
/// `data_center`, when given, is shown as the stock column instead of the
/// overall band (see [`GpuType::stock_in`]).
#[must_use]
pub fn gpu_table(gpus: &[GpuType], data_center: Option<&str>) -> Vec<String> {
    if gpus.is_empty() {
        return Vec::new();
    }
    let rows: Vec<Vec<String>> = gpus
        .iter()
        .map(|gpu| {
            let price = gpu
                .secure_price()
                .map_or_else(|| "-".to_string(), |price| format!("{price:.2}"));
            let stock = data_center.map_or(gpu.availability, |center| gpu.stock_in(center));
            vec![
                gpu.id.clone(),
                gpu.memory.to_string(),
                price,
                gpu.max_count.secure.to_string(),
                stock.name().to_string(),
            ]
        })
        .collect();
    columns(
        &["ID", "VRAM GB", "$/H", "MAX COUNT", "STOCK"],
        &[
            Align::Left,
            Align::Right,
            Align::Right,
            Align::Right,
            Align::Left,
        ],
        &rows,
    )
}

/// `text`, from the Runpod API, without what could move the cursor or change
/// the terminal's state: ANSI escape sequences (CSI, string controls such as
/// OSC or DCS through their terminator, and two-character ones) are dropped, a control character that is whitespace (newline, tab,
/// CR...) becomes a space, and every other one (C0, DEL, C1) is dropped.
#[must_use]
pub fn printable(text: &str) -> String {
    let mut kept = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\u{1b}' => match chars.next() {
                Some('[') => skip_csi(&mut chars),
                Some(']' | 'P' | 'X' | '^' | '_') => skip_string(&mut chars),
                _ => {},
            },
            '\u{9b}' => skip_csi(&mut chars),
            '\u{90}' | '\u{98}' | '\u{9d}' | '\u{9e}' | '\u{9f}' => skip_string(&mut chars),
            c if c.is_control() && c.is_whitespace() => kept.push(' '),
            c if c.is_control() => {},
            c => kept.push(c),
        }
    }
    kept
}

/// Skips a CSI sequence's parameters and intermediates, then its final byte.
fn skip_csi(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) {
    while chars.next_if(|c| matches!(c, ' '..='?')).is_some() {}
    chars.next_if(|c| matches!(c, '@'..='~'));
}

/// Skips a string control (OSC, DCS, SOS, PM or APC) up to its terminator:
/// BEL, ST or `ESC \`; an unterminated one takes the rest of the text.
fn skip_string(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) {
    while let Some(c) = chars.next() {
        match c {
            '\u{7}' | '\u{9c}' => return,
            '\u{1b}' => {
                chars.next_if_eq(&'\\');
                return;
            },
            _ => {},
        }
    }
}

/// Whether a [`columns`] column is aligned to the left or the right.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Align {
    Left,
    Right,
}

/// `header` and `rows` laid out in columns two spaces apart, each as wide as
/// its longest value, `align` giving each column's side; the last column is
/// never padded. Each cell is [`printable`].
fn columns(header: &[&str], align: &[Align], rows: &[Vec<String>]) -> Vec<String> {
    let rows: Vec<Vec<String>> = rows
        .iter()
        .map(|row| row.iter().map(|cell| printable(cell)).collect())
        .collect();
    let mut widths: Vec<usize> = header.iter().map(|title| title.chars().count()).collect();
    for row in &rows {
        for (width, cell) in widths.iter_mut().zip(row) {
            *width = (*width).max(cell.chars().count());
        }
    }
    let line = |cells: Vec<&str>| {
        let last = cells.len().saturating_sub(1);
        let padded: Vec<String> = cells
            .iter()
            .zip(&widths)
            .zip(align)
            .enumerate()
            .map(|(index, ((cell, width), side))| match side {
                _ if index == last => (*cell).to_string(),
                Align::Left => format!("{cell:<width$}"),
                Align::Right => format!("{cell:>width$}"),
            })
            .collect();
        padded.join("  ")
    };
    let mut lines = vec![line(header.to_vec())];
    lines.extend(
        rows.iter()
            .map(|row| line(row.iter().map(String::as_str).collect())),
    );
    lines
}

/// A data center with the stock of chosen GPU types.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DataCenterStock {
    /// Its ID.
    pub id: String,
    /// Display name.
    pub name: String,
    /// Continental region.
    pub region: String,
    /// One entry per chosen GPU type, in the chosen order; `NONE` when the data
    /// center does not offer it.
    pub stock: Vec<Stock>,
}

impl DataCenterStock {
    /// Whether at least one chosen GPU type is in stock here.
    #[must_use]
    pub fn in_stock(&self) -> bool {
        self.stock
            .iter()
            .any(|entry| entry.availability.is_in_stock())
    }
}

/// Every data center with the stock of each `chosen` GPU type, ordered by ID.
#[must_use]
pub fn data_center_stock<S: AsRef<str>>(
    data_centers: &[DataCenter],
    chosen: &[S],
) -> Vec<DataCenterStock> {
    let mut rows: Vec<DataCenterStock> = data_centers
        .iter()
        .map(|center| DataCenterStock {
            id: center.id.clone(),
            name: center.name.clone(),
            region: center.region.clone(),
            stock: chosen
                .iter()
                .map(|gpu| {
                    let gpu = gpu.as_ref();
                    center
                        .gpu_availability
                        .iter()
                        .find(|entry| entry.id == gpu)
                        .cloned()
                        .unwrap_or_else(|| Stock {
                            id: gpu.to_string(),
                            name: String::new(),
                            availability: Availability::None,
                        })
                })
                .collect(),
        })
        .collect();
    rows.sort_by(|a, b| a.id.cmp(&b.id));
    rows
}

/// The rows of `overbrainer pod datacenters`, header first, sorted by ID;
/// nothing when `data_centers` is empty. The stock column counts the GPU
/// types `data_centers` reports in stock there, not a chosen set.
#[must_use]
pub fn data_center_table(data_centers: &[DataCenter]) -> Vec<String> {
    if data_centers.is_empty() {
        return Vec::new();
    }
    let mut rows: Vec<&DataCenter> = data_centers.iter().collect();
    rows.sort_by(|a, b| a.id.cmp(&b.id));
    let rows: Vec<Vec<String>> = rows
        .into_iter()
        .map(|center| {
            let in_stock = center
                .gpu_availability
                .iter()
                .filter(|entry| entry.availability.is_in_stock())
                .count();
            vec![
                center.id.clone(),
                center.name.clone(),
                center.region.clone(),
                in_stock.to_string(),
            ]
        })
        .collect();
    columns(
        &["ID", "NAME", "REGION", "GPU TYPES IN STOCK"],
        &[Align::Left; 4],
        &rows,
    )
}

/// The data centers with at least one `chosen` GPU type in stock, ordered by
/// the cheapest such GPU type they have (see [`by_price`]), ties by ID.
///
/// Built only from each chosen GPU's own `data_centers` (as
/// [`RunpodClient::list_gpu_types`](super::RunpodClient::list_gpu_types)
/// scopes it to a GPU count), never from the unscoped `catalog/datacenters`
/// stock: a data center is picked only when the GPU itself reports stock
/// there for that count.
#[must_use]
pub fn stocked_data_centers<S: AsRef<str>>(gpus: &[GpuType], chosen: &[S]) -> Vec<DataCenterStock> {
    let chosen_gpus: Vec<&GpuType> = chosen
        .iter()
        .filter_map(|id| gpus.iter().find(|gpu| gpu.id == id.as_ref()))
        .collect();
    let mut ids: Vec<(String, String)> = Vec::new();
    for gpu in &chosen_gpus {
        for entry in &gpu.data_centers {
            if entry.availability.is_in_stock() && !ids.iter().any(|(id, _)| *id == entry.id) {
                ids.push((entry.id.clone(), entry.name.clone()));
            }
        }
    }
    let cheapest = |row: &DataCenterStock| -> Option<&GpuType> {
        row.stock
            .iter()
            .filter(|entry| entry.availability.is_in_stock())
            .filter_map(|entry| gpus.iter().find(|gpu| gpu.id == entry.id))
            .min_by(|a, b| by_price(a, b))
    };
    let mut rows: Vec<DataCenterStock> = ids
        .into_iter()
        .map(|(id, name)| DataCenterStock {
            stock: chosen
                .iter()
                .map(|gpu_id| gpu_stock_at(&chosen_gpus, gpu_id.as_ref(), &id))
                .collect(),
            id,
            name,
            region: String::new(),
        })
        .collect();
    rows.sort_by(|a, b| {
        let order = match (cheapest(a), cheapest(b)) {
            (Some(x), Some(y)) => by_price(x, y),
            (Some(_), None) => Ordering::Less,
            (None, Some(_)) => Ordering::Greater,
            (None, None) => Ordering::Equal,
        };
        order.then_with(|| a.id.cmp(&b.id))
    });
    rows
}

/// `gpu_id`'s own stock at the data center `center_id`, `NONE` when that GPU
/// (among `chosen_gpus`) does not report it. `id` names the GPU, not the data
/// center, to match [`DataCenterStock::stock`]'s "one entry per chosen GPU".
fn gpu_stock_at(chosen_gpus: &[&GpuType], gpu_id: &str, center_id: &str) -> Stock {
    let availability = chosen_gpus
        .iter()
        .find(|gpu| gpu.id == gpu_id)
        .and_then(|gpu| gpu.data_centers.iter().find(|entry| entry.id == center_id))
        .map_or(Availability::None, |entry| entry.availability);
    Stock {
        id: gpu_id.to_string(),
        name: String::new(),
        availability,
    }
}

/// Why an `auto` choice of a Runpod target found nothing: each message says
/// what was asked.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ResolveError {
    /// No GPU type in stock matches `gpu_types = "auto"`.
    #[error("no GPU type in stock on Runpod's Secure Cloud for gpu_types = \"auto\" ({asked})")]
    NoGpuType {
        /// The target's fields that narrowed the choice, as `name = value`.
        asked: String,
    },
    /// No data center has a chosen GPU type in stock for
    /// `data_center_ids = "auto"`.
    #[error(
        "no data center has {gpu_types} in stock for data_center_ids = \"auto\" \
         (gpu_count = {gpu_count})"
    )]
    NoDataCenter {
        /// The chosen GPU types, as `a, b or c`.
        gpu_types: String,
        /// GPUs per pod.
        gpu_count: u32,
    },
}

/// `target` with its `auto` choices replaced by lists, from the catalog's
/// `gpus`, listed for the target's `gpu_count`; listed choices are kept as
/// they are.
///
/// `auto` GPU types are those in stock whose Secure Cloud pod maximum covers
/// `gpu_count`, within `min_vram_gb` and `max_price_per_hour`, in stock in one
/// of the listed data centers when there are any, cheapest first (see
/// [`by_price`]). `auto` data centers are those with a chosen GPU type in
/// stock for that count, ordered by the cheapest one they have (see
/// [`stocked_data_centers`]).
///
/// # Errors
///
/// Returns a [`ResolveError`] saying what was asked when nothing in stock
/// matches.
pub fn resolve(target: &RunpodTarget, gpus: &[GpuType]) -> Result<RunpodTarget, ResolveError> {
    resolve_with_floor(target, gpus, None)
}

/// [`resolve`], `auto` GPU types keeping only those with at least
/// `floor_gb` of VRAM (the estimate of what the run needs, see
/// [`crate::train::sizing`]) when the target sets no `min_vram_gb`: an
/// explicit `min_vram_gb` wins.
///
/// # Errors
///
/// Returns a [`ResolveError`] saying what was asked when nothing in stock
/// matches.
pub fn resolve_with_floor(
    target: &RunpodTarget,
    gpus: &[GpuType],
    floor_gb: Option<u32>,
) -> Result<RunpodTarget, ResolveError> {
    let mut resolved = target.clone();
    let floor = floor_gb.filter(|_| target.min_vram_gb.is_none());
    if target.gpu_types.is_auto() {
        let filter = GpuFilter {
            min_vram_gb: target.min_vram_gb.or(floor),
            max_price: target.max_price_per_hour,
            data_center: None,
            in_stock: true,
            gpu_count: Some(target.gpu_count),
        };
        let listed = target.data_center_ids.list();
        let chosen: Vec<String> = select_gpus(gpus, &filter)
            .into_iter()
            .filter(|gpu| {
                listed.is_empty()
                    || listed
                        .iter()
                        .any(|center| gpu.stock_in(center).is_in_stock())
            })
            .map(|gpu| gpu.id)
            .collect();
        if chosen.is_empty() {
            return Err(ResolveError::NoGpuType {
                asked: asked(target, floor),
            });
        }
        resolved.gpu_types = ListOrAuto::List(chosen);
    }
    if target.data_center_ids.is_auto() {
        let chosen = resolved.gpu_types.list();
        let centers: Vec<String> = stocked_data_centers(gpus, chosen)
            .into_iter()
            .map(|row| row.id)
            .collect();
        if centers.is_empty() {
            return Err(ResolveError::NoDataCenter {
                gpu_types: or_list(chosen),
                gpu_count: target.gpu_count,
            });
        }
        resolved.data_center_ids = ListOrAuto::List(centers);
    }
    Ok(resolved)
}

/// A GPU type in stock and what a pod of it costs.
#[derive(Debug, Clone, PartialEq)]
pub struct GpuOffer {
    /// The GPU type's ID.
    pub gpu_type: String,
    /// Secure Cloud price of the pod, all its GPUs, in USD per hour.
    pub per_hour: f64,
}

/// The cheapest GPU type in stock a pod of `target` would get, from the
/// catalog `gpus`, priced for `target.gpu_count` GPUs, as `overbrainer pod
/// gpus` lists prices: its `auto` GPU types as [`resolve_with_floor`] picks
/// them (with `floor_gb`), else its listed ones. `None` when none is in stock
/// with a price.
#[must_use]
pub fn cheapest_in_stock(
    target: &RunpodTarget,
    gpus: &[GpuType],
    floor_gb: Option<u32>,
) -> Option<GpuOffer> {
    let resolved = resolve_with_floor(target, gpus, floor_gb).ok()?;
    let wanted = resolved.gpu_types.list();
    let filter = GpuFilter {
        in_stock: true,
        gpu_count: Some(target.gpu_count),
        ..GpuFilter::default()
    };
    select_gpus(gpus, &filter)
        .into_iter()
        .filter(|gpu| wanted.contains(&gpu.id))
        .find_map(|gpu| {
            gpu.secure_price().map(|price| GpuOffer {
                per_hour: price * f64::from(target.gpu_count),
                gpu_type: gpu.id,
            })
        })
}

/// Most GPU types reported out of stock that one walk over `auto` GPU types
/// tries (see [`walk_order`]).
pub(crate) const MAX_OUT_OF_STOCK: usize = 3;

/// The order in which a walk tries the `auto` GPU types of a target.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct WalkOrder {
    /// The target with its `auto` choices resolved: the GPU types reported out
    /// of stock first, then those in stock not tried yet.
    pub target: RunpodTarget,
    /// The GPU types of `target` reported out of stock.
    pub out_of_stock: Vec<String>,
}

/// [`resolve_with_floor`] for a walk that already tried the GPU types `tried`:
/// with `auto` GPU types, those in stock not tried yet, cheapest first, come
/// after at most `cap` GPU types reported out of stock that are cheaper than
/// the cheapest of them and meet every other limit (`max_price_per_hour`,
/// `min_vram_gb` or `floor_gb`, `gpu_count`), cheapest first. Stock reports
/// change within seconds, and a type reported out of stock can still be
/// placed: trying one costs a single refused create call.
///
/// With listed data centers, a type out of stock is kept when it lists one of
/// them or lists none (Runpod gives no data center for a type out of stock
/// everywhere); the create call still names the listed ones. `auto` data
/// centers are those with an untried type in stock. A target with listed GPU
/// types is returned as [`resolve_with_floor`] gives it.
///
/// # Errors
///
/// Returns a [`ResolveError`] when nothing in stock matches, or when every
/// type in stock was tried already.
pub(crate) fn walk_order(
    target: &RunpodTarget,
    gpus: &[GpuType],
    floor_gb: Option<u32>,
    tried: &[String],
    cap: usize,
) -> Result<WalkOrder, ResolveError> {
    let mut resolved = resolve_with_floor(target, gpus, floor_gb)?;
    if !target.gpu_types.is_auto() {
        return Ok(WalkOrder {
            target: resolved,
            out_of_stock: Vec::new(),
        });
    }
    let in_stock = resolved.gpu_types.list().to_vec();
    let untried: Vec<String> = in_stock
        .iter()
        .filter(|id| !tried.contains(id))
        .cloned()
        .collect();
    let floor = floor_gb.filter(|_| target.min_vram_gb.is_none());
    let Some(cheapest) = untried.first() else {
        return Err(ResolveError::NoGpuType {
            asked: asked(target, floor),
        });
    };
    let below = gpus
        .iter()
        .find(|gpu| &gpu.id == cheapest)
        .and_then(GpuType::secure_price);
    let out_of_stock: Vec<String> = match below {
        None => Vec::new(),
        Some(below) => {
            let filter = GpuFilter {
                min_vram_gb: target.min_vram_gb.or(floor),
                max_price: target.max_price_per_hour,
                data_center: None,
                in_stock: false,
                gpu_count: Some(target.gpu_count),
            };
            let listed = target.data_center_ids.list();
            select_gpus(gpus, &filter)
                .into_iter()
                .filter(|gpu| !in_stock.contains(&gpu.id) && !tried.contains(&gpu.id))
                .filter(|gpu| gpu.secure_price().is_some_and(|price| price < below))
                .filter(|gpu| {
                    listed.is_empty()
                        || gpu.data_centers.is_empty()
                        || gpu
                            .data_centers
                            .iter()
                            .any(|entry| listed.contains(&entry.id))
                })
                .take(cap)
                .map(|gpu| gpu.id)
                .collect()
        },
    };
    if target.data_center_ids.is_auto() {
        let centers: Vec<String> = stocked_data_centers(gpus, &untried)
            .into_iter()
            .map(|row| row.id)
            .collect();
        if centers.is_empty() {
            return Err(ResolveError::NoDataCenter {
                gpu_types: or_list(&untried),
                gpu_count: target.gpu_count,
            });
        }
        resolved.data_center_ids = ListOrAuto::List(centers);
    }
    resolved.gpu_types = ListOrAuto::List(out_of_stock.iter().chain(&untried).cloned().collect());
    Ok(WalkOrder {
        target: resolved,
        out_of_stock,
    })
}

/// What an `auto` choice of GPU types asked for, as the target's fields,
/// with the estimated VRAM `floor` when it applied.
fn asked(target: &RunpodTarget, floor: Option<u32>) -> String {
    let mut asked = vec![format!("gpu_count = {}", target.gpu_count)];
    if let Some(gb) = target.min_vram_gb {
        asked.push(format!("min_vram_gb = {gb}"));
    }
    if let Some(gb) = floor {
        asked.push(format!("at least {gb} GB of VRAM estimated for the model"));
    }
    if let Some(price) = target.max_price_per_hour {
        asked.push(format!("max_price_per_hour = {price}"));
    }
    if let ListOrAuto::List(centers) = &target.data_center_ids
        && !centers.is_empty()
    {
        asked.push(format!("data_center_ids = {}", centers.join(", ")));
    }
    asked.join(", ")
}

/// `a`, `a or b`, `a, b or c`.
fn or_list(items: &[String]) -> String {
    match items.split_last() {
        None => String::new(),
        Some((last, [])) => last.clone(),
        Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
    }
}

/// The rows of `overbrainer pod volumes`, header first, sorted by name;
/// nothing when `volumes` is empty.
#[must_use]
pub fn volume_table(volumes: &[NetworkVolume]) -> Vec<String> {
    if volumes.is_empty() {
        return Vec::new();
    }
    let mut rows: Vec<&NetworkVolume> = volumes.iter().collect();
    rows.sort_by(|a, b| a.name.cmp(&b.name));
    let rows: Vec<Vec<String>> = rows
        .into_iter()
        .map(|volume| {
            vec![
                volume.id.clone(),
                volume.name.clone(),
                volume.size.to_string(),
                volume.data_center.clone(),
            ]
        })
        .collect();
    columns(
        &["ID", "NAME", "SIZE GB", "DATA CENTER"],
        &[Align::Left, Align::Left, Align::Right, Align::Left],
        &rows,
    )
}

/// The rows of `overbrainer pod templates`, header first, sorted by name;
/// nothing when `templates` is empty.
#[must_use]
pub fn template_table(templates: &[Template]) -> Vec<String> {
    if templates.is_empty() {
        return Vec::new();
    }
    let mut rows: Vec<&Template> = templates.iter().collect();
    rows.sort_by(|a, b| a.name.cmp(&b.name));
    let rows: Vec<Vec<String>> = rows
        .into_iter()
        .map(|template| {
            vec![
                template.id.clone(),
                template.name.clone(),
                template.image.clone(),
            ]
        })
        .collect();
    columns(&["ID", "NAME", "IMAGE"], &[Align::Left; 3], &rows)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::ListOrAuto;
    use crate::runpod::types::{GpuMaxCount, GpuPrice};

    fn stock(id: &str, availability: Availability) -> Stock {
        Stock {
            id: id.to_string(),
            name: String::new(),
            availability,
        }
    }

    fn gpu(id: &str, memory: u32, price: Option<f64>) -> GpuType {
        GpuType {
            id: id.to_string(),
            memory,
            price: GpuPrice {
                secure: price,
                community: None,
            },
            max_count: GpuMaxCount {
                secure: 8,
                community: 0,
            },
            availability: Availability::High,
            ..GpuType::default()
        }
    }

    /// A Runpod target with the given GPU types and data centers and no other limit.
    fn target(gpu_types: ListOrAuto, data_center_ids: ListOrAuto) -> RunpodTarget {
        RunpodTarget {
            gpu_types,
            min_vram_gb: None,
            max_price_per_hour: None,
            gpu_count: 1,
            image: "img".to_string(),
            venv: Some("/venv".to_string()),
            container_disk_gb: 50,
            max_hours: 1.0,
            max_cost_usd: None,
            boot_grace: std::time::Duration::from_mins(30),
            retrieve_grace: std::time::Duration::from_secs(3600),
            data_center_ids,
            network_volume_id: None,
            max_volume_gb: None,
            ssh_client: crate::config::SshClient::Openssh,
        }
    }

    fn list(items: &[&str]) -> ListOrAuto {
        ListOrAuto::List(items.iter().map(|item| (*item).to_string()).collect())
    }

    fn ids(gpus: &[GpuType]) -> Vec<&str> {
        gpus.iter().map(|gpu| gpu.id.as_str()).collect()
    }

    fn center(id: &str, gpus: Vec<Stock>) -> DataCenter {
        DataCenter {
            id: id.to_string(),
            name: format!("{id} name"),
            region: "EUROPE".to_string(),
            gpu_availability: gpus,
        }
    }

    #[test]
    fn gpus_are_cheapest_first_ties_by_more_vram_then_id() {
        let gpus = [
            gpu("none", 80, None),
            gpu("b", 24, Some(0.5)),
            gpu("big", 48, Some(0.5)),
            gpu("a", 24, Some(0.5)),
            gpu("cheap", 16, Some(0.2)),
        ];
        let sorted = select_gpus(&gpus, &GpuFilter::default());
        assert_eq!(ids(&sorted), vec!["cheap", "big", "a", "b", "none"]);
    }

    #[test]
    fn a_zero_price_is_unknown_neither_first_nor_under_a_limit() {
        let gpus = [gpu("free", 24, Some(0.0)), gpu("paid", 24, Some(0.5))];
        let sorted = select_gpus(&gpus, &GpuFilter::default());
        assert_eq!(ids(&sorted), vec!["paid", "free"]);
        let capped = GpuFilter {
            max_price: Some(1.0),
            ..GpuFilter::default()
        };
        assert_eq!(ids(&select_gpus(&gpus, &capped)), vec!["paid"]);
    }

    #[test]
    fn vram_and_price_limits_filter() {
        let gpus = [
            gpu("small", 16, Some(0.2)),
            gpu("mid", 48, Some(0.8)),
            gpu("dear", 80, Some(2.5)),
            gpu("unpriced", 80, None),
        ];
        let filter = GpuFilter {
            min_vram_gb: Some(40),
            max_price: Some(1.0),
            ..GpuFilter::default()
        };
        assert_eq!(ids(&select_gpus(&gpus, &filter)), vec!["mid"]);
        let vram_only = GpuFilter {
            min_vram_gb: Some(48),
            ..GpuFilter::default()
        };
        assert_eq!(
            ids(&select_gpus(&gpus, &vram_only)),
            vec!["mid", "dear", "unpriced"]
        );
    }

    #[test]
    fn stock_and_gpu_count_filter() {
        let mut out = gpu("out", 24, Some(0.1));
        out.availability = Availability::None;
        let mut unknown = gpu("unknown", 24, Some(0.2));
        unknown.availability = Availability::Unknown;
        let mut single = gpu("single", 24, Some(0.3));
        single.max_count.secure = 1;
        let gpus = [out, unknown, single, gpu("ok", 24, Some(0.4))];
        let in_stock = GpuFilter {
            in_stock: true,
            ..GpuFilter::default()
        };
        assert_eq!(ids(&select_gpus(&gpus, &in_stock)), vec!["single", "ok"]);
        let two = GpuFilter {
            in_stock: true,
            gpu_count: Some(2),
            ..GpuFilter::default()
        };
        assert_eq!(ids(&select_gpus(&gpus, &two)), vec!["ok"]);
    }

    #[test]
    fn community_only_gpus_are_dropped() {
        let mut community = gpu("community", 24, Some(0.1));
        community.secure = Some(false);
        let gpus = [community, gpu("secure", 24, Some(0.2))];
        assert_eq!(
            ids(&select_gpus(&gpus, &GpuFilter::default())),
            vec!["secure"]
        );
    }

    #[test]
    fn a_data_center_filter_judges_stock_there() {
        let mut here = gpu("here", 24, Some(0.3));
        here.data_centers = vec![stock("EU-RO-1", Availability::Low)];
        let mut empty_here = gpu("empty-here", 24, Some(0.2));
        empty_here.data_centers = vec![stock("EU-RO-1", Availability::None)];
        let mut elsewhere = gpu("elsewhere", 24, Some(0.1));
        elsewhere.data_centers = vec![stock("US-KS-2", Availability::High)];
        let gpus = [here, empty_here, elsewhere];
        let offered = GpuFilter {
            data_center: Some("EU-RO-1".to_string()),
            ..GpuFilter::default()
        };
        assert_eq!(
            ids(&select_gpus(&gpus, &offered)),
            vec!["empty-here", "here"]
        );
        let stocked = GpuFilter {
            in_stock: true,
            ..offered
        };
        assert_eq!(ids(&select_gpus(&gpus, &stocked)), vec!["here"]);
    }

    #[test]
    fn data_centers_show_the_chosen_gpus_stock_in_order() {
        let centers = [
            center("US-KS-2", vec![stock("A", Availability::High)]),
            center(
                "EU-RO-1",
                vec![
                    stock("B", Availability::Medium),
                    stock("A", Availability::None),
                ],
            ),
        ];
        let rows = data_center_stock(&centers, &["B", "A", "C"]);
        let row_ids: Vec<&str> = rows.iter().map(|row| row.id.as_str()).collect();
        assert_eq!(row_ids, vec!["EU-RO-1", "US-KS-2"]);
        let bands: Vec<Availability> = rows[0].stock.iter().map(|s| s.availability).collect();
        assert_eq!(
            bands,
            vec![Availability::Medium, Availability::None, Availability::None]
        );
        assert_eq!(rows[1].stock[0].id, "B");
        assert!(rows[0].in_stock() && rows[1].in_stock());
        assert!(!data_center_stock(&centers, &["C"])[0].in_stock());
        assert_eq!(rows[0].name, "EU-RO-1 name");
        assert_eq!(rows[0].region, "EUROPE");
    }

    #[test]
    fn stocked_data_centers_are_ordered_by_their_cheapest_chosen_gpu() {
        let mut cheap = gpu("cheap", 24, Some(0.2));
        cheap.data_centers = vec![
            stock("B-EMPTY", Availability::None),
            stock("C-CHEAP", Availability::Low),
            stock("D-CHEAP", Availability::High),
        ];
        let mut dear = gpu("dear", 80, Some(1.5));
        dear.data_centers = vec![
            stock("A-DEAR", Availability::High),
            stock("B-EMPTY", Availability::None),
            stock("C-CHEAP", Availability::High),
        ];
        // "E-OTHER" is not in either chosen GPU's own list, unlike an unscoped
        // catalog/datacenters listing might show: it must never appear.
        let gpus = [cheap, dear];
        let rows = stocked_data_centers(&gpus, &["dear", "cheap"]);
        let row_ids: Vec<&str> = rows.iter().map(|row| row.id.as_str()).collect();
        assert_eq!(row_ids, vec!["C-CHEAP", "D-CHEAP", "A-DEAR"]);
    }

    #[test]
    fn listed_choices_are_kept_as_they_are() {
        let listed = target(list(&["B", "A"]), list(&["EU-RO-1"]));
        assert_eq!(resolve(&listed, &[]), Ok(listed.clone()));
        let any = target(list(&["A"]), ListOrAuto::default());
        assert_eq!(resolve(&any, &[]), Ok(any.clone()));
    }

    #[test]
    fn auto_gpus_are_those_in_stock_cheapest_first_ties_by_more_vram() {
        let mut out = gpu("out", 80, Some(0.1));
        out.availability = Availability::None;
        let mut single = gpu("single", 80, Some(0.2));
        single.max_count.secure = 1;
        let mut community = gpu("community", 80, Some(0.2));
        community.secure = Some(false);
        let gpus = [
            out,
            single,
            community,
            gpu("dear", 80, Some(1.0)),
            gpu("a", 24, Some(0.5)),
            gpu("big", 48, Some(0.5)),
        ];
        let mut auto = target(ListOrAuto::Auto, ListOrAuto::default());
        auto.gpu_count = 2;
        let resolved = resolve(&auto, &gpus);
        assert_eq!(
            resolved.map(|target| target.gpu_types),
            Ok(list(&["big", "a", "dear"]))
        );
    }

    /// The cheapest GPU type in stock a target would get prices its pod, for
    /// its GPU count: `auto` within its limits and the VRAM floor, a list
    /// among its own types.
    #[test]
    fn the_cheapest_gpu_in_stock_prices_the_pod() {
        let mut out = gpu("out", 80, Some(0.1));
        out.availability = Availability::None;
        let gpus = [
            out,
            gpu("small", 16, Some(0.2)),
            gpu("mid", 48, Some(0.8)),
            gpu("unpriced", 80, None),
        ];
        let offer = |gpu_type: &str, per_hour| {
            Some(GpuOffer {
                gpu_type: gpu_type.to_string(),
                per_hour,
            })
        };
        let auto = target(ListOrAuto::Auto, ListOrAuto::default());
        assert_eq!(cheapest_in_stock(&auto, &gpus, None), offer("small", 0.2));
        assert_eq!(cheapest_in_stock(&auto, &gpus, Some(20)), offer("mid", 0.8));
        let mut listed = target(list(&["out", "unpriced", "mid"]), ListOrAuto::default());
        listed.gpu_count = 2;
        assert_eq!(cheapest_in_stock(&listed, &gpus, None), offer("mid", 1.6));
        let sold_out = target(list(&["out", "unpriced"]), ListOrAuto::default());
        assert_eq!(cheapest_in_stock(&sold_out, &gpus, None), None);
    }

    #[test]
    fn auto_gpus_meet_the_vram_and_price_limits() {
        let gpus = [
            gpu("small", 16, Some(0.2)),
            gpu("mid", 48, Some(0.8)),
            gpu("dear", 80, Some(2.5)),
            gpu("unpriced", 80, None),
        ];
        let mut auto = target(ListOrAuto::Auto, ListOrAuto::default());
        auto.min_vram_gb = Some(40);
        assert_eq!(
            resolve(&auto, &gpus).map(|target| target.gpu_types),
            Ok(list(&["mid", "dear", "unpriced"]))
        );
        auto.max_price_per_hour = Some(1.0);
        assert_eq!(
            resolve(&auto, &gpus).map(|target| target.gpu_types),
            Ok(list(&["mid"]))
        );
    }

    #[test]
    fn the_estimated_floor_applies_only_without_min_vram_gb() {
        let gpus = [
            gpu("small", 16, Some(0.2)),
            gpu("mid", 48, Some(0.8)),
            gpu("dear", 80, Some(2.5)),
        ];
        let mut auto = target(ListOrAuto::Auto, ListOrAuto::default());
        let picked = |target: &RunpodTarget, floor| {
            resolve_with_floor(target, &gpus, floor).map(|target| target.gpu_types)
        };
        assert_eq!(picked(&auto, Some(20)), Ok(list(&["mid", "dear"])));
        assert_eq!(picked(&auto, None), Ok(list(&["small", "mid", "dear"])));
        // The floor is used, never saved into the resolved target.
        assert_eq!(
            resolve_with_floor(&auto, &gpus, Some(20)).map(|target| target.min_vram_gb),
            Ok(None)
        );
        auto.min_vram_gb = Some(10);
        assert_eq!(picked(&auto, Some(60)), Ok(list(&["small", "mid", "dear"])));
        auto.min_vram_gb = None;
        assert_eq!(
            picked(&auto, Some(100)),
            Err(ResolveError::NoGpuType {
                asked: "gpu_count = 1, at least 100 GB of VRAM estimated for the model".into()
            })
        );
        let listed = target(list(&["small"]), ListOrAuto::default());
        assert_eq!(picked(&listed, Some(60)), Ok(list(&["small"])));
    }

    #[test]
    fn auto_gpus_are_in_stock_in_a_listed_data_center() {
        let mut here = gpu("here", 24, Some(0.3));
        here.data_centers = vec![stock("EU-RO-1", Availability::Low)];
        let mut empty_here = gpu("empty-here", 24, Some(0.2));
        empty_here.data_centers = vec![stock("EU-RO-1", Availability::None)];
        let mut elsewhere = gpu("elsewhere", 24, Some(0.1));
        elsewhere.data_centers = vec![stock("US-KS-2", Availability::High)];
        let gpus = [here, empty_here, elsewhere];
        let auto = target(ListOrAuto::Auto, list(&["EU-RO-1"]));
        let resolved = resolve(&auto, &gpus);
        assert_eq!(
            resolved.clone().map(|target| target.gpu_types),
            Ok(list(&["here"]))
        );
        assert_eq!(
            resolved.map(|target| target.data_center_ids),
            Ok(list(&["EU-RO-1"]))
        );
    }

    #[test]
    fn auto_data_centers_have_a_chosen_gpu_in_stock_cheapest_first() {
        let mut cheap = gpu("cheap", 24, Some(0.2));
        cheap.data_centers = vec![
            stock("B-EMPTY", Availability::None),
            stock("C-CHEAP", Availability::Low),
        ];
        let mut dear = gpu("dear", 80, Some(1.5));
        dear.data_centers = vec![stock("A-DEAR", Availability::High)];
        let gpus = [cheap, dear];
        let listed = target(list(&["dear", "cheap"]), ListOrAuto::Auto);
        let resolved = resolve(&listed, &gpus);
        assert_eq!(
            resolved.clone().map(|target| target.data_center_ids),
            Ok(list(&["C-CHEAP", "A-DEAR"]))
        );
        assert_eq!(
            resolved.map(|target| target.gpu_types),
            Ok(list(&["dear", "cheap"]))
        );
        let both = target(ListOrAuto::Auto, ListOrAuto::Auto);
        let resolved = resolve(&both, &gpus);
        assert_eq!(
            resolved.clone().map(|target| target.gpu_types),
            Ok(list(&["cheap", "dear"]))
        );
        assert_eq!(
            resolved.map(|target| target.data_center_ids),
            Ok(list(&["C-CHEAP", "A-DEAR"]))
        );
    }

    #[test]
    fn nothing_in_stock_says_what_was_asked() {
        let mut out = gpu("out", 80, Some(0.1));
        out.availability = Availability::None;
        let gpus = [out, gpu("small", 16, Some(0.2))];
        let mut auto = target(ListOrAuto::Auto, list(&["EU-RO-1", "US-KS-2"]));
        auto.gpu_count = 2;
        auto.min_vram_gb = Some(48);
        auto.max_price_per_hour = Some(0.5);
        assert_eq!(
            resolve(&auto, &gpus).map_err(|error| error.to_string()),
            Err(
                "no GPU type in stock on Runpod's Secure Cloud for gpu_types = \"auto\" \
                 (gpu_count = 2, min_vram_gb = 48, max_price_per_hour = 0.5, \
                 data_center_ids = EU-RO-1, US-KS-2)"
                    .to_string()
            )
        );
        let plain = target(ListOrAuto::Auto, ListOrAuto::default());
        assert_eq!(
            resolve(&plain, &[]).map_err(|error| error.to_string()),
            Err(
                "no GPU type in stock on Runpod's Secure Cloud for gpu_types = \"auto\" \
                 (gpu_count = 1)"
                    .to_string()
            )
        );
        let mut a = gpu("A", 24, Some(0.3));
        a.data_centers = vec![stock("EU-RO-1", Availability::None)];
        let listed = target(list(&["A", "B"]), ListOrAuto::Auto);
        assert_eq!(
            resolve(&listed, &[a]).map_err(|error| error.to_string()),
            Err(
                "no data center has A or B in stock for data_center_ids = \"auto\" \
                 (gpu_count = 1)"
                    .to_string()
            )
        );
    }

    #[test]
    fn gpu_table_is_empty_without_rows() {
        assert_eq!(gpu_table(&[], None), [] as [String; 0]);
    }

    #[test]
    fn gpu_table_lists_price_vram_count_and_overall_stock() {
        let mut a40 = gpu("NVIDIA A40", 48, Some(0.4));
        a40.availability = Availability::High;
        let mut cheap = gpu("cheap", 16, None);
        cheap.availability = Availability::Low;
        let lines = gpu_table(&[a40, cheap], None);
        assert_eq!(lines.len(), 3, "{lines:?}");
        assert!(
            lines[0].starts_with("ID") && lines[0].ends_with("STOCK"),
            "{}",
            lines[0]
        );
        assert!(
            lines[1].starts_with("NVIDIA A40")
                && lines[1].contains("48")
                && lines[1].contains("0.40")
                && lines[1].ends_with("HIGH"),
            "{}",
            lines[1]
        );
        assert!(
            lines[2].starts_with("cheap") && lines[2].ends_with("LOW"),
            "{}",
            lines[2]
        );
    }

    #[test]
    fn gpu_table_shows_stock_at_a_data_center_when_given() {
        let mut a40 = gpu("NVIDIA A40", 48, Some(0.4));
        a40.availability = Availability::High;
        a40.data_centers = vec![stock("EU-RO-1", Availability::Low)];
        let lines = gpu_table(&[a40], Some("EU-RO-1"));
        assert_eq!(lines.len(), 2, "{lines:?}");
        assert!(lines[1].ends_with("LOW"), "{}", lines[1]);
    }

    #[test]
    fn data_center_table_is_empty_without_rows() {
        assert_eq!(data_center_table(&[]), [] as [String; 0]);
    }

    #[test]
    fn data_center_table_counts_gpu_types_in_stock_sorted_by_id() {
        let centers = [
            center(
                "B-ID",
                vec![
                    stock("x", Availability::High),
                    stock("y", Availability::None),
                ],
            ),
            center("A-ID", vec![stock("x", Availability::Low)]),
        ];
        let lines = data_center_table(&centers);
        assert_eq!(lines.len(), 3, "{lines:?}");
        assert!(
            lines[0].starts_with("ID") && lines[0].ends_with("GPU TYPES IN STOCK"),
            "{}",
            lines[0]
        );
        assert!(
            lines[1].starts_with("A-ID") && lines[1].ends_with('1'),
            "{}",
            lines[1]
        );
        assert!(
            lines[2].starts_with("B-ID") && lines[2].ends_with('1'),
            "{}",
            lines[2]
        );
    }

    #[test]
    fn volume_table_is_empty_without_rows() {
        assert_eq!(volume_table(&[]), [] as [String; 0]);
    }

    #[test]
    fn volume_table_is_sorted_by_name() {
        let volumes = [
            NetworkVolume {
                id: "v2".to_string(),
                name: "zeta".to_string(),
                size: 50,
                data_center: "EU-RO-1".to_string(),
            },
            NetworkVolume {
                id: "v1".to_string(),
                name: "alpha".to_string(),
                size: 100,
                data_center: "US-KS-2".to_string(),
            },
        ];
        let lines = volume_table(&volumes);
        assert_eq!(lines.len(), 3, "{lines:?}");
        assert!(
            lines[0].starts_with("ID") && lines[0].ends_with("DATA CENTER"),
            "{}",
            lines[0]
        );
        assert!(
            lines[1].contains("v1") && lines[1].contains("alpha") && lines[1].ends_with("US-KS-2"),
            "{}",
            lines[1]
        );
        assert!(
            lines[2].contains("v2") && lines[2].contains("zeta") && lines[2].ends_with("EU-RO-1"),
            "{}",
            lines[2]
        );
    }

    #[test]
    fn template_table_is_empty_without_rows() {
        assert_eq!(template_table(&[]), [] as [String; 0]);
    }

    #[test]
    fn template_table_is_sorted_by_name() {
        let templates = [
            Template {
                id: "t2".to_string(),
                name: "zeta".to_string(),
                image: "img/z:1".to_string(),
                serverless: false,
            },
            Template {
                id: "t1".to_string(),
                name: "alpha".to_string(),
                image: "img/a:1".to_string(),
                serverless: false,
            },
        ];
        let lines = template_table(&templates);
        assert_eq!(lines.len(), 3, "{lines:?}");
        assert!(
            lines[0].starts_with("ID") && lines[0].ends_with("IMAGE"),
            "{}",
            lines[0]
        );
        assert!(
            lines[1].contains("t1") && lines[1].ends_with("img/a:1"),
            "{}",
            lines[1]
        );
        assert!(
            lines[2].contains("t2") && lines[2].ends_with("img/z:1"),
            "{}",
            lines[2]
        );
    }

    /// A live GPU ID, far longer than the old fixed ID column of 28.
    const LONG: &str = "NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition";

    /// Where `word` starts in `line`, for checking that a row lines up with
    /// its header.
    fn at(line: &str, word: &str) -> Option<usize> {
        line.find(word)
    }

    #[test]
    fn gpu_table_widens_its_id_column_to_the_longest_id() {
        let lines = gpu_table(&[gpu(LONG, 32, Some(0.9)), gpu("a", 8, Some(0.1))], None);
        assert!(lines[1].starts_with(&format!("{LONG}  ")), "{}", lines[1]);
        for line in &lines[1..] {
            assert_eq!(at(line, "HIGH"), at(&lines[0], "STOCK"), "{lines:#?}");
        }
        assert_eq!(
            at(&lines[2], "0.10").map(|at| at + 4),
            at(&lines[0], "$/H").map(|at| at + 3),
            "{lines:#?}"
        );
    }

    #[test]
    fn data_center_table_widens_its_columns_to_the_longest_values() {
        let mut long = center("A", vec![stock("x", Availability::High)]);
        long.name = LONG.to_string();
        let lines = data_center_table(&[long, center("B", Vec::new())]);
        for line in &lines[1..] {
            assert_eq!(
                line.rfind("  ").map(|at| at + 2),
                at(&lines[0], "GPU TYPES"),
                "{lines:#?}"
            );
        }
        assert_eq!(
            at(&lines[2], "EUROPE"),
            at(&lines[0], "REGION"),
            "{lines:#?}"
        );
    }

    #[test]
    fn volume_and_template_tables_widen_their_name_columns() {
        let volume = |id: &str, name: &str| NetworkVolume {
            id: id.to_string(),
            name: name.to_string(),
            size: 50,
            data_center: "EU-RO-1".to_string(),
        };
        let lines = volume_table(&[volume("v1", LONG), volume("v2", "z")]);
        for line in &lines[1..] {
            assert_eq!(
                at(line, "EU-RO-1"),
                at(&lines[0], "DATA CENTER"),
                "{lines:#?}"
            );
        }
        let template = |id: &str, name: &str| Template {
            id: id.to_string(),
            name: name.to_string(),
            image: "img/a:1".to_string(),
            serverless: false,
        };
        let lines = template_table(&[template("t1", LONG), template("t2", "z")]);
        for line in &lines[1..] {
            assert_eq!(at(line, "img/"), at(&lines[0], "IMAGE"), "{lines:#?}");
        }
    }

    #[test]
    fn printable_strips_control_characters_and_escape_sequences() {
        assert_eq!(printable("A40\u{1b}[2J\nname"), "A40 name");
        assert_eq!(printable("a\nb\tc\r\nd  e"), "a b c  d  e", "no collapsing");
        assert_eq!(
            printable("a\u{1b}]0;title\u{7}b\u{1b}]8;;x\u{1b}\\c"),
            "abc"
        );
        assert_eq!(printable("a\u{1b}Mb\u{7f}c\u{9b}31md\te"), "abcd e");
        assert_eq!(
            printable("RTX 4090 é"),
            "RTX 4090 é",
            "printable text stays"
        );
    }

    #[test]
    fn string_controls_are_skipped_through_their_terminator() {
        for introducer in ['P', 'X', '^', '_'] {
            let st = format!("a\u{1b}{introducer}bad\u{1b}\\b");
            assert_eq!(printable(&st), "ab", "ESC {introducer}");
            let bel = format!("a\u{1b}{introducer}bad\u{7}b");
            assert_eq!(printable(&bel), "ab", "ESC {introducer} ended by BEL");
            let open = format!("a\u{1b}{introducer}bad and more");
            assert_eq!(printable(&open), "a", "ESC {introducer} unterminated");
        }
        for introducer in ['\u{90}', '\u{98}', '\u{9e}', '\u{9f}'] {
            let st = format!("a{introducer}bad\u{9c}b");
            assert_eq!(printable(&st), "ab", "{introducer:?}");
            let open = format!("a{introducer}bad and more");
            assert_eq!(printable(&open), "a", "{introducer:?} unterminated");
        }
    }

    #[test]
    fn every_table_prints_api_strings_without_control_characters() {
        let odd = "odd\u{1b}[2J\nname";
        let mut named = center("EU-RO-1", Vec::new());
        named.name = odd.to_string();
        let volume = NetworkVolume {
            id: "v1".to_string(),
            name: odd.to_string(),
            size: 50,
            data_center: "EU-RO-1".to_string(),
        };
        let template = Template {
            id: "t1".to_string(),
            name: odd.to_string(),
            image: "img\u{1b}[31m:1".to_string(),
            serverless: false,
        };
        let tables = [
            gpu_table(&[gpu(odd, 48, Some(0.4))], None),
            data_center_table(&[named]),
            volume_table(&[volume]),
            template_table(&[template]),
        ];
        for lines in tables {
            let text = lines.join("\n");
            assert!(text.contains("odd name"), "{text:?}");
            assert_eq!(lines.len(), 2, "{lines:?}");
            assert!(
                !text.chars().any(|c| c.is_control() && c != '\n'),
                "{text:?}"
            );
        }
    }

    #[test]
    fn a_gpu_id_from_the_api_reaches_a_resolve_error_clean() -> Result<(), serde_json::Error> {
        let gpus: Vec<GpuType> = serde_json::from_value(serde_json::json!([
            {"id": "odd\u{1b}[2J\ngpu", "memory": 48, "price": {"secure": 0.3},
             "maxCount": {"secure": 8}, "availability": "HIGH",
             "dataCenters": [{"id": "EU\u{1b}[31m-RO-1", "availability": "NONE"}]}
        ]))?;
        assert_eq!(gpus[0].id, "odd gpu", "cleaned when parsed");
        assert_eq!(gpus[0].data_centers[0].id, "EU-RO-1");
        let error = resolve(&target(list(&["odd gpu"]), ListOrAuto::Auto), &gpus)
            .err()
            .map(|error| error.to_string());
        assert_eq!(
            error.as_deref(),
            Some(
                "no data center has odd gpu in stock for data_center_ids = \"auto\" (gpu_count = 1)"
            )
        );
        Ok(())
    }

    fn out_of_stock(id: &str, memory: u32, price: f64) -> GpuType {
        GpuType {
            availability: Availability::None,
            ..gpu(id, memory, Some(price))
        }
    }

    fn strings(items: &[&str]) -> Vec<String> {
        items.iter().map(|item| (*item).to_string()).collect()
    }

    fn order(
        target: &RunpodTarget,
        gpus: &[GpuType],
        floor: Option<u32>,
        tried: &[&str],
        cap: usize,
    ) -> Result<(ListOrAuto, Vec<String>), ResolveError> {
        walk_order(target, gpus, floor, &strings(tried), cap)
            .map(|order| (order.target.gpu_types, order.out_of_stock))
    }

    #[test]
    fn cheaper_types_out_of_stock_come_first_cheapest_first_capped() {
        let gpus = [
            gpu("stocked", 24, Some(0.5)),
            gpu("dearer", 24, Some(0.9)),
            out_of_stock("same", 24, 0.5),
            out_of_stock("c", 24, 0.3),
            out_of_stock("a", 24, 0.1),
            out_of_stock("b", 24, 0.2),
            out_of_stock("d", 24, 0.4),
        ];
        let auto = target(ListOrAuto::Auto, ListOrAuto::default());
        assert_eq!(
            order(&auto, &gpus, None, &[], MAX_OUT_OF_STOCK),
            Ok((
                list(&["a", "b", "c", "stocked", "dearer"]),
                strings(&["a", "b", "c"])
            ))
        );
        // Tried types are left out, and the cap is what the walk has left.
        assert_eq!(
            order(&auto, &gpus, None, &["a", "stocked"], 1),
            Ok((list(&["b", "dearer"]), strings(&["b"])))
        );
        assert_eq!(
            order(&auto, &gpus, None, &[], 0),
            Ok((list(&["stocked", "dearer"]), Vec::new()))
        );
    }

    #[test]
    fn types_out_of_stock_keep_every_limit() {
        let mut single = out_of_stock("single", 80, 0.1);
        single.max_count.secure = 1;
        let mut community = out_of_stock("community", 80, 0.1);
        community.secure = Some(false);
        let gpus = [
            gpu("stocked", 48, Some(0.8)),
            single,
            community,
            out_of_stock("small", 16, 0.1),
            out_of_stock("over", 80, 0.7),
            out_of_stock("fits", 48, 0.2),
        ];
        let mut auto = target(ListOrAuto::Auto, ListOrAuto::default());
        auto.gpu_count = 2;
        auto.max_price_per_hour = Some(0.6);
        // "stocked" is over the price limit itself: nothing in stock.
        assert!(matches!(
            order(&auto, &gpus, Some(40), &[], 3),
            Err(ResolveError::NoGpuType { .. })
        ));
        auto.max_price_per_hour = Some(0.8);
        // Not "single" (one GPU per pod at most), "community" (not on Secure
        // Cloud) or "small" (under the floor).
        assert_eq!(
            order(&auto, &gpus, Some(40), &[], 3),
            Ok((
                list(&["fits", "over", "stocked"]),
                strings(&["fits", "over"])
            ))
        );
        auto.min_vram_gb = Some(60);
        // An explicit min_vram_gb wins over the floor: "stocked" is too small.
        assert!(order(&auto, &gpus, Some(10), &[], 3).is_err());
    }

    #[test]
    fn nothing_in_stock_or_nothing_left_untried_is_an_error() {
        let auto = target(ListOrAuto::Auto, ListOrAuto::default());
        let none = [out_of_stock("a", 24, 0.1)];
        assert_eq!(
            order(&auto, &none, None, &[], 3),
            Err(ResolveError::NoGpuType {
                asked: "gpu_count = 1".into()
            })
        );
        let gpus = [gpu("stocked", 24, Some(0.5)), out_of_stock("a", 24, 0.1)];
        assert!(matches!(
            order(&auto, &gpus, None, &["stocked"], 3),
            Err(ResolveError::NoGpuType { .. })
        ));
    }

    #[test]
    fn listed_data_centers_bound_the_types_out_of_stock() {
        let mut stocked = gpu("stocked", 24, Some(0.5));
        stocked.data_centers = vec![stock("EU-RO-1", Availability::Low)];
        let mut here = out_of_stock("here", 24, 0.1);
        here.data_centers = vec![stock("EU-RO-1", Availability::None)];
        let mut elsewhere = out_of_stock("elsewhere", 24, 0.1);
        elsewhere.data_centers = vec![stock("US-KS-2", Availability::None)];
        let unknown = out_of_stock("unknown", 24, 0.2);
        let gpus = [stocked, here, elsewhere, unknown];
        let listed = target(ListOrAuto::Auto, list(&["EU-RO-1"]));
        let walk = walk_order(&listed, &gpus, None, &[], 3);
        assert_eq!(
            walk.as_ref().map(|order| &order.target.gpu_types),
            Ok(&list(&["here", "unknown", "stocked"]))
        );
        assert_eq!(
            walk.map(|order| order.target.data_center_ids),
            Ok(list(&["EU-RO-1"]))
        );
    }

    #[test]
    fn auto_data_centers_come_from_the_untried_types_in_stock() {
        let mut cheap = gpu("cheap", 24, Some(0.3));
        cheap.data_centers = vec![stock("EU-RO-1", Availability::Low)];
        let mut dear = gpu("dear", 24, Some(0.6));
        dear.data_centers = vec![stock("US-KS-2", Availability::High)];
        let gpus = [cheap, dear, out_of_stock("out", 24, 0.1)];
        let auto = target(ListOrAuto::Auto, ListOrAuto::Auto);
        let centers = |tried: &[&str]| {
            walk_order(&auto, &gpus, None, &strings(tried), 3)
                .map(|order| order.target.data_center_ids)
        };
        assert_eq!(centers(&[]), Ok(list(&["EU-RO-1", "US-KS-2"])));
        assert_eq!(centers(&["cheap"]), Ok(list(&["US-KS-2"])));
    }

    #[test]
    fn listed_types_have_no_walk_order_of_their_own() {
        let gpus = [gpu("stocked", 24, Some(0.5)), out_of_stock("a", 24, 0.1)];
        let listed = target(list(&["x", "y"]), ListOrAuto::default());
        assert_eq!(
            order(&listed, &gpus, None, &["x"], 3),
            Ok((list(&["x", "y"]), Vec::new()))
        );
    }
}