skippy-runtime 0.76.1

Rust runtime layer for Skippy staged model execution
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
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
use std::{
    collections::BTreeMap,
    fs,
    io::Read,
    path::{Path, PathBuf},
    time::UNIX_EPOCH,
};

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::write_gguf_from_parts;

mod materialized_cache;

#[derive(Debug, Clone)]
pub struct PackageStageRequest {
    pub model_id: String,
    pub topology_id: String,
    pub package_ref: String,
    pub stage_id: String,
    pub layer_start: u32,
    pub layer_end: u32,
    pub include_embeddings: bool,
    pub include_output: bool,
}

#[derive(Debug, Clone)]
pub struct MaterializedPackage {
    pub output_path: PathBuf,
    pub manifest_sha256: String,
    pub selected_parts: Vec<PackagePart>,
}

#[derive(Debug, Clone)]
pub struct SelectedPackageParts {
    pub package_dir: PathBuf,
    pub manifest_sha256: String,
    pub selected_parts: Vec<PackagePart>,
    pub absolute_paths: Vec<PathBuf>,
    pub projector_paths: Vec<PathBuf>,
    pub integrity: PackageIntegrityReport,
}

#[derive(Debug, Clone)]
pub struct LayerPackageInfo {
    pub package_dir: PathBuf,
    pub manifest_sha256: String,
    pub model_id: String,
    pub source_model_path: String,
    pub source_model_sha256: String,
    pub source_model_bytes: Option<u64>,
    pub layer_count: u32,
    pub generation: Option<PackageGenerationInfo>,
    pub projectors: Vec<PackageProjectorInfo>,
    pub layers: Vec<LayerPackageLayerInfo>,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PackageGenerationInfo {
    pub speculative_decoding: Option<PackageSpeculativeDecodingInfo>,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PackageSpeculativeDecodingInfo {
    pub default: String,
    pub proposers: BTreeMap<String, PackageSpeculativeProposerInfo>,
    pub strategies: BTreeMap<String, PackageSpeculativeStrategyInfo>,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PackageSpeculativeProposerInfo {
    pub proposer_type: String,
    pub prediction_depth: Option<u32>,
    pub layer_indices: Vec<u32>,
    pub ngram_min: Option<u32>,
    pub ngram_max: Option<u32>,
    pub max_proposal_tokens: Option<u32>,
    pub history_scope: Option<String>,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PackageSpeculativeStrategyInfo {
    pub strategy_type: String,
    pub prediction_depth: Option<u32>,
    pub layer_indices: Vec<u32>,
    pub window_policy: Option<PackageWindowPolicyInfo>,
    pub proposer: Option<String>,
    pub primary: Option<String>,
    pub extender: Option<String>,
    pub extension_policy: Option<PackageExtensionPolicyInfo>,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PackageExtensionPolicyInfo {
    pub max_tokens: u32,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PackageWindowPolicyInfo {
    pub default: String,
    pub initial_window: u32,
    pub min_window: u32,
    pub max_window: u32,
    pub pipeline_depth: Option<u32>,
}

#[derive(Debug, Clone)]
pub struct PackageProjectorInfo {
    pub kind: String,
    pub path: PathBuf,
    pub artifact_bytes: u64,
}

#[derive(Debug, Clone)]
pub struct LayerPackageLayerInfo {
    pub layer_index: u32,
    pub tensor_count: usize,
    pub tensor_bytes: u64,
    pub artifact_bytes: u64,
}

#[derive(Debug, Clone)]
pub struct PackagePart {
    pub role: String,
    pub layer_index: Option<u32>,
    pub path: PathBuf,
    pub sha256: String,
    pub artifact_bytes: u64,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PackageIntegrityOptions {
    verify_sha256: bool,
    cache_dir: Option<PathBuf>,
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PackageIntegrityReport {
    pub manifest_sha256: String,
    pub artifacts: usize,
    pub verified_artifacts: usize,
    pub cached_artifacts: usize,
}

impl PackageIntegrityOptions {
    pub fn manifest_only() -> Self {
        Self {
            verify_sha256: false,
            cache_dir: None,
        }
    }

    pub fn verify_without_cache() -> Self {
        Self {
            verify_sha256: true,
            cache_dir: None,
        }
    }

    pub fn verify_with_cache(cache_dir: impl AsRef<Path>) -> Self {
        Self {
            verify_sha256: true,
            cache_dir: Some(cache_dir.as_ref().to_path_buf()),
        }
    }

    fn from_env() -> Self {
        let mut options = if env_flag("SKIPPY_VERIFY_PACKAGE_SHA") {
            Self::verify_without_cache()
        } else {
            Self::manifest_only()
        };
        if let Some(cache_dir) = std::env::var_os("SKIPPY_PACKAGE_VERIFY_CACHE_DIR") {
            options.cache_dir = Some(PathBuf::from(cache_dir));
        }
        options
    }
}

#[derive(Debug, Deserialize)]
struct PackageManifest {
    schema_version: u32,
    model_id: String,
    source_model: PackageSourceModel,
    format: String,
    layer_count: u32,
    #[serde(default)]
    generation: Option<PackageGeneration>,
    shared: PackageShared,
    #[serde(default)]
    projectors: Vec<PackageProjector>,
    layers: Vec<PackageLayer>,
    skippy_abi_version: String,
}

#[derive(Debug, Deserialize)]
struct PackageSourceModel {
    path: String,
    sha256: String,
    repo: Option<String>,
    revision: Option<String>,
    primary_file: Option<String>,
    canonical_ref: Option<String>,
    distribution_id: Option<String>,
    #[serde(default)]
    files: Vec<PackageSourceFile>,
}

#[derive(Debug, Deserialize)]
struct PackageSourceFile {
    path: String,
    size_bytes: Option<u64>,
    sha256: Option<String>,
}

#[derive(Debug, Deserialize)]
struct PackageShared {
    metadata: PackageArtifact,
    embeddings: PackageArtifact,
    output: PackageArtifact,
}

#[derive(Debug, Deserialize)]
struct PackageGeneration {
    #[serde(default)]
    speculative_decoding: Option<PackageSpeculativeDecoding>,
}

#[derive(Debug, Deserialize)]
struct PackageSpeculativeDecoding {
    default: String,
    #[serde(default)]
    proposers: BTreeMap<String, PackageSpeculativeProposer>,
    #[serde(default)]
    strategies: BTreeMap<String, PackageSpeculativeStrategy>,
}

#[derive(Debug, Deserialize)]
struct PackageSpeculativeProposer {
    #[serde(rename = "type")]
    proposer_type: String,
    #[serde(default)]
    prediction_depth: Option<u32>,
    #[serde(default)]
    layer_indices: Vec<u32>,
    #[serde(default)]
    ngram_min: Option<u32>,
    #[serde(default)]
    ngram_max: Option<u32>,
    #[serde(default)]
    max_proposal_tokens: Option<u32>,
    #[serde(default)]
    history_scope: Option<String>,
}

#[derive(Debug, Deserialize)]
struct PackageSpeculativeStrategy {
    #[serde(rename = "type")]
    strategy_type: String,
    #[serde(default)]
    prediction_depth: Option<u32>,
    #[serde(default)]
    layer_indices: Vec<u32>,
    #[serde(default)]
    window_policy: Option<PackageWindowPolicy>,
    #[serde(default)]
    proposer: Option<String>,
    #[serde(default)]
    primary: Option<String>,
    #[serde(default)]
    extender: Option<String>,
    #[serde(default)]
    extension_policy: Option<PackageExtensionPolicy>,
}

#[derive(Debug, Deserialize)]
struct PackageExtensionPolicy {
    max_tokens: u32,
}

#[derive(Debug, Deserialize)]
struct PackageWindowPolicy {
    default: String,
    initial_window: u32,
    min_window: u32,
    max_window: u32,
    #[serde(default)]
    pipeline_depth: Option<u32>,
}

#[derive(Debug, Deserialize)]
struct PackageArtifact {
    path: String,
    tensor_count: usize,
    tensor_bytes: u64,
    artifact_bytes: u64,
    sha256: String,
}

#[derive(Debug, Deserialize)]
struct PackageProjector {
    kind: String,
    path: String,
    tensor_count: usize,
    tensor_bytes: u64,
    artifact_bytes: u64,
    sha256: String,
}

#[derive(Debug, Deserialize)]
struct PackageLayer {
    layer_index: u32,
    path: String,
    tensor_count: usize,
    tensor_bytes: u64,
    artifact_bytes: u64,
    sha256: String,
}

pub fn materialize_layer_package(request: &PackageStageRequest) -> Result<PathBuf> {
    Ok(materialize_layer_package_details(request)?.output_path)
}

pub fn materialized_layer_package_cache_record_path(output: &Path) -> PathBuf {
    materialized_cache::record_path(output)
}

pub fn materialize_layer_package_details(
    request: &PackageStageRequest,
) -> Result<MaterializedPackage> {
    let selection = select_layer_package_parts(request)?;
    let output = materialized_path(
        request,
        &selection.package_dir,
        &selection.manifest_sha256,
        &selection.selected_parts,
    );
    let cache_identity = materialized_cache::MaterializedCacheIdentity::new(
        request,
        &selection.manifest_sha256,
        &selection.selected_parts,
    );
    let force_materialize = env_flag("SKIPPY_FORCE_MATERIALIZE");
    if !force_materialize
        && materialized_cache::record_matches_output(&output, &cache_identity)?
        && crate::ModelInfo::open(&output).is_ok()
    {
        return Ok(MaterializedPackage {
            output_path: output,
            manifest_sha256: selection.manifest_sha256,
            selected_parts: selection.selected_parts,
        });
    }

    let _lock = materialized_cache::lock_output(&output)?;
    if !force_materialize
        && materialized_cache::record_matches_output(&output, &cache_identity)?
        && crate::ModelInfo::open(&output).is_ok()
    {
        return Ok(MaterializedPackage {
            output_path: output,
            manifest_sha256: selection.manifest_sha256,
            selected_parts: selection.selected_parts,
        });
    }

    let tmp_output = materialized_cache::temporary_output_path(&output, &selection.manifest_sha256);
    if let Some(parent) = tmp_output.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("create materialization staging {}", parent.display()))?;
    }
    if let Err(error) =
        write_gguf_from_parts(&selection.absolute_paths, &tmp_output).with_context(|| {
            format!(
                "materialize layer package {}",
                selection.package_dir.display()
            )
        })
    {
        materialized_cache::cleanup_temporary_output(&tmp_output);
        return Err(error);
    }
    if let Err(error) = crate::ModelInfo::open(&tmp_output)
        .with_context(|| format!("validate materialized model {}", tmp_output.display()))
    {
        materialized_cache::cleanup_temporary_output(&tmp_output);
        return Err(error);
    }
    materialized_cache::publish_output(&tmp_output, &output)?;
    materialized_cache::write_record(&output, &cache_identity)?;

    Ok(MaterializedPackage {
        output_path: output,
        manifest_sha256: selection.manifest_sha256,
        selected_parts: selection.selected_parts,
    })
}

pub fn select_layer_package_parts(request: &PackageStageRequest) -> Result<SelectedPackageParts> {
    select_layer_package_parts_with_integrity(request, &PackageIntegrityOptions::from_env())
}

pub fn select_layer_package_parts_with_integrity(
    request: &PackageStageRequest,
    integrity_options: &PackageIntegrityOptions,
) -> Result<SelectedPackageParts> {
    let package_dir = resolve_package_dir(&request.package_ref)?;
    let manifest_path = package_dir.join("model-package.json");
    let manifest_contents = fs::read(&manifest_path)
        .with_context(|| format!("read package manifest {}", manifest_path.display()))?;
    let manifest_sha256 = sha256_bytes(&manifest_contents);
    let manifest = load_manifest(&manifest_path, &manifest_contents)?;
    validate_manifest(&manifest, request)?;

    let layer_by_index = manifest
        .layers
        .iter()
        .map(|layer| {
            (
                layer.layer_index,
                PackageArtifact {
                    path: layer.path.clone(),
                    tensor_count: layer.tensor_count,
                    tensor_bytes: layer.tensor_bytes,
                    artifact_bytes: layer.artifact_bytes,
                    sha256: layer.sha256.clone(),
                },
            )
        })
        .collect::<BTreeMap<_, _>>();

    let mut parts = Vec::new();
    push_part(
        &mut parts,
        "metadata",
        None,
        &manifest.shared.metadata,
        &package_dir,
    )?;
    if request.include_embeddings {
        push_part(
            &mut parts,
            "embeddings",
            None,
            &manifest.shared.embeddings,
            &package_dir,
        )?;
    }
    for layer_index in request.layer_start..request.layer_end {
        let artifact = layer_by_index
            .get(&layer_index)
            .with_context(|| format!("package is missing layer {layer_index}"))?;
        push_part(
            &mut parts,
            "layer",
            Some(layer_index),
            artifact,
            &package_dir,
        )?;
    }
    if request.include_output {
        push_part(
            &mut parts,
            "output",
            None,
            &manifest.shared.output,
            &package_dir,
        )?;
    }

    let absolute_paths = parts
        .iter()
        .map(|part| package_dir.join(&part.path))
        .collect::<Vec<_>>();
    let projector_paths = manifest
        .projectors
        .iter()
        .map(|projector| projector_path(projector, &package_dir))
        .collect::<Result<Vec<_>>>()?;
    let integrity = verify_package_artifacts(
        &package_dir,
        &manifest_sha256,
        &parts,
        &manifest.projectors,
        integrity_options,
    )?;

    Ok(SelectedPackageParts {
        package_dir,
        manifest_sha256,
        selected_parts: parts,
        absolute_paths,
        projector_paths,
        integrity,
    })
}

pub fn verify_layer_package_integrity(
    request: &PackageStageRequest,
    integrity_options: &PackageIntegrityOptions,
) -> Result<PackageIntegrityReport> {
    Ok(select_layer_package_parts_with_integrity(request, integrity_options)?.integrity)
}

pub fn verify_layer_package_metadata_integrity(
    package_ref: &str,
    integrity_options: &PackageIntegrityOptions,
) -> Result<PackageIntegrityReport> {
    let package_dir = resolve_package_dir(package_ref)?;
    let manifest_path = package_dir.join("model-package.json");
    let manifest_contents = fs::read(&manifest_path)
        .with_context(|| format!("read package manifest {}", manifest_path.display()))?;
    let manifest_sha256 = sha256_bytes(&manifest_contents);
    let manifest = load_manifest(&manifest_path, &manifest_contents)?;
    validate_manifest_identity(&manifest)?;
    validate_layer_manifest(&manifest)?;

    let mut parts = Vec::new();
    push_part(
        &mut parts,
        "metadata",
        None,
        &manifest.shared.metadata,
        &package_dir,
    )?;
    verify_package_artifacts(
        &package_dir,
        &manifest_sha256,
        &parts,
        &[],
        integrity_options,
    )
}

pub fn inspect_layer_package(package_ref: &str) -> Result<LayerPackageInfo> {
    let package_dir = resolve_package_dir(package_ref)?;
    let manifest_path = package_dir.join("model-package.json");
    let manifest_contents = fs::read(&manifest_path)
        .with_context(|| format!("read package manifest {}", manifest_path.display()))?;
    let manifest_sha256 = sha256_bytes(&manifest_contents);
    let manifest = load_manifest(&manifest_path, &manifest_contents)?;
    validate_manifest_identity(&manifest)?;
    validate_layer_manifest(&manifest)?;
    let projectors = manifest
        .projectors
        .into_iter()
        .map(|projector| {
            let path = safe_relative_manifest_path(&projector.path)?;
            Ok(PackageProjectorInfo {
                kind: projector.kind,
                path: package_dir.join(path),
                artifact_bytes: projector.artifact_bytes,
            })
        })
        .collect::<Result<Vec<_>>>()?;
    Ok(LayerPackageInfo {
        package_dir,
        manifest_sha256,
        model_id: manifest.model_id,
        source_model_path: manifest.source_model.path,
        source_model_sha256: manifest.source_model.sha256,
        source_model_bytes: (!manifest.source_model.files.is_empty())
            .then(|| {
                manifest
                    .source_model
                    .files
                    .iter()
                    .try_fold(0u64, |total, file| {
                        file.size_bytes
                            .map(|bytes| total.saturating_add(bytes))
                            .ok_or(())
                    })
                    .ok()
            })
            .flatten(),
        layer_count: manifest.layer_count,
        generation: manifest.generation.map(package_generation_info),
        projectors,
        layers: manifest
            .layers
            .into_iter()
            .map(|layer| LayerPackageLayerInfo {
                layer_index: layer.layer_index,
                tensor_count: layer.tensor_count,
                tensor_bytes: layer.tensor_bytes,
                artifact_bytes: layer.artifact_bytes,
            })
            .collect(),
    })
}

fn package_generation_info(generation: PackageGeneration) -> PackageGenerationInfo {
    PackageGenerationInfo {
        speculative_decoding: generation
            .speculative_decoding
            .map(package_speculative_decoding_info),
    }
}

fn package_speculative_decoding_info(
    speculative: PackageSpeculativeDecoding,
) -> PackageSpeculativeDecodingInfo {
    PackageSpeculativeDecodingInfo {
        default: speculative.default,
        proposers: speculative
            .proposers
            .into_iter()
            .map(|(name, proposer)| (name, package_speculative_proposer_info(proposer)))
            .collect(),
        strategies: speculative
            .strategies
            .into_iter()
            .map(|(name, strategy)| (name, package_speculative_strategy_info(strategy)))
            .collect(),
    }
}

fn package_speculative_proposer_info(
    proposer: PackageSpeculativeProposer,
) -> PackageSpeculativeProposerInfo {
    PackageSpeculativeProposerInfo {
        proposer_type: proposer.proposer_type,
        prediction_depth: proposer.prediction_depth,
        layer_indices: proposer.layer_indices,
        ngram_min: proposer.ngram_min,
        ngram_max: proposer.ngram_max,
        max_proposal_tokens: proposer.max_proposal_tokens,
        history_scope: proposer.history_scope,
    }
}

fn package_speculative_strategy_info(
    strategy: PackageSpeculativeStrategy,
) -> PackageSpeculativeStrategyInfo {
    PackageSpeculativeStrategyInfo {
        strategy_type: strategy.strategy_type,
        prediction_depth: strategy.prediction_depth,
        layer_indices: strategy.layer_indices,
        window_policy: strategy
            .window_policy
            .map(|window| PackageWindowPolicyInfo {
                default: window.default,
                initial_window: window.initial_window,
                min_window: window.min_window,
                max_window: window.max_window,
                pipeline_depth: window.pipeline_depth,
            }),
        proposer: strategy.proposer,
        primary: strategy.primary,
        extender: strategy.extender,
        extension_policy: strategy
            .extension_policy
            .map(|policy| PackageExtensionPolicyInfo {
                max_tokens: policy.max_tokens,
            }),
    }
}

pub fn is_hf_package_ref(value: &str) -> bool {
    value.starts_with("hf://")
}

fn resolve_package_dir(package_ref: &str) -> Result<PathBuf> {
    if is_hf_package_ref(package_ref) {
        bail!(
            "hf:// package refs must be resolved to a local path before calling skippy-runtime. \
             Use the mesh-llm layer package resolver to download first. Got: {package_ref}"
        );
    }
    Ok(PathBuf::from(package_ref))
}

#[cfg(test)]
#[derive(Debug, PartialEq, Eq)]
struct HfPackageRef {
    repo_id: String,
    revision: Option<String>,
}

#[cfg(test)]
fn parse_hf_package_ref(value: &str) -> Result<HfPackageRef> {
    let Some(rest) = value.strip_prefix("hf://") else {
        bail!("HF package references must start with hf://");
    };
    if rest.is_empty() {
        bail!("HF package reference is missing a repo id");
    }

    let (repo_id, revision) = if let Some((repo_id, revision)) = rest.split_once('@') {
        (repo_id, Some(revision))
    } else if let Some(index) = rest.rfind(':') {
        (&rest[..index], Some(&rest[index + 1..]))
    } else {
        (rest, None)
    };

    if repo_id.split('/').count() != 2 || repo_id.contains(':') || repo_id.contains('@') {
        bail!("HF package repo id must look like namespace/repo");
    }
    if let Some(revision) = revision
        && revision.is_empty()
    {
        bail!("HF package revision is empty");
    }

    Ok(HfPackageRef {
        repo_id: repo_id.to_string(),
        revision: revision.map(ToString::to_string),
    })
}

fn load_manifest(path: &Path, contents: &[u8]) -> Result<PackageManifest> {
    serde_json::from_slice(contents)
        .with_context(|| format!("parse package manifest {}", path.display()))
}

fn validate_manifest(manifest: &PackageManifest, request: &PackageStageRequest) -> Result<()> {
    validate_manifest_identity(manifest)?;
    let layer_counts = validate_layer_manifest(manifest)?;
    if request.layer_start >= request.layer_end {
        bail!("stage layer_start must be less than layer_end");
    }
    if request.layer_end > manifest.layer_count {
        bail!(
            "stage layer_end {} exceeds package layer_count {}",
            request.layer_end,
            manifest.layer_count
        );
    }

    for layer_index in request.layer_start..request.layer_end {
        if !layer_counts.contains_key(&layer_index) {
            bail!("package is missing layer {layer_index}");
        }
    }
    Ok(())
}

fn validate_layer_manifest(manifest: &PackageManifest) -> Result<BTreeMap<u32, usize>> {
    let mut layer_counts = BTreeMap::<u32, usize>::new();
    for layer in &manifest.layers {
        *layer_counts.entry(layer.layer_index).or_default() += 1;
        if layer.layer_index >= manifest.layer_count {
            bail!(
                "package layer index {} exceeds layer_count {}",
                layer.layer_index,
                manifest.layer_count
            );
        }
        validate_artifact_manifest(
            &format!("layer {}", layer.layer_index),
            &PackageArtifact {
                path: layer.path.clone(),
                tensor_count: layer.tensor_count,
                tensor_bytes: layer.tensor_bytes,
                artifact_bytes: layer.artifact_bytes,
                sha256: layer.sha256.clone(),
            },
        )?;
    }
    let duplicates = layer_counts
        .iter()
        .filter_map(|(layer, count)| (*count > 1).then_some(*layer))
        .collect::<Vec<_>>();
    if !duplicates.is_empty() {
        bail!("package manifest contains duplicate layers: {duplicates:?}");
    }
    Ok(layer_counts)
}

fn validate_manifest_identity(manifest: &PackageManifest) -> Result<()> {
    if manifest.schema_version != 1 {
        bail!(
            "unsupported package manifest schema_version {}",
            manifest.schema_version
        );
    }
    if manifest.format != "layer-package" {
        bail!("package manifest format must be layer-package");
    }
    if !abi_version_supported(&manifest.skippy_abi_version)? {
        bail!(
            "package ABI version {} is not compatible with runtime ABI {}.{}.{}",
            manifest.skippy_abi_version,
            skippy_ffi::ABI_VERSION_MAJOR,
            skippy_ffi::ABI_VERSION_MINOR,
            skippy_ffi::ABI_VERSION_PATCH
        );
    }
    if manifest.model_id.trim().is_empty() {
        bail!("package manifest model_id must not be empty");
    }
    if manifest.source_model.path.trim().is_empty()
        || manifest
            .source_model
            .repo
            .as_deref()
            .is_some_and(|repo| repo.trim().is_empty())
        || manifest
            .source_model
            .revision
            .as_deref()
            .is_some_and(|revision| revision.trim().is_empty())
        || manifest
            .source_model
            .primary_file
            .as_deref()
            .is_some_and(|primary_file| primary_file.trim().is_empty())
        || manifest
            .source_model
            .canonical_ref
            .as_deref()
            .is_some_and(|canonical_ref| canonical_ref.trim().is_empty())
        || manifest
            .source_model
            .distribution_id
            .as_deref()
            .is_some_and(|distribution_id| distribution_id.trim().is_empty())
    {
        bail!("package manifest source_model identity fields must not be empty");
    }
    validate_sha256_digest("source_model sha256", &manifest.source_model.sha256)?;
    for file in &manifest.source_model.files {
        if file.path.trim().is_empty()
            || file
                .sha256
                .as_deref()
                .is_some_and(|sha256| sha256.trim().is_empty())
        {
            bail!("package manifest source_model files must not contain empty path or sha256");
        }
        if let Some(sha256) = &file.sha256 {
            validate_sha256_digest("source_model file sha256", sha256)?;
        }
        let _ = file.size_bytes;
    }
    validate_artifact_manifest("metadata", &manifest.shared.metadata)?;
    validate_artifact_manifest("embeddings", &manifest.shared.embeddings)?;
    validate_artifact_manifest("output", &manifest.shared.output)?;
    for projector in &manifest.projectors {
        validate_projector_manifest(projector)?;
    }
    Ok(())
}

fn validate_artifact_manifest(role: &str, artifact: &PackageArtifact) -> Result<()> {
    if artifact.path.trim().is_empty() {
        bail!("package {role} artifact path must not be empty");
    }
    let _ = safe_relative_manifest_path(&artifact.path)
        .with_context(|| format!("package {role} artifact path must be a safe relative path"))?;
    validate_sha256_digest(&format!("package {role} artifact sha256"), &artifact.sha256)?;
    if artifact.artifact_bytes == 0 {
        bail!("package {role} artifact_bytes must be greater than zero");
    }
    if artifact.tensor_count == 0 && artifact.tensor_bytes > 0 {
        bail!("package {role} tensor_bytes must be zero when tensor_count is zero");
    }
    if artifact.tensor_count > 0 && artifact.tensor_bytes == 0 {
        bail!("package {role} tensor_bytes must be greater than zero when tensors are present");
    }
    Ok(())
}

fn validate_projector_manifest(projector: &PackageProjector) -> Result<()> {
    if projector.kind.trim().is_empty() {
        bail!("package projector kind must not be empty");
    }
    if projector.kind != "mmproj" {
        bail!("unsupported package projector kind {}", projector.kind);
    }
    validate_artifact_manifest(
        &format!("{} projector", projector.kind),
        &PackageArtifact {
            path: projector.path.clone(),
            tensor_count: projector.tensor_count,
            tensor_bytes: projector.tensor_bytes,
            artifact_bytes: projector.artifact_bytes,
            sha256: projector.sha256.clone(),
        },
    )
}

fn push_part(
    parts: &mut Vec<PackagePart>,
    role: &str,
    layer_index: Option<u32>,
    artifact: &PackageArtifact,
    package_dir: &Path,
) -> Result<()> {
    let path = safe_relative_manifest_path(&artifact.path)?;
    let absolute = package_dir.join(&path);
    let metadata = fs::metadata(&absolute)
        .with_context(|| format!("read package part metadata {}", path.display()))?;
    if !metadata.is_file() {
        bail!("package part is not a file: {}", path.display());
    }
    if metadata.len() != artifact.artifact_bytes {
        bail!(
            "package part size mismatch for {}: expected {}, got {}",
            path.display(),
            artifact.artifact_bytes,
            metadata.len()
        );
    }
    parts.push(PackagePart {
        role: role.to_string(),
        layer_index,
        path,
        sha256: artifact.sha256.to_ascii_lowercase(),
        artifact_bytes: artifact.artifact_bytes,
    });
    Ok(())
}

fn projector_path(projector: &PackageProjector, package_dir: &Path) -> Result<PathBuf> {
    let path = safe_relative_manifest_path(&projector.path)?;
    let absolute = package_dir.join(&path);
    let metadata = fs::metadata(&absolute)
        .with_context(|| format!("read package projector metadata {}", path.display()))?;
    if !metadata.is_file() {
        bail!("package projector is not a file: {}", path.display());
    }
    if metadata.len() != projector.artifact_bytes {
        bail!(
            "package projector size mismatch for {}: expected {}, got {}",
            path.display(),
            projector.artifact_bytes,
            metadata.len()
        );
    }
    Ok(absolute)
}

#[derive(Debug)]
struct ArtifactVerification<'a> {
    role: &'a str,
    layer_index: Option<u32>,
    path: PathBuf,
    sha256: String,
    artifact_bytes: u64,
}

#[derive(Debug, Deserialize, Serialize)]
struct IntegrityCacheRecord {
    schema_version: u32,
    manifest_sha256: String,
    artifact_sha256: String,
    artifact_bytes: u64,
    file_len: u64,
    modified_unix_nanos: Option<u128>,
}

fn verify_package_artifacts(
    package_dir: &Path,
    manifest_sha256: &str,
    parts: &[PackagePart],
    projectors: &[PackageProjector],
    options: &PackageIntegrityOptions,
) -> Result<PackageIntegrityReport> {
    let artifacts = parts
        .iter()
        .map(|part| ArtifactVerification {
            role: &part.role,
            layer_index: part.layer_index,
            path: part.path.clone(),
            sha256: part.sha256.clone(),
            artifact_bytes: part.artifact_bytes,
        })
        .chain(projectors.iter().map(|projector| ArtifactVerification {
            role: "projector",
            layer_index: None,
            path: PathBuf::from(&projector.path),
            sha256: projector.sha256.to_ascii_lowercase(),
            artifact_bytes: projector.artifact_bytes,
        }))
        .collect::<Vec<_>>();

    let mut report = PackageIntegrityReport {
        manifest_sha256: manifest_sha256.to_string(),
        artifacts: artifacts.len(),
        verified_artifacts: 0,
        cached_artifacts: 0,
    };

    if !options.verify_sha256 {
        return Ok(report);
    }

    for artifact in artifacts {
        let relative_path = safe_relative_manifest_path(&artifact.path)?;
        let absolute = package_dir.join(&relative_path);
        let metadata = fs::metadata(&absolute).with_context(|| {
            format!("read package artifact metadata {}", relative_path.display())
        })?;
        let fingerprint = file_fingerprint(&metadata);
        if let Some(cache_dir) = &options.cache_dir
            && integrity_cache_hit(
                cache_dir,
                manifest_sha256,
                &artifact,
                metadata.len(),
                fingerprint,
            )?
        {
            report.cached_artifacts += 1;
            continue;
        }

        let actual = file_sha256(&absolute)?;
        if actual != artifact.sha256 {
            bail!(
                "package artifact checksum mismatch for {}: expected {}, got {}",
                relative_path.display(),
                artifact.sha256,
                actual
            );
        }
        report.verified_artifacts += 1;
        if let Some(cache_dir) = &options.cache_dir {
            write_integrity_cache_record(
                cache_dir,
                manifest_sha256,
                &artifact,
                metadata.len(),
                fingerprint,
            )?;
        }
    }

    Ok(report)
}

fn integrity_cache_hit(
    cache_dir: &Path,
    manifest_sha256: &str,
    artifact: &ArtifactVerification<'_>,
    file_len: u64,
    modified_unix_nanos: Option<u128>,
) -> Result<bool> {
    let path = integrity_cache_path(cache_dir, manifest_sha256, artifact);
    let Ok(bytes) = fs::read(&path) else {
        return Ok(false);
    };
    let Ok(record) = serde_json::from_slice::<IntegrityCacheRecord>(&bytes) else {
        return Ok(false);
    };
    Ok(record.schema_version == 1
        && record.manifest_sha256 == manifest_sha256
        && record.artifact_sha256 == artifact.sha256
        && record.artifact_bytes == artifact.artifact_bytes
        && record.file_len == file_len
        && record.modified_unix_nanos == modified_unix_nanos)
}

fn write_integrity_cache_record(
    cache_dir: &Path,
    manifest_sha256: &str,
    artifact: &ArtifactVerification<'_>,
    file_len: u64,
    modified_unix_nanos: Option<u128>,
) -> Result<()> {
    fs::create_dir_all(cache_dir)
        .with_context(|| format!("create package integrity cache {}", cache_dir.display()))?;
    let record = IntegrityCacheRecord {
        schema_version: 1,
        manifest_sha256: manifest_sha256.to_string(),
        artifact_sha256: artifact.sha256.clone(),
        artifact_bytes: artifact.artifact_bytes,
        file_len,
        modified_unix_nanos,
    };
    fs::write(
        integrity_cache_path(cache_dir, manifest_sha256, artifact),
        serde_json::to_vec_pretty(&record)?,
    )
    .with_context(|| format!("write package integrity cache {}", cache_dir.display()))
}

fn integrity_cache_path(
    cache_dir: &Path,
    manifest_sha256: &str,
    artifact: &ArtifactVerification<'_>,
) -> PathBuf {
    let mut hasher = Sha256::new();
    hasher.update(b"skippy-package-integrity-cache-v1\0");
    hasher.update(manifest_sha256.as_bytes());
    hasher.update(b"\0");
    hasher.update(artifact.role.as_bytes());
    hasher.update(b"\0");
    hasher.update(artifact.layer_index.unwrap_or(u32::MAX).to_le_bytes());
    hasher.update(b"\0");
    hasher.update(artifact.path.to_string_lossy().as_bytes());
    hasher.update(b"\0");
    hasher.update(artifact.sha256.as_bytes());
    hasher.update(b"\0");
    hasher.update(artifact.artifact_bytes.to_le_bytes());
    cache_dir.join(format!("{}.json", hex_lower(&hasher.finalize())))
}

fn file_fingerprint(metadata: &fs::Metadata) -> Option<u128> {
    metadata
        .modified()
        .ok()
        .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
        .map(|duration| duration.as_nanos())
}

fn safe_relative_manifest_path(path: impl AsRef<Path>) -> Result<PathBuf> {
    let path = path.as_ref();
    let mut components = path.components();
    let Some(first) = components.next() else {
        bail!("manifest file path is empty");
    };
    anyhow::ensure!(
        matches!(first, std::path::Component::Normal(_))
            && components.all(|component| matches!(component, std::path::Component::Normal(_))),
        "manifest file path must be a safe relative path: {}",
        path.display()
    );
    Ok(path.to_path_buf())
}

fn validate_sha256_digest(label: &str, value: &str) -> Result<()> {
    if value.len() != 64 || !value.chars().all(|ch| ch.is_ascii_hexdigit()) {
        bail!("{label} must be a hex SHA-256 digest");
    }
    Ok(())
}

fn materialized_path(
    request: &PackageStageRequest,
    package_dir: &Path,
    manifest_sha256: &str,
    parts: &[PackagePart],
) -> PathBuf {
    let root = std::env::var_os("SKIPPY_MATERIALIZED_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|| std::env::temp_dir().join("skippy-runtime/materialized"));
    let stable_package_dir = fs::canonicalize(package_dir).unwrap_or_else(|_| package_dir.into());
    let mut hasher = Sha256::new();
    hasher.update(stable_package_dir.to_string_lossy().as_bytes());
    hasher.update(b"\0");
    hasher.update(request.model_id.as_bytes());
    hasher.update(b"\0");
    hasher.update(request.topology_id.as_bytes());
    hasher.update(b"\0");
    hasher.update(request.stage_id.as_bytes());
    hasher.update(b"\0");
    hasher.update(request.layer_start.to_le_bytes());
    hasher.update(request.layer_end.to_le_bytes());
    hasher.update([
        u8::from(request.include_embeddings),
        u8::from(request.include_output),
    ]);
    hasher.update(manifest_sha256.as_bytes());
    for part in parts {
        hasher.update(b"\0");
        hasher.update(part.role.as_bytes());
        hasher.update(b"\0");
        hasher.update(part.layer_index.unwrap_or(u32::MAX).to_le_bytes());
        hasher.update(part.path.to_string_lossy().as_bytes());
        hasher.update(b"\0");
        hasher.update(part.sha256.as_bytes());
    }
    let digest = hex_lower(&hasher.finalize());
    let cache_key = &digest[..24];
    root.join(format!(
        "{}-{}-{}-{}-{}.gguf",
        sanitize(&request.model_id),
        sanitize(&request.stage_id),
        request.layer_start,
        request.layer_end,
        cache_key
    ))
}

fn abi_version_supported(version: &str) -> Result<bool> {
    let mut parts = version.split('.');
    let major = parts
        .next()
        .context("package ABI version is missing a major version")?
        .parse::<u32>()
        .context("parse package ABI major version")?;
    let minor = parts
        .next()
        .context("package ABI version is missing a minor version")?
        .parse::<u32>()
        .context("parse package ABI minor version")?;
    let _patch = parts
        .next()
        .unwrap_or("0")
        .parse::<u32>()
        .context("parse package ABI patch version")?;
    Ok(major == skippy_ffi::ABI_VERSION_MAJOR && minor <= skippy_ffi::ABI_VERSION_MINOR)
}

fn env_flag(name: &str) -> bool {
    std::env::var_os(name).is_some_and(|value| {
        let value = value.to_string_lossy();
        value != "0" && !value.eq_ignore_ascii_case("false")
    })
}

fn file_sha256(path: &Path) -> Result<String> {
    let mut file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?;
    let mut hasher = Sha256::new();
    let mut buffer = [0_u8; 1024 * 1024];
    loop {
        let read = file
            .read(&mut buffer)
            .with_context(|| format!("read {}", path.display()))?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    Ok(hex_lower(&hasher.finalize()))
}

fn sha256_bytes(bytes: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    hex_lower(&hasher.finalize())
}

fn hex_lower(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut output = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        output.push(HEX[(byte >> 4) as usize] as char);
        output.push(HEX[(byte & 0x0f) as usize] as char);
    }
    output
}

fn sanitize(value: &str) -> String {
    value
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
                ch
            } else {
                '_'
            }
        })
        .collect()
}

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

    fn write_package_fixture(dir: &Path) -> serde_json::Value {
        fs::create_dir_all(dir.join("layers")).unwrap();
        fs::create_dir_all(dir.join("projectors")).unwrap();
        fs::write(dir.join("metadata.gguf"), b"metadata").unwrap();
        fs::write(dir.join("embeddings.gguf"), b"embeddings").unwrap();
        fs::write(dir.join("output.gguf"), b"output").unwrap();
        fs::write(dir.join("layers/00000.gguf"), b"layer0").unwrap();
        fs::write(dir.join("projectors/mmproj.gguf"), b"projector").unwrap();
        let manifest = serde_json::json!({
            "schema_version": 1,
            "model_id": "model-a",
            "source_model": {
                "path": "model-a.gguf",
                "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "files": [
                    {
                        "path": "model-a.gguf",
                        "size_bytes": 123,
                        "sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                    }
                ]
            },
            "format": "layer-package",
            "layer_count": 1,
            "shared": {
                "metadata": {
                    "path": "metadata.gguf",
                    "tensor_count": 1,
                    "tensor_bytes": 1,
                    "artifact_bytes": 8,
                    "sha256": sha256_bytes(b"metadata")
                },
                "embeddings": {
                    "path": "embeddings.gguf",
                    "tensor_count": 1,
                    "tensor_bytes": 1,
                    "artifact_bytes": 10,
                    "sha256": sha256_bytes(b"embeddings")
                },
                "output": {
                    "path": "output.gguf",
                    "tensor_count": 1,
                    "tensor_bytes": 1,
                    "artifact_bytes": 6,
                    "sha256": sha256_bytes(b"output")
                }
            },
            "projectors": [
                {
                    "kind": "mmproj",
                    "path": "projectors/mmproj.gguf",
                    "tensor_count": 1,
                    "tensor_bytes": 1,
                    "artifact_bytes": 9,
                    "sha256": sha256_bytes(b"projector")
                }
            ],
            "layers": [
                {
                    "layer_index": 0,
                    "path": "layers/00000.gguf",
                    "tensor_count": 1,
                    "tensor_bytes": 1,
                    "artifact_bytes": 6,
                    "sha256": sha256_bytes(b"layer0")
                }
            ],
            "skippy_abi_version": format!(
                "{}.{}.{}",
                skippy_ffi::ABI_VERSION_MAJOR,
                skippy_ffi::ABI_VERSION_MINOR,
                skippy_ffi::ABI_VERSION_PATCH
            ),
        });
        fs::write(
            dir.join("model-package.json"),
            serde_json::to_vec_pretty(&manifest).unwrap(),
        )
        .unwrap();
        manifest
    }

    fn package_stage_request(package_ref: &Path) -> PackageStageRequest {
        PackageStageRequest {
            model_id: "model-a".to_string(),
            topology_id: "topology-a".to_string(),
            package_ref: package_ref.to_string_lossy().to_string(),
            stage_id: "stage-0".to_string(),
            layer_start: 0,
            layer_end: 1,
            include_embeddings: true,
            include_output: true,
        }
    }

    fn materialized_cache_parts() -> Vec<PackagePart> {
        vec![
            PackagePart {
                role: "metadata".to_string(),
                layer_index: None,
                path: PathBuf::from("metadata.gguf"),
                sha256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                    .to_string(),
                artifact_bytes: 8,
            },
            PackagePart {
                role: "layer".to_string(),
                layer_index: Some(0),
                path: PathBuf::from("layers/00000.gguf"),
                sha256: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
                    .to_string(),
                artifact_bytes: 6,
            },
        ]
    }

    #[test]
    fn materialized_cache_record_requires_matching_identity_and_output_metadata() {
        let dir = tempfile::tempdir().unwrap();
        let package_dir = dir.path().join("package");
        fs::create_dir_all(&package_dir).unwrap();
        let request = package_stage_request(&package_dir);
        let parts = materialized_cache_parts();
        let manifest_sha = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";
        let output = dir.path().join("stage.gguf");
        fs::write(&output, b"materialized-output").unwrap();
        let identity =
            materialized_cache::MaterializedCacheIdentity::new(&request, manifest_sha, &parts);

        assert!(
            !materialized_cache::record_matches_output(&output, &identity).unwrap(),
            "a final artifact without a provenance record must not be a cache hit"
        );

        materialized_cache::write_record(&output, &identity).unwrap();
        assert!(materialized_cache::record_matches_output(&output, &identity).unwrap());

        let mut changed_parts = parts.clone();
        changed_parts[1].sha256 =
            "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd".to_string();
        let changed_identity = materialized_cache::MaterializedCacheIdentity::new(
            &request,
            manifest_sha,
            &changed_parts,
        );
        assert!(
            !materialized_cache::record_matches_output(&output, &changed_identity).unwrap(),
            "selected artifact identity must be part of the cache hit contract"
        );

        fs::write(&output, b"materialized-output-corrupted").unwrap();
        assert!(
            !materialized_cache::record_matches_output(&output, &identity).unwrap(),
            "changed final output metadata must invalidate the provenance record"
        );
    }

    #[test]
    fn materialized_cache_tmp_paths_are_unique_for_same_output() {
        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("stage.gguf");
        let first = materialized_cache::temporary_output_path(
            &output,
            "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
        );
        let second = materialized_cache::temporary_output_path(
            &output,
            "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
        );

        assert_ne!(first, second);
        assert!(
            first.starts_with(dir.path().join(".staging")),
            "temporary materialization must stay in the cache-owned staging directory"
        );
        assert!(
            second.starts_with(dir.path().join(".staging")),
            "temporary materialization must stay in the cache-owned staging directory"
        );
    }

    #[test]
    fn materialized_cache_publish_replaces_existing_output() {
        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("stage.gguf");
        let tmp = dir.path().join(".staging").join("stage.tmp");
        fs::create_dir_all(tmp.parent().unwrap()).unwrap();
        fs::write(&output, b"old-output").unwrap();
        fs::write(&tmp, b"new-output").unwrap();

        materialized_cache::publish_output(&tmp, &output).unwrap();

        assert_eq!(fs::read(&output).unwrap(), b"new-output");
        assert!(!tmp.exists());
    }

    #[test]
    fn parses_hf_package_refs() {
        assert_eq!(
            parse_hf_package_ref("hf://Mesh-LLM/Qwen3.6-package").unwrap(),
            HfPackageRef {
                repo_id: "Mesh-LLM/Qwen3.6-package".to_string(),
                revision: None,
            }
        );
        assert_eq!(
            parse_hf_package_ref("hf://Mesh-LLM/Qwen3.6-package:abc123").unwrap(),
            HfPackageRef {
                repo_id: "Mesh-LLM/Qwen3.6-package".to_string(),
                revision: Some("abc123".to_string()),
            }
        );
        assert_eq!(
            parse_hf_package_ref("hf://Mesh-LLM/Qwen3.6-package@branch-name").unwrap(),
            HfPackageRef {
                repo_id: "Mesh-LLM/Qwen3.6-package".to_string(),
                revision: Some("branch-name".to_string()),
            }
        );
    }

    #[test]
    fn rejects_invalid_hf_package_refs() {
        assert!(parse_hf_package_ref("hf://").is_err());
        assert!(parse_hf_package_ref("hf://namespace-only").is_err());
        assert!(parse_hf_package_ref("hf://namespace/repo@").is_err());
        assert!(parse_hf_package_ref("hf://namespace/repo:").is_err());
    }

    #[test]
    fn checks_abi_version_compatibility() {
        assert!(
            abi_version_supported(&format!(
                "{}.{}.0",
                skippy_ffi::ABI_VERSION_MAJOR,
                skippy_ffi::ABI_VERSION_MINOR
            ))
            .unwrap()
        );
        assert!(
            !abi_version_supported(&format!("{}.{}.0", skippy_ffi::ABI_VERSION_MAJOR + 1, 0))
                .unwrap()
        );
        assert!(
            !abi_version_supported(&format!(
                "{}.{}.0",
                skippy_ffi::ABI_VERSION_MAJOR,
                skippy_ffi::ABI_VERSION_MINOR + 1
            ))
            .unwrap()
        );
    }

    #[test]
    fn inspect_layer_package_returns_manifest_identity() {
        let dir = tempfile::tempdir().unwrap();
        write_package_fixture(dir.path());

        let info = inspect_layer_package(&dir.path().to_string_lossy()).unwrap();

        assert_eq!(info.model_id, "model-a");
        assert_eq!(info.layer_count, 1);
        assert_eq!(info.source_model_bytes, Some(123));
        assert_eq!(info.projectors.len(), 1);
        assert_eq!(info.projectors[0].kind, "mmproj");
        assert_eq!(
            info.projectors[0].path,
            dir.path().join("projectors/mmproj.gguf")
        );
        assert_eq!(info.manifest_sha256.len(), 64);
    }

    #[test]
    fn verify_layer_package_integrity_rejects_selected_artifact_sha_mismatch() {
        let dir = tempfile::tempdir().unwrap();
        write_package_fixture(dir.path());
        fs::write(dir.path().join("layers/00000.gguf"), b"wrong0").unwrap();

        let error = verify_layer_package_integrity(
            &package_stage_request(dir.path()),
            &PackageIntegrityOptions::verify_without_cache(),
        )
        .unwrap_err()
        .to_string();

        assert!(error.contains("checksum mismatch"), "{error}");
        assert!(error.contains("layers/00000.gguf"), "{error}");
    }

    #[test]
    fn verify_layer_package_metadata_integrity_allows_metadata_only_scope() {
        let dir = tempfile::tempdir().unwrap();
        write_package_fixture(dir.path());
        fs::write(dir.path().join("layers/00000.gguf"), b"wrong0").unwrap();
        fs::write(
            dir.path().join("projectors/mmproj.gguf"),
            b"wrong-projector",
        )
        .unwrap();

        let report = verify_layer_package_metadata_integrity(
            &dir.path().to_string_lossy(),
            &PackageIntegrityOptions::verify_without_cache(),
        )
        .expect("metadata-only verification should not require a stage layer range");

        assert_eq!(report.artifacts, 1);
        assert_eq!(report.verified_artifacts, 1);
        assert_eq!(report.cached_artifacts, 0);
    }

    #[test]
    fn verify_layer_package_metadata_integrity_checks_metadata_sha() {
        let dir = tempfile::tempdir().unwrap();
        write_package_fixture(dir.path());
        fs::write(dir.path().join("metadata.gguf"), b"metadota").unwrap();

        let error = verify_layer_package_metadata_integrity(
            &dir.path().to_string_lossy(),
            &PackageIntegrityOptions::verify_without_cache(),
        )
        .unwrap_err()
        .to_string();

        assert!(error.contains("checksum mismatch"), "{error}");
        assert!(error.contains("metadata.gguf"), "{error}");
    }

    #[test]
    fn verify_layer_package_integrity_uses_private_cache_records() {
        let dir = tempfile::tempdir().unwrap();
        let cache_dir = tempfile::tempdir().unwrap();
        write_package_fixture(dir.path());

        let options = PackageIntegrityOptions::verify_with_cache(cache_dir.path());
        let first = verify_layer_package_integrity(&package_stage_request(dir.path()), &options)
            .expect("first verification should hash artifacts");
        assert_eq!(first.verified_artifacts, 5);
        assert_eq!(first.cached_artifacts, 0);

        let second = verify_layer_package_integrity(&package_stage_request(dir.path()), &options)
            .expect("second verification should reuse cache");
        assert_eq!(second.verified_artifacts, 0);
        assert_eq!(second.cached_artifacts, 5);

        let cache_blob = fs::read_to_string(
            fs::read_dir(cache_dir.path())
                .unwrap()
                .next()
                .unwrap()
                .unwrap()
                .path(),
        )
        .unwrap();
        assert!(
            !cache_blob.contains(&dir.path().to_string_lossy().to_string()),
            "cache records must not store raw local package paths"
        );
    }

    #[test]
    fn validates_source_model_sha256_as_hex_digest() {
        let dir = tempfile::tempdir().unwrap();
        let mut manifest = write_package_fixture(dir.path());
        manifest["source_model"]["sha256"] = serde_json::Value::String("not-a-sha".to_string());
        fs::write(
            dir.path().join("model-package.json"),
            serde_json::to_vec_pretty(&manifest).unwrap(),
        )
        .unwrap();

        let error = inspect_layer_package(&dir.path().to_string_lossy())
            .unwrap_err()
            .to_string();

        assert!(error.contains("source_model sha256"), "{error}");
    }

    #[test]
    fn rejects_package_artifact_paths_that_escape_package_dir() {
        let dir = tempfile::tempdir().unwrap();
        let mut manifest = write_package_fixture(dir.path());
        manifest["layers"][0]["path"] = serde_json::Value::String("../outside.gguf".to_string());
        fs::write(
            dir.path().join("model-package.json"),
            serde_json::to_vec_pretty(&manifest).unwrap(),
        )
        .unwrap();

        let error = select_layer_package_parts(&package_stage_request(dir.path()))
            .unwrap_err()
            .to_string();

        assert!(error.contains("safe relative"), "{error}");
    }

    #[test]
    fn inspect_layer_package_rejects_unsafe_layer_paths() {
        let dir = tempfile::tempdir().unwrap();
        let mut manifest = write_package_fixture(dir.path());
        manifest["layers"][0]["path"] = serde_json::Value::String("../outside.gguf".to_string());
        fs::write(
            dir.path().join("model-package.json"),
            serde_json::to_vec_pretty(&manifest).unwrap(),
        )
        .unwrap();

        let error = inspect_layer_package(&dir.path().to_string_lossy())
            .unwrap_err()
            .to_string();

        assert!(error.contains("safe relative"), "{error}");
    }
}