hawdb-storage 0.35.1

An embedded Rust graph database for local data-plane workloads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Shared immutable handles. Logical references survive idle descriptor eviction.

use crate::file_descriptors::{BudgetState, DescriptorCache, DescriptorKind, FileOpenContext};
use crate::file_io::captured_immutable::{CacheKey, CapturedIdentity, CapturedSource};
use crate::file_io::{self as fs, File, OpenOptions};
use crate::immutable_object::{ObjectReference, ObjectStamp};
use std::collections::BTreeMap;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};

static NEXT_ALIAS_CANDIDATE: AtomicU64 = AtomicU64::new(0);

mod checkpoint;
pub(crate) use checkpoint::CheckpointImmutableFileError;

#[cfg(test)]
#[path = "immutable_files/checkpoint_lock_tests.rs"]
mod checkpoint_lock_tests;

/// How a verified open established the object's identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IdentityCheck {
    /// The complete object was hashed. Carries the descriptor's stamp taken
    /// before the first payload byte was read, if it could be taken.
    Hashed(Option<ObjectStamp>),
    /// A captured native identity, or this process's publication record.
    Trusted,
    /// The preceding mount's verification of this unmodified inode.
    ReusedMount,
}

struct AliasCandidate(PathBuf);

impl Drop for AliasCandidate {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.0);
    }
}

fn alias_candidate_path(path: &Path) -> io::Result<PathBuf> {
    let mut name = path
        .file_name()
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "alias has no filename"))?
        .to_os_string();
    name.push(format!(
        ".alias-{}-{}",
        std::process::id(),
        NEXT_ALIAS_CANDIDATE.fetch_add(1, Ordering::Relaxed),
    ));
    Ok(path.with_file_name(name))
}

#[derive(Debug, Clone)]
pub(crate) struct ImmutableFileBinding {
    pub(crate) reference: ObjectReference,
    pub(crate) object_path: PathBuf,
}

#[derive(Debug)]
struct CachedHandle {
    file: Arc<File>,
    last_used: u64,
}

#[derive(Debug)]
pub(crate) struct ImmutableFileHandles {
    state: Arc<BudgetState>,
    handles: Mutex<BTreeMap<CacheKey, CachedHandle>>,
    access_tick: AtomicU64,
    bindings: Mutex<BTreeMap<PathBuf, ImmutableFileBinding>>,
    /// Objects whose complete identity hash the most recent mount computed,
    /// with the stamp of the hashed descriptor. The next cold handle open of
    /// that object consumes the entry; see [`Self::mount`]. Bounded by
    /// [`MOUNT_VERIFICATION_RECORDS_PER_PROJECT`].
    mount_verified: Mutex<MountVerificationRecords>,
    opening: Mutex<()>,
    // Private checkpoint validation keeps objects protected after releasing
    // the short cache-opening lock. Retirement can defer without waiting.
    checkpoint_validation: RwLock<()>,
}

/// Per-project cap on unconsumed mount-verification records. A record is
/// optional performance state: evicting one only restores the full identity
/// hash on that object's next cold open. One admission mounts each object of
/// its checkpoint closure once (about 50 on LDBC SF0.1), so the cap leaves
/// ample room for a whole admission while bounding a long-lived project that
/// mounts objects which are already warm in the cache or never opened.
pub(crate) const MOUNT_VERIFICATION_RECORDS_PER_PROJECT: usize = 4096;

/// Unconsumed mount-verification records, evicted oldest-inserted first.
#[derive(Debug, Default)]
pub(crate) struct MountVerificationRecords {
    records: BTreeMap<ObjectReference, (u64, ObjectStamp)>,
    order: BTreeMap<u64, ObjectReference>,
    next: u64,
}

impl MountVerificationRecords {
    /// Inserts or replaces `reference`'s record. Returns whether an older
    /// record was evicted to stay within `capacity`.
    fn insert(&mut self, reference: ObjectReference, stamp: ObjectStamp, capacity: usize) -> bool {
        self.remove(&reference);
        let mut evicted = false;
        while self.records.len() >= capacity.max(1) {
            let Some((_, oldest)) = self.order.pop_first() else {
                break;
            };
            self.records.remove(&oldest);
            evicted = true;
        }
        let sequence = self.next;
        self.next = self.next.wrapping_add(1);
        self.order.insert(sequence, reference);
        self.records.insert(reference, (sequence, stamp));
        evicted
    }

    fn remove(&mut self, reference: &ObjectReference) -> Option<ObjectStamp> {
        let (sequence, stamp) = self.records.remove(reference)?;
        self.order.remove(&sequence);
        Some(stamp)
    }

    #[cfg(test)]
    pub(crate) fn len(&self) -> usize {
        debug_assert_eq!(self.records.len(), self.order.len());
        self.records.len()
    }
}

impl ImmutableFileHandles {
    pub(crate) fn new(state: Arc<BudgetState>) -> Self {
        Self {
            state,
            handles: Mutex::new(BTreeMap::new()),
            access_tick: AtomicU64::new(0),
            bindings: Mutex::new(BTreeMap::new()),
            mount_verified: Mutex::new(MountVerificationRecords::default()),
            opening: Mutex::new(()),
            checkpoint_validation: RwLock::new(()),
        }
    }

    pub(crate) fn bind(&self, path: &Path, binding: ImmutableFileBinding) -> io::Result<()> {
        self.bindings
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .insert(crate::file_descriptors::absolute_path(path)?, binding);
        Ok(())
    }

    pub(crate) fn binding(&self, path: &Path) -> io::Result<Option<ImmutableFileBinding>> {
        let path = crate::file_descriptors::absolute_path_ref(path)?;
        Ok(self
            .bindings
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .get(path.as_ref())
            .cloned())
    }

    pub(crate) fn unbind(&self, path: &Path) -> io::Result<()> {
        let path = crate::file_descriptors::absolute_path_ref(path)?;
        self.bindings
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .remove(path.as_ref());
        Ok(())
    }

    /// The caller's reachability barrier excludes new users of this object.
    /// Refuse to unlink an in-flight read; idle cache entries must not retain
    /// unlinked storage indefinitely in a long-lived project.
    pub(crate) fn retire_unreachable(&self, reference: ObjectReference) -> io::Result<()> {
        let _opening = self
            .opening
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        let _validation = match self.checkpoint_validation.try_write() {
            Ok(validation) => validation,
            Err(std::sync::TryLockError::Poisoned(error)) => error.into_inner(),
            Err(std::sync::TryLockError::WouldBlock) => {
                return Err(io::Error::new(
                    io::ErrorKind::WouldBlock,
                    "immutable checkpoint validation is active",
                ));
            }
        };
        let handles = self
            .handles
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        if handles.iter().any(|(key, handle)| {
            key.reference() == Some(reference) && Arc::strong_count(&handle.file) != 1
        }) {
            return Err(io::Error::new(
                io::ErrorKind::WouldBlock,
                "unreachable immutable object still has an active read",
            ));
        }
        drop(handles);
        self.remove_idle_matching(|key| key.reference() == Some(reference), usize::MAX);
        self.mount_verified
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .remove(&reference);
        self.bindings
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .retain(|_, binding| binding.reference != reference);
        Ok(())
    }

    /// Mounts verified checkpoint content without copying the dataset. The
    /// alias and the immutable object share an inode; mutable opens detach it.
    ///
    /// Every mount hashes the complete object (unless this process published
    /// that exact inode). Admission then opens the mounted artifacts through
    /// the handle cache, whose cold validation would hash the same inode a
    /// second time. The mount therefore leaves a one-shot record: the next
    /// cold open of the object skips the identity hash only when its
    /// descriptor still has the hashed descriptor's native identity, length
    /// and modification time. Later cold opens hash in full again.
    #[cfg(test)]
    pub(crate) fn mount_verification_record_count(&self) -> usize {
        self.mount_verified
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .len()
    }

    pub(crate) fn mount(
        &self,
        path: &Path,
        binding: ImmutableFileBinding,
        context: &FileOpenContext,
    ) -> io::Result<()> {
        self.mount_controlled(path, binding, context, &mut ValidationAdmission(|_| Ok(())))
    }

    pub(crate) fn mount_controlled(
        &self,
        path: &Path,
        binding: ImmutableFileBinding,
        context: &FileOpenContext,
        control: &mut impl crate::file_io::ReadAdmissionControl,
    ) -> io::Result<()> {
        // Mount validation uses a transient handle and a fixed-size buffer;
        // mounting an unopened artifact must not warm the descriptor cache.
        // Keep the verified handle alive until the alias has been installed.
        // A failed remount must not leave an earlier mount's record behind.
        self.mount_verified
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .remove(&binding.reference);
        let (verified, hashed, check) = Self::open_verified_object_controlled_from(
            Some(&binding),
            None,
            context,
            DescriptorKind::Transient,
            control,
            None,
        )?;
        self.state.record_identity_verified(hashed);
        // Record only a complete hash whose descriptor stamp, taken before the
        // first payload read, still matches after the hash. A skipped
        // (same-process publication) hash leaves no mount record.
        let verified_stamp = match check {
            IdentityCheck::Hashed(Some(before)) if hashed == binding.reference.byte_length => {
                verified
                    .with_native(ObjectStamp::of_native)
                    .ok()
                    .filter(|after| *after == before)
            }
            _ => None,
        };
        let reference = binding.reference;
        let mounted = self.mount_alias(path, binding, &verified);
        let mut records = self
            .mount_verified
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        match verified_stamp.filter(|_| mounted.is_ok()) {
            Some(stamp) => {
                if records.insert(reference, stamp, MOUNT_VERIFICATION_RECORDS_PER_PROJECT) {
                    self.state.record_mount_verification_eviction();
                }
            }
            None => {
                records.remove(&reference);
            }
        }
        mounted
    }

    fn mount_alias(
        &self,
        path: &Path,
        binding: ImmutableFileBinding,
        _verified: &File,
    ) -> io::Result<()> {
        // Reopening a branch usually finds the checkpoint alias already mounted.
        // Only reuse a regular, no-follow alias to this exact verified inode.
        // Equal bytes, link counts and the binding map cannot establish that.
        // The live verified handle prevents file-ID reuse during this check.
        // Cooperating branch admission still excludes concurrent alias mutation.
        #[cfg(unix)]
        if let Ok(alias) = fs::symlink_metadata(path)
            && alias.is_file()
            && crate::native_file_identity::of_metadata(&alias)
                == crate::native_file_identity::of_metadata(&_verified.metadata()?)
        {
            // Restore copy-on-write tracking even when admission cleared it.
            return self.bind(path, binding);
        }
        let candidate = loop {
            let candidate = alias_candidate_path(path)?;
            match fs::hard_link(&binding.object_path, &candidate) {
                Ok(()) => break AliasCandidate(candidate),
                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
                Err(error) => return Err(error),
            }
        };
        // Aliases are recoverable from the durable head. Their installation
        // does not publish a schema/data commit or require a durability barrier.
        fs::rename(&candidate.0, path)?;
        self.bind(path, binding)
    }

    /// Gives a mutator an independent inode before it can change shared bytes.
    /// Only an actual write copies content; a truncating write copies no data.
    pub(crate) fn detach_for_write(
        &self,
        path: &Path,
        context: &FileOpenContext,
        truncate: bool,
    ) -> io::Result<()> {
        let (candidate, mut destination) = loop {
            let candidate = alias_candidate_path(path)?;
            match OpenOptions::new()
                .write(true)
                .create_new(true)
                .open_with_context(&candidate, context)
            {
                Ok(file) => break (AliasCandidate(candidate), file),
                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
                Err(error) => return Err(error),
            }
        };
        if !truncate {
            // Read through the immutable binding's positioned cursor, never
            // through the shared cache handle's sequential cursor.
            let mut source = OpenOptions::new()
                .read(true)
                .open_with_context(path, context)?;
            io::copy(&mut source, &mut destination)?;
            destination.set_permissions(source.metadata()?.permissions())?;
        }
        destination.flush()?;
        destination.sync_all()?;
        // Close the candidate before replacement, including on Windows.
        drop(destination);
        crate::durability::durable_replace_file(&candidate.0, path)
    }

    /// A live read owns an Arc. Only the cache's final, idle Arc is evictable.
    pub(crate) fn get(
        &self,
        binding: &ImmutableFileBinding,
        context: &FileOpenContext,
    ) -> io::Result<Arc<File>> {
        self.get_admitted(binding, context, |_| Ok(()))
            .map(|(file, _)| file)
    }

    /// Cold validation is admitted before payload I/O while the opening lock
    /// coalesces readers. A warm lease performs no additional validation read.
    pub(crate) fn get_admitted(
        &self,
        binding: &ImmutableFileBinding,
        context: &FileOpenContext,
        admit_validation: impl FnMut(u64) -> io::Result<()>,
    ) -> io::Result<(Arc<File>, u64)> {
        self.get_controlled(binding, context, &mut ValidationAdmission(admit_validation))
    }

    pub(crate) fn get_controlled(
        &self,
        binding: &ImmutableFileBinding,
        context: &FileOpenContext,
        control: &mut impl crate::file_io::ReadAdmissionControl,
    ) -> io::Result<(Arc<File>, u64)> {
        self.get_controlled_from(Some(binding), None, context, control)
    }

    pub(crate) fn get_captured_controlled(
        &self,
        binding: Option<&ImmutableFileBinding>,
        source: &CapturedSource,
        context: &FileOpenContext,
        control: &mut impl crate::file_io::ReadAdmissionControl,
    ) -> io::Result<(Arc<File>, u64)> {
        self.get_controlled_from(binding, Some(source), context, control)
    }

    fn get_controlled_from(
        &self,
        binding: Option<&ImmutableFileBinding>,
        source: Option<&CapturedSource>,
        context: &FileOpenContext,
        control: &mut impl crate::file_io::ReadAdmissionControl,
    ) -> io::Result<(Arc<File>, u64)> {
        // Keep retirement from racing the gap between cache lookup and the
        // returned lease. A held native Arc then provides the in-flight proof.
        let _validation = match self.checkpoint_validation.try_read() {
            Ok(guard) => guard,
            Err(std::sync::TryLockError::Poisoned(error)) => error.into_inner(),
            Err(std::sync::TryLockError::WouldBlock) => {
                return Err(io::Error::new(
                    io::ErrorKind::WouldBlock,
                    "immutable retirement is active",
                ))
            }
        };
        let key = match source {
            Some(source) => CacheKey::Captured(source.key.clone()),
            None => CacheKey::Managed(
                binding
                    .ok_or_else(|| io::Error::other("missing managed binding"))?
                    .reference,
            ),
        };
        control.checkpoint()?;
        if let Some(file) = self.cached_key(&key) {
            self.state.record_cache_hit();
            return Ok((file, 0));
        }
        // Coalesce cold opens without holding the eviction map across admission.
        // This serializes file validation, never waits for descriptor capacity.
        let _opening = self
            .opening
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        control.checkpoint()?;
        if let Some(file) = self.cached_key(&key) {
            self.state.record_cache_hit();
            return Ok((file, 0));
        }
        self.state.record_cache_miss();
        // Consume the mount's one-shot record whether or not it still matches.
        let mount_verified = match (source, binding) {
            (None, Some(binding)) => self
                .mount_verified
                .lock()
                .unwrap_or_else(|error| error.into_inner())
                .remove(&binding.reference),
            _ => None,
        };
        let (file, validated, check) = Self::open_verified_object_controlled_from(
            binding,
            source,
            context,
            DescriptorKind::ImmutableCache,
            control,
            mount_verified,
        )?;
        match check {
            IdentityCheck::Hashed(_) => self.state.record_identity_verified(validated),
            IdentityCheck::ReusedMount => self.state.record_mount_verification_reuse(),
            IdentityCheck::Trusted => {}
        }
        let file = Arc::new(file);
        self.handles
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .insert(
                key,
                CachedHandle {
                    file: file.clone(),
                    last_used: self.next_tick(),
                },
            );
        Ok((file, validated))
    }

    fn next_tick(&self) -> u64 {
        self.access_tick
            .try_update(Ordering::Relaxed, Ordering::Relaxed, |tick| {
                Some(tick.saturating_add(1))
            })
            .expect("the access tick update always succeeds")
    }

    fn cached(&self, reference: ObjectReference) -> Option<Arc<File>> {
        let _validation = match self.checkpoint_validation.try_read() {
            Ok(guard) => guard,
            Err(std::sync::TryLockError::Poisoned(error)) => error.into_inner(),
            Err(std::sync::TryLockError::WouldBlock) => return None,
        };
        self.cached_key(&CacheKey::Managed(reference))
    }

    fn cached_key(&self, key: &CacheKey) -> Option<Arc<File>> {
        let mut handles = self
            .handles
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        let handle = handles.get_mut(key)?;
        handle.last_used = self.next_tick();
        Some(handle.file.clone())
    }

    /// Returns the verified handle and the number of payload bytes hashed.
    /// Returns the handle, the validation bytes charged, and how identity was
    /// established. `mount_verified` is the stamp a mount recorded after
    /// hashing this object; it is used only if the opened descriptor matches.
    fn open_verified_object_controlled_from(
        binding: Option<&ImmutableFileBinding>,
        source: Option<&CapturedSource>,
        context: &FileOpenContext,
        kind: DescriptorKind,
        control: &mut impl crate::file_io::ReadAdmissionControl,
        mount_verified: Option<ObjectStamp>,
    ) -> io::Result<(File, u64, IdentityCheck)> {
        control.checkpoint()?;
        let mut file = match source {
            Some(source) => source
                .directory
                .open_child_kind(context, &source.key.name, kind)?,
            None => OpenOptions::new()
                .read(true)
                .descriptor_kind(kind)
                .open_with_context(
                    &binding
                        .ok_or_else(|| io::Error::other("missing managed binding"))?
                        .object_path,
                    context,
                )?,
        };
        let metadata = file.metadata()?;
        if let Some(source) = source
            && let CapturedIdentity::Native { identity, length } = source.key.identity
        {
            control.checkpoint()?;
            if !metadata.is_file()
                || metadata.len() != length
                || file.with_native(crate::native_file_identity::of_file)? != identity
            {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "captured native identity mismatch",
                ));
            }
            // Preserve the cache's existing validation accounting.
            return Ok((
                file,
                binding.map_or(0, |binding| binding.reference.byte_length),
                IdentityCheck::Trusted,
            ));
        }
        let binding = binding.ok_or_else(|| io::Error::other("missing managed binding"))?;
        if !metadata.is_file() || metadata.len() != binding.reference.byte_length {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "immutable handle identity length mismatch",
            ));
        }
        // The exact inode this process hashed while publishing it, unmodified
        // since, is not re-hashed. Demand reads keep their block checks.
        if file.with_native(|native| {
            Ok(crate::immutable_object::skip_published_rehash(
                binding.reference,
                native,
            ))
        })? {
            return Ok((file, 0, IdentityCheck::Trusted));
        }
        // The mount that just hashed this exact inode, unmodified since,
        // already authenticated these bytes. Demand reads keep block checks.
        if let Some(stamp) = mount_verified
            && file
                .with_native(ObjectStamp::of_native)
                .is_ok_and(|current| current == stamp)
        {
            return Ok((file, 0, IdentityCheck::ReusedMount));
        }
        // Descriptor rejection occurs before this charge. No payload may be
        // read until the caller has reserved the complete identity validation.
        control.admit_validation(binding.reference.byte_length)?;
        // Stamp before hashing: a mount records only a stamp that is unchanged
        // across the whole hash, so a write racing the hash cannot be recorded.
        let pre_hash_stamp = file.with_native(ObjectStamp::of_native).ok();
        let mut hasher = crate::immutable_object::identity_hasher(
            binding.reference.kind,
            binding.reference.format_version,
            binding.reference.byte_length,
        );
        let mut buffer = [0_u8; 64 * 1024];
        let mut remaining = binding.reference.byte_length;
        while remaining > 0 {
            control.checkpoint()?;
            let chunk = remaining.min(buffer.len() as u64) as usize;
            let read = match file.read(&mut buffer[..chunk]) {
                Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
                result => result?,
            };
            if read == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "immutable identity validation ended early",
                ));
            }
            remaining -= read as u64;
            hasher.update(&buffer[..read]);
        }
        control.checkpoint()?;
        // Detect length drift without fetching an unadmitted EOF sentinel.
        if file.metadata()?.len() != binding.reference.byte_length
            || hasher.finish().sha256 != binding.reference.sha256
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "immutable handle identity digest mismatch",
            ));
        }
        Ok((
            file,
            binding.reference.byte_length,
            IdentityCheck::Hashed(pre_hash_stamp),
        ))
    }
}

impl ImmutableFileHandles {
    // No temporary key vectors: the cloned key keeps its metadata admitted
    // through native close and empty BTree node deallocation outside the lock.
    fn remove_idle_matching(
        &self,
        eligible: impl Fn(&CacheKey) -> bool,
        requested: usize,
    ) -> usize {
        let mut count = 0;
        while count < requested {
            let removed = {
                let mut handles = self.handles.lock().unwrap_or_else(|e| e.into_inner());
                let key = handles
                    .iter()
                    .filter(|(key, handle)| eligible(key) && Arc::strong_count(&handle.file) == 1)
                    .min_by_key(|(_, handle)| handle.last_used)
                    .map(|(key, _)| key.clone());
                key.map(|key| {
                    let handle = handles.remove(&key).expect("selected idle handle exists");
                    let empty = handles.is_empty().then(|| std::mem::take(&mut *handles));
                    (key, handle, empty)
                })
            };
            let Some((key, handle, empty)) = removed else {
                break;
            };
            drop(handle);
            drop(empty);
            drop(key);
            count += 1;
        }
        self.state.record_cache_evictions(count);
        count
    }

    pub(crate) fn retire_source(&self, capture: u64) {
        self.remove_idle_matching(|key| key.capture() == Some(capture), usize::MAX);
    }
}

impl DescriptorCache for ImmutableFileHandles {
    fn evict_idle(&self, requested: usize) -> usize {
        self.remove_idle_matching(|_| true, requested)
    }
}

impl Drop for ImmutableFileHandles {
    fn drop(&mut self) {
        let handles = self.handles.get_mut().unwrap_or_else(|e| e.into_inner());
        while let Some((key, handle)) = handles.pop_first() {
            let empty = handles.is_empty().then(|| std::mem::take(handles));
            drop(handle);
            drop(empty);
            drop(key);
        }
    }
}

struct ValidationAdmission<F>(F);
impl<F: FnMut(u64) -> io::Result<()>> crate::file_io::ReadAdmissionControl
    for ValidationAdmission<F>
{
    fn admit_validation(&mut self, bytes: u64) -> io::Result<()> {
        (self.0)(bytes)
    }
    fn checkpoint(&mut self) -> io::Result<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::file_descriptors::ProjectFileDescriptors;
    use crate::immutable_object::{ImmutableObjectStore, ObjectKind};
    use std::io::{Seek, SeekFrom};

    struct Fixture {
        root: PathBuf,
        project: ProjectFileDescriptors,
        objects: ImmutableObjectStore,
        reference: ObjectReference,
        bytes: Vec<u8>,
    }

    impl Fixture {
        fn new() -> Self {
            Self::new_with(|_| ()).0
        }

        fn new_with<T>(attach: impl FnOnce(&ProjectFileDescriptors) -> T) -> (Self, T) {
            let root = loop {
                let root = std::env::temp_dir().join(format!(
                    "hawdb-immutable-alias-{}-{}",
                    std::process::id(),
                    NEXT_ALIAS_CANDIDATE.fetch_add(1, Ordering::Relaxed),
                ));
                match fs::create_dir(&root) {
                    Ok(()) => break root,
                    Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
                    Err(error) => panic!("create immutable alias fixture: {error}"),
                }
            };
            let project = ProjectFileDescriptors::acquire_existing(&root, 8).unwrap();
            let attached = attach(&project);
            let mut objects = ImmutableObjectStore::open(root.join("immutable")).unwrap();
            let bytes = (0..128 * 1024).map(|i| (i % 251) as u8).collect::<Vec<_>>();
            let reference = ObjectReference::for_bytes(ObjectKind::CheckpointArtifact, 1, &bytes);
            objects.publish(reference, &bytes).unwrap();
            (
                Self {
                    root,
                    project,
                    objects,
                    reference,
                    bytes,
                },
                attached,
            )
        }

        fn mount(&self, name: &str) -> PathBuf {
            let path = self.root.join(name);
            self.project
                .immutable_handles
                .mount(
                    &path,
                    ImmutableFileBinding {
                        reference: self.reference,
                        object_path: self.objects.object_path(self.reference),
                    },
                    &crate::file_descriptors::context_for_path(&path).unwrap(),
                )
                .unwrap();
            #[cfg(unix)]
            {
                use std::os::unix::fs::MetadataExt;
                let alias = std::fs::metadata(&path).unwrap();
                let object = std::fs::metadata(self.objects.object_path(self.reference)).unwrap();
                assert_eq!((alias.dev(), alias.ino()), (object.dev(), object.ino()));
            }
            path
        }
    }

    impl Drop for Fixture {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.root);
        }
    }

    #[cfg(unix)]
    #[test]
    fn verified_alias_reuse_avoids_namespace_mutation_and_restores_copy_on_write() {
        use crate::power_loss::{
            image::ImageLimits, IoEvent, ObservationBoundary, ObservationPoint, PowerLossModel,
        };
        for event in [IoEvent::HardLink, IoEvent::Rename] {
            let (fixture, model) = Fixture::new_with(|project| {
                PowerLossModel::attach(project, ImageLimits::default()).unwrap()
            });
            // The fault model itself retains its native root descriptor.
            let retained = fixture.project.metrics().open;
            let point = ObservationPoint {
                event,
                relative_path: PathBuf::from("checkpoint"),
                boundary: ObservationBoundary::Before,
                skip_matches: 0,
                include_descendants: true,
                keep_last: false,
            };
            // Exercise the observer on a real first installation, including
            // the randomly named hard-link candidate in this directory.
            fs::create_dir(fixture.root.join("checkpoint")).unwrap();
            model.observe(point.clone()).unwrap();
            let path = fixture.mount("checkpoint/selected.hawdb");
            assert!(model.take_observation().unwrap().is_some());
            fixture.project.immutable_handles.unbind(&path).unwrap();
            assert!(fixture
                .project
                .immutable_handles
                .binding(&path)
                .unwrap()
                .is_none());
            model.observe(point).unwrap();
            fixture.mount("checkpoint/selected.hawdb");
            assert!(model.take_observation().unwrap().is_none(), "{event:?}");
            assert!(fixture
                .project
                .immutable_handles
                .binding(&path)
                .unwrap()
                .is_some());
            assert_eq!(fixture.project.metrics().open, retained);
            assert_eq!(fixture.project.metrics().cached_handles, 0);
            // Audit the actual native history, then mutate through the rebound
            // alias. The immutable object and a preexisting reader must survive.
            model.capture().unwrap();
            let mut reader = File::open(&path).unwrap();
            fs::write(&path, b"private update").unwrap();
            assert_eq!(
                fixture.objects.read(fixture.reference).unwrap(),
                fixture.bytes
            );
            let mut old = Vec::new();
            reader.read_to_end(&mut old).unwrap();
            assert_eq!(old, fixture.bytes);
            drop(reader);
            // Recovery remounts the checkpoint rather than reusing a detached
            // writable inode. Its old reader still retains the private update.
            let mut private = File::open(&path).unwrap();
            fixture.mount("checkpoint/selected.hawdb");
            assert_eq!(fs::read(&path).unwrap(), fixture.bytes);
            let mut old_private = Vec::new();
            private.read_to_end(&mut old_private).unwrap();
            assert_eq!(old_private, b"private update");
            drop(private);
            model.capture().unwrap();
        }
    }

    #[cfg(unix)]
    #[test]
    fn equal_content_alias_with_multiple_links_is_remounted_to_verified_object() {
        let fixture = Fixture::new();
        let path = fixture.mount("selected.hawdb");
        // Bypass binding-aware IO to simulate an existing wrong alias on reopen.
        std::fs::remove_file(&path).unwrap();
        std::fs::copy(fixture.objects.object_path(fixture.reference), &path).unwrap();
        let other = fixture.root.join("other-copy");
        std::fs::hard_link(&path, &other).unwrap();
        let mut private = File::open(&path).unwrap();
        fixture.mount("selected.hawdb");
        assert_eq!(fs::read(&path).unwrap(), fixture.bytes);
        fs::write(&path, b"new private bytes").unwrap();
        assert_eq!(
            fixture.objects.read(fixture.reference).unwrap(),
            fixture.bytes
        );
        let mut previous = Vec::new();
        private.read_to_end(&mut previous).unwrap();
        assert_eq!(previous, fixture.bytes);
        assert_eq!(std::fs::read(other).unwrap(), fixture.bytes);
    }

    #[cfg(unix)]
    #[test]
    fn symlink_to_verified_object_is_replaced_with_regular_alias() {
        let fixture = Fixture::new();
        let path = fixture.mount("selected.hawdb");
        std::fs::remove_file(&path).unwrap();
        std::os::unix::fs::symlink(fixture.objects.object_path(fixture.reference), &path).unwrap();
        fixture.mount("selected.hawdb");
        assert!(std::fs::symlink_metadata(&path).unwrap().is_file());
        fs::write(path, b"private update").unwrap();
        assert_eq!(
            fixture.objects.read(fixture.reference).unwrap(),
            fixture.bytes
        );
    }

    #[test]
    fn existing_alias_never_bypasses_complete_object_validation() {
        let fixture = Fixture::new();
        let path = fixture.mount("selected.hawdb");
        let binding = fixture
            .project
            .immutable_handles
            .binding(&path)
            .unwrap()
            .unwrap();
        // A same-length in-place corruption preserves both alias identity and
        // metadata. Managed-object validation must still reject its digest.
        let mut bytes = fixture.bytes.clone();
        let middle = bytes.len() / 2;
        bytes[middle] ^= 1;
        std::fs::write(&binding.object_path, &bytes).unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), bytes);
        let context = crate::file_descriptors::context_for_path(&path).unwrap();
        let error = fixture
            .project
            .immutable_handles
            .mount(&path, binding, &context)
            .unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
        assert!(error.to_string().contains("digest mismatch"));
        assert_eq!(fixture.project.metrics().open, 0);
        assert_eq!(fixture.project.metrics().cached_handles, 0);
        assert_eq!(std::fs::read(&path).unwrap(), bytes);
    }

    #[test]
    fn repeated_checkpoint_mounts_keep_cache_cold_and_rebind_every_alias() {
        let fixture = Fixture::new();
        let aliases = (0..32)
            .map(|i| format!("checkpoint-{i}"))
            .collect::<Vec<_>>();
        for alias in &aliases {
            fixture.mount(alias);
        }
        let peak = fixture.project.metrics().high_water;
        let start = std::time::Instant::now();
        for _ in 0..8 {
            // A new admission cannot rely on the previous binding map.
            for alias in &aliases {
                fixture
                    .project
                    .immutable_handles
                    .unbind(&fixture.root.join(alias))
                    .unwrap();
            }
            for alias in &aliases {
                let path = fixture.mount(alias);
                let binding = fixture
                    .project
                    .immutable_handles
                    .binding(&path)
                    .unwrap()
                    .unwrap();
                assert_eq!(binding.reference, fixture.reference);
            }
            let metrics = fixture.project.metrics();
            assert_eq!(metrics.open, 0);
            assert_eq!(metrics.cached_handles, 0);
            assert_eq!(metrics.reserved, 0);
            assert_eq!(metrics.high_water, peak);
        }
        eprintln!(
            "256 remounts / 128 KiB per verified object: {:?}",
            start.elapsed()
        );
    }

    #[test]
    fn checkpoint_units_immutable_handle_contended_opening_defers_and_retries() {
        use crate::background::{CheckpointWorkContext, CheckpointWorkError};
        let fixture = Fixture::new();
        let path = fixture.mount("checkpoint.page");
        let handles = &fixture.project.immutable_handles;
        let binding = handles.binding(&path).unwrap().unwrap();
        let context = crate::file_descriptors::context_for_path(&path).unwrap();
        let work = CheckpointWorkContext::default();
        let opening = handles.opening.lock().unwrap();
        assert!(matches!(
            handles.checkpoint_get(&binding, &context, &work),
            Err(CheckpointImmutableFileError::Work(
                CheckpointWorkError::Contended("immutable file validation")
            ))
        ));
        assert_eq!(fixture.project.metrics().open, 0);
        drop(opening);
        let file = handles.checkpoint_get(&binding, &context, &work).unwrap();
        let mut borrowed = file.as_ref();
        borrowed.seek(SeekFrom::Start(0)).unwrap();
        let mut bytes = Vec::new();
        borrowed.read_to_end(&mut bytes).unwrap();
        assert_eq!(bytes, fixture.bytes);
        assert_eq!(fixture.project.metrics().cached_handles, 1);
        assert_eq!(handles.evict_idle(1), 0);
        drop(file);
        assert_eq!(handles.evict_idle(1), 1);
        assert_eq!(fixture.project.metrics().open, 0);
    }

    #[test]
    fn shared_alias_detaches_before_append_or_truncate_and_preserves_readers() {
        for (truncate, native_flags) in [(false, false), (true, false), (false, true), (true, true)]
        {
            let fixture = Fixture::new();
            let path = fixture.mount("selected.hawdb");
            let sibling = fixture.mount("sibling.hawdb");
            assert_eq!(fixture.project.metrics().open, 0);
            assert_eq!(fixture.project.metrics().cached_handles, 0);
            let mut snapshot = File::open(&path).unwrap();
            assert_eq!(
                OpenOptions::new()
                    .write(true)
                    .create_new(true)
                    .open(&path)
                    .unwrap_err()
                    .kind(),
                io::ErrorKind::AlreadyExists,
            );
            assert_eq!(fs::read(&path).unwrap(), fixture.bytes);
            #[cfg(unix)]
            let _native_read_only = if native_flags {
                use std::os::unix::fs::OpenOptionsExt;
                // Opaque native flags detach before removing the binding, so
                // a later ordinary write cannot mutate the shared object.
                Some(
                    OpenOptions::new()
                        .read(true)
                        .custom_flags(0)
                        .open(&path)
                        .unwrap(),
                )
            } else {
                None
            };
            #[cfg(not(unix))]
            let _ = native_flags;
            if truncate {
                fs::write(&path, b"replacement").unwrap();
                assert_eq!(fs::read(&path).unwrap(), b"replacement");
            } else {
                let mut writer = OpenOptions::new().append(true).open(&path).unwrap();
                writer.write_all(b"suffix").unwrap();
                drop(writer);
                let mut expected = fixture.bytes.clone();
                expected.extend_from_slice(b"suffix");
                assert_eq!(fs::read(&path).unwrap(), expected);
            }
            assert_eq!(
                fixture.objects.read(fixture.reference).unwrap(),
                fixture.bytes
            );
            assert_eq!(fs::read(&sibling).unwrap(), fixture.bytes);
            let mut original = Vec::new();
            snapshot.read_to_end(&mut original).unwrap();
            assert_eq!(original, fixture.bytes);
            assert!(fixture.project.metrics().high_water <= 8);
        }
    }

    #[test]
    fn replacement_and_removal_update_future_opens_without_invalidating_snapshot_identity() {
        let fixture = Fixture::new();
        let path = fixture.mount("selected.hawdb");
        let mut snapshot = File::open(&path).unwrap();
        let candidate = fixture.root.join("replacement.tmp");
        let mut replacement = File::create(&candidate).unwrap();
        replacement.write_all(b"published replacement").unwrap();
        replacement.sync_all().unwrap();
        drop(replacement);
        crate::durability::durable_replace_file(&candidate, &path).unwrap();
        assert_eq!(fs::read(&path).unwrap(), b"published replacement");
        fs::remove_file(&path).unwrap();
        assert_eq!(
            File::open(&path).unwrap_err().kind(),
            io::ErrorKind::NotFound
        );
        let mut original = Vec::new();
        snapshot.read_to_end(&mut original).unwrap();
        assert_eq!(original, fixture.bytes);
        snapshot.seek(SeekFrom::Start(0)).unwrap();
        assert_eq!(
            fixture.objects.read(fixture.reference).unwrap(),
            fixture.bytes
        );
    }
}