Skip to main content

reddb_server/storage/
compact.rs

1//! Offline native rewrite. Source is read-locked against writers and never
2//! opened by a recovering writer. A new directory owns all output; the main
3//! filename is published only after sync and a complete record-by-record
4//! readback.
5use crate::storage::engine::{Page, PageType, Pager, PagerConfig, HEADER_SIZE, PAGE_SIZE};
6use reddb_engine::storage::{
7    btree::BTree,
8    pager_io::{DWB_ZONE_PAGES, DWB_ZONE_START_PAGE, FIRST_ALLOCATABLE_PAGE},
9};
10use reddb_file as f;
11use std::{
12    collections::BTreeMap,
13    fs::{File, OpenOptions},
14    io::{BufRead, BufReader, Read, Write},
15    path::{Path, PathBuf},
16    sync::Arc,
17};
18mod assets;
19pub(crate) mod boot_system_wal;
20mod catalog;
21pub(crate) mod catalog_aliases;
22mod internal_metadata;
23#[cfg(test)]
24pub(crate) mod legacy_fixture;
25mod salvage;
26mod scrub;
27mod source;
28use catalog::Catalog;
29pub use salvage::{
30    salvage_paged_collections, salvage_paged_indexes, PagedCollectionLoss,
31    PagedCollectionSalvageReport, PagedIndexSalvageFinding, PagedIndexSalvageReport,
32};
33pub use scrub::{
34    scrub_paged, scrub_paged_trees, PagedScrubReport, PagedTreeFinding, PagedTreeScrubReport,
35};
36use source::Source;
37type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
38
39#[derive(Debug)]
40pub struct CompactionReport {
41    pub source_bytes: u64,
42    pub destination_bytes: u64,
43    pub source_allocated_bytes: Option<u64>,
44    pub destination_allocated_bytes: Option<u64>,
45    /// Includes exact persisted key and secondary-index records.
46    pub records: u64,
47    pub trees: usize,
48    /// Historical stale backlinks reconstructed from validated forward/owner order.
49    pub repaired_leaf_backlinks: u64,
50    /// Only operator-selected canonical recovery can retire boot-derived WAL actions.
51    pub retired_boot_system_wal_actions: usize,
52    pub reconciled_system_collections: usize,
53    pub imported_system_records: usize,
54}
55
56impl CompactionReport {
57    pub fn machine_json(&self) -> String {
58        format!(
59            r#"{{"source_bytes":{},"destination_bytes":{},"records":{},"trees":{},"repaired_leaf_backlinks":{},"retired_boot_system_wal_actions":{},"reconciled_system_collections":{},"imported_system_records":{},"source_allocated_bytes":{},"destination_allocated_bytes":{}}}"#,
60            self.source_bytes,
61            self.destination_bytes,
62            self.records,
63            self.trees,
64            self.repaired_leaf_backlinks,
65            self.retired_boot_system_wal_actions,
66            self.reconciled_system_collections,
67            self.imported_system_records,
68            self.source_allocated_bytes
69                .map_or_else(|| "null".into(), |n| n.to_string()),
70            self.destination_allocated_bytes
71                .map_or_else(|| "null".into(), |n| n.to_string())
72        )
73    }
74}
75
76/// Rewrite a closed, checkpointed paged file into an exclusively-created output
77/// directory. On failure the source is unchanged and the incomplete output is
78/// retained for diagnosis. This does not switch a serving database or vacuum MVCC.
79pub fn compact_paged(source: &Path, destination: &Path) -> Result<CompactionReport> {
80    compact_paged_inner(source, destination, None, None, false)
81}
82
83/// Rewrite a closed store while explicitly retiring the obsolete physical
84/// `red_config` identity. A populated legacy tree is promoted when the
85/// canonical tree is empty; two populated trees fail closed. The source
86/// remains unchanged and ordinary compaction never enables this.
87pub fn compact_paged_canonical_system_config(
88    source: &Path,
89    destination: &Path,
90) -> Result<CompactionReport> {
91    compact_paged_inner(source, destination, None, None, true)
92}
93
94/// Replay a supported pending unified WAL only against an isolated copy, then
95/// publish a validated compacted database. The locked source is never opened
96/// by a writer. Unsupported WAL families and ambiguous recovery fail closed.
97pub fn recover_paged_wal(source: &Path, destination: &Path) -> Result<CompactionReport> {
98    recover_paged_wal_inner(source, destination, false)
99}
100
101/// Recover an isolated copy while explicitly retaining `red.config`.
102/// WAL actions targeting the divergent `red_config` are refused, except for
103/// proven process metadata recreated at boot. Those actions are retired without
104/// retargeting their entity IDs; every other committed action is replayed.
105pub fn recover_paged_wal_canonical_system_config(
106    source: &Path,
107    destination: &Path,
108) -> Result<CompactionReport> {
109    recover_paged_wal_inner(source, destination, true)
110}
111
112fn recover_paged_wal_inner(
113    source: &Path,
114    destination: &Path,
115    retain_canonical_system_config: bool,
116) -> Result<CompactionReport> {
117    use crate::storage::wal::{WalReader, WalRecord};
118    let source = source.canonicalize()?;
119    let parent = destination
120        .parent()
121        .filter(|p| !p.as_os_str().is_empty())
122        .unwrap_or_else(|| Path::new("."))
123        .canonicalize()?;
124    for owned in [
125        f::support_dir_for(&source),
126        source.with_file_name(format!("{}.ops", f::data_file_name(&source))),
127    ] {
128        if owned.exists() {
129            ensure(
130                !parent.starts_with(owned.canonicalize()?),
131                "destination is inside source storage",
132            )?;
133        }
134    }
135    let guard = Arc::new(Source::open_for_wal_recovery(&source)?);
136    guard.verify_superblocks()?;
137    salvage::verify_wal_recovery_sidecars(&source)?;
138    let wal = f::unified_wal_path(&source);
139    let engine_wal = f::engine_wal_path(&source);
140    let pending_unified = wal_has_records(&wal)?;
141    let pending_engine = wal_has_records(&engine_wal)?;
142    ensure(
143        pending_unified
144            || pending_engine
145            || guard.pending_double_write
146            || guard.header.checkpoint_in_progress,
147        "no pending recovery",
148    )?;
149    ensure(
150        !guard.header.checkpoint_in_progress || pending_engine,
151        "interrupted page checkpoint requires its engine WAL",
152    )?;
153    let mut boot_wal =
154        if retain_canonical_system_config && pending_unified && !guard.pending_double_write {
155            boot_system_wal::BootSystemWalPlan::prepare(&guard, &wal, pending_engine)?
156        } else {
157            boot_system_wal::BootSystemWalPlan::default()
158        };
159    let pending_ownership = if pending_unified {
160        verify_wal_recovery_records(
161            &wal,
162            retain_canonical_system_config && !guard.pending_double_write,
163            &boot_wal,
164        )?
165    } else {
166        false
167    };
168    if !guard.pending_double_write
169        && !guard.header.checkpoint_in_progress
170        && !pending_ownership
171        && !pending_engine
172    {
173        salvage::verify_vault(&source, &guard)?;
174    }
175    let mut recovered_engine_xid = 0;
176    if pending_engine {
177        for entry in WalReader::open(&engine_wal)?.iter() {
178            match entry?.1 {
179                WalRecord::Begin { .. }
180                | WalRecord::Commit { .. }
181                | WalRecord::Rollback { .. }
182                | WalRecord::Checkpoint { .. } => {}
183                WalRecord::PageWrite { page_id, data, .. } => {
184                    ensure(
185                        page_id > 0
186                            && !(DWB_ZONE_START_PAGE..FIRST_ALLOCATABLE_PAGE).contains(&page_id)
187                            && u64::from(page_id) < guard.bytes.div_ceil(PAGE_SIZE as u64)
188                            && data.len() == PAGE_SIZE,
189                        "invalid engine WAL page",
190                    )?;
191                    let page = Page::from_slice(&data)?;
192                    ensure(
193                        page.page_id() == page_id,
194                        "engine WAL page identity mismatch",
195                    )?;
196                    page.page_type()?;
197                    // Engine transactions log page bytes before Pager::write_page
198                    // updates the page checksum. The WAL frame itself protects
199                    // the image; redo will seal the page before writing it.
200                }
201                _ => return Err("unsupported engine WAL record".into()),
202            }
203        }
204    }
205    std::fs::create_dir(destination)?;
206    #[cfg(unix)]
207    {
208        use std::os::unix::fs::PermissionsExt;
209        std::fs::set_permissions(destination, std::fs::Permissions::from_mode(0o700))?;
210    }
211    let stage = destination.join(".wal-replay");
212    std::fs::create_dir(&stage)?;
213    let name = source.file_name().ok_or("source filename is missing")?;
214    let staged_source = stage.join(name);
215    guard.copy_snapshot(&staged_source)?;
216    copy_sidecars(&source, &staged_source, true)?;
217    copy_physical_metadata_files(&source, &staged_source)?;
218    let preserved_audit = detach_recovery_audit_logs(&staged_source, &stage)?;
219    let config = crate::storage::unified::UnifiedStoreConfig {
220        resident_memory_bytes_max: guard
221            .header
222            .requires_disk_residency()
223            .then_some(64 * 1024 * 1024),
224        ..Default::default()
225    };
226    if pending_engine {
227        let pager = Pager::open(
228            &staged_source,
229            PagerConfig {
230                disk_residency: config.resident_memory_bytes_max.is_some(),
231                ..PagerConfig::default()
232            },
233        )?;
234        let wal = f::engine_wal_path(&staged_source);
235        recovered_engine_xid = replay_engine_wal_on_copy(&pager, &wal)?;
236        let mut writer = crate::storage::wal::WalWriter::open(&wal)?;
237        writer.truncate()?;
238        writer.sync()?;
239    }
240    if retain_canonical_system_config && pending_unified && guard.pending_double_write {
241        // Restore the copy's DWB before trusting catalog roots or deletion IDs.
242        // The preserved source and its pending frame remain untouched.
243        {
244            let pager = Pager::open(
245                &staged_source,
246                PagerConfig {
247                    disk_residency: config.resident_memory_bytes_max.is_some(),
248                    ..PagerConfig::default()
249                },
250            )?;
251            pager.sync()?;
252        }
253        let checkpoint = Arc::new(Source::open_for_wal_recovery(&staged_source)?);
254        let staged_wal = f::unified_wal_path(&staged_source);
255        boot_wal =
256            boot_system_wal::BootSystemWalPlan::prepare(&checkpoint, &staged_wal, pending_engine)?;
257        verify_wal_recovery_records(&staged_wal, true, &boot_wal)?;
258    }
259    let catalog_plan = if retain_canonical_system_config {
260        catalog_aliases::CanonicalCatalogPlan::prepare(
261            &staged_source,
262            &f::unified_wal_path(&staged_source),
263        )?
264    } else {
265        catalog_aliases::CanonicalCatalogPlan::default()
266    };
267    let probabilistic_deltas;
268    let mut has_vector_cache = false;
269    {
270        let store = crate::storage::unified::UnifiedStore::open_with_config_for_recovery(
271            &staged_source,
272            config,
273            retain_canonical_system_config,
274            Some(&boot_wal),
275            Some(&catalog_plan),
276        )?;
277        boot_wal.preserve_identity_floors(&store)?;
278        catalog_plan.restore(&store)?;
279        if pending_engine || guard.pending_double_write {
280            store.reconcile_physical_recovery()?;
281        }
282        if pending_unified || pending_engine || guard.pending_double_write {
283            // Replayed physical pages or logical overlays may contain newer
284            // identifiers than the old catalog. Capture their floors before
285            // checkpoint turns the overlay into an immutable base.
286            let mut high = store
287                .startup_xid_high_water_mark()
288                .unwrap_or(0)
289                .max(recovered_engine_xid);
290            for name in store.list_collections() {
291                let manager = store
292                    .get_collection(&name)
293                    .ok_or("recovered collection disappeared")?;
294                let mut max_entity = 0u64;
295                let mut max_row = 0u64;
296                let mut max_sequence = 0u64;
297                let mut has_entity = false;
298                manager.try_for_each_entity(32 * 1024 * 1024, |entity| {
299                    has_entity = true;
300                    high = high.max(entity.max_transaction_id());
301                    max_entity = max_entity.max(entity.id.raw());
302                    max_sequence = max_sequence.max(entity.sequence_id);
303                    if let crate::storage::EntityKind::TableRow { row_id, .. } = &entity.kind {
304                        max_row = max_row.max(*row_id);
305                    }
306                    true
307                })?;
308                if !has_entity {
309                    continue;
310                }
311                let entity_next = max_entity
312                    .checked_add(1)
313                    .ok_or("recovered entity IDs are exhausted")?;
314                let row_next = max_row
315                    .checked_add(1)
316                    .ok_or("recovered row IDs are exhausted")?;
317                let sequence_next = max_sequence
318                    .checked_add(1)
319                    .ok_or("recovered sequence IDs are exhausted")?;
320                manager.restore_identity_counters(entity_next, row_next);
321                manager.restore_sequence_id_next(sequence_next);
322                store.register_entity_id(crate::storage::EntityId::new(max_entity));
323            }
324            ensure(
325                high < u64::MAX,
326                "recovered transaction high-water mark is exhausted",
327            )?;
328            store.remember_startup_xid_high_water_mark(high);
329        }
330        // Turbo WAL is an index projection, while the persisted entity owns
331        // its content and metadata. Do not discard a vector that cannot be
332        // rebuilt exactly from the recovered entities.
333        for (collection, records) in store.replayed_turbo_inserts.lock().iter() {
334            has_vector_cache = true;
335            ensure(
336                crate::runtime::vector_turbo_kind::is_turbo(&store, collection),
337                "WAL vector collection is not a turbo collection",
338            )?;
339            for (id, vector) in records {
340                let entity = store
341                    .try_get(
342                        collection,
343                        crate::storage::EntityId::new(*id),
344                        32 * 1024 * 1024,
345                    )?
346                    .ok_or("WAL vector has no recovered entity")?;
347                let crate::storage::EntityData::Vector(data) = entity.data else {
348                    return Err("WAL vector points to a non-vector entity".into());
349                };
350                ensure(
351                    data.dense.len() == vector.len()
352                        && data
353                            .dense
354                            .iter()
355                            .zip(vector)
356                            .all(|(a, b)| a.to_bits() == b.to_bits()),
357                    "WAL vector differs from recovered entity",
358                )?;
359            }
360        }
361        has_vector_cache |= verify_turbo_snapshots(&staged_source, &store)?;
362        probabilistic_deltas = store.take_replayed_probabilistic_deltas();
363        store.persist()?;
364    }
365    if !probabilistic_deltas.is_empty() {
366        let options = crate::RedDBOptions::persistent(&staged_source)
367            .with_memory_budget(64 * 1024 * 1024)
368            .with_bounded_disk_residency(guard.header.requires_disk_residency());
369        let runtime = crate::RedDBRuntime::with_options(options)?;
370        runtime.persist_offline_probabilistic_recovery(probabilistic_deltas)?;
371        runtime.checkpoint()?;
372        runtime.graceful_shutdown(false)?;
373    }
374    if has_vector_cache {
375        scrub::verify_recovery_vector_pages(&staged_source)?;
376    }
377    let validated_dir = stage.join("validated");
378    let mut report = compact_paged(&staged_source, &validated_dir)?;
379    report.retired_boot_system_wal_actions = boot_wal.action_count();
380    report.reconciled_system_collections = catalog_plan.reconciled_count();
381    report.imported_system_records = catalog_plan.imported_count();
382    let verified = scrub_paged(&validated_dir.join(name))?;
383    ensure(
384        verified.assets_verified
385            && verified.trees.findings.is_empty()
386            && verified.unclassified_pages == 0,
387        "replayed store failed scrub",
388    )?;
389    if let Some(audit) = preserved_audit {
390        restore_recovery_audit_logs(&audit, &validated_dir.join(name))?;
391    }
392    let final_path = destination.join(name);
393    copy_sidecars(&validated_dir.join(name), &final_path, false)?;
394    copy_physical_metadata_files(&validated_dir.join(name), &final_path)?;
395    write_new(
396        &destination.join("compaction.json"),
397        report.machine_json().as_bytes(),
398    )?;
399    sync_directory(destination)?;
400    std::fs::hard_link(validated_dir.join(name), &final_path)?;
401    sync_directory(destination)?;
402    // The published database must not retain a second pathname with a
403    // different WAL family: future opens through that name would be unsafe.
404    std::fs::remove_file(validated_dir.join(name))?;
405    sync_directory(&validated_dir)?;
406    Ok(report)
407}
408
409fn verify_wal_recovery_records(
410    wal: &Path,
411    retain_canonical_system_config: bool,
412    boot_wal: &boot_system_wal::BootSystemWalPlan,
413) -> Result<bool> {
414    use crate::storage::wal::{WalReader, WalRecord};
415    let mut pending_ownership = false;
416    for entry in WalReader::open(wal)?.iter() {
417        let (lsn, record) = entry?;
418        match record {
419            WalRecord::PageWrite { data, .. } => {
420                verify_wal_recovery_action(&data, retain_canonical_system_config)?
421            }
422            WalRecord::TxCommitBatch { actions, .. } => {
423                for (index, action) in actions.iter().enumerate() {
424                    if !boot_wal.skips_action(lsn, index) {
425                        verify_wal_recovery_action(action, retain_canonical_system_config)?;
426                    }
427                }
428            }
429            WalRecord::VectorInsert { collection, .. } => {
430                ensure(
431                    !retain_canonical_system_config || collection != "red_config",
432                    "WAL references divergent legacy red_config",
433                )?;
434            }
435            WalRecord::ProbabilisticDelta { name, .. } => {
436                ensure(
437                    !retain_canonical_system_config || name != "red_config",
438                    "WAL references divergent legacy red_config",
439                )?;
440            }
441            WalRecord::PageOwnership { .. } | WalRecord::FullPageImage { .. } => {
442                pending_ownership = true
443            }
444            _ => {}
445        }
446    }
447    Ok(pending_ownership)
448}
449
450fn verify_wal_recovery_action(bytes: &[u8], retain_canonical_system_config: bool) -> Result<()> {
451    let action = f::decode_store_wal_action_frame(bytes)?;
452    if retain_canonical_system_config {
453        let name = match &action {
454            f::StoreWalActionFrame::CreateCollection { name }
455            | f::StoreWalActionFrame::DropCollection { name } => Some(name),
456            f::StoreWalActionFrame::UpsertEntityRecord { collection, .. }
457            | f::StoreWalActionFrame::DeleteEntityRecord { collection, .. }
458            | f::StoreWalActionFrame::BulkUpsertEntityRecords { collection, .. }
459            | f::StoreWalActionFrame::RefreshCollection { collection, .. } => Some(collection),
460            f::StoreWalActionFrame::SetAuxMetadata { bytes } => {
461                if bytes.first() == Some(&b'[') {
462                    let contracts: crate::serde_json::Value = crate::serde_json::from_slice(bytes)?;
463                    let contracts = contracts.as_array().ok_or("invalid WAL contract catalog")?;
464                    ensure(
465                        contracts.iter().all(|contract| {
466                            contract
467                                .get("name")
468                                .and_then(crate::serde_json::Value::as_str)
469                                != Some("red_config")
470                        }),
471                        "WAL references divergent legacy red_config",
472                    )?;
473                }
474                None
475            }
476        };
477        ensure(
478            name.is_none_or(|name| name != "red_config"),
479            "WAL references divergent legacy red_config",
480        )?;
481    }
482    Ok(())
483}
484
485#[cfg(test)]
486mod canonical_config_wal_tests {
487    use super::*;
488
489    fn legacy_config_without_resume(path: &Path) -> crate::storage::unified::UnifiedStoreConfig {
490        use crate::storage::{EntityData, EntityId, EntityKind, RowData, UnifiedEntity};
491
492        let config = crate::storage::unified::UnifiedStoreConfig::default();
493        {
494            let store =
495                crate::storage::unified::UnifiedStore::open_with_config(path, config.clone())
496                    .expect("create legacy fixture");
497            store
498                .create_collection("cfg_legacy")
499                .expect("create legacy config collection");
500            store
501                .insert_auto(
502                    "cfg_legacy",
503                    UnifiedEntity::new(
504                        EntityId::new(1),
505                        EntityKind::TableRow {
506                            table: "red_config".into(),
507                            row_id: 1,
508                        },
509                        EntityData::Row(RowData::with_names(
510                            vec![
511                                reddb_types::Value::text("red.auth.require_auth"),
512                                reddb_types::Value::Boolean(true),
513                            ],
514                            vec!["key".into(), "value".into()],
515                        )),
516                    ),
517                )
518                .expect("insert legacy config row");
519            store.persist().expect("publish prepared fixture");
520        }
521
522        let source = Arc::new(Source::open(path).expect("open prepared fixture"));
523        let mut catalog = Catalog::read(&source).expect("read prepared catalog");
524        assert!(!source.header.requires_disk_residency());
525        assert!(
526            catalog.resume.is_none(),
527            "legacy fixture has no resume trailer"
528        );
529        let config_root = catalog
530            .roots
531            .iter_mut()
532            .find(|root| root.collection == "cfg_legacy")
533            .expect("legacy fixture root");
534        config_root.collection = "red_config".into();
535        let identity = catalog
536            .roots
537            .iter()
538            .map(|root| (root.root_page, root.root_page))
539            .collect();
540        let encoded = catalog
541            .encode_with_proofs(&identity, None)
542            .expect("encode legacy catalog");
543        drop(source);
544
545        let pager = Pager::open(path, PagerConfig::default()).expect("open fixture pager");
546        catalog::write_catalog(&pager, &encoded).expect("publish no-resume legacy catalog");
547        pager.sync().expect("sync no-resume legacy catalog");
548        drop(pager);
549        crate::storage::operational_manifest::OperationalManifest::for_db_path(path)
550            .rename_collections(&[("cfg_legacy", "red_config")])
551            .expect("publish legacy operational name");
552
553        let source = Arc::new(Source::open(path).expect("reopen no-resume fixture"));
554        let catalog = Catalog::read(&source).expect("read no-resume catalog");
555        assert!(catalog.resume.is_none());
556        assert!(catalog
557            .roots
558            .iter()
559            .any(|root| root.collection == "red_config"));
560        config
561    }
562
563    #[test]
564    fn canonical_compaction_prepares_legacy_catalog_without_resume_trailer() {
565        let directory = tempfile::tempdir().expect("temporary store");
566        let source = directory.path().join("data.rdb");
567        let destination = directory.path().join("compacted");
568        let config = legacy_config_without_resume(&source);
569        let original = std::fs::read(&source).expect("source bytes");
570
571        let report = compact_paged_canonical_system_config(&source, &destination)
572            .expect("compact and prepare legacy catalog");
573
574        assert_eq!(report.reconciled_system_collections, 1);
575        assert_eq!(report.imported_system_records, 1);
576        assert_eq!(std::fs::read(&source).unwrap(), original);
577        let output = destination.join("data.rdb");
578        {
579            let prepared = Arc::new(Source::open(&output).expect("inspect compacted store"));
580            assert!(!prepared.header.requires_disk_residency());
581            let catalog = Catalog::read(&prepared).expect("read compacted catalog");
582            assert!(catalog.resume.is_none());
583            assert!(catalog
584                .roots
585                .iter()
586                .all(|root| root.collection != "red_config"));
587        }
588        for _ in 0..2 {
589            let compacted =
590                crate::storage::unified::UnifiedStore::open_with_config(&output, config.clone())
591                    .expect("cold reopen compacted store");
592            assert_eq!(compacted.list_collections(), vec!["red.config".to_string()]);
593            assert_eq!(
594                compacted.get_config("auth.require_auth"),
595                Some(reddb_types::Value::Boolean(true))
596            );
597            assert_eq!(compacted.legacy_red_config_key_count().unwrap(), 0);
598        }
599    }
600
601    #[test]
602    fn compaction_progress_is_machine_readable() {
603        let directory = tempfile::tempdir().expect("progress directory");
604        write_compaction_progress(directory.path(), "rewrite", 2, 5, 1_000)
605            .expect("write progress");
606        let progress: crate::serde_json::Value = crate::serde_json::from_slice(
607            &std::fs::read(directory.path().join("compaction.progress.json"))
608                .expect("progress file"),
609        )
610        .expect("progress JSON");
611        assert_eq!(progress["phase"].as_str(), Some("rewrite"));
612        assert_eq!(progress["completed_trees"].as_u64(), Some(2));
613        assert_eq!(progress["total_trees"].as_u64(), Some(5));
614        assert_eq!(progress["records"].as_u64(), Some(1_000));
615    }
616
617    #[test]
618    fn every_legacy_collection_action_is_rejected_before_name_normalization() {
619        use f::StoreWalActionFrame as Action;
620
621        let actions = [
622            Action::CreateCollection {
623                name: "red_config".into(),
624            },
625            Action::DropCollection {
626                name: "red_config".into(),
627            },
628            Action::UpsertEntityRecord {
629                collection: "red_config".into(),
630                record: vec![1],
631            },
632            Action::DeleteEntityRecord {
633                collection: "red_config".into(),
634                entity_id: 1,
635            },
636            Action::BulkUpsertEntityRecords {
637                collection: "red_config".into(),
638                records: vec![vec![1]],
639            },
640            Action::RefreshCollection {
641                collection: "red_config".into(),
642                records: vec![vec![1]],
643            },
644        ];
645        for action in actions {
646            let bytes = f::encode_store_wal_action_frame(&action).unwrap();
647            assert!(verify_wal_recovery_action(&bytes, false).is_ok());
648            assert!(verify_wal_recovery_action(&bytes, true)
649                .unwrap_err()
650                .to_string()
651                .contains("WAL references divergent legacy red_config"));
652        }
653        let canonical = f::encode_store_wal_action_frame(&Action::DeleteEntityRecord {
654            collection: "red.config".into(),
655            entity_id: 1,
656        })
657        .unwrap();
658        assert!(verify_wal_recovery_action(&canonical, true).is_ok());
659        let legacy_contract = f::encode_store_wal_action_frame(&Action::SetAuxMetadata {
660            bytes: br#"[{"name":"red\u005fconfig"}]"#.to_vec(),
661        })
662        .unwrap();
663        assert!(verify_wal_recovery_action(&legacy_contract, true).is_err());
664    }
665}
666
667fn verify_turbo_snapshots(
668    path: &Path,
669    store: &crate::storage::unified::UnifiedStore,
670) -> Result<bool> {
671    let snapshots = f::support_dir_for(path).join("snapshots");
672    if !snapshots.exists() {
673        return Ok(false);
674    }
675    let mut found = false;
676    for entry in std::fs::read_dir(snapshots)? {
677        let entry = entry?;
678        if entry.file_type()?.is_dir() {
679            continue;
680        }
681        found = true;
682        let path = entry.path();
683        let name = path
684            .file_stem()
685            .and_then(|name| name.to_str())
686            .ok_or("invalid turbo snapshot name")?;
687        ensure(
688            crate::runtime::vector_turbo_kind::is_turbo(store, name),
689            "snapshot has no turbo collection",
690        )?;
691        let length = entry.metadata()?.len();
692        ensure(
693            length <= 64 * 1024 * 1024,
694            "turbo snapshot exceeds recovery budget",
695        )?;
696        let mut header = [0u8; f::TURBOQUANT_SNAPSHOT_HEADER_BYTES];
697        File::open(&path)?.read_exact(&mut header)?;
698        let dim = u32::from_le_bytes(header[12..16].try_into()?);
699        let count = u64::from_le_bytes(header[32..40].try_into()?);
700        let record_size = u64::from(dim)
701            .checked_mul(4)
702            .and_then(|v| v.checked_add(12))
703            .ok_or("snapshot dimension overflow")?;
704        let expected = count
705            .checked_mul(record_size)
706            .and_then(|v| v.checked_add(header.len() as u64))
707            .ok_or("snapshot length overflow")?;
708        ensure(expected == length, "invalid turbo snapshot length")?;
709        let payload = f::read_turboquant_snapshot(
710            &path,
711            dim,
712            crate::runtime::vector_turbo_kind::TURBO_CODEC_SEED,
713        )?;
714        for (id, vector) in payload.vectors {
715            let entity = store
716                .try_get(name, crate::storage::EntityId::new(id), 32 * 1024 * 1024)?
717                .ok_or("snapshot vector has no recovered entity")?;
718            let crate::storage::EntityData::Vector(data) = entity.data else {
719                return Err("snapshot points to a non-vector entity".into());
720            };
721            ensure(
722                data.dense.len() == vector.len()
723                    && data
724                        .dense
725                        .iter()
726                        .zip(&vector)
727                        .all(|(a, b)| a.to_bits() == b.to_bits()),
728                "snapshot vector differs from recovered entity",
729            )?;
730        }
731        // This verified cache predates WAL replay. Rebuild it from the durable
732        // entities instead of allowing a stale snapshot to hide recovered rows.
733        std::fs::remove_file(path)?;
734    }
735    Ok(found)
736}
737
738fn wal_has_records(path: &Path) -> Result<bool> {
739    match std::fs::metadata(path) {
740        Ok(metadata) => Ok(metadata.len() > f::WAL_FILE_HEADER_BYTES as u64),
741        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
742        Err(error) => Err(error.into()),
743    }
744}
745
746fn replay_engine_wal_on_copy(pager: &Pager, path: &Path) -> Result<u64> {
747    use crate::storage::wal::{WalReader, WalRecord};
748    let mut transactions = std::collections::HashMap::new();
749    let mut last_lsn = 0;
750    let mut highest_tx = 0u64;
751    let header = pager.header()?;
752    let mut target_seen = !header.checkpoint_in_progress;
753    for item in WalReader::open(path)?.iter() {
754        let (lsn, record) = item?;
755        last_lsn = lsn;
756        target_seen |= lsn == header.checkpoint_target_lsn;
757        match record {
758            WalRecord::Begin { tx_id } => {
759                highest_tx = highest_tx.max(tx_id);
760                transactions.insert(tx_id, false);
761            }
762            WalRecord::Commit { tx_id } => {
763                highest_tx = highest_tx.max(tx_id);
764                transactions.insert(tx_id, true);
765            }
766            WalRecord::Rollback { tx_id } => {
767                highest_tx = highest_tx.max(tx_id);
768                transactions.remove(&tx_id);
769            }
770            WalRecord::PageWrite { tx_id, .. } => highest_tx = highest_tx.max(tx_id),
771            _ => {}
772        }
773    }
774    ensure(
775        target_seen,
776        "engine WAL does not contain the interrupted checkpoint target",
777    )?;
778    // Store only the LSN of each latest committed page, not every page image.
779    let mut latest = std::collections::HashMap::new();
780    for item in WalReader::open(path)?.iter() {
781        let (lsn, record) = item?;
782        if let WalRecord::PageWrite { tx_id, page_id, .. } = record {
783            if transactions.get(&tx_id).copied().unwrap_or(false) {
784                latest.insert(page_id, lsn);
785            }
786        }
787    }
788    ensure(
789        !header.checkpoint_in_progress || !latest.is_empty(),
790        "interrupted checkpoint has no committed page images",
791    )?;
792    if !latest.is_empty() {
793        pager.set_checkpoint_in_progress(true, last_lsn)?;
794        for item in WalReader::open(path)?.iter() {
795            let (lsn, record) = item?;
796            if let WalRecord::PageWrite { page_id, data, .. } = record {
797                if latest.get(&page_id) == Some(&lsn) {
798                    pager.write_page(page_id, Page::from_slice(&data)?)?;
799                }
800            }
801        }
802        pager.sync()?;
803        pager.complete_checkpoint(last_lsn)?;
804    }
805    Ok(highest_tx)
806}
807
808fn copy_physical_metadata_files(source: &Path, destination: &Path) -> Result<()> {
809    for (old, new) in [
810        (
811            f::physical_metadata_binary_path(source),
812            f::physical_metadata_binary_path(destination),
813        ),
814        (
815            f::physical_metadata_json_path(source),
816            f::physical_metadata_json_path(destination),
817        ),
818    ] {
819        match std::fs::symlink_metadata(&old) {
820            Ok(stat) => {
821                ensure(
822                    stat.is_file() && stat.len() <= 64 * 1024 * 1024,
823                    "invalid physical metadata sidecar",
824                )?;
825                let mut input = File::open(&old)?;
826                let mut output = create_new(&new)?;
827                std::io::copy(&mut input, &mut output)?;
828                output.sync_all()?;
829                drop(output);
830                verify_file_copy(&old, &new)?;
831            }
832            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
833            Err(error) => return Err(error.into()),
834        }
835    }
836    Ok(())
837}
838
839fn compact_paged_inner(
840    source: &Path,
841    destination: &Path,
842    salvage: Option<&PagedIndexSalvageReport>,
843    lost_collections: Option<&PagedCollectionSalvageReport>,
844    retain_canonical_system_config: bool,
845) -> Result<CompactionReport> {
846    let source_path = source.canonicalize()?;
847    let parent = destination
848        .parent()
849        .filter(|parent| !parent.as_os_str().is_empty())
850        .unwrap_or_else(|| Path::new("."))
851        .canonicalize()?;
852    for source_directory in [
853        f::support_dir_for(&source_path),
854        source_path.with_file_name(format!("{}.ops", f::data_file_name(&source_path))),
855    ] {
856        if source_directory.exists() {
857            ensure(
858                !parent.starts_with(source_directory.canonicalize()?),
859                "destination is inside source storage",
860            )?;
861        }
862    }
863    let source = Arc::new(Source::open(&source_path)?);
864    let mut catalog = Catalog::read(&source)?;
865    let prepare_legacy_catalog = retain_canonical_system_config && catalog.resume.is_none();
866    let had_legacy_system_config = catalog
867        .roots
868        .iter()
869        .any(|root| root.collection == "red_config");
870    let had_canonical_system_config = catalog
871        .roots
872        .iter()
873        .any(|root| root.collection == "red.config");
874    let migrated_system_config = retain_canonical_system_config && had_legacy_system_config;
875    if prepare_legacy_catalog {
876        let legacy_roots = catalog
877            .roots
878            .iter()
879            .filter(|root| root.collection == "red_config")
880            .count();
881        let canonical_roots = catalog
882            .roots
883            .iter()
884            .filter(|root| root.collection == "red.config")
885            .count();
886        ensure(
887            legacy_roots <= 1 && canonical_roots <= 1,
888            "canonical config migration requires unique config roots",
889        )?;
890        ensure(
891            legacy_roots + canonical_roots > 0,
892            "canonical config migration requires a config root",
893        )?;
894        ensure(
895            salvage.is_none() && lost_collections.is_none(),
896            "legacy catalog preparation cannot be combined with salvage",
897        )?;
898        ensure(
899            !wal_has_records(&f::unified_wal_path(&source_path))?
900                && !wal_has_records(&f::engine_wal_path(&source_path))?,
901            "legacy catalog preparation requires checkpointed WALs",
902        )?;
903        if migrated_system_config {
904            catalog.verify_alias_has_no_references("red_config")?;
905        }
906    }
907    let mut migrated_system_config_records =
908        if retain_canonical_system_config && !prepare_legacy_catalog {
909            catalog.migrate_legacy_system_config()?
910        } else {
911            0
912        };
913    ensure(
914        !source.header.requires_disk_residency()
915            || catalog.resume.is_some()
916            || prepare_legacy_catalog,
917        "prepared disk-resident file has no resume catalog",
918    )?;
919    if let Some(salvage) = salvage {
920        let resume = catalog
921            .resume
922            .as_mut()
923            .ok_or("index recovery requires a resume catalog")?;
924        for finding in &salvage.indexes {
925            let state = resume
926                .collections
927                .get_mut(&finding.collection)
928                .ok_or("index collection missing from resume")?;
929            let index = state
930                .secondary_indices
931                .remove(&finding.index)
932                .ok_or("index missing from resume")?;
933            ensure(
934                index.root_page == finding.root_page,
935                "index root changed during salvage",
936            )?;
937        }
938    }
939    if let Some(losses) = lost_collections {
940        ensure(
941            catalog.resume.is_none() && !catalog.has_cross_references(),
942            "collection recovery requires a reference-free legacy catalog",
943        )?;
944        for loss in &losses.collections {
945            let root = catalog
946                .roots
947                .iter_mut()
948                .find(|root| root.collection == loss.collection)
949                .ok_or("collection missing from catalog")?;
950            ensure(
951                root.root_page == loss.root_page,
952                "collection root changed during salvage",
953            )?;
954            if loss.skipped_pages == [loss.root_page] {
955                root.root_page = 0;
956            }
957        }
958    }
959    let name = source_path
960        .file_name()
961        .ok_or("source filename is missing")?;
962    // Exclusive creation prevents clobbering files, symlinks and other runs.
963    std::fs::create_dir(destination)?;
964    #[cfg(unix)]
965    {
966        use std::os::unix::fs::PermissionsExt;
967        std::fs::set_permissions(destination, std::fs::Permissions::from_mode(0o700))?;
968    }
969    let total_trees = catalog.roots.len()
970        + catalog.resume.as_ref().map_or(0, |resume| {
971            resume
972                .collections
973                .values()
974                .map(|state| {
975                    usize::from(state.key_index_root.is_some()) + state.secondary_indices.len()
976                })
977                .sum::<usize>()
978        });
979    let mut completed_trees = 0usize;
980    write_compaction_progress(destination, "rewrite", completed_trees, total_trees, 0)?;
981    let output = destination.join(name);
982    let temporary = destination.join(".compacting.rdb");
983    ensure(output != temporary, "reserved compaction source filename")?;
984    let target = Arc::new(Pager::open(
985        &temporary,
986        PagerConfig {
987            cache_size: 1024,
988            disk_residency: source.header.requires_disk_residency(),
989            ..PagerConfig::default()
990        },
991    )?);
992    let mut roots = BTreeMap::new();
993    if source.header.required_capabilities & f::file_format::FILE_CAPABILITY_TREE_PROOFS != 0 {
994        target.fence_required_capabilities(
995            f::file_format::FILE_CAPABILITY_TREE_PROOFS
996                | f::file_format::FILE_CAPABILITY_DWB_PUBLICATION,
997        )?;
998    }
999    let mut tree_proofs = f::page_proof::CatalogProofs::new();
1000    let mut recovered_trees = BTreeMap::new();
1001    let mut records = 0;
1002    let mut repaired_leaf_backlinks = 0;
1003    let mut legacy_config_records = 0;
1004    let mut canonical_config_records = 0;
1005    for collection in &catalog.roots {
1006        let loss = lost_collections.and_then(|report| {
1007            report
1008                .collections
1009                .iter()
1010                .find(|loss| loss.collection == collection.collection && collection.root_page != 0)
1011        });
1012        let count = if let Some(loss) = loss {
1013            let (count, hash) =
1014                rewrite_recoverable_tree(&source, &target, loss, &mut roots, &mut tree_proofs)?;
1015            recovered_trees.insert(loss.root_page, (count, hash));
1016            count
1017        } else {
1018            rewrite_tree(
1019                &source,
1020                &target,
1021                collection.root_page,
1022                &mut roots,
1023                &mut repaired_leaf_backlinks,
1024                &mut tree_proofs,
1025            )?
1026        };
1027        if let Some(resume) = &catalog.resume {
1028            ensure(
1029                resume.collections[&collection.collection].entities == count,
1030                "collection count disagrees with resume",
1031            )?;
1032        }
1033        if prepare_legacy_catalog {
1034            match collection.collection.as_str() {
1035                "red_config" => legacy_config_records = count,
1036                "red.config" => canonical_config_records = count,
1037                _ => {}
1038            }
1039        }
1040        records += count;
1041        completed_trees += 1;
1042        write_compaction_progress(
1043            destination,
1044            "rewrite",
1045            completed_trees,
1046            total_trees,
1047            records,
1048        )?;
1049    }
1050    if let Some(resume) = &catalog.resume {
1051        for state in resume.collections.values() {
1052            if let Some(root) = state.key_index_root {
1053                let count = rewrite_tree(
1054                    &source,
1055                    &target,
1056                    root,
1057                    &mut roots,
1058                    &mut repaired_leaf_backlinks,
1059                    &mut tree_proofs,
1060                )?;
1061                records += count;
1062                completed_trees += 1;
1063                write_compaction_progress(
1064                    destination,
1065                    "rewrite",
1066                    completed_trees,
1067                    total_trees,
1068                    records,
1069                )?;
1070            }
1071            for index in state.secondary_indices.values() {
1072                let count = rewrite_tree(
1073                    &source,
1074                    &target,
1075                    index.root_page,
1076                    &mut roots,
1077                    &mut repaired_leaf_backlinks,
1078                    &mut tree_proofs,
1079                )?;
1080                records += count;
1081                completed_trees += 1;
1082                write_compaction_progress(
1083                    destination,
1084                    "rewrite",
1085                    completed_trees,
1086                    total_trees,
1087                    records,
1088                )?;
1089            }
1090        }
1091    }
1092    if prepare_legacy_catalog {
1093        ensure(
1094            legacy_config_records == 0 || canonical_config_records == 0,
1095            "both red_config and red.config contain records; refusing lossy migration",
1096        )?;
1097        if legacy_config_records > 0 {
1098            migrated_system_config_records = usize::try_from(legacy_config_records)?;
1099        }
1100    }
1101    write_compaction_progress(destination, "assets", completed_trees, total_trees, records)?;
1102    let mut assets = assets::Assets::new(&source, &target);
1103    assets.vault()?;
1104    let physical = assets.physical()?;
1105    let internal = internal_metadata::read(&source, &catalog)?;
1106    let rewritten_document = assets.metadata(
1107        &source_path,
1108        Some(&output),
1109        internal.as_ref().map(|record| record.document.as_str()),
1110    )?;
1111    let mut rewritten_metadata = None;
1112    if let (Some(record), Some(document)) = (internal, rewritten_document) {
1113        let old_root = record.root;
1114        let key = record.key.clone();
1115        let value = record.rewrite(document)?;
1116        let previous_root = roots[&old_root];
1117        let tree = match tree_proofs.get(&previous_root).copied() {
1118            Some(proof) => BTree::with_verified_root(Arc::clone(&target), previous_root, proof)?,
1119            None => BTree::with_root(Arc::clone(&target), previous_root),
1120        };
1121        tree.upsert(&key, &value)?;
1122        tree_proofs.remove(&previous_root);
1123        remember_output_proof(&tree, &mut tree_proofs)?;
1124        roots.insert(old_root, tree.root_page_id());
1125        rewritten_metadata = Some((old_root, key, value));
1126    }
1127    catalog.claim_retired(&source)?;
1128    if salvage.is_some() || lost_collections.is_some() {
1129        if let Some(salvage) = salvage {
1130            for index in &salvage.indexes {
1131                if index.root_page != 0 {
1132                    if source.claim_published_tree(index.root_page)? {
1133                        continue;
1134                    }
1135                    match source.raw_page(index.root_page, true) {
1136                        Ok(_) => {
1137                            let tree = source.tree(index.root_page)?;
1138                            let skipped = tree.visit_recoverable_leaves(
1139                                |id| {
1140                                    source.claim(id).map_err(|error| {
1141                                        reddb_engine::storage::btree::BTreeError::Corrupted(
1142                                            error.to_string(),
1143                                        )
1144                                    })
1145                                },
1146                                |_, _| Ok(()),
1147                            )?;
1148                            ensure(
1149                                !skipped.is_empty(),
1150                                "index damage is not a verified leaf checksum failure",
1151                            )?;
1152                        }
1153                        Err(error) => {
1154                            ensure(
1155                                matches!(
1156                                    error.downcast_ref::<reddb_engine::storage::page::PageError>(),
1157                                    Some(
1158                                        reddb_engine::storage::page::PageError::ChecksumMismatch { .. }
1159                                    )
1160                                ),
1161                                "index root failure is not a checksum mismatch",
1162                            )?;
1163                            ensure(
1164                                source.raw_page(index.root_page, false)?.page_type()?
1165                                    == PageType::BTreeLeaf,
1166                                "damaged interior index root cannot be recovered",
1167                            )?;
1168                            source.claim(index.root_page)?;
1169                        }
1170                    }
1171                }
1172            }
1173        }
1174        if let Some(losses) = lost_collections {
1175            for collection in &losses.collections {
1176                if collection.skipped_pages == [collection.root_page] {
1177                    if !source.claim_published_tree(collection.root_page)? {
1178                        source.claim(collection.root_page)?;
1179                    }
1180                }
1181            }
1182        }
1183        ensure(
1184            source.unclaimed_pages() == 0,
1185            "unclassified source pages require separate recovery verification",
1186        )?;
1187    }
1188    // The unpublished output has no readers or prior authoritative generation.
1189    let (pending, _) = target.deferred_reclamation_pages()?;
1190    target.complete_deferred_publication(&[], &pending)?;
1191    let enabled =
1192        target.header()?.required_capabilities & f::file_format::FILE_CAPABILITY_TREE_PROOFS != 0;
1193    catalog::write_catalog(
1194        &target,
1195        &catalog.encode_with_proofs(&roots, enabled.then_some(&tree_proofs))?,
1196    )?;
1197    target.update_physical_header(physical)?;
1198    let capabilities = (source.header.required_capabilities
1199        & !f::file_format::FILE_CAPABILITY_RECOVERY_READ_ONLY)
1200        | if source.header.requires_disk_residency() {
1201            f::FILE_CAPABILITY_DISK_RESIDENCY
1202        } else {
1203            0
1204        };
1205    if capabilities != 0 {
1206        target.fence_required_capabilities(capabilities)?;
1207    }
1208    target.fence_file_format_version(source.header.version.max(target.header()?.version))?;
1209    target.sync()?;
1210    // Preserve source schema/LSN, but retain the newly allocated page boundary.
1211    for _ in 0..2 {
1212        target.commit_superblock(|slot| {
1213            let mut header = f::decode_published_database_header(slot).map_err(|error| {
1214                reddb_engine::storage::pager::PagerError::InvalidDatabase(error.to_string())
1215            })?;
1216            header.schema_version = source.header.schema_version;
1217            header.checkpoint_lsn = source.header.checkpoint_lsn;
1218            f::encode_database_header(slot, &header).map_err(|error| {
1219                reddb_engine::storage::pager::PagerError::InvalidDatabase(error.to_string())
1220            })
1221        })?;
1222    }
1223    if lost_collections.is_some() || source.header.is_recovery_read_only() {
1224        // Both copies must be fenced before the recovered filename is published.
1225        // Old engines reject this newer version; this engine admits it read-only.
1226        target.fence_required_capabilities(f::file_format::FILE_CAPABILITY_RECOVERY_READ_ONLY)?;
1227    }
1228    let assets_verification = assets.into_verification();
1229    drop(target);
1230    write_compaction_progress(destination, "verify", completed_trees, total_trees, records)?;
1231    let reopened = Arc::new(Source::open(&temporary)?);
1232    if salvage.is_some() || lost_collections.is_some() {
1233        salvage::verify_vault(&temporary, &reopened)?;
1234    }
1235    ensure(
1236        reopened.header.physical == physical,
1237        "rewritten physical header failed parity",
1238    )?;
1239    let rewritten_catalog = Catalog::read(&reopened)?;
1240    ensure(
1241        rewritten_catalog.encode(&identity_roots(&roots))?
1242            == catalog.encode_with_proofs(&roots, enabled.then_some(&tree_proofs))?,
1243        "rewritten catalog differs from source",
1244    )?;
1245    for (&old, &new) in &roots {
1246        if let Some((count, hash)) = recovered_trees.get(&old) {
1247            verify_recovered_tree(&reopened, new, *count, *hash)?;
1248        } else {
1249            verify_tree(
1250                &source,
1251                &reopened,
1252                old,
1253                new,
1254                rewritten_metadata.as_ref().filter(|record| record.0 == old),
1255            )?;
1256        }
1257    }
1258    for (id, expected, checksum) in assets_verification {
1259        let page = reopened.raw_page(id, checksum)?;
1260        if id != 2 {
1261            reopened.claim(id)?;
1262        }
1263        ensure(
1264            blake3::hash(page.content()) == expected,
1265            "native asset failed readback parity",
1266        )?;
1267    }
1268    let mut report = CompactionReport {
1269        retired_boot_system_wal_actions: 0,
1270        reconciled_system_collections: usize::from(migrated_system_config),
1271        imported_system_records: migrated_system_config_records,
1272        source_bytes: source.bytes,
1273        destination_bytes: reopened.bytes,
1274        source_allocated_bytes: allocated_bytes(&source_path)?,
1275        destination_allocated_bytes: allocated_bytes(&temporary)?,
1276        records,
1277        trees: roots.len(),
1278        repaired_leaf_backlinks,
1279    };
1280    drop(reopened);
1281    copy_sidecars(&source_path, &output, false)?;
1282    if retain_canonical_system_config && had_legacy_system_config {
1283        let operational_path = output.with_file_name(format!("{}.ops", f::data_file_name(&output)));
1284        if operational_path.exists() {
1285            let collision = if !had_canonical_system_config || migrated_system_config_records > 0 {
1286                ("red_config", "red.config", "red.config")
1287            } else {
1288                ("red.config", "red_config", "red.config")
1289            };
1290            crate::storage::operational_manifest::OperationalManifest::for_db_path(&output)
1291                .reconcile_collection_collisions(&[collision])?;
1292        }
1293    }
1294    if !prepare_legacy_catalog {
1295        write_new(
1296            &destination.join("compaction.json"),
1297            report.machine_json().as_bytes(),
1298        )?;
1299    }
1300    if let Some(salvage) = salvage {
1301        write_new(
1302            &destination.join("salvage.json"),
1303            salvage.machine_json().as_bytes(),
1304        )?;
1305    }
1306    if let Some(losses) = lost_collections {
1307        write_new(
1308            &destination.join("salvage.json"),
1309            losses.machine_json().as_bytes(),
1310        )?;
1311    }
1312    sync_directory(destination)?;
1313    write_compaction_progress(
1314        destination,
1315        "publish",
1316        completed_trees,
1317        total_trees,
1318        records,
1319    )?;
1320    // hard_link is create-new even if an unexpected file appears during work.
1321    std::fs::hard_link(&temporary, &output)?;
1322    sync_directory(destination)?;
1323    std::fs::remove_file(&temporary)?;
1324    sync_directory(destination)?;
1325    if prepare_legacy_catalog {
1326        write_compaction_progress(
1327            destination,
1328            "prepare",
1329            completed_trees,
1330            total_trees,
1331            records,
1332        )?;
1333        let config = crate::storage::unified::UnifiedStoreConfig {
1334            resident_memory_bytes_max: source
1335                .header
1336                .requires_disk_residency()
1337                .then_some(64 * 1024 * 1024),
1338            ..Default::default()
1339        };
1340        {
1341            let prepared =
1342                crate::storage::unified::UnifiedStore::open_with_config(&output, config)?;
1343            prepared.persist()?;
1344        }
1345        let verified = scrub_paged(&output)?;
1346        ensure(
1347            verified.assets_verified
1348                && verified.trees.findings.is_empty()
1349                && verified.unclassified_pages == 0,
1350            "prepared legacy catalog failed scrub",
1351        )?;
1352        let prepared = Arc::new(Source::open(&output)?);
1353        let prepared_catalog = Catalog::read(&prepared)?;
1354        ensure(
1355            !source.header.requires_disk_residency() || prepared_catalog.resume.is_some(),
1356            "disk-resident legacy catalog preparation did not publish a resume catalog",
1357        )?;
1358        ensure(
1359            prepared_catalog
1360                .roots
1361                .iter()
1362                .all(|root| root.collection != "red_config")
1363                && prepared_catalog
1364                    .roots
1365                    .iter()
1366                    .any(|root| root.collection == "red.config"),
1367            "legacy config identity survived catalog preparation",
1368        )?;
1369        drop(prepared);
1370        report.destination_bytes = std::fs::metadata(&output)?.len();
1371        report.destination_allocated_bytes = allocated_bytes(&output)?;
1372        report.records = verified.trees.records_verified;
1373        report.trees = usize::try_from(verified.trees.trees_verified)?;
1374        write_new(
1375            &destination.join("compaction.json"),
1376            report.machine_json().as_bytes(),
1377        )?;
1378        sync_directory(destination)?;
1379    }
1380    if let Some(parent) = destination.parent().filter(|p| !p.as_os_str().is_empty()) {
1381        sync_directory(parent)?;
1382    }
1383    write_compaction_progress(
1384        destination,
1385        "complete",
1386        completed_trees,
1387        total_trees,
1388        records,
1389    )?;
1390    sync_directory(destination)?;
1391    std::fs::remove_file(destination.join("compaction.progress.json"))?;
1392    sync_directory(destination)?;
1393    Ok(report)
1394}
1395
1396fn write_compaction_progress(
1397    destination: &Path,
1398    phase: &str,
1399    completed_trees: usize,
1400    total_trees: usize,
1401    records: u64,
1402) -> Result<()> {
1403    let mut file = OpenOptions::new()
1404        .create(true)
1405        .write(true)
1406        .truncate(true)
1407        .open(destination.join("compaction.progress.json"))?;
1408    write!(
1409        file,
1410        "{{\"phase\":\"{phase}\",\"completed_trees\":{completed_trees},\"total_trees\":{total_trees},\"records\":{records}}}"
1411    )?;
1412    file.flush()?;
1413    Ok(())
1414}
1415fn identity_roots(roots: &BTreeMap<u32, u32>) -> BTreeMap<u32, u32> {
1416    roots.values().map(|root| (*root, *root)).collect()
1417}
1418
1419fn hash_record(hasher: &mut blake3::Hasher, key: &[u8], value: &[u8]) {
1420    hasher.update(&(key.len() as u64).to_le_bytes());
1421    hasher.update(key);
1422    hasher.update(&(value.len() as u64).to_le_bytes());
1423    hasher.update(value);
1424}
1425
1426fn new_output_tree(target: &Arc<Pager>) -> Result<BTree<Pager>> {
1427    if target.header()?.required_capabilities & f::file_format::FILE_CAPABILITY_TREE_PROOFS != 0 {
1428        Ok(BTree::new_verified(Arc::clone(target))?)
1429    } else {
1430        Ok(BTree::new(Arc::clone(target)))
1431    }
1432}
1433
1434fn remember_output_proof(
1435    tree: &BTree<Pager>,
1436    proofs: &mut f::page_proof::CatalogProofs,
1437) -> Result<()> {
1438    if let Some((root, proof)) = tree.seal_page_proofs()? {
1439        if root != 0 {
1440            ensure(
1441                proofs.insert(root, proof).is_none(),
1442                "duplicate output tree proof",
1443            )?;
1444        }
1445    }
1446    Ok(())
1447}
1448
1449fn rewrite_recoverable_tree(
1450    source: &Arc<Source>,
1451    target: &Arc<Pager>,
1452    loss: &PagedCollectionLoss,
1453    roots: &mut BTreeMap<u32, u32>,
1454    proofs: &mut f::page_proof::CatalogProofs,
1455) -> Result<(u64, blake3::Hash)> {
1456    ensure(
1457        !roots.contains_key(&loss.root_page),
1458        "duplicate live tree owner",
1459    )?;
1460    let original = source.tree(loss.root_page)?;
1461    let destination = new_output_tree(target)?;
1462    let mut hash = blake3::Hasher::new();
1463    let mut count = 0u64;
1464    let mut batch = Vec::new();
1465    let mut size = 0usize;
1466    let skipped = original.visit_recoverable_leaves(
1467        |id| {
1468            source.claim(id).map_err(|error| {
1469                reddb_engine::storage::btree::BTreeError::Corrupted(error.to_string())
1470            })
1471        },
1472        |key, value| {
1473            hash_record(&mut hash, &key, &value);
1474            size += key.len() + value.len();
1475            batch.push((key, value));
1476            count += 1;
1477            if size >= 1024 * 1024 || batch.len() >= 512 {
1478                destination.bulk_insert_sorted(&batch)?;
1479                batch.clear();
1480                size = 0;
1481            }
1482            Ok(())
1483        },
1484    )?;
1485    ensure(
1486        skipped == loss.skipped_pages,
1487        "damaged pages changed during recovery",
1488    )?;
1489    destination.bulk_insert_sorted(&batch)?;
1490    remember_output_proof(&destination, proofs)?;
1491    roots.insert(loss.root_page, destination.root_page_id());
1492    Ok((count, hash.finalize()))
1493}
1494
1495fn verify_recovered_tree(
1496    source: &Arc<Source>,
1497    root: u32,
1498    count: u64,
1499    expected: blake3::Hash,
1500) -> Result<()> {
1501    let tree = source.tree(root)?;
1502    let (owned, _) = inventory_tree(source, &tree, false)?;
1503    ensure(owned == count, "recovered tree record count differs")?;
1504    let mut cursor = tree.cursor_first()?;
1505    let mut hash = blake3::Hasher::new();
1506    let mut actual = 0u64;
1507    while let Some((key, value)) = cursor.next_with_budget(32 * 1024 * 1024)? {
1508        hash_record(&mut hash, &key, &value);
1509        actual += 1;
1510        ensure(actual <= count, "recovered tree has extra records")?;
1511    }
1512    ensure(
1513        actual == count && hash.finalize() == expected,
1514        "recovered tree failed record parity",
1515    )
1516}
1517
1518fn rewrite_tree(
1519    source: &Arc<Source>,
1520    target: &Arc<Pager>,
1521    root: u32,
1522    roots: &mut BTreeMap<u32, u32>,
1523    repaired_leaf_backlinks: &mut u64,
1524    proofs: &mut f::page_proof::CatalogProofs,
1525) -> Result<u64> {
1526    if root == 0 {
1527        return Ok(0);
1528    }
1529    ensure(!roots.contains_key(&root), "duplicate live tree owner")?;
1530    let tree = source.tree(root)?;
1531    let (expected, repairs) = inventory_tree(source, &tree, true)?;
1532    *repaired_leaf_backlinks += repairs;
1533    let destination = new_output_tree(target)?;
1534    let mut cursor = tree.cursor_first()?;
1535    let mut count = 0;
1536    let mut previous: Option<Vec<u8>> = None;
1537    let mut batch = Vec::new();
1538    let mut bytes = 0;
1539    while let Some((key, value)) = cursor.next_with_budget(32 * 1024 * 1024)? {
1540        ensure(
1541            previous.as_ref().is_none_or(|old| old < &key),
1542            "source tree keys are not strictly ordered",
1543        )?;
1544        previous = Some(key.clone());
1545        bytes += key.len() + value.len();
1546        batch.push((key, value));
1547        count += 1;
1548        ensure(
1549            count <= expected,
1550            "tree cursor exceeds structural inventory",
1551        )?;
1552        if bytes >= 1024 * 1024 || batch.len() >= 512 {
1553            destination.bulk_insert_sorted(&batch)?;
1554            batch.clear();
1555            bytes = 0;
1556        }
1557    }
1558    destination.bulk_insert_sorted(&batch)?;
1559    remember_output_proof(&destination, proofs)?;
1560    ensure(count == expected, "tree cursor omits owned records")?;
1561    roots.insert(root, destination.root_page_id());
1562    Ok(count)
1563}
1564// Interior ownership and forward traversal must agree exactly. Old split code
1565// omitted the successor backlink update; that redundant edge can be rebuilt
1566// without guessing any ownership or key/value. Never repair forward omissions.
1567fn inventory_tree(
1568    source: &Source,
1569    tree: &BTree<Source>,
1570    allow_backlinks: bool,
1571) -> Result<(u64, u64)> {
1572    let pages = tree.retired_pages()?;
1573    let mut leaves = Vec::new();
1574    let mut expected = 0u64;
1575    for id in pages {
1576        source.claim(id)?;
1577        let page = source.raw_page(id, true)?;
1578        if page.page_type()? == PageType::BTreeLeaf {
1579            leaves.push((id, number(page.content(), 0)?, number(page.content(), 4)?));
1580            expected += u64::from(page.cell_count());
1581        }
1582    }
1583    // Ownership traversal is right-to-left. A cursor follows the independent
1584    // leaf chain; prove it visits exactly the structurally owned leaves.
1585    leaves.reverse();
1586    let mut repaired = 0;
1587    for (index, &(id, previous, next)) in leaves.iter().enumerate() {
1588        ensure(
1589            next == leaves.get(index + 1).map_or(0, |leaf| leaf.0),
1590            &format!(
1591                "broken forward leaf chain at page {id}, root {}",
1592                tree.root_page_id()
1593            ),
1594        )?;
1595        if previous != index.checked_sub(1).map_or(0, |i| leaves[i].0) {
1596            ensure(
1597                allow_backlinks,
1598                &format!("broken backward leaf chain at page {id}"),
1599            )?;
1600            repaired += 1;
1601        }
1602    }
1603    Ok((expected, repaired))
1604}
1605fn verify_tree(
1606    source: &Arc<Source>,
1607    destination: &Arc<Source>,
1608    old: u32,
1609    new: u32,
1610    rewritten: Option<&(u32, Vec<u8>, Vec<u8>)>,
1611) -> Result<()> {
1612    let old = source.tree(old)?;
1613    let new = destination.tree(new)?;
1614    inventory_tree(destination, &new, false)?;
1615    let mut left = old.cursor_first()?;
1616    let mut right = new.cursor_first()?;
1617    loop {
1618        let mut expected = left.next_with_budget(32 * 1024 * 1024)?;
1619        if let (Some((key, value)), Some((_, rewritten_key, rewritten_value))) =
1620            (&mut expected, rewritten)
1621        {
1622            if key == rewritten_key {
1623                *value = rewritten_value.clone();
1624            }
1625        }
1626        let actual = right.next_with_budget(32 * 1024 * 1024)?;
1627        ensure(
1628            expected == actual,
1629            "compacted tree failed complete key/value parity",
1630        )?;
1631        if expected.is_none() {
1632            return Ok(());
1633        }
1634    }
1635}
1636fn copy_sidecars(source: &Path, destination: &Path, recovery: bool) -> Result<()> {
1637    // These files contain logical records, not physical page addresses. Empty
1638    // checkpointed WALs also preserve their version exactly.
1639    for (old, new) in [
1640        (
1641            f::unified_wal_path(source),
1642            f::unified_wal_path(destination),
1643        ),
1644        (f::engine_wal_path(source), f::engine_wal_path(destination)),
1645        (
1646            f::logical_wal_path(source),
1647            f::logical_wal_path(destination),
1648        ),
1649        (
1650            f::legacy_logical_slots_path(source),
1651            f::legacy_logical_slots_path(destination),
1652        ),
1653    ] {
1654        match File::open(&old) {
1655            Ok(_) => copy_file_verified(&old, &new)?,
1656            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1657            Err(error) => return Err(error.into()),
1658        }
1659    }
1660    copy_audit_log_family(source, destination)?;
1661    let support = f::support_dir_for(source);
1662    if support.exists() {
1663        if recovery {
1664            validate_recovery_support(&support, 0, false)?;
1665        } else {
1666            validate_empty_directory(&support, 0)?;
1667        }
1668        copy_directory(&support, &f::support_dir_for(destination), 0)?;
1669    }
1670    let old = source.with_file_name(format!("{}.ops", f::data_file_name(source)));
1671    let new = destination.with_file_name(format!("{}.ops", f::data_file_name(destination)));
1672    if old.exists() {
1673        f::OperationalManifest::for_db_path(source).verify_owned_for_copy()?;
1674        copy_directory(&old, &new, 0)?;
1675    }
1676    Ok(())
1677}
1678
1679fn detach_recovery_audit_logs(source: &Path, stage: &Path) -> Result<Option<PathBuf>> {
1680    let family = audit_log_family(source)?;
1681    if family.is_empty() {
1682        return Ok(None);
1683    }
1684    let preserved = stage.join("preserved-audit");
1685    std::fs::create_dir(&preserved)?;
1686    for audit in family {
1687        let name = audit.file_name().ok_or("audit log filename is missing")?;
1688        std::fs::rename(&audit, preserved.join(name))?;
1689    }
1690    sync_directory(&preserved)?;
1691    sync_directory(stage)?;
1692    Ok(Some(preserved))
1693}
1694
1695fn restore_recovery_audit_logs(preserved: &Path, destination: &Path) -> Result<()> {
1696    let parent = destination
1697        .parent()
1698        .ok_or("destination parent is missing")?;
1699    for entry in std::fs::read_dir(preserved)? {
1700        let entry = entry?;
1701        ensure(
1702            entry.file_type()?.is_file(),
1703            "preserved audit log must be a regular file",
1704        )?;
1705        copy_file_verified(&entry.path(), &parent.join(entry.file_name()))?;
1706    }
1707    sync_directory(parent)
1708}
1709
1710fn copy_file_verified(source: &Path, destination: &Path) -> Result<()> {
1711    let mut input = File::open(source)?;
1712    let mut output = create_new(destination)?;
1713    std::io::copy(&mut input, &mut output)?;
1714    output.sync_all()?;
1715    verify_file_copy(source, destination)
1716}
1717
1718fn audit_log_family(data_path: &Path) -> Result<Vec<PathBuf>> {
1719    let active = f::legacy_audit_log_path(data_path);
1720    let parent = active.parent().ok_or("audit log parent is missing")?;
1721    let mut rotated = Vec::new();
1722    for entry in std::fs::read_dir(parent)? {
1723        let entry = entry?;
1724        let name = entry.file_name();
1725        let Some(name) = name.to_str() else {
1726            continue;
1727        };
1728        let Some(timestamp) = f::parse_audit_log_rotated_timestamp(&active, name) else {
1729            continue;
1730        };
1731        ensure(
1732            entry.file_type()?.is_file(),
1733            "rotated audit log must be a regular file",
1734        )?;
1735        rotated.push((timestamp, entry.path()));
1736    }
1737    rotated.sort_by_key(|(timestamp, _)| *timestamp);
1738    for pair in rotated.windows(2) {
1739        ensure(
1740            pair[0].0 != pair[1].0,
1741            "duplicate rotated audit log timestamp",
1742        )?;
1743    }
1744    let mut family: Vec<PathBuf> = rotated.into_iter().map(|(_, path)| path).collect();
1745    match std::fs::symlink_metadata(&active) {
1746        Ok(metadata) => {
1747            ensure(metadata.is_file(), "audit log must be a regular file")?;
1748            family.push(active);
1749        }
1750        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1751        Err(error) => return Err(error.into()),
1752    }
1753    Ok(family)
1754}
1755
1756fn copy_audit_log_family(source: &Path, destination: &Path) -> Result<()> {
1757    let destination_parent = destination
1758        .parent()
1759        .ok_or("audit log destination parent is missing")?;
1760    for old in audit_log_family(source)? {
1761        let name = old.file_name().ok_or("audit log filename is missing")?;
1762        copy_file_verified(&old, &destination_parent.join(name))?;
1763    }
1764    Ok(())
1765}
1766
1767pub(super) fn verify_audit_log_family(data_path: &Path) -> Result<()> {
1768    let mut previous = None;
1769    let mut has_events = false;
1770    for path in audit_log_family(data_path)? {
1771        let input = File::open(&path)?;
1772        if path
1773            .extension()
1774            .is_some_and(|extension| extension == f::layout::AUDIT_LOG_ROTATED_COMPRESSED_EXTENSION)
1775        {
1776            let decoder = zstd::stream::read::Decoder::new(input)?;
1777            (previous, has_events) = verify_audit_log_chain(decoder, previous, has_events)?;
1778        } else {
1779            (previous, has_events) = verify_audit_log_chain(input, previous, has_events)?;
1780        }
1781    }
1782    Ok(())
1783}
1784
1785fn verify_audit_log_chain(
1786    input: impl Read,
1787    mut previous: Option<String>,
1788    mut has_events: bool,
1789) -> Result<(Option<String>, bool)> {
1790    const MAX_EVENT_BYTES: usize = 1024 * 1024;
1791    let mut reader = BufReader::new(input);
1792    let mut line = Vec::new();
1793    loop {
1794        line.clear();
1795        loop {
1796            let buffer = reader.fill_buf()?;
1797            if buffer.is_empty() {
1798                if line.is_empty() {
1799                    return Ok((previous, has_events));
1800                }
1801                break;
1802            }
1803            let count = buffer
1804                .iter()
1805                .position(|byte| *byte == b'\n')
1806                .map_or(buffer.len(), |position| position + 1);
1807            ensure(
1808                line.len().saturating_add(count) <= MAX_EVENT_BYTES,
1809                "audit log event exceeds recovery verification budget",
1810            )?;
1811            line.extend_from_slice(&buffer[..count]);
1812            let ended = buffer[count - 1] == b'\n';
1813            reader.consume(count);
1814            if ended {
1815                break;
1816            }
1817        }
1818        if line.last() == Some(&b'\n') {
1819            line.pop();
1820        }
1821        if line.last() == Some(&b'\r') {
1822            line.pop();
1823        }
1824        ensure(!line.is_empty(), "audit log contains an empty event")?;
1825        let value: crate::serde_json::Value = crate::serde_json::from_slice(&line)?;
1826        ensure(
1827            value.as_object().is_some(),
1828            "audit log event must be a JSON object",
1829        )?;
1830        let declared = match value.get("prev_hash") {
1831            Some(value) => Some(
1832                value
1833                    .as_str()
1834                    .ok_or("audit log prev_hash must be a string")?,
1835            ),
1836            None => None,
1837        };
1838        if has_events {
1839            ensure(
1840                declared == previous.as_deref(),
1841                "audit log hash chain verification failed",
1842            )?;
1843        } else if let Some(anchor) = declared {
1844            ensure(
1845                anchor.len() == 64 && anchor.bytes().all(|byte| byte.is_ascii_hexdigit()),
1846                "audit log initial prev_hash is invalid",
1847            )?;
1848        }
1849        previous = Some(crate::utils::to_hex(&crate::crypto::sha256(&line)));
1850        has_events = true;
1851    }
1852}
1853
1854fn copy_directory(source: &Path, destination: &Path, depth: usize) -> Result<()> {
1855    ensure(depth < 32, "operational directory nesting exceeds limit")?;
1856    ensure(
1857        std::fs::symlink_metadata(source)?.is_dir(),
1858        "operational directory must not be a symlink",
1859    )?;
1860    std::fs::create_dir(destination)?;
1861    for entry in std::fs::read_dir(source)? {
1862        let entry = entry?;
1863        let kind = entry.file_type()?;
1864        let output = destination.join(entry.file_name());
1865        if kind.is_dir() {
1866            copy_directory(&entry.path(), &output, depth + 1)?;
1867        } else {
1868            ensure(
1869                kind.is_file(),
1870                "operational directory contains a symlink or special file",
1871            )?;
1872            let mut input = File::open(entry.path())?;
1873            let mut target = create_new(&output)?;
1874            std::io::copy(&mut input, &mut target)?;
1875            target.sync_all()?;
1876            verify_file_copy(&entry.path(), &output)?;
1877        }
1878    }
1879    sync_directory(destination)
1880}
1881fn validate_empty_directory(path: &Path, depth: usize) -> Result<()> {
1882    ensure(depth < 32, "support directory nesting exceeds limit")?;
1883    ensure(
1884        std::fs::symlink_metadata(path)?.is_dir(),
1885        "support directory must not be a symlink",
1886    )?;
1887    for entry in std::fs::read_dir(path)? {
1888        let entry = entry?;
1889        ensure(
1890            entry.file_type()?.is_dir(),
1891            "non-empty support layout requires separate compaction qualification",
1892        )?;
1893        validate_empty_directory(&entry.path(), depth + 1)?;
1894    }
1895    Ok(())
1896}
1897fn validate_recovery_support(path: &Path, depth: usize, snapshots: bool) -> Result<()> {
1898    ensure(depth < 32, "support directory nesting exceeds limit")?;
1899    ensure(
1900        std::fs::symlink_metadata(path)?.is_dir(),
1901        "support directory must not be a symlink",
1902    )?;
1903    for entry in std::fs::read_dir(path)? {
1904        let entry = entry?;
1905        let kind = entry.file_type()?;
1906        if kind.is_dir() {
1907            validate_recovery_support(
1908                &entry.path(),
1909                depth + 1,
1910                depth == 0 && entry.file_name() == "snapshots",
1911            )?;
1912        } else {
1913            ensure(
1914                snapshots
1915                    && kind.is_file()
1916                    && entry.path().extension().is_some_and(|ext| ext == "tv"),
1917                "unsupported recovery support file",
1918            )?;
1919        }
1920    }
1921    Ok(())
1922}
1923
1924fn verify_file_copy(source: &Path, destination: &Path) -> Result<()> {
1925    ensure(
1926        hash_reader(&mut File::open(source)?)? == hash_reader(&mut File::open(destination)?)?,
1927        "sidecar failed complete readback parity",
1928    )
1929}
1930fn hash_reader(input: &mut impl Read) -> Result<blake3::Hash> {
1931    let mut hash = blake3::Hasher::new();
1932    let mut buffer = [0; 64 * 1024];
1933    loop {
1934        let count = input.read(&mut buffer)?;
1935        if count == 0 {
1936            break;
1937        }
1938        hash.update(&buffer[..count]);
1939    }
1940    Ok(hash.finalize())
1941}
1942fn allocated_bytes(path: &Path) -> Result<Option<u64>> {
1943    #[cfg(unix)]
1944    {
1945        use std::os::unix::fs::MetadataExt;
1946        Ok(Some(
1947            std::fs::metadata(path)?
1948                .blocks()
1949                .checked_mul(512)
1950                .ok_or("allocated byte count overflow")?,
1951        ))
1952    }
1953    #[cfg(not(unix))]
1954    {
1955        let _ = path;
1956        Ok(None)
1957    }
1958}
1959fn create_new(path: &Path) -> std::io::Result<File> {
1960    let mut options = OpenOptions::new();
1961    options.write(true).create_new(true);
1962    #[cfg(unix)]
1963    {
1964        use std::os::unix::fs::OpenOptionsExt;
1965        options.mode(0o600);
1966    }
1967    options.open(path)
1968}
1969fn write_new(path: &Path, bytes: &[u8]) -> Result<()> {
1970    let mut file = create_new(path)?;
1971    file.write_all(bytes)?;
1972    file.sync_all()?;
1973    Ok(())
1974}
1975fn sync_directory(_path: &Path) -> Result<()> {
1976    #[cfg(unix)]
1977    File::open(_path)?.sync_all()?;
1978    Ok(())
1979}
1980fn ensure(condition: bool, message: &str) -> Result<()> {
1981    if condition {
1982        Ok(())
1983    } else {
1984        Err(std::io::Error::new(std::io::ErrorKind::InvalidData, message).into())
1985    }
1986}
1987fn number(bytes: &[u8], offset: usize) -> Result<u32> {
1988    Ok(u32::from_le_bytes(
1989        bytes
1990            .get(offset..offset + 4)
1991            .ok_or("truncated native integer")?
1992            .try_into()?,
1993    ))
1994}