frankensearch-embed 0.2.2

Embedder implementations for frankensearch (hash, model2vec, fastembed)
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
//! Integration tests for model integrity verification (SHA-256, corruption detection,
//! verification markers, and cached verification).
//!
//! These tests exercise the full integrity pipeline:
//! - `verify_file_sha256()` for individual file checks
//! - `VerificationMarker` for caching verification results
//! - `verify_dir_cached()` for the combined cached-verification workflow

use sha2::{Digest, Sha256};
use std::fmt::Write as _;

use frankensearch_embed::model_manifest::VERIFICATION_MARKER_SCHEMA_VERSION;
use frankensearch_embed::{
    ModelFile, ModelManifest, PLACEHOLDER_VERIFY_AFTER_DOWNLOAD, VerificationMarker,
    is_verification_cached, verify_dir_and_record, verify_dir_cached, verify_file_sha256,
};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn sha256_hex(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    lower_hex(hasher.finalize())
}

fn lower_hex(bytes: impl AsRef<[u8]>) -> String {
    let bytes = bytes.as_ref();
    let mut hex = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        let _ = write!(&mut hex, "{byte:02x}");
    }
    hex
}

fn make_manifest(file_name: &str, content: &[u8]) -> ModelManifest {
    ModelManifest {
        id: "integrity-test-model".to_owned(),
        repo: "test/integrity".to_owned(),
        revision: "a".repeat(40),
        files: vec![ModelFile {
            name: file_name.to_owned(),
            sha256: sha256_hex(content),
            size: u64::try_from(content.len()).unwrap(),
            url: None,
        }],
        license: "MIT".to_owned(),
        tier: None,
        dimension: None,
        display_name: None,
        version: String::new(),
        description: None,
        download_size_bytes: u64::try_from(content.len()).unwrap(),
    }
}

// ---------------------------------------------------------------------------
// verify_file_sha256: valid files pass
// ---------------------------------------------------------------------------

#[test]
fn verify_file_sha256_succeeds_for_matching_content() {
    let tmp = tempfile::tempdir().unwrap();
    let content = b"hello model data for integrity check";
    let path = tmp.path().join("model.bin");
    std::fs::write(&path, content).unwrap();

    let hash = sha256_hex(content);
    let size = u64::try_from(content.len()).unwrap();

    let result = verify_file_sha256(&path, &hash, size);
    assert!(result.is_ok(), "valid file should pass: {:?}", result.err());
}

// ---------------------------------------------------------------------------
// verify_file_sha256: corrupt files fail
// ---------------------------------------------------------------------------

#[test]
fn verify_file_sha256_fails_for_flipped_bit() {
    let tmp = tempfile::tempdir().unwrap();
    let original = b"hello model data";
    let path = tmp.path().join("model.bin");
    std::fs::write(&path, original).unwrap();

    // Compute hash of original, then corrupt the file.
    let hash = sha256_hex(original);
    let size = u64::try_from(original.len()).unwrap();

    // Flip one bit in the first byte.
    let mut corrupted = original.to_vec();
    corrupted[0] ^= 0x01;
    std::fs::write(&path, &corrupted).unwrap();

    let result = verify_file_sha256(&path, &hash, size);
    assert!(result.is_err(), "corrupted file should fail verification");

    let err_msg = format!("{:?}", result.unwrap_err());
    assert!(
        err_msg.contains("sha256=") || err_msg.contains("HashMismatch"),
        "error should mention hash mismatch: {err_msg}"
    );
}

#[test]
fn verify_file_sha256_fails_for_truncated_file() {
    let tmp = tempfile::tempdir().unwrap();
    let original = b"some model data with more bytes";
    let path = tmp.path().join("model.bin");

    let hash = sha256_hex(original);
    let size = u64::try_from(original.len()).unwrap();

    // Write only a partial file.
    std::fs::write(&path, &original[..10]).unwrap();

    let result = verify_file_sha256(&path, &hash, size);
    assert!(result.is_err(), "truncated file should fail verification");
}

#[test]
fn verify_file_sha256_fails_for_appended_data() {
    let tmp = tempfile::tempdir().unwrap();
    let original = b"model data";
    let path = tmp.path().join("model.bin");

    let hash = sha256_hex(original);
    let size = u64::try_from(original.len()).unwrap();

    // Write original + extra bytes.
    let mut extended = original.to_vec();
    extended.extend_from_slice(b"extra garbage");
    std::fs::write(&path, &extended).unwrap();

    let result = verify_file_sha256(&path, &hash, size);
    assert!(
        result.is_err(),
        "file with appended data should fail verification"
    );
}

// ---------------------------------------------------------------------------
// verify_file_sha256: missing files
// ---------------------------------------------------------------------------

#[test]
fn verify_file_sha256_fails_for_missing_file() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("nonexistent.bin");

    let result = verify_file_sha256(&path, &"a".repeat(64), 100);
    assert!(result.is_err(), "missing file should fail verification");

    let err_msg = format!("{:?}", result.unwrap_err());
    assert!(
        err_msg.contains("ModelNotFound") || err_msg.contains("missing"),
        "error should indicate model not found: {err_msg}"
    );
}

// ---------------------------------------------------------------------------
// verify_file_sha256: zero-length expected size rejected
// ---------------------------------------------------------------------------

#[test]
fn verify_file_sha256_rejects_zero_expected_size() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("model.bin");
    std::fs::write(&path, b"data").unwrap();

    let result = verify_file_sha256(&path, &"a".repeat(64), 0);
    assert!(result.is_err(), "zero expected size should be rejected");
}

// ---------------------------------------------------------------------------
// verify_file_sha256: placeholder checksum rejected
// ---------------------------------------------------------------------------

#[test]
fn verify_file_sha256_rejects_placeholder_checksum() {
    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("model.bin");
    std::fs::write(&path, b"data").unwrap();

    let result = verify_file_sha256(&path, PLACEHOLDER_VERIFY_AFTER_DOWNLOAD, 4);
    assert!(result.is_err(), "placeholder checksum should be rejected");
}

// ---------------------------------------------------------------------------
// verify_file_sha256: directory instead of file
// ---------------------------------------------------------------------------

#[test]
fn verify_file_sha256_rejects_directory_path() {
    let tmp = tempfile::tempdir().unwrap();
    let dir_path = tmp.path().join("subdir");
    std::fs::create_dir_all(&dir_path).unwrap();

    let result = verify_file_sha256(&dir_path, &"a".repeat(64), 100);
    assert!(result.is_err(), "directory path should fail verification");
}

// ---------------------------------------------------------------------------
// VerificationMarker: roundtrip and validity
// ---------------------------------------------------------------------------

#[test]
fn verification_marker_roundtrip_preserves_fields() {
    let tmp = tempfile::tempdir().unwrap();
    let content = b"marker roundtrip test";
    let manifest = make_manifest("model.bin", content);
    std::fs::write(tmp.path().join("model.bin"), content).unwrap();

    verify_dir_and_record(&manifest, tmp.path()).unwrap();

    let marker_path = tmp.path().join(".verified");
    assert!(marker_path.exists(), ".verified marker should be created");

    let raw = std::fs::read_to_string(&marker_path).unwrap();
    let marker: VerificationMarker = serde_json::from_str(&raw).unwrap();

    assert_eq!(marker.manifest_id, "integrity-test-model");
    assert_eq!(marker.schema_version, VERIFICATION_MARKER_SCHEMA_VERSION);
    assert_eq!(
        marker.manifest_fingerprint.len(),
        64,
        "marker must bind the complete frozen production manifest"
    );
    assert!(
        marker.file_states.contains_key("model.bin"),
        "marker should record file mtime"
    );
}

// ---------------------------------------------------------------------------
// Verification cache: hit and miss scenarios
// ---------------------------------------------------------------------------

#[test]
fn verification_cache_hit_after_writing_marker() {
    let tmp = tempfile::tempdir().unwrap();
    let content = b"cache hit test";
    let manifest = make_manifest("model.bin", content);
    std::fs::write(tmp.path().join("model.bin"), content).unwrap();

    assert!(
        !is_verification_cached(&manifest, tmp.path()),
        "should not be cached before marker written"
    );

    verify_dir_and_record(&manifest, tmp.path()).unwrap();

    assert!(
        is_verification_cached(&manifest, tmp.path()),
        "should be cached after marker written"
    );
}

#[test]
fn verification_cache_miss_with_different_manifest_id() {
    let tmp = tempfile::tempdir().unwrap();
    let content = b"different manifest id test";
    let manifest = make_manifest("model.bin", content);
    std::fs::write(tmp.path().join("model.bin"), content).unwrap();

    verify_dir_and_record(&manifest, tmp.path()).unwrap();

    // Create a different manifest with a different ID.
    let mut different = manifest;
    different.id = "completely-different-model".to_owned();

    assert!(
        !is_verification_cached(&different, tmp.path()),
        "changed manifest ID should invalidate cache"
    );
}

#[test]
fn verification_cache_miss_when_file_mtime_tampered() {
    let tmp = tempfile::tempdir().unwrap();
    let content = b"mtime tamper test";
    let manifest = make_manifest("model.bin", content);
    std::fs::write(tmp.path().join("model.bin"), content).unwrap();

    verify_dir_and_record(&manifest, tmp.path()).unwrap();
    assert!(is_verification_cached(&manifest, tmp.path()));

    // Tamper with the recorded mtime in the marker.
    let marker_path = tmp.path().join(".verified");
    let raw = std::fs::read_to_string(&marker_path).unwrap();
    let mut marker: VerificationMarker = serde_json::from_str(&raw).unwrap();
    // Remove the real entry so fingerprint won't match.
    marker.file_states.remove("model.bin");
    std::fs::write(&marker_path, serde_json::to_string(&marker).unwrap()).unwrap();

    assert!(
        !is_verification_cached(&manifest, tmp.path()),
        "tampered mtime should invalidate cache"
    );
}

#[test]
fn verification_cache_miss_when_marker_is_corrupt_json() {
    let tmp = tempfile::tempdir().unwrap();
    let content = b"corrupt json test";
    let manifest = make_manifest("model.bin", content);
    std::fs::write(tmp.path().join("model.bin"), content).unwrap();

    verify_dir_and_record(&manifest, tmp.path()).unwrap();

    // Overwrite the marker with invalid JSON.
    std::fs::write(tmp.path().join(".verified"), "NOT VALID JSON {{{{").unwrap();

    assert!(
        !is_verification_cached(&manifest, tmp.path()),
        "corrupt marker JSON should not be treated as cached"
    );
}

#[test]
fn verification_cache_miss_when_marker_file_missing() {
    let tmp = tempfile::tempdir().unwrap();
    let content = b"no marker test";
    let manifest = make_manifest("model.bin", content);
    std::fs::write(tmp.path().join("model.bin"), content).unwrap();

    assert!(
        !is_verification_cached(&manifest, tmp.path()),
        "missing marker should not be treated as cached"
    );
}

// ---------------------------------------------------------------------------
// verify_dir_cached: end-to-end cached verification
// ---------------------------------------------------------------------------

#[test]
fn verify_dir_cached_is_observational_on_first_call() {
    let tmp = tempfile::tempdir().unwrap();
    let content = b"verify dir cached e2e";
    let manifest = make_manifest("model.bin", content);
    std::fs::write(tmp.path().join("model.bin"), content).unwrap();

    let marker_path = tmp.path().join(".verified");
    assert!(!marker_path.exists());

    verify_dir_cached(&manifest, tmp.path()).unwrap();

    assert!(
        !marker_path.exists(),
        "observational verification must not create a .verified receipt"
    );
}

#[test]
fn verify_dir_cached_succeeds_from_cache_on_second_call() {
    let tmp = tempfile::tempdir().unwrap();
    let content = b"verify dir cached second call";
    let manifest = make_manifest("model.bin", content);
    std::fs::write(tmp.path().join("model.bin"), content).unwrap();

    // The authority-bearing path performs full verification and records a receipt.
    verify_dir_and_record(&manifest, tmp.path()).unwrap();

    // The observational consumer may then use that receipt.
    verify_dir_cached(&manifest, tmp.path()).unwrap();

    // The marker should still exist.
    assert!(is_verification_cached(&manifest, tmp.path()));
}

#[test]
fn verify_dir_cached_rejects_placeholder_checksums() {
    let tmp = tempfile::tempdir().unwrap();
    let manifest = ModelManifest {
        id: "placeholder-test".to_owned(),
        repo: "test/repo".to_owned(),
        revision: "v1".to_owned(),
        files: vec![ModelFile {
            name: "model.bin".to_owned(),
            sha256: PLACEHOLDER_VERIFY_AFTER_DOWNLOAD.to_owned(),
            size: 0,
            url: None,
        }],
        license: "MIT".to_owned(),
        tier: None,
        dimension: None,
        display_name: None,
        version: String::new(),
        description: None,
        download_size_bytes: 0,
    };

    let result = verify_dir_cached(&manifest, tmp.path());
    assert!(
        result.is_err(),
        "placeholder manifests must never receive cached admission"
    );
    assert!(!tmp.path().join(".verified").exists());
}

#[test]
fn verify_dir_cached_fails_for_corrupt_file() {
    let tmp = tempfile::tempdir().unwrap();
    let original = b"original model data";
    let manifest = make_manifest("model.bin", original);

    // Write corrupted content.
    std::fs::write(tmp.path().join("model.bin"), b"CORRUPTED DATA").unwrap();

    let result = verify_dir_cached(&manifest, tmp.path());
    assert!(
        result.is_err(),
        "corrupt file should fail verify_dir_cached"
    );
}

// ---------------------------------------------------------------------------
// Multi-file manifest verification
// ---------------------------------------------------------------------------

#[test]
fn verify_dir_cached_checks_all_files_in_manifest() {
    let tmp = tempfile::tempdir().unwrap();
    let content_a = b"file a content";
    let content_b = b"file b content";

    let manifest = ModelManifest {
        id: "multi-file-test".to_owned(),
        repo: "test/multi".to_owned(),
        revision: "a".repeat(40),
        files: vec![
            ModelFile {
                name: "a.bin".to_owned(),
                sha256: sha256_hex(content_a),
                size: u64::try_from(content_a.len()).unwrap(),
                url: None,
            },
            ModelFile {
                name: "b.bin".to_owned(),
                sha256: sha256_hex(content_b),
                size: u64::try_from(content_b.len()).unwrap(),
                url: None,
            },
        ],
        license: "MIT".to_owned(),
        tier: None,
        dimension: None,
        display_name: None,
        version: String::new(),
        description: None,
        download_size_bytes: u64::try_from(content_a.len() + content_b.len()).unwrap(),
    };

    std::fs::write(tmp.path().join("a.bin"), content_a).unwrap();
    std::fs::write(tmp.path().join("b.bin"), content_b).unwrap();

    let result = verify_dir_cached(&manifest, tmp.path());
    assert!(
        result.is_ok(),
        "multi-file verification should pass: {:?}",
        result.err()
    );
}

#[test]
fn verify_dir_cached_fails_when_one_of_multiple_files_corrupt() {
    let tmp = tempfile::tempdir().unwrap();
    let content_a = b"good file content";
    let content_b = b"will be corrupted";

    let manifest = ModelManifest {
        id: "multi-file-corrupt".to_owned(),
        repo: "test/multi".to_owned(),
        revision: "a".repeat(40),
        files: vec![
            ModelFile {
                name: "a.bin".to_owned(),
                sha256: sha256_hex(content_a),
                size: u64::try_from(content_a.len()).unwrap(),
                url: None,
            },
            ModelFile {
                name: "b.bin".to_owned(),
                sha256: sha256_hex(content_b),
                size: u64::try_from(content_b.len()).unwrap(),
                url: None,
            },
        ],
        license: "MIT".to_owned(),
        tier: None,
        dimension: None,
        display_name: None,
        version: String::new(),
        description: None,
        download_size_bytes: u64::try_from(content_a.len() + content_b.len()).unwrap(),
    };

    std::fs::write(tmp.path().join("a.bin"), content_a).unwrap();
    // Write corrupted content for b.bin.
    std::fs::write(tmp.path().join("b.bin"), b"WRONG CONTENT").unwrap();

    let result = verify_dir_cached(&manifest, tmp.path());
    assert!(
        result.is_err(),
        "one corrupt file in multi-file manifest should fail verification"
    );
}