cassadilia 0.4.7

A content-addressable storage (CAS) system optimized for large blobs with read-mostly access patterns
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
pub(crate) mod utils;
use utils::setup_tracing;
mod checkpoint;

use std::fs;
use std::num::NonZeroU64;
use std::os::unix::fs::PermissionsExt;

use anyhow::Result;
use tempfile::tempdir;

use crate::{Cas, Config, LibError, LibIoOperation, SyncMode};

#[test]
fn test_put_get_remove_string_key() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let cas = Cas::open(dir.path(), Config::default())?;

    let key = "my_first_blob".to_string();
    let data = b"Hello, Bubs!";

    let mut tx = cas.put(key.clone())?;
    tx.write(data)?;
    tx.finish()?;

    let retrieved = cas.get(&key)?.expect("blob should exist");
    assert_eq!(retrieved.as_ref(), data);

    assert!(cas.get(&"does_not_exist".to_string())?.is_none());

    assert!(cas.remove(&key)?);
    assert!(cas.get(&key)?.is_none());
    assert!(!cas.remove(&key)?); // false when removing a non-existent key

    Ok(())
}

#[test]
fn test_put_get_remove_bytes_key() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let cas = Cas::open(dir.path(), Config::default())?;

    let key = b"my_bytes_blob".to_vec();
    let data = b"rofls";

    let mut tx = cas.put(key.clone())?;
    tx.write(data)?;
    tx.finish()?;

    let retrieved = cas.get(&key)?.expect("blob should exist");
    assert_eq!(retrieved.as_ref(), data);

    assert!(cas.remove(&key)?);
    assert!(cas.get(&key)?.is_none());

    Ok(())
}

#[test]
fn test_get_range() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let cas = Cas::open(dir.path(), Config::default())?;

    let key = "range_blob".to_string();
    let data = b"0123456789abcdef";

    let mut tx = cas.put(key.clone())?;
    tx.write(data)?;
    tx.finish()?;

    assert_eq!(cas.get_range(&key, 0, 16)?.unwrap().as_ref(), b"0123456789abcdef");
    assert_eq!(cas.get_range(&key, 4, 8)?.unwrap().as_ref(), b"4567");
    assert_eq!(cas.get_range(&key, 10, 16)?.unwrap().as_ref(), b"abcdef");

    // Range extending beyond the end of the data is truncated
    assert_eq!(cas.get_range(&key, 12, 100)?.unwrap().as_ref(), b"cdef");

    // Zero-length or out-of-bounds ranges
    assert!(cas.get_range(&key, 100, 200)?.unwrap().is_empty());
    assert!(cas.get_range(&key, 5, 5)?.unwrap().is_empty());

    // Invalid range (start > end)
    assert!(cas.get_range(&key, 8, 4).is_err());

    Ok(())
}

#[test]
fn test_overwrite_persists_across_reopen() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let db_path = dir.path();
    let key = "overwrite_test".to_string();

    {
        let cas = Cas::open(db_path, Config::default())?;
        let mut tx = cas.put(key.clone())?;
        tx.write(b"Version 1")?;
        tx.finish()?;

        assert_eq!(cas.get(&key)?.unwrap().as_ref(), b"Version 1");
    }

    {
        let cas = Cas::open(db_path, Config::default())?;
        assert_eq!(cas.get(&key)?.unwrap().as_ref(), b"Version 1");

        let mut tx = cas.put(key.clone())?;
        tx.write(b"Version 2 is better")?;
        tx.finish()?;

        assert_eq!(cas.get(&key)?.unwrap().as_ref(), b"Version 2 is better");
    }

    {
        let cas = Cas::open(db_path, Config::default())?;
        let retrieved = cas.get(&key)?.unwrap();
        assert_eq!(retrieved.as_ref(), b"Version 2 is better");
    }
    Ok(())
}

#[test]
fn test_stats_unique_and_bytes_shared_blob() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let cas = Cas::open(dir.path(), Config::default())?;

    let data = b"abc";
    let size = data.len() as u64;
    let key1 = "key1".to_string();
    let key2 = "key2".to_string();

    let mut tx = cas.put(key1.clone())?;
    tx.write(data)?;
    tx.finish()?;

    let stats = cas.stats();
    assert_eq!(stats.cas.unique_blobs, 1);
    assert_eq!(stats.cas.total_bytes, size);

    let mut tx = cas.put(key2.clone())?;
    tx.write(data)?;
    tx.finish()?;

    let stats = cas.stats();
    assert_eq!(stats.cas.unique_blobs, 1);
    assert_eq!(stats.cas.total_bytes, size);

    assert!(cas.remove(&key1)?);
    let stats = cas.stats();
    assert_eq!(stats.cas.unique_blobs, 1);
    assert_eq!(stats.cas.total_bytes, size);

    assert!(cas.remove(&key2)?);
    let stats = cas.stats();
    assert_eq!(stats.cas.unique_blobs, 0);
    assert_eq!(stats.cas.total_bytes, 0);

    Ok(())
}

#[test]
fn test_stats_repoint_overwrite_updates_bytes() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let cas = Cas::open(dir.path(), Config::default())?;

    let key = "key".to_string();
    let data_a = b"a";
    let data_b = b"bbbbb";

    let mut tx = cas.put(key.clone())?;
    tx.write(data_a)?;
    tx.finish()?;

    let stats = cas.stats();
    assert_eq!(stats.cas.unique_blobs, 1);
    assert_eq!(stats.cas.total_bytes, data_a.len() as u64);

    let mut tx = cas.put(key.clone())?;
    tx.write(data_b)?;
    tx.finish()?;

    let stats = cas.stats();
    assert_eq!(stats.cas.unique_blobs, 1);
    assert_eq!(stats.cas.total_bytes, data_b.len() as u64);

    Ok(())
}

#[test]
fn test_stats_recomputed_after_reopen() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let db_path = dir.path();

    {
        let cas = Cas::open(db_path, Config::default())?;
        let data = b"abc";

        let mut tx = cas.put("k1".to_string())?;
        tx.write(data)?;
        tx.finish()?;

        let mut tx = cas.put("k2".to_string())?;
        tx.write(data)?;
        tx.finish()?;

        let stats = cas.stats();
        assert_eq!(stats.cas.unique_blobs, 1);
        assert_eq!(stats.cas.total_bytes, data.len() as u64);
    }

    {
        let cas = Cas::<String>::open(db_path, Config::default())?;
        let stats = cas.stats();
        assert_eq!(stats.cas.unique_blobs, 1);
        assert_eq!(stats.cas.total_bytes, 3);
    }

    Ok(())
}

#[test]
fn test_remove_persists_across_reopen() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let db_path = dir.path();
    let key = "remove_persist_test".to_string();

    {
        let cas = Cas::open(db_path, Config::default())?;
        let mut tx = cas.put(key.clone())?;
        tx.write(b"Data to be removed")?;
        tx.finish()?;

        assert!(cas.get(&key)?.is_some());
        assert!(cas.remove(&key)?);
        assert!(cas.get(&key)?.is_none());
    }

    {
        let cas = Cas::open(db_path, Config::default())?;
        assert!(cas.get(&key)?.is_none(), "data should still be removed after reopen");
    }
    Ok(())
}

#[test]
fn test_transaction_drop_cleans_up_staging_file() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let cas = Cas::open(dir.path(), Config::default())?;
    let key = "dropped_tx_key".to_string();

    let staging_path;
    {
        let mut tx = cas.put(key.clone())?;
        tx.write(b"This data won't be saved")?;

        // Capture path before the transaction is dropped and its temp file is removed.
        staging_path = tx.temp_file.path().to_path_buf();
        assert!(staging_path.exists(), "staging file should exist during tx");
    }

    assert!(!staging_path.exists(), "staging file should be removed on drop");
    assert!(cas.get(&key)?.is_none(), "data should not be present if tx was dropped");

    Ok(())
}

#[test]
fn test_checkpoint_persists_index() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let db_path = dir.path();

    let index_file_path = db_path.join("index");

    {
        let cas = Cas::open(db_path, Config::default())?;
        let mut tx = cas.put("key1".to_string())?;
        tx.write(b"data1")?;
        tx.finish()?;

        cas.checkpoint()?;

        assert!(index_file_path.exists(), "no index");
        assert!(index_file_path.metadata()?.len() > 0, "empty index");
        assert_eq!(cas.0.index.state.read().last_persisted_version, NonZeroU64::new(1));
    }

    {
        // Reopen and ensure data is loaded correctly, proving the checkpoint worked.
        let cas = Cas::open(db_path, Config::default())?;
        assert_eq!(cas.get(&"key1".to_string())?.unwrap().as_ref(), b"data1");
    }
    Ok(())
}

#[test]
fn test_wal_rollover_and_cleanup() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let db_path = dir.path();

    // Configure a very small WAL segment size to force rollovers.
    let config = Config {
        sync_mode: SyncMode::Sync,
        num_ops_per_wal: NonZeroU64::new(2).unwrap(),
        pre_create_cas_dirs: false,
        ..Default::default()
    };

    let wal0_path = db_path.join("0_index.wal");
    let wal1_path = db_path.join("1_index.wal");

    {
        let cas = Cas::open(db_path, config.clone())?;
        let mut tx = cas.put("key1".to_string())?;
        tx.write(b"d1")?;
        tx.finish()?;

        let mut tx = cas.put("key2".to_string())?;
        tx.write(b"d2")?;
        tx.finish()?;

        assert!(wal0_path.exists());
        assert!(!wal1_path.exists());

        // This operation should trigger the rollover to the next WAL segment.
        let mut tx = cas.put("key3".to_string())?;
        tx.write(b"d3")?;
        tx.finish()?;
        assert!(wal1_path.exists());

        // Checkpoint should persist data from all segments and clean up old ones.
        cas.checkpoint()?;

        assert!(!wal0_path.exists(), "stale wal (0) should be cleaned up by checkpoint");
        assert!(wal1_path.exists(), "active wal (1) should remain");
    }

    {
        let cas = Cas::open(db_path, config)?;
        assert_eq!(cas.get(&"key1".to_string())?.unwrap().as_ref(), b"d1");
        assert_eq!(cas.get(&"key2".to_string())?.unwrap().as_ref(), b"d2");
        assert_eq!(cas.get(&"key3".to_string())?.unwrap().as_ref(), b"d3");
    }

    Ok(())
}

#[test]
fn test_remove_range_persists() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let db_path = dir.path();

    {
        let cas = Cas::open(db_path, Config::default())?;
        for i in 1..=4 {
            let mut tx = cas.put(format!("key_{i}"))?;
            tx.write(format!("data_{i}",).as_bytes())?;
            tx.finish()?;
        }

        // remove key_1 and key_2 (exclusive end)
        let count = cas.remove_range("key_1".to_string().."key_3".to_string())?;
        assert_eq!(count, 2);

        assert!(cas.get(&"key_1".to_string())?.is_none());
        assert!(cas.get(&"key_2".to_string())?.is_none());
        assert!(cas.get(&"key_3".to_string())?.is_some());
    }

    {
        let cas = Cas::open(db_path, Config::default())?;
        assert!(cas.get(&"key_1".to_string())?.is_none());
        assert!(cas.get(&"key_2".to_string())?.is_none());
        assert!(cas.get(&"key_3".to_string())?.is_some());
        assert!(cas.get(&"key_4".to_string())?.is_some());

        assert_eq!(cas.index.read_state().known_blobs().count(), 2);
    }

    Ok(())
}

#[test]
fn test_api_on_nonexistent_key() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let cas = Cas::open(dir.path(), Config::default())?;
    let key = "nonexistent_key".to_string();

    let result = cas.get_reader(&key).unwrap();
    match result {
        None => {}
        _ => panic!("Expected KeyNotFound error, got: {result:?}"),
    }

    // High-level APIs should gracefully return None.
    assert!(cas.get(&key)?.is_none());
    assert!(cas.get_size(&key)?.is_none());
    assert!(cas.get_range(&key, 0, 10)?.is_none());

    Ok(())
}

#[test]
fn test_io_error_on_staging_file_creation() -> anyhow::Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let cas = Cas::open(dir.path(), Config::default())?;

    // make the staging directory read-only to force a permissions error.
    let staging_dir = dir.path().join("staging");
    fs::set_permissions(&staging_dir, fs::Permissions::from_mode(0o555))?; // r-xr-xr-x

    let result = cas.put("test_key".to_string());
    assert!(result.is_err());

    let err = result.unwrap_err();
    let LibError::Io { operation, path, .. } = err else {
        panic!("Expected a specific IO error, but got: {err}");
    };
    assert!(matches!(operation, LibIoOperation::CreateStagingFile));
    let path_str = path.unwrap().to_string_lossy().to_string();
    assert!(path_str.contains("staging"));

    Ok(())
}

#[test]
fn test_orphan_detection_and_cleanup() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;

    // First, create a CAS with some valid data
    let cas = Cas::open(dir.path(), Config::default())?;

    // Add some valid data
    let key1 = "valid_key1".to_string();
    let data1 = b"valid data 1";
    let mut tx = cas.put(key1.clone())?;
    tx.write(data1)?;
    tx.finish()?;

    // Get the hash for later
    let _valid_hash = cas.index.read_state().get_item(&key1).unwrap();

    // Now create an orphaned blob by writing directly to CAS
    let orphan_data = b"orphaned data";
    let orphan_hash = crate::calculate_blob_hash(orphan_data);
    let orphan_path = dir.path().join("cas").join(orphan_hash.relative_path());

    // Create parent directories
    if let Some(parent) = orphan_path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&orphan_path, orphan_data)?;

    // Also create an invalid file in CAS
    let invalid_file_path = dir.path().join("cas").join(".DS_Store");
    fs::write(&invalid_file_path, b"invalid")?;

    // Create an old staging file
    let staging_file = dir.path().join("staging").join("old_file.tmp");
    fs::write(&staging_file, b"old staging data")?;

    // Drop the CAS to ensure clean shutdown
    drop(cas);

    // Reopen with recovery to get orphan stats
    let config = Config { scan_orphans_on_startup: true, ..Default::default() };
    let (cas, orphan_stats) = Cas::open_with_recover(dir.path(), config)?;

    // Should have orphan stats
    let stats = orphan_stats.expect("Should have orphan stats");
    let [only] = stats.orphaned_blobs.as_slice() else {
        panic!("Expected one orphaned blob");
    };
    assert_eq!(*only, orphan_hash);
    assert_eq!(stats.invalid_files.len(), 1);

    // Valid blob should still exist
    let retrieved = cas.get(&key1)?.expect("valid blob should still exist");
    assert_eq!(retrieved.as_ref(), data1);

    // Orphan should still exist (not auto-deleted)
    assert!(orphan_path.exists(), "orphaned blob should still exist before cleanup");

    // Now explicitly delete orphans
    let result = stats.delete_orphans()?;
    assert_eq!(result.orphans_deleted, 1);
    assert_eq!(result.invalid_files_removed, 1);

    // Verify orphaned blob was removed
    assert!(!orphan_path.exists(), "orphaned blob should be removed after cleanup");
    assert!(!invalid_file_path.exists(), "invalid file should be removed after cleanup");

    Ok(())
}

#[test]
fn test_orphan_detection_with_integrity_check() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;

    // Create a CAS with some valid data
    let cas = Cas::open(dir.path(), Config::default())?;

    let key1 = "valid_key1".to_string();
    let data1 = b"valid data 1";
    let mut tx = cas.put(key1.clone())?;
    tx.write(data1)?;
    tx.finish()?;

    let item = cas.index.read_state().get_item(&key1).unwrap();
    let valid_path = dir.path().join("cas").join(item.blob_hash.relative_path());

    // Corrupt the blob by modifying its contents
    fs::write(&valid_path, b"corrupted data")?;

    drop(cas);

    // Reopen with integrity check enabled
    let config = Config {
        scan_orphans_on_startup: true,
        verify_blob_integrity: true,
        fail_on_integrity_errors: true,
        ..Default::default()
    };

    let result = Cas::<String>::open(dir.path(), config);

    // Should fail due to corrupted blob
    match result {
        Err(LibError::IntegrityCheckFailed { corrupted_blobs, .. }) => {
            let [only] = corrupted_blobs.as_slice() else {
                panic!("Expected one corrupted blob");
            };
            assert_eq!(*only, item.blob_hash);
        }
        _ => panic!("Expected IntegrityCheckFailed error"),
    }

    Ok(())
}

#[test]
fn test_orphan_detection_with_missing_blobs() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;

    // Create a CAS with some data
    let cas = Cas::open(dir.path(), Config::default())?;

    let key1 = "key1".to_string();
    let data1 = b"data 1";
    let mut tx = cas.put(key1.clone())?;
    tx.write(data1)?;
    tx.finish()?;

    let item1 = cas.index.read_state().get_item(&key1).unwrap();
    let blob_path = dir.path().join("cas").join(item1.blob_hash.relative_path());

    // Delete the blob file to simulate missing blob
    fs::remove_file(&blob_path)?;

    drop(cas);

    // Reopen with cleanup
    let config = Config {
        scan_orphans_on_startup: true,
        fail_on_integrity_errors: true,
        ..Default::default()
    };

    let result = Cas::<String>::open(dir.path(), config);

    // Should fail due to missing blob
    match result {
        Err(LibError::IntegrityCheckFailed { missing_blobs, .. }) => {
            let [only] = missing_blobs.as_slice() else {
                panic!("Expected one missing blob");
            };
            assert_eq!(*only, item1.blob_hash);
        }
        _ => panic!("Expected IntegrityCheckFailed error"),
    }

    Ok(())
}

#[test]
fn test_orphan_quarantine() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;
    let quarantine_dir = dir.path().join("quarantine");

    let cas = Cas::open(dir.path(), Config::default())?;

    // Add valid data
    let key1 = "key1".to_string();
    let data1 = b"data 1";
    let mut tx = cas.put(key1.clone())?;
    tx.write(data1)?;
    tx.finish()?;

    // Create orphaned blob
    let orphan_data = b"orphan";
    let orphan_hash = crate::calculate_blob_hash(orphan_data);
    let orphan_path = dir.path().join("cas").join(orphan_hash.relative_path());
    if let Some(parent) = orphan_path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&orphan_path, orphan_data)?;

    drop(cas);

    // Reopen with recovery
    let config = Config { scan_orphans_on_startup: true, ..Default::default() };
    let (_cas, orphan_stats) = Cas::<String>::open_with_recover(dir.path(), config)?;
    let stats = orphan_stats.expect("Should have orphan stats");

    // Quarantine orphans
    let result = stats.quarantine_orphans(&quarantine_dir)?;
    assert_eq!(result.orphans_quarantined, 1);

    // Verify orphan was moved to quarantine
    assert!(!orphan_path.exists());
    assert!(quarantine_dir.join(orphan_hash.to_string()).exists());

    Ok(())
}

#[test]
fn test_orphan_stats_holds_lock() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;

    // Create CAS with orphaned blob
    let cas = Cas::<String>::open(dir.path(), Config::default())?;

    let orphan_data = b"orphan";
    let orphan_hash = crate::calculate_blob_hash(orphan_data);
    let orphan_path = dir.path().join("cas").join(orphan_hash.relative_path());
    if let Some(parent) = orphan_path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&orphan_path, orphan_data)?;

    drop(cas);

    // Reopen with recovery
    let config = Config { scan_orphans_on_startup: true, ..Default::default() };
    let (_cas, orphan_stats) = Cas::<String>::open_with_recover(dir.path(), config)?;
    let stats = orphan_stats.expect("Should have orphan stats");

    assert_eq!(stats.orphaned_blobs.len(), 1);

    // Note: We cannot do any CAS operations while holding OrphanStats
    // because it holds the filesystem lock for its entire lifetime.
    // This is by design to ensure consistency during cleanup.

    // Now delete orphans
    let result = stats.delete_orphans()?;
    assert_eq!(result.orphans_deleted, 1);
    assert!(!orphan_path.exists());

    // Drop stats to release the lock
    drop(stats);

    Ok(())
}

#[test]
fn test_cleanup_disabled() -> Result<()> {
    setup_tracing();
    let dir = tempdir()?;

    let cas = Cas::<String>::open(dir.path(), Config::default())?;

    // Create orphaned blob
    let orphan_data = b"orphan";
    let orphan_hash = crate::calculate_blob_hash(orphan_data);
    let orphan_path = dir.path().join("cas").join(orphan_hash.relative_path());
    if let Some(parent) = orphan_path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&orphan_path, orphan_data)?;

    drop(cas);

    // Reopen with cleanup disabled
    let config = Config { scan_orphans_on_startup: false, ..Default::default() };
    let (_cas, orphan_stats) = Cas::<String>::open_with_recover(dir.path(), config)?;

    // Should have no orphan stats
    assert!(orphan_stats.is_none());

    // Orphan should still exist
    assert!(orphan_path.exists(), "orphan should not be removed when cleanup is disabled");

    Ok(())
}

#[test]
fn regression_put_same_content_should_not_delete_blob() {
    use tempfile::tempdir;

    use crate::{Cas, Config};

    let dir = tempdir().unwrap();
    let cas = Cas::open(dir.path(), Config::default()).unwrap();

    let key = b"same key";
    let data = b"same content";

    // First put
    {
        let mut tx = cas.put(*key).unwrap();
        tx.write(data).unwrap();
        tx.finish().unwrap();
    }

    // Second put with EXACT same bytes (same hash)
    {
        let mut tx = cas.put(*key).unwrap();
        tx.write(data).unwrap();
        tx.finish().unwrap();
    }

    let got = cas.get(key);
    assert!(got.is_ok(), "unexpected error: {:?}", got);
    assert_eq!(got.unwrap().unwrap(), bytes::Bytes::from_static(data));
}