apr-cli 0.4.12

CLI tool for APR model inspection, debugging, and operations
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

    #[test]
    fn test_gh213_resolve_hf_invalid_uri_fails() {
        let result = resolve_hf_model("hf://invalid");
        assert!(result.is_err());
    }

    #[test]
    fn test_gh213_resolve_bare_org_repo_normalizes() {
        // "Qwen/Qwen2.5-Coder-3B-Instruct" should be treated as "hf://Qwen/Qwen2.5-Coder-3B-Instruct"
        // Can't test full resolution without network, but verify it doesn't return as SingleFile unchanged
        let result = resolve_hf_model("Qwen/FakeRepo");
        // Will fail with network error (repo doesn't exist), which proves it tried HF API
        assert!(
            result.is_err(),
            "Bare org/repo should attempt HF resolution"
        );
    }

    #[test]
    fn test_gh213_resolve_bare_org_repo_with_gguf_extension() {
        // "org/repo/file.gguf" should normalize to "hf://org/repo/file.gguf" → SingleFile
        let result = resolve_hf_model("org/repo/model.gguf").unwrap();
        match result {
            ResolvedModel::SingleFile(s) => {
                assert_eq!(s, "hf://org/repo/model.gguf");
            }
            ResolvedModel::Sharded { .. } => panic!("Expected SingleFile"),
        }
    }

    #[test]
    fn test_gh213_resolve_bare_single_component_unchanged() {
        // "justAName" (no slash) should not be normalized, stays as local path
        let result = resolve_hf_model("justAName").unwrap();
        match result {
            ResolvedModel::SingleFile(s) => assert_eq!(s, "justAName"),
            ResolvedModel::Sharded { .. } => panic!("Expected SingleFile"),
        }
    }

    #[test]
    fn test_gh213_resolve_relative_path_not_normalized() {
        // "./path/to/model" should NOT be treated as org/repo
        let result = resolve_hf_model("./path/to/model").unwrap();
        match result {
            ResolvedModel::SingleFile(s) => assert_eq!(s, "./path/to/model"),
            ResolvedModel::Sharded { .. } => panic!("Expected SingleFile"),
        }
    }

    #[test]
    fn test_gh213_resolve_absolute_path_not_normalized() {
        // "/home/user/model" should NOT be treated as org/repo
        let result = resolve_hf_model("/home/user/model").unwrap();
        match result {
            ResolvedModel::SingleFile(s) => assert_eq!(s, "/home/user/model"),
            ResolvedModel::Sharded { .. } => panic!("Expected SingleFile"),
        }
    }

    // Integration tests (require network, marked ignore for CI)
    #[test]
    #[ignore]
    fn test_gh213_resolve_small_model_is_single_file() {
        // 0.5B model has a single model.safetensors
        let result = resolve_hf_model("hf://Qwen/Qwen2.5-Coder-0.5B-Instruct").unwrap();
        match result {
            ResolvedModel::SingleFile(s) => {
                assert!(
                    s.contains("model.safetensors"),
                    "Should resolve to model.safetensors: {}",
                    s
                );
            }
            ResolvedModel::Sharded { .. } => panic!("0.5B should be single file, not sharded"),
        }
    }

    #[test]
    #[ignore]
    fn test_gh213_resolve_large_model_is_sharded() {
        // 3B+ models use sharded SafeTensors
        let result = resolve_hf_model("hf://Qwen/Qwen2.5-Coder-3B-Instruct").unwrap();
        match result {
            ResolvedModel::Sharded {
                org,
                repo,
                shard_files,
            } => {
                assert_eq!(org, "Qwen");
                assert_eq!(repo, "Qwen2.5-Coder-3B-Instruct");
                assert!(
                    shard_files.len() > 1,
                    "3B model should have multiple shards, got {}",
                    shard_files.len()
                );
                // All shards should end with .safetensors
                for f in &shard_files {
                    assert!(
                        f.ends_with(".safetensors"),
                        "Shard should be .safetensors: {}",
                        f
                    );
                }
            }
            ResolvedModel::SingleFile(s) => {
                panic!("3B should be sharded, got SingleFile({})", s)
            }
        }
    }

    #[test]
    #[ignore]
    fn test_gh213_resolve_7b_model_is_sharded() {
        let result = resolve_hf_model("hf://Qwen/Qwen2.5-Coder-7B-Instruct").unwrap();
        match result {
            ResolvedModel::Sharded { shard_files, .. } => {
                assert!(
                    shard_files.len() > 1,
                    "7B model should have multiple shards, got {}",
                    shard_files.len()
                );
            }
            ResolvedModel::SingleFile(s) => {
                panic!("7B should be sharded, got SingleFile({})", s)
            }
        }
    }

    // =========================================================================
    // format_bytes: exhaustive boundary tests
    // =========================================================================

    #[test]
    fn test_format_bytes_boundary_just_below_kb() {
        assert_eq!(format_bytes(1023), "1023 B");
    }

    #[test]
    fn test_format_bytes_boundary_exact_kb() {
        assert_eq!(format_bytes(1024), "1.0 KB");
    }

    #[test]
    fn test_format_bytes_boundary_just_above_kb() {
        assert_eq!(format_bytes(1025), "1.0 KB");
    }

    #[test]
    fn test_format_bytes_boundary_just_below_mb() {
        // 1 MB - 1 byte = 1048575 bytes → KB range
        assert_eq!(format_bytes(1_048_575), "1024.0 KB");
    }

    #[test]
    fn test_format_bytes_boundary_exact_mb() {
        assert_eq!(format_bytes(1_048_576), "1.0 MB");
    }

    #[test]
    fn test_format_bytes_boundary_just_below_gb() {
        // 1 GB - 1 byte = 1073741823 bytes → MB range
        assert_eq!(format_bytes(1_073_741_823), "1024.0 MB");
    }

    #[test]
    fn test_format_bytes_boundary_exact_gb() {
        assert_eq!(format_bytes(1_073_741_824), "1.0 GB");
    }

    #[test]
    fn test_format_bytes_large_gb() {
        // 100 GB
        assert_eq!(format_bytes(107_374_182_400), "100.0 GB");
    }

    #[test]
    fn test_format_bytes_u64_max() {
        // u64::MAX should not panic, gives some large TB value
        let result = format_bytes(u64::MAX);
        assert!(
            result.contains("TB"),
            "u64::MAX should be in TB range: {}",
            result
        );
    }

    #[test]
    fn test_format_bytes_fractional_kb() {
        // 1.5 KB = 1536 bytes
        assert_eq!(format_bytes(1536), "1.5 KB");
    }

    #[test]
    fn test_format_bytes_7b_model_size() {
        // ~4.1 GB typical for 7B Q4_K_M
        assert_eq!(format_bytes(4_402_341_888), "4.1 GB");
    }

    // =========================================================================
    // extract_hf_repo: comprehensive edge cases
    // =========================================================================

    #[test]
    fn test_extract_hf_repo_just_prefix() {
        // "hf://" with nothing after → parts = [""], len < 2
        assert_eq!(extract_hf_repo("hf://"), None);
    }

    #[test]
    fn test_extract_hf_repo_single_slash_after_prefix() {
        // "hf://org/" → parts = ["org", ""], but parts[1] is empty
        // Still returns Some because len >= 2 and format just joins
        let result = extract_hf_repo("hf://org/");
        assert_eq!(result, Some("org/".to_string()));
    }

    #[test]
    fn test_extract_hf_repo_with_multiple_nested_paths() {
        // Deep nesting: only org/repo extracted
        let uri = "hf://org/repo/subdir1/subdir2/model.safetensors";
        assert_eq!(extract_hf_repo(uri), Some("org/repo".to_string()));
    }

    #[test]
    fn test_extract_hf_repo_wrong_scheme() {
        assert_eq!(extract_hf_repo("https://huggingface.co/org/repo"), None);
    }

    #[test]
    fn test_extract_hf_repo_no_scheme() {
        assert_eq!(extract_hf_repo("org/repo/model.gguf"), None);
    }

    #[test]
    fn test_extract_hf_repo_hf_prefix_case_sensitive() {
        // "HF://" (uppercase) should not match
        assert_eq!(extract_hf_repo("HF://org/repo"), None);
    }

    #[test]
    fn test_extract_hf_repo_special_chars_in_name() {
        let uri = "hf://TheBloke/Llama-2-7B-GGUF/model.gguf";
        assert_eq!(
            extract_hf_repo(uri),
            Some("TheBloke/Llama-2-7B-GGUF".to_string())
        );
    }

    #[test]
    fn test_extract_hf_repo_dots_in_name() {
        let uri = "hf://org/model.name.v2/file.safetensors";
        assert_eq!(extract_hf_repo(uri), Some("org/model.name.v2".to_string()));
    }

    // =========================================================================
    // extract_shard_files_from_index: comprehensive edge cases
    // =========================================================================

    #[test]
    fn test_extract_shard_files_single_shard() {
        let json = r#"{"weight_map": {"a.weight": "model-00001-of-00001.safetensors"}}"#;
        let shards = extract_shard_files_from_index(json);
        assert_eq!(shards.len(), 1);
        assert_eq!(shards[0], "model-00001-of-00001.safetensors");
    }

    #[test]
    fn test_extract_shard_files_many_shards() {
        // 6 shards with heavy deduplication
        let json = r#"{
            "weight_map": {
                "a": "model-00001-of-00006.safetensors",
                "b": "model-00001-of-00006.safetensors",
                "c": "model-00002-of-00006.safetensors",
                "d": "model-00003-of-00006.safetensors",
                "e": "model-00004-of-00006.safetensors",
                "f": "model-00005-of-00006.safetensors",
                "g": "model-00005-of-00006.safetensors",
                "h": "model-00006-of-00006.safetensors"
            }
        }"#;
        let shards = extract_shard_files_from_index(json);
        assert_eq!(shards.len(), 6);
        assert_eq!(shards[0], "model-00001-of-00006.safetensors");
        assert_eq!(shards[5], "model-00006-of-00006.safetensors");
    }

    #[test]
    fn test_extract_shard_files_empty_string() {
        let shards = extract_shard_files_from_index("");
        assert!(shards.is_empty());
    }

    #[test]
    fn test_extract_shard_files_no_weight_map_key() {
        let json = r#"{"other_key": {"a": "file.safetensors"}}"#;
        let shards = extract_shard_files_from_index(json);
        assert!(shards.is_empty());
    }

    #[test]
    fn test_extract_shard_files_weight_map_not_object() {
        // weight_map is a string, not object — should not crash
        let json = r#"{"weight_map": "not an object"}"#;
        let shards = extract_shard_files_from_index(json);
        assert!(shards.is_empty());
    }

    #[test]
    fn test_extract_shard_files_mixed_extensions() {
        // Only .safetensors files should be included
        let json = r#"{
            "weight_map": {
                "a": "model-00001.safetensors",
                "b": "model-00002.bin",
                "c": "model-00003.pt",
                "d": "model-00004.safetensors"
            }
        }"#;
        let shards = extract_shard_files_from_index(json);
        assert_eq!(shards.len(), 2);
        assert!(shards.contains(&"model-00001.safetensors".to_string()));
        assert!(shards.contains(&"model-00004.safetensors".to_string()));
    }

    #[test]
    fn test_extract_shard_files_nested_braces() {
        // JSON with nested braces in metadata before weight_map
        let json = r#"{
            "metadata": {"nested": {"deep": "value"}},
            "weight_map": {
                "a.weight": "shard-001.safetensors",
                "b.weight": "shard-002.safetensors"
            }
        }"#;
        let shards = extract_shard_files_from_index(json);
        assert_eq!(shards.len(), 2);
    }

    #[test]
    fn test_extract_shard_files_whitespace_in_values() {
        // Extra whitespace and newlines around values
        let json = r#"{
            "weight_map": {
                "a.weight":   "  model-00001.safetensors  "  ,
                "b.weight":
                    "model-00002.safetensors"
            }
        }"#;
        let shards = extract_shard_files_from_index(json);
        assert_eq!(shards.len(), 2);
    }

    #[test]
    fn test_extract_shard_files_values_with_path_separators() {
        // GH-490: Filenames with path separators must be rejected to prevent path traversal
        let json = r#"{"weight_map": {"a": "subdir/model.safetensors"}}"#;
        let shards = extract_shard_files_from_index(json);
        assert_eq!(shards.len(), 0);

        let json_traversal = r#"{"weight_map": {"a": "../../etc/model.safetensors"}}"#;
        let shards = extract_shard_files_from_index(json_traversal);
        assert_eq!(shards.len(), 0);

        let json_backslash = r#"{"weight_map": {"a": "sub\\model.safetensors"}}"#;
        let shards = extract_shard_files_from_index(json_backslash);
        assert_eq!(shards.len(), 0);
    }

    #[test]
    fn test_extract_shard_files_real_qwen_format() {
        // Realistic index.json fragment from Qwen2.5-Coder-3B-Instruct
        let json = r#"{
  "metadata": {
    "total_size": 6534782976
  },
  "weight_map": {
    "lm_head.weight": "model-00002-of-00002.safetensors",
    "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
    "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
    "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
    "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
    "model.layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
    "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
    "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
    "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
    "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
    "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
    "model.layers.35.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
    "model.norm.weight": "model-00002-of-00002.safetensors"
  }
}"#;
        let shards = extract_shard_files_from_index(json);
        assert_eq!(shards.len(), 2);
        assert_eq!(shards[0], "model-00001-of-00002.safetensors");
        assert_eq!(shards[1], "model-00002-of-00002.safetensors");
    }

    // =========================================================================
    // resolve_hf_model: offline URI normalization & extension detection
    // =========================================================================

    #[test]
    fn test_resolve_hf_model_with_apr_extension() {
        let result = resolve_hf_model("hf://org/repo/model.apr").unwrap();
        match result {
            ResolvedModel::SingleFile(s) => assert_eq!(s, "hf://org/repo/model.apr"),
            ResolvedModel::Sharded { .. } => panic!("Expected SingleFile for .apr"),
        }
    }

    #[test]
    fn test_resolve_hf_model_with_pt_extension() {
        let result = resolve_hf_model("hf://org/repo/model.pt").unwrap();
        match result {
            ResolvedModel::SingleFile(s) => assert_eq!(s, "hf://org/repo/model.pt"),
            ResolvedModel::Sharded { .. } => panic!("Expected SingleFile for .pt"),
        }
    }

    #[test]
    fn test_resolve_hf_model_case_insensitive_safetensors() {
        let result = resolve_hf_model("hf://org/repo/model.SafeTensors").unwrap();
        match result {
            ResolvedModel::SingleFile(s) => assert_eq!(s, "hf://org/repo/model.SafeTensors"),
            ResolvedModel::Sharded { .. } => panic!("Expected SingleFile"),
        }
    }

    #[test]
    fn test_resolve_hf_model_with_mixed_case_apr() {
        let result = resolve_hf_model("hf://org/repo/model.APR").unwrap();
        match result {
            ResolvedModel::SingleFile(s) => assert_eq!(s, "hf://org/repo/model.APR"),
            ResolvedModel::Sharded { .. } => panic!("Expected SingleFile for .APR"),
        }
    }

    #[test]
    fn test_resolve_hf_model_bare_org_repo_with_safetensors() {
        // "org/repo/model.safetensors" → "hf://org/repo/model.safetensors" → SingleFile
        let result = resolve_hf_model("org/repo/model.safetensors").unwrap();
        match result {
            ResolvedModel::SingleFile(s) => assert_eq!(s, "hf://org/repo/model.safetensors"),
            ResolvedModel::Sharded { .. } => panic!("Expected SingleFile"),
        }
    }