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