hawdb-vector-projection 0.27.0

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
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
// 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.

use crate::build::BuildState;
use crate::error::{ProjectionError, Result};
use crate::model::{
    ids_bytes, reconstruction_factor_bytes, ProjectionBuildConfig, ProjectionBuildReport,
    ProjectionManifest, RaBitQBitWidth, SegmentDescriptor,
};
use crc32fast::Hasher;
use hawdb_core::SharedAllocation;
#[cfg(feature = "storage-io")]
use hawdb_integrity::Crc32cHasher;
#[cfg(feature = "storage-io")]
use hawdb_storage::file_io::try_exists as target_exists;
#[cfg(feature = "storage-io")]
use hawdb_storage::file_io::{self as fs, File, OpenOptions};
#[cfg(feature = "storage-io")]
use hawdb_storage::immutable_object::{ObjectKind, ObjectReference, ObjectReferenceWriter};
use memmap2::Mmap;
#[cfg(not(feature = "storage-io"))]
use std::fs::exists as target_exists;
#[cfg(not(feature = "storage-io"))]
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

mod admission;
mod stream_verify;

#[doc(hidden)]
pub use admission::ProjectionReadAdmission;
pub(crate) use admission::Unaccounted;

const FOOTER_MAGIC: &[u8; 8] = b"SKRQBF01";
const FOOTER_BYTES: u64 = 8 + 4 + FOOTER_MAGIC.len() as u64;
static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);

#[cfg(test)]
thread_local! {
    static BEFORE_PROJECTION_MAP: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
        const { std::cell::RefCell::new(None) };
}

#[cfg(all(test, feature = "storage-io"))]
thread_local! {
    static BEFORE_PROJECTION_OPEN: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
        const { std::cell::RefCell::new(None) };
}

#[cfg(test)]
thread_local! {
    static SEGMENT_CHECKSUM_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

#[derive(Debug)]
pub struct ProjectionWriter {
    target: PathBuf,
    temporary: PathBuf,
    file: Option<File>,
    state: BuildState,
    payload_hasher: Hasher,
    payload_bytes: u64,
    segments: Vec<SegmentDescriptor>,
    finished: bool,
}

impl ProjectionWriter {
    pub fn create(path: impl AsRef<Path>, config: ProjectionBuildConfig) -> Result<Self> {
        let target = path.as_ref().to_path_buf();
        let parent = target.parent().ok_or_else(|| {
            ProjectionError::InvalidConfiguration(
                "projection artifact path must have a parent".to_string(),
            )
        })?;
        fs::create_dir_all(parent)?;
        if target_exists(&target)? {
            return Err(ProjectionError::InvalidConfiguration(format!(
                "projection generation already exists at {}",
                target.display()
            )));
        }
        let state = BuildState::new(config.validated()?)?;
        let temporary = temporary_path(&target);
        let file = OpenOptions::new()
            .create_new(true)
            .write(true)
            .open(&temporary)?;
        Ok(Self {
            target,
            temporary,
            file: Some(file),
            state,
            payload_hasher: Hasher::new(),
            payload_bytes: 0,
            segments: Vec::new(),
            finished: false,
        })
    }

    pub fn push(&mut self, id: u64, vector: &[f32]) -> Result<()> {
        self.state.push(id, vector)?;
        if self.state.pending_is_full() {
            self.flush_segment(true)?;
        }
        Ok(())
    }

    pub fn finish(mut self) -> Result<FileProjection> {
        self.flush_segment(false)?;
        let payload_checksum = self.payload_hasher.clone().finalize();
        let manifest = ProjectionManifest::new(
            &self.state.config,
            self.state.document_count,
            self.state.source_digest,
            self.payload_bytes,
            payload_checksum,
            std::mem::take(&mut self.segments),
        );
        manifest.validate()?;
        let manifest_bytes = serde_json::to_vec(&manifest)?;
        let manifest_checksum = crc32fast::hash(&manifest_bytes);
        let file = self.file.as_mut().expect("unfinished writer owns a file");
        file.write_all(&manifest_bytes)?;
        file.write_all(&(manifest_bytes.len() as u64).to_le_bytes())?;
        file.write_all(&manifest_checksum.to_le_bytes())?;
        file.write_all(FOOTER_MAGIC)?;
        file.sync_all()?;
        drop(self.file.take());
        // Admit and validate the complete mapping before publishing the name.
        // Keep capacity through rename and the directory barrier so another
        // project owner cannot exhaust this operation's remaining IO slots.
        #[cfg(feature = "storage-io")]
        let _publication_quota = {
            let project =
                hawdb_storage::file_descriptors::ProjectFileDescriptors::acquire_component(
                    self.temporary
                        .parent()
                        .expect("temporary artifact has a parent"),
                    false,
                )
                .map_err(|error| ProjectionError::Io(std::io::Error::other(error)))?;
            project.reserve_admission(2)?
        };
        #[cfg(feature = "storage-io")]
        let projection = FileProjection::open_named_with_reference(&self.temporary, &self.target)?;
        #[cfg(not(feature = "storage-io"))]
        let projection = FileProjection::open_named(&self.temporary, &self.target)?;
        fs::rename(&self.temporary, &self.target)?;
        sync_parent(&self.target)?;
        self.finished = true;
        Ok(projection)
    }

    fn flush_segment(&mut self, reserve_next_segment: bool) -> Result<()> {
        if self.state.pending.is_empty() {
            return Ok(());
        }
        let segment = self.state.take_pending();
        let offset = self.payload_bytes;
        let mut segment_hasher = Hasher::new();
        let file = self.file.as_mut().expect("unfinished writer owns a file");
        for id in &segment.ids {
            write_payload(
                file,
                &id.to_le_bytes(),
                &mut segment_hasher,
                &mut self.payload_hasher,
            )?;
        }
        for scale in &segment.reconstruction_scales {
            write_payload(
                file,
                &scale.to_bits().to_le_bytes(),
                &mut segment_hasher,
                &mut self.payload_hasher,
            )?;
        }
        for offset in &segment.reconstruction_offsets {
            write_payload(
                file,
                &offset.to_bits().to_le_bytes(),
                &mut segment_hasher,
                &mut self.payload_hasher,
            )?;
        }
        for norm in &segment.original_norms {
            write_payload(
                file,
                &norm.to_le_bytes(),
                &mut segment_hasher,
                &mut self.payload_hasher,
            )?;
        }
        write_payload(
            file,
            &segment.codes,
            &mut segment_hasher,
            &mut self.payload_hasher,
        )?;
        let payload_bytes = segment.payload_len() as u64;
        self.segments.push(SegmentDescriptor {
            index: self.segments.len(),
            base_ordinal: segment.base_ordinal,
            row_count: segment.row_count(),
            payload_offset: offset,
            payload_bytes,
            payload_checksum: segment_hasher.finalize(),
        });
        self.payload_bytes = self.payload_bytes.saturating_add(payload_bytes);
        drop(segment);
        if reserve_next_segment {
            self.state.reserve_pending();
        }
        Ok(())
    }
}

impl Drop for ProjectionWriter {
    fn drop(&mut self) {
        if !self.finished {
            #[cfg(feature = "storage-io")]
            let Ok(context) =
                hawdb_storage::file_descriptors::FileOpenContext::for_path(&self.temporary)
            else {
                return;
            };
            #[cfg(feature = "storage-io")]
            let Ok(_operation) = context.internal_operation() else {
                return;
            };
            drop(self.file.take());
            // Internal cleanup keeps the original ledger and may exceed the
            // foreground target. Native failure retains only the unpublished
            // temporary name; the final generation is never removed here.
            let _ = fs::remove_file(&self.temporary);
        }
    }
}

#[derive(Debug)]
pub struct FileProjection<Memory = ()> {
    contents: SharedAllocation<ProjectionContents<Memory>>,
}

#[derive(Debug)]
struct ProjectionContents<Memory> {
    path: PathBuf,
    manifest: ProjectionManifest,
    #[cfg(feature = "storage-io")]
    object_reference: Option<ObjectReference>,
    #[cfg(feature = "storage-io")]
    artifact_checksum: Option<u64>,
    mmap: Mmap,
    // Payloads and their shared allocation die before either capacity owner.
    _path_memory: Memory,
    _metadata_memory: Memory,
}

impl<Memory> Clone for FileProjection<Memory> {
    fn clone(&self) -> Self {
        Self {
            contents: self.contents.clone(),
        }
    }
}

impl FileProjection {
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        Self::open_named(path, path)
    }

    /// Open an already selected native file. The path is display metadata;
    /// callers retain the source authority and immutable lifetime separately.
    pub fn open_file(input: File, identity_path: &Path) -> Result<Self> {
        Self::open_admitted_file(input, identity_path, &admission::Unaccounted)
    }

    #[cfg(feature = "storage-io")]
    #[doc(hidden)]
    pub fn open_file_with_reference(input: File, identity_path: &Path) -> Result<Self> {
        Self::open_admitted_file_with_reference(input, identity_path, &admission::Unaccounted)
    }

    fn open_named(source: &Path, identity_path: &Path) -> Result<Self> {
        #[cfg(all(test, feature = "storage-io"))]
        if let Some(callback) = BEFORE_PROJECTION_OPEN.with(|slot| slot.replace(None)) {
            callback();
        }
        Self::open_file(File::open(source)?, identity_path)
    }

    #[cfg(feature = "storage-io")]
    fn open_named_with_reference(source: &Path, identity_path: &Path) -> Result<Self> {
        #[cfg(test)]
        if let Some(callback) = BEFORE_PROJECTION_OPEN.with(|slot| slot.replace(None)) {
            callback();
        }
        Self::open_file_with_reference(File::open(source)?, identity_path)
    }

    /// Constructs shared metadata under caller-supplied admission. The supplied
    /// handle must already have native admission and an immutable lifetime.
    /// `identity_path` is display metadata, not a source/binding certificate.
    #[doc(hidden)]
    pub fn open_admitted_file<A: ProjectionReadAdmission>(
        input: File,
        identity_path: &Path,
        admission: &A,
    ) -> Result<FileProjection<A::Retained>> {
        Self::open_admitted_file_impl(input, identity_path, admission, false)
    }

    #[cfg(feature = "storage-io")]
    #[doc(hidden)]
    pub fn open_admitted_file_with_reference<A: ProjectionReadAdmission>(
        input: File,
        identity_path: &Path,
        admission: &A,
    ) -> Result<FileProjection<A::Retained>> {
        Self::open_admitted_file_impl(input, identity_path, admission, true)
    }

    fn open_admitted_file_impl<A: ProjectionReadAdmission>(
        input: File,
        identity_path: &Path,
        admission: &A,
        #[cfg(feature = "storage-io")] capture_reference: bool,
        #[cfg(not(feature = "storage-io"))] _capture_reference: bool,
    ) -> Result<FileProjection<A::Retained>> {
        admission.checkpoint()?;
        let fixed = admission::add(
            stream_verify::BUFFER_BYTES + 4096 + FOOTER_BYTES as usize,
            std::mem::size_of::<ProjectionContents<A::Retained>>(),
        )?;
        let _open_scratch = admission.reserve_scratch(fixed)?;
        let path_bytes = admission::mul(identity_path.as_os_str().as_encoded_bytes().len(), 2)?;
        let allocation = admission::add(
            std::mem::size_of::<ProjectionContents<A::Retained>>(),
            admission::add(
                2 * std::mem::size_of::<usize>(),
                std::mem::align_of::<ProjectionContents<A::Retained>>(),
            )?,
        )?;
        let path_memory = admission.reserve_retained(admission::add(path_bytes, allocation)?)?;
        let path = identity_path.to_path_buf();
        let mut file = input;
        let file_bytes = {
            let _io = admission.acquire_io()?;
            file.metadata()?.len()
        };
        if file_bytes < FOOTER_BYTES {
            return Err(ProjectionError::CorruptArtifact(
                "artifact is shorter than the footer".into(),
            ));
        }
        {
            let _io = admission.acquire_io()?;
            file.seek(SeekFrom::End(-(FOOTER_BYTES as i64)))?;
        }
        let mut footer = [0u8; FOOTER_BYTES as usize];
        admission::read_exact(&mut file, &mut footer, admission)?;
        let manifest_bytes =
            u64::from_le_bytes(footer[..8].try_into().expect("fixed footer length"));
        let manifest_checksum =
            u32::from_le_bytes(footer[8..12].try_into().expect("fixed footer length"));
        if &footer[12..] != FOOTER_MAGIC {
            return Err(ProjectionError::CorruptArtifact(
                "footer magic mismatch".into(),
            ));
        }
        let manifest_offset = file_bytes
            .checked_sub(FOOTER_BYTES)
            .and_then(|offset| offset.checked_sub(manifest_bytes))
            .ok_or_else(|| {
                ProjectionError::CorruptArtifact("manifest length exceeds artifact".to_string())
            })?;
        let manifest_len = usize::try_from(manifest_bytes).map_err(|_| {
            ProjectionError::CorruptArtifact("manifest length exceeds address space".to_string())
        })?;
        let _encoded_memory = admission.reserve_scratch(manifest_len)?;
        let mut encoded_manifest = vec![0u8; manifest_len];
        {
            let _io = admission.acquire_io()?;
            file.seek(SeekFrom::Start(manifest_offset))?;
        }
        admission::read_exact(&mut file, &mut encoded_manifest, admission)?;
        if crc32fast::hash(&encoded_manifest) != manifest_checksum {
            return Err(ProjectionError::CorruptArtifact(
                "manifest checksum mismatch".to_string(),
            ));
        }
        let plan = admission::DecodePlan::inspect(&encoded_manifest, admission)?;
        let metadata_memory = admission.reserve_retained(plan.retained)?;
        let _decode_scratch = admission.reserve_scratch(plan.scratch)?;
        let manifest: ProjectionManifest = serde_json::from_slice(&encoded_manifest)?;
        admission.checkpoint()?;
        manifest.validate()?;
        if manifest.payload_bytes != manifest_offset {
            return Err(ProjectionError::CorruptArtifact(
                "manifest offset does not match payload length".to_string(),
            ));
        }

        // Validate the held file before mapping it. Opening a reader must not
        // fault the complete payload into its mapping just to establish integrity.
        #[cfg(feature = "storage-io")]
        let mut reference = if capture_reference {
            Some(
                ObjectReferenceWriter::new(ObjectKind::CheckpointArtifact, 1, file_bytes)
                    .map_err(|error| ProjectionError::CorruptArtifact(error.to_string()))?,
            )
        } else {
            None
        };
        #[cfg(feature = "storage-io")]
        let mut artifact_checksum = capture_reference.then(Crc32cHasher::new);
        #[cfg(feature = "storage-io")]
        if let (Some(reference), Some(artifact_checksum)) =
            (reference.as_mut(), artifact_checksum.as_mut())
        {
            stream_verify::verify_admitted_observing(
                &mut file,
                &manifest,
                admission,
                &mut |bytes| {
                    reference.write_all(bytes)?;
                    artifact_checksum.update(bytes);
                    Ok(())
                },
            )?;
        } else {
            stream_verify::verify_admitted(&mut file, &manifest, admission)?;
        }
        #[cfg(not(feature = "storage-io"))]
        stream_verify::verify_admitted(&mut file, &manifest, admission)?;
        #[cfg(feature = "storage-io")]
        let object_reference = reference
            .map(|mut reference| {
                reference.write_all(&encoded_manifest)?;
                reference.write_all(&footer)?;
                reference
                    .finish()
                    .map_err(|error| ProjectionError::CorruptArtifact(error.to_string()))
            })
            .transpose()?;
        #[cfg(feature = "storage-io")]
        let artifact_checksum = artifact_checksum.map(|mut checksum| {
            checksum.update(&encoded_manifest);
            checksum.update(&footer);
            checksum.finish()
        });

        // SAFETY: the artifact is published via atomic rename and never mutated in
        // place after that point, so external truncation/mutation racing this map is
        // not part of HawDB's supported artifact lifecycle.
        #[cfg(test)]
        if let Some(callback) = BEFORE_PROJECTION_MAP.with(|slot| slot.replace(None)) {
            callback();
        }
        let mmap = {
            admission.checkpoint()?;
            let _io = admission.acquire_io()?;
            #[cfg(feature = "storage-io")]
            let mapped = unsafe { file.map_read_only()? };
            #[cfg(not(feature = "storage-io"))]
            let mapped = unsafe { Mmap::map(&file)? };
            mapped
        };

        Ok(FileProjection {
            contents: SharedAllocation::new(ProjectionContents {
                path,
                manifest,
                #[cfg(feature = "storage-io")]
                object_reference,
                #[cfg(feature = "storage-io")]
                artifact_checksum,
                mmap,
                _path_memory: path_memory,
                _metadata_memory: metadata_memory,
            }),
        })
    }
}

impl<Memory> FileProjection<Memory> {
    /// Conservative retained capacity including the complete mapped file.
    pub fn retained_capacity_bytes(&self) -> usize {
        self.contents
            .manifest
            .retained_capacity_bytes()
            .saturating_add(self.contents.path.capacity())
            .saturating_add(self.contents.mmap.len())
            .saturating_add(std::mem::size_of::<ProjectionContents<Memory>>())
            .saturating_add(2 * std::mem::size_of::<usize>())
    }

    /// Producer reference computed during the existing complete validation pass.
    #[cfg(feature = "storage-io")]
    #[doc(hidden)]
    pub fn object_reference(&self) -> Option<ObjectReference> {
        self.contents.object_reference
    }

    /// Full artifact CRC32C computed during the same validation pass.
    #[cfg(feature = "storage-io")]
    #[doc(hidden)]
    pub fn artifact_checksum(&self) -> Option<u64> {
        self.contents.artifact_checksum
    }

    pub fn manifest(&self) -> &ProjectionManifest {
        &self.contents.manifest
    }

    pub fn path(&self) -> &Path {
        &self.contents.path
    }

    pub fn build_report(&self) -> ProjectionBuildReport {
        ProjectionBuildReport {
            document_count: self.contents.manifest.document_count,
            segment_count: self.contents.manifest.segments.len(),
            raw_vector_bytes: (self.contents.manifest.document_count as u64)
                .saturating_mul(self.contents.manifest.dimension as u64)
                .saturating_mul(std::mem::size_of::<f32>() as u64),
            projection_payload_bytes: self.contents.manifest.payload_bytes,
            configured_working_bytes: self.contents.manifest.configured_build_working_bytes,
            peak_working_bytes: self.contents.manifest.peak_build_working_bytes,
            requested_segment_rows: self.contents.manifest.requested_segment_rows,
            admitted_segment_rows: self.contents.manifest.admitted_segment_rows,
        }
    }

    /// Revalidates the mapped payload against the manifest and segment checksums.
    ///
    /// Normal searches trust the immutable artifact established by [`Self::open`]
    /// and avoid checksum work on the query hot path. Scrub and deep-verification
    /// callers can use this method to detect payload mutation after open.
    pub fn verify(&self) -> Result<()> {
        verify_projection_payload(&self.contents.mmap, &self.contents.manifest)
    }

    /// Zero-copy view of a segment's payload backed by the projection's mmap.
    ///
    /// Unlike the previous per-call `File::open` + `seek` + `read_exact`, this
    /// borrows directly from the mapping opened and fully validated once in
    /// `open()`: no syscall, checksum pass, or heap allocation/copy per search.
    pub(crate) fn read_segment(&self, index: usize) -> Result<SegmentBuffer<'_>> {
        let descriptor = self.contents.manifest.segments.get(index).ok_or_else(|| {
            ProjectionError::CorruptArtifact(format!("missing segment descriptor {index}"))
        })?;
        segment_buffer(&self.contents.mmap, descriptor)
    }
}

fn verify_projection_payload(mmap: &Mmap, manifest: &ProjectionManifest) -> Result<()> {
    let mut previous_id = None;
    let mut payload_hasher = Hasher::new();
    for descriptor in &manifest.segments {
        let buffer = verified_segment_buffer(mmap, descriptor)?;
        payload_hasher.update(buffer.bytes);
        let parts = buffer.parts(
            manifest.dimension,
            RaBitQBitWidth::from_bits(manifest.bit_width)?,
            descriptor.row_count,
        )?;
        for row in 0..descriptor.row_count {
            let id = parts.id(row);
            if let Some(previous) = previous_id
                && id <= previous
            {
                return Err(ProjectionError::CorruptArtifact(format!(
                    "ids are not strictly increasing at {id} after {previous}"
                )));
            }
            previous_id = Some(id);
            let scale = parts.reconstruction_scale(row);
            if !scale.is_finite() || scale < 0.0 {
                return Err(ProjectionError::CorruptArtifact(format!(
                    "invalid RaBitQ reconstruction scale in segment {} row {row}",
                    descriptor.index
                )));
            }
            if !parts.reconstruction_offset(row).is_finite() {
                return Err(ProjectionError::CorruptArtifact(format!(
                    "invalid RaBitQ reconstruction offset in segment {} row {row}",
                    descriptor.index
                )));
            }
            let norm = parts.original_norm(row);
            if !norm.is_finite() || norm < 0.0 {
                return Err(ProjectionError::CorruptArtifact(format!(
                    "invalid RaBitQ original norm in segment {} row {row}",
                    descriptor.index
                )));
            }
        }
    }
    if payload_hasher.finalize() != manifest.payload_checksum {
        return Err(ProjectionError::CorruptArtifact(
            "payload checksum mismatch".to_string(),
        ));
    }
    Ok(())
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct SegmentBuffer<'a> {
    pub bytes: &'a [u8],
}

impl<'a> SegmentBuffer<'a> {
    pub fn parts(
        &self,
        dimension: usize,
        bit_width: RaBitQBitWidth,
        rows: usize,
    ) -> Result<SegmentParts<'a>> {
        let ids_end = ids_bytes(rows);
        let scales_end = ids_end.saturating_add(reconstruction_factor_bytes(rows));
        let offsets_end = scales_end.saturating_add(reconstruction_factor_bytes(rows));
        let norms_end = offsets_end.saturating_add(rows.saturating_mul(std::mem::size_of::<f64>()));
        if norms_end > self.bytes.len() {
            return Err(ProjectionError::CorruptArtifact(
                "segment header arrays exceed payload".to_string(),
            ));
        }
        let codes = &self.bytes[norms_end..];
        let expected_codes =
            rows.saturating_mul(crate::model::encoded_vector_bytes(dimension, bit_width));
        if codes.len() != expected_codes {
            return Err(ProjectionError::CorruptArtifact(format!(
                "segment codes have {} bytes, expected {expected_codes}",
                codes.len()
            )));
        }
        Ok(SegmentParts {
            ids: &self.bytes[..ids_end],
            reconstruction_scales: &self.bytes[ids_end..scales_end],
            reconstruction_offsets: &self.bytes[scales_end..offsets_end],
            original_norms: &self.bytes[offsets_end..norms_end],
            codes,
        })
    }
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct SegmentParts<'a> {
    pub ids: &'a [u8],
    pub reconstruction_scales: &'a [u8],
    pub reconstruction_offsets: &'a [u8],
    pub original_norms: &'a [u8],
    pub codes: &'a [u8],
}

impl SegmentParts<'_> {
    pub fn id(self, row: usize) -> u64 {
        let offset = row * std::mem::size_of::<u64>();
        u64::from_le_bytes(
            self.ids[offset..offset + std::mem::size_of::<u64>()]
                .try_into()
                .expect("validated id slice"),
        )
    }

    pub fn reconstruction_scale(self, row: usize) -> f32 {
        let offset = row * std::mem::size_of::<f32>();
        f32::from_bits(u32::from_le_bytes(
            self.reconstruction_scales[offset..offset + std::mem::size_of::<f32>()]
                .try_into()
                .expect("validated scale slice"),
        ))
    }

    pub fn original_norm(self, row: usize) -> f64 {
        let offset = row * std::mem::size_of::<f64>();
        f64::from_le_bytes(
            self.original_norms[offset..offset + std::mem::size_of::<f64>()]
                .try_into()
                .expect("validated norm slice"),
        )
    }

    pub fn reconstruction_offset(self, row: usize) -> f32 {
        let offset = row * std::mem::size_of::<f32>();
        f32::from_bits(u32::from_le_bytes(
            self.reconstruction_offsets[offset..offset + std::mem::size_of::<f32>()]
                .try_into()
                .expect("validated offset slice"),
        ))
    }
}

fn write_payload(
    file: &mut File,
    bytes: &[u8],
    segment_hasher: &mut Hasher,
    payload_hasher: &mut Hasher,
) -> Result<()> {
    file.write_all(bytes)?;
    segment_hasher.update(bytes);
    payload_hasher.update(bytes);
    Ok(())
}

fn segment_buffer<'a>(mmap: &'a Mmap, descriptor: &SegmentDescriptor) -> Result<SegmentBuffer<'a>> {
    let offset = usize::try_from(descriptor.payload_offset).map_err(|_| {
        ProjectionError::CorruptArtifact(format!(
            "segment {} payload offset exceeds address space",
            descriptor.index
        ))
    })?;
    let payload_len = usize::try_from(descriptor.payload_bytes).map_err(|_| {
        ProjectionError::CorruptArtifact(format!(
            "segment {} payload exceeds address space",
            descriptor.index
        ))
    })?;
    let end = offset.checked_add(payload_len).ok_or_else(|| {
        ProjectionError::CorruptArtifact(format!(
            "segment {} payload range overflows",
            descriptor.index
        ))
    })?;
    let bytes = mmap.get(offset..end).ok_or_else(|| {
        ProjectionError::CorruptArtifact(format!(
            "segment {} payload range exceeds mapped artifact",
            descriptor.index
        ))
    })?;
    Ok(SegmentBuffer { bytes })
}

fn verified_segment_buffer<'a>(
    mmap: &'a Mmap,
    descriptor: &SegmentDescriptor,
) -> Result<SegmentBuffer<'a>> {
    let buffer = segment_buffer(mmap, descriptor)?;
    if segment_checksum(buffer.bytes) != descriptor.payload_checksum {
        return Err(ProjectionError::CorruptArtifact(format!(
            "segment {} checksum mismatch",
            descriptor.index
        )));
    }
    Ok(buffer)
}

fn segment_checksum(bytes: &[u8]) -> u32 {
    #[cfg(test)]
    SEGMENT_CHECKSUM_CALLS.with(|calls| calls.set(calls.get().saturating_add(1)));
    crc32fast::hash(bytes)
}

#[cfg(test)]
fn reset_segment_checksum_calls() {
    SEGMENT_CHECKSUM_CALLS.with(|calls| calls.set(0));
}

#[cfg(test)]
fn segment_checksum_calls() -> usize {
    SEGMENT_CHECKSUM_CALLS.with(std::cell::Cell::get)
}

fn temporary_path(target: &Path) -> PathBuf {
    let sequence = TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
    target.with_extension(format!("tmp.{}.{}", std::process::id(), sequence))
}

#[cfg(unix)]
fn sync_parent(path: &Path) -> Result<()> {
    if let Some(parent) = path.parent() {
        File::open(parent)?.sync_all()?;
    }
    Ok(())
}

#[cfg(not(unix))]
fn sync_parent(_path: &Path) -> Result<()> {
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{ProjectionIdentity, DEFAULT_BUILD_MEMORY_BYTES};
    use std::time::{SystemTime, UNIX_EPOCH};

    #[test]
    fn generation_artifact_round_trips_and_validates_checksums() {
        let root = unique_test_dir("roundtrip");
        fs::create_dir_all(&root).unwrap();
        let artifact = root.join("search_rabitq.1.hawdb");
        let config = ProjectionBuildConfig::new(8, ProjectionIdentity::new(1))
            .with_bit_width(RaBitQBitWidth::One)
            .with_segment_rows(2);
        let mut writer = ProjectionWriter::create(&artifact, config).unwrap();
        writer
            .push(10, &[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
            .unwrap();
        writer
            .push(20, &[0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
            .unwrap();
        writer
            .push(30, &[0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0])
            .unwrap();
        let projection = writer.finish().unwrap();

        assert_eq!(projection.manifest().document_count, 3);
        assert_eq!(projection.manifest().segments.len(), 2);
        let build_report = projection.build_report();
        assert_eq!(
            build_report.configured_working_bytes,
            DEFAULT_BUILD_MEMORY_BYTES
        );
        assert!(build_report.peak_working_bytes > 0);
        assert!(build_report.peak_working_bytes <= build_report.configured_working_bytes);
        assert_eq!(build_report.raw_vector_bytes, 3 * 8 * 4);
        let first = projection.read_segment(0).unwrap();
        let first = first.parts(8, RaBitQBitWidth::One, 2).unwrap();
        assert_eq!([first.id(0), first.id(1)], [10, 20]);
        let second = projection.read_segment(1).unwrap();
        let second = second.parts(8, RaBitQBitWidth::One, 1).unwrap();
        assert_eq!(second.id(0), 30);
        FileProjection::open(&artifact).unwrap();
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn corrupted_segment_fails_closed() {
        let root = unique_test_dir("corruption");
        fs::create_dir_all(&root).unwrap();
        let artifact = root.join("search_rabitq.1.hawdb");
        let config = ProjectionBuildConfig::new(8, ProjectionIdentity::new(1));
        let mut writer = ProjectionWriter::create(&artifact, config).unwrap();
        writer.push(10, &[1.0; 8]).unwrap();
        writer.finish().unwrap();

        let mut file = OpenOptions::new().write(true).open(&artifact).unwrap();
        file.seek(SeekFrom::Start(0)).unwrap();
        file.write_all(&[0xff]).unwrap();
        file.sync_all().unwrap();
        let error = FileProjection::open(&artifact).unwrap_err();
        assert!(matches!(error, ProjectionError::CorruptArtifact(_)));
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn cloned_file_projection_shares_manifest_and_path_ownership() {
        let root = unique_test_dir("shared-projection-metadata");
        fs::create_dir_all(&root).unwrap();
        let artifact = root.join("search_rabitq.1.hawdb");
        let mut writer = ProjectionWriter::create(
            &artifact,
            ProjectionBuildConfig::new(8, ProjectionIdentity::new(1)),
        )
        .unwrap();
        writer.push(10, &[1.0; 8]).unwrap();
        let original = writer.finish().unwrap();
        let cloned = original.clone();
        assert!(std::ptr::eq(original.manifest(), cloned.manifest()));
        assert!(std::ptr::eq(original.path(), cloned.path()));
        drop(original);
        assert_eq!(cloned.manifest().document_count, 1);
        assert_eq!(
            cloned
                .read_segment(0)
                .unwrap()
                .parts(8, RaBitQBitWidth::Four, 1)
                .unwrap()
                .id(0),
            10
        );
        drop(cloned);
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    #[cfg(feature = "storage-io")]
    fn streamed_validation_returns_the_complete_producer_reference() {
        let root = unique_test_dir("streamed-producer-reference");
        fs::create_dir_all(&root).unwrap();
        let artifact = root.join("search_rabitq.1.hawdb");
        let mut writer = ProjectionWriter::create(
            &artifact,
            ProjectionBuildConfig::new(8, ProjectionIdentity::new(1)).with_segment_rows(2),
        )
        .unwrap();
        for id in [10, 20, 30] {
            writer.push(id, &[id as f32; 8]).unwrap();
        }
        let published = writer.finish().unwrap();
        let expected = ObjectReference::for_bytes(
            ObjectKind::CheckpointArtifact,
            1,
            &fs::read(&artifact).unwrap(),
        );
        assert_eq!(published.object_reference(), Some(expected));
        assert_eq!(
            published.artifact_checksum(),
            Some(hawdb_integrity::checksum_u64(&fs::read(&artifact).unwrap()))
        );
        assert!(FileProjection::open(&artifact)
            .unwrap()
            .object_reference()
            .is_none());
        let reopened =
            FileProjection::open_file_with_reference(File::open(&artifact).unwrap(), &artifact)
                .unwrap();
        assert_eq!(reopened.object_reference(), Some(expected));
        assert_eq!(reopened.artifact_checksum(), published.artifact_checksum());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn corrupt_payload_is_rejected_before_mapping() {
        let root = unique_test_dir("reject-before-map");
        fs::create_dir_all(&root).unwrap();
        let artifact = root.join("search_rabitq.1.hawdb");
        let mut writer = ProjectionWriter::create(
            &artifact,
            ProjectionBuildConfig::new(8, ProjectionIdentity::new(1)),
        )
        .unwrap();
        writer.push(10, &[1.0; 8]).unwrap();
        writer.finish().unwrap();
        let mut file = OpenOptions::new().write(true).open(&artifact).unwrap();
        file.seek(SeekFrom::Start(0)).unwrap();
        file.write_all(&[0xff]).unwrap();
        file.sync_all().unwrap();
        let mapped = std::rc::Rc::new(std::cell::Cell::new(false));
        let observed = mapped.clone();
        BEFORE_PROJECTION_MAP.with(|slot| {
            slot.replace(Some(Box::new(move || observed.set(true))));
        });
        let result = FileProjection::open(&artifact);
        BEFORE_PROJECTION_MAP.with(|slot| slot.replace(None));
        let corrupt = matches!(&result, Err(ProjectionError::CorruptArtifact(_)));
        drop(result);
        drop(file);
        fs::remove_dir_all(root).unwrap();
        assert!(corrupt);
        assert!(
            !mapped.get(),
            "corrupt payload reached mmap before validation"
        );
    }

    #[test]
    fn streamed_payload_verification_matches_mapped_corruption_oracle() {
        for bit_width in [RaBitQBitWidth::One, RaBitQBitWidth::Four] {
            let root = unique_test_dir("streamed-verification-oracle");
            fs::create_dir_all(&root).unwrap();
            let artifact = root.join("search_rabitq.1.hawdb");
            let mut writer = ProjectionWriter::create(
                &artifact,
                ProjectionBuildConfig::new(8, ProjectionIdentity::new(1))
                    .with_bit_width(bit_width)
                    .with_segment_rows(3),
            )
            .unwrap();
            for id in [10, 20, 30, 40, 50, 60] {
                writer.push(id, &[1.0; 8]).unwrap();
            }
            let projection = writer.finish().unwrap();
            let original_manifest = projection.manifest().clone();
            assert_eq!(original_manifest.segments.len(), 2);
            drop(projection);
            let mut original = fs::read(&artifact).unwrap();
            original.truncate(original_manifest.payload_bytes as usize);
            for case in [
                "valid",
                "duplicate",
                "cross-segment",
                "negative-scale",
                "nan-scale",
                "infinite-offset",
                "negative-norm",
                "nan-norm",
                "infinite-norm",
                "field-order-offset-before-norm",
                "row-order-norm-first",
                "row-order-scale-first",
                "row-order-offset-first",
                "field-order-id-first",
                "bad-segment-checksum",
                "bad-total-checksum",
                "bad-header-and-checksum",
                "negative-zero-scale",
            ] {
                let mut bytes = original.clone();
                let mut manifest = original_manifest.clone();
                let second = manifest.segments[1].payload_offset as usize;
                match case {
                    "duplicate" => bytes[8..16].copy_from_slice(&10_u64.to_le_bytes()),
                    "cross-segment" => {
                        bytes[second..second + 8].copy_from_slice(&30_u64.to_le_bytes())
                    }
                    "negative-scale" => bytes[24..28].copy_from_slice(&(-1_f32).to_le_bytes()),
                    "nan-scale" | "bad-header-and-checksum" => {
                        bytes[24..28].copy_from_slice(&f32::NAN.to_le_bytes())
                    }
                    "infinite-offset" => {
                        bytes[36..40].copy_from_slice(&f32::INFINITY.to_le_bytes())
                    }
                    "negative-norm" => bytes[48..56].copy_from_slice(&(-1_f64).to_le_bytes()),
                    "nan-norm" => bytes[48..56].copy_from_slice(&f64::NAN.to_le_bytes()),
                    "infinite-norm" => bytes[48..56].copy_from_slice(&f64::INFINITY.to_le_bytes()),
                    "field-order-offset-before-norm" => {
                        bytes[36..40].copy_from_slice(&f32::INFINITY.to_le_bytes());
                        bytes[48..56].copy_from_slice(&f64::NAN.to_le_bytes());
                    }
                    "row-order-norm-first" => {
                        bytes[40..44].copy_from_slice(&f32::INFINITY.to_le_bytes());
                        bytes[48..56].copy_from_slice(&f64::NAN.to_le_bytes());
                    }
                    "row-order-scale-first" => {
                        bytes[8..16].copy_from_slice(&10_u64.to_le_bytes());
                        bytes[24..28].copy_from_slice(&f32::NAN.to_le_bytes());
                    }
                    "row-order-offset-first" => {
                        bytes[28..32].copy_from_slice(&f32::NAN.to_le_bytes());
                        bytes[36..40].copy_from_slice(&f32::INFINITY.to_le_bytes());
                    }
                    "field-order-id-first" => {
                        bytes[second..second + 8].copy_from_slice(&30_u64.to_le_bytes());
                        bytes[second + 24..second + 28].copy_from_slice(&f32::NAN.to_le_bytes());
                    }
                    "negative-zero-scale" => bytes[24..28].copy_from_slice(&(-0_f32).to_le_bytes()),
                    "valid" | "bad-segment-checksum" | "bad-total-checksum" => {}
                    _ => unreachable!(),
                }
                if case != "bad-header-and-checksum" {
                    for segment in &mut manifest.segments {
                        let start = segment.payload_offset as usize;
                        let end = start + segment.payload_bytes as usize;
                        segment.payload_checksum = crc32fast::hash(&bytes[start..end]);
                    }
                    manifest.payload_checksum = crc32fast::hash(&bytes);
                }
                if case == "bad-segment-checksum" {
                    manifest.segments[0].payload_checksum ^= 1;
                } else if case == "bad-total-checksum" {
                    manifest.payload_checksum ^= 1;
                }
                manifest.validate().unwrap();
                let mut mapped = memmap2::MmapMut::map_anon(bytes.len()).unwrap();
                mapped.copy_from_slice(&bytes);
                let mapped = mapped.make_read_only().unwrap();
                let expected =
                    verify_projection_payload(&mapped, &manifest).map_err(|e| e.to_string());
                let actual = stream_verify::verify(&mut std::io::Cursor::new(&bytes), &manifest)
                    .map_err(|e| e.to_string());
                assert_eq!(actual, expected, "{bit_width:?} {case}");
                if matches!(case, "valid" | "negative-zero-scale") {
                    assert!(actual.is_ok());
                } else {
                    assert!(
                        actual.is_err(),
                        "the oracle must exercise rejection: {case}"
                    );
                }
            }
            fs::remove_dir_all(root).unwrap();
        }
    }

    #[test]
    fn streamed_payload_verification_bounds_reads_and_handles_short_reads() {
        struct ShortReader<'a> {
            cursor: std::io::Cursor<&'a [u8]>,
            max_request: usize,
            seeks: usize,
        }
        impl Read for ShortReader<'_> {
            fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
                self.max_request = self.max_request.max(bytes.len());
                assert!(bytes.len() <= stream_verify::BUFFER_BYTES);
                let length = bytes.len().min(3);
                self.cursor.read(&mut bytes[..length])
            }
        }
        impl Seek for ShortReader<'_> {
            fn seek(&mut self, position: SeekFrom) -> std::io::Result<u64> {
                self.seeks += 1;
                self.cursor.seek(position)
            }
        }
        let root = unique_test_dir("streamed-bounded-reads");
        fs::create_dir_all(&root).unwrap();
        let artifact = root.join("search_rabitq.1.hawdb");
        let mut writer = ProjectionWriter::create(
            &artifact,
            ProjectionBuildConfig::new(8, ProjectionIdentity::new(1)).with_segment_rows(2200),
        )
        .unwrap();
        for id in 1..=2200 {
            writer.push(id, &[1.0; 8]).unwrap();
        }
        let projection = writer.finish().unwrap();
        let bytes = fs::read(&artifact).unwrap();
        let mut reader = ShortReader {
            cursor: std::io::Cursor::new(&bytes),
            max_request: 0,
            seeks: 0,
        };
        stream_verify::verify(&mut reader, projection.manifest()).unwrap();
        assert_eq!(reader.max_request, stream_verify::BUFFER_BYTES);
        assert_eq!(reader.seeks, 1);
        assert_eq!(
            reader.cursor.position(),
            projection.manifest().payload_bytes
        );
        assert!(reader.cursor.position() < bytes.len() as u64);
        drop(projection);
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn repeated_segment_reads_skip_crc_but_explicit_verify_detects_mutation() {
        let root = unique_test_dir("steady-state-checksum");
        fs::create_dir_all(&root).unwrap();
        let artifact = root.join("search_rabitq.1.hawdb");
        let config = ProjectionBuildConfig::new(8, ProjectionIdentity::new(1));
        let mut writer = ProjectionWriter::create(&artifact, config).unwrap();
        writer.push(10, &[1.0; 8]).unwrap();
        let projection = writer.finish().unwrap();

        reset_segment_checksum_calls();
        projection.read_segment(0).unwrap();
        projection.read_segment(0).unwrap();
        assert_eq!(segment_checksum_calls(), 0);

        let descriptor = &projection.manifest().segments[0];
        let original = projection.read_segment(0).unwrap().bytes[0];
        let mut file = OpenOptions::new().write(true).open(&artifact).unwrap();
        file.seek(SeekFrom::Start(descriptor.payload_offset))
            .unwrap();
        file.write_all(&[original ^ 0xff]).unwrap();
        file.sync_all().unwrap();

        let error = projection.verify().unwrap_err();
        assert!(matches!(error, ProjectionError::CorruptArtifact(_)));
        assert_eq!(segment_checksum_calls(), 1);
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn one_bit_generation_uses_one_bit_code_payloads() {
        let root = unique_test_dir("one-bit");
        fs::create_dir_all(&root).unwrap();
        let artifact = root.join("search_rabitq.1.hawdb");
        let config = ProjectionBuildConfig::new(9, ProjectionIdentity::new(1))
            .with_bit_width(RaBitQBitWidth::One)
            .with_segment_rows(2);
        let mut writer = ProjectionWriter::create(&artifact, config).unwrap();
        writer.push(10, &[1.0; 9]).unwrap();
        writer.push(20, &[-1.0; 9]).unwrap();
        writer.push(30, &[0.5; 9]).unwrap();
        let projection = writer.finish().unwrap();

        assert_eq!(projection.manifest().bit_width, 1);
        assert_eq!(
            projection.manifest().quantizer,
            "rabitq_sign_then_refinement_scalar_1bit_v1"
        );
        assert_eq!(
            projection.manifest().segments[0].payload_bytes,
            2 * (8 + 8 + 8 + 2)
        );
        let first = projection.read_segment(0).unwrap();
        let first = first.parts(9, RaBitQBitWidth::One, 2).unwrap();
        assert_eq!([first.id(0), first.id(1)], [10, 20]);
        FileProjection::open(&artifact).unwrap();
        fs::remove_dir_all(root).unwrap();
    }

    pub(super) fn unique_test_dir(name: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!(
            "hawdb_vector_projection_{name}_{}_{nanos}",
            std::process::id()
        ))
    }
}

#[cfg(all(test, feature = "storage-io"))]
mod descriptor_tests;