Skip to main content

reddb_server/storage/compact/
salvage.rs

1use super::*;
2
3#[derive(Debug)]
4pub struct PagedIndexSalvageFinding {
5    pub collection: String,
6    pub index: String,
7    pub root_page: u32,
8    pub reason: String,
9}
10
11#[derive(Debug)]
12pub struct PagedIndexSalvageReport {
13    pub indexes: Vec<PagedIndexSalvageFinding>,
14}
15
16impl PagedIndexSalvageReport {
17    pub fn machine_json(&self) -> String {
18        let indexes: Vec<_> = self
19            .indexes
20            .iter()
21            .map(|finding| {
22                crate::serde_json::json!({
23                    "collection": finding.collection.clone(),
24                    "index": finding.index.clone(),
25                    "root_page": finding.root_page,
26                    "reason": finding.reason.clone(),
27                })
28            })
29            .collect();
30        crate::serde_json::json!({
31            "scope": "secondary_indexes_only",
32            "action": "discarded_for_rebuild",
33            "page_generation_freshness_verified": false,
34            "indexes": indexes,
35        })
36        .to_string_compact()
37    }
38}
39
40/// Recover a closed, checkpointed store when only derived secondary index
41/// trees are damaged. Data and primary-key trees must verify. The output
42/// retains index definitions but omits damaged physical roots so the runtime
43/// can rebuild them from the surviving rows. Other corruption fails closed.
44pub fn salvage_paged_indexes(source: &Path, destination: &Path) -> Result<PagedIndexSalvageReport> {
45    let canonical_path = source.canonicalize()?;
46    let source = canonical_path.as_path();
47    // Hold the source lock across both verification and publication.
48    let guard = Source::open(source)?;
49    verify_supported_source(source, &guard)?;
50    let scrub = scrub_paged_trees(source)?;
51    let mut indexes = Vec::new();
52    for finding in scrub.findings {
53        let index = finding
54            .tree
55            .strip_prefix("secondary index ")
56            .ok_or_else(|| {
57                format!(
58                    "cannot safely recover {} tree of {}: {}",
59                    finding.tree, finding.collection, finding.reason
60                )
61            })?;
62        indexes.push(PagedIndexSalvageFinding {
63            collection: finding.collection,
64            index: index.to_owned(),
65            root_page: finding.root_page,
66            reason: finding.reason,
67        });
68    }
69    ensure(!indexes.is_empty(), "no damaged secondary index to recover")?;
70    let report = PagedIndexSalvageReport { indexes };
71    compact_paged_inner(source, destination, Some(&report), None, false)?;
72    Ok(report)
73}
74
75#[derive(Debug)]
76pub struct PagedCollectionLoss {
77    pub collection: String,
78    pub root_page: u32,
79    pub skipped_pages: Vec<u32>,
80}
81
82#[derive(Debug)]
83pub struct PagedCollectionSalvageReport {
84    pub collections: Vec<PagedCollectionLoss>,
85}
86
87impl PagedCollectionSalvageReport {
88    pub fn machine_json(&self) -> String {
89        let collections: Vec<_> = self
90            .collections
91            .iter()
92            .map(|loss| {
93                crate::serde_json::json!({
94                    "collection": loss.collection.clone(), "root_page": loss.root_page,
95                    "action": if loss.skipped_pages == [loss.root_page] { "collection_emptied" } else { "damaged_leaves_skipped" },
96                    "reason": "page_checksum_mismatch", "skipped_pages": loss.skipped_pages.clone(),
97                    "skipped_entities": crate::serde_json::Value::Null,
98                })
99            })
100            .collect();
101        crate::serde_json::json!({"scope": "legacy_collection_trees", "page_generation_freshness_verified": false, "identity_high_water_verified": false, "safe_for_writes": false, "collections": collections}).to_string_compact()
102    }
103}
104
105/// Recover intact collections and verified leaves in a reference-free legacy
106/// store. Lost entity counts and identity high-water marks remain unknown.
107pub fn salvage_paged_collections(
108    source: &Path,
109    destination: &Path,
110) -> Result<PagedCollectionSalvageReport> {
111    let canonical_path = source.canonicalize()?;
112    let source = canonical_path.as_path();
113    let guard = Arc::new(Source::open(source)?);
114    verify_supported_source(source, &guard)?;
115    ensure(
116        guard.header.physical == f::PhysicalFileHeader::default(),
117        "physical metadata requires separate data recovery verification",
118    )?;
119    ensure(
120        !f::physical_metadata_binary_path(source).exists()
121            && !f::physical_metadata_json_path(source).exists(),
122        "metadata sidecar requires separate data recovery verification",
123    )?;
124    let catalog = Catalog::read(&guard)?;
125    ensure(
126        catalog.resume.is_none() && !catalog.has_cross_references(),
127        "collection recovery requires a reference-free legacy catalog",
128    )?;
129    let scrub = scrub_paged_trees(source)?;
130    let mut collections = Vec::new();
131    for finding in scrub.findings {
132        ensure(
133            finding.tree == "collection",
134            "only collection root damage is supported",
135        )?;
136        let canonical =
137            reddb_engine::storage::system_collection_names::canonical_or_self(&finding.collection);
138        ensure(
139            !canonical.starts_with("red.") && !canonical.starts_with('_'),
140            "system collections cannot be dropped",
141        )?;
142        let skipped_pages = match guard.raw_page(finding.root_page, true) {
143            Ok(_) => {
144                let tree = BTree::with_root(Arc::clone(&guard), finding.root_page);
145                tree.visit_recoverable_leaves(
146                    |id| {
147                        guard.claim(id).map_err(|error| {
148                            reddb_engine::storage::btree::BTreeError::Corrupted(error.to_string())
149                        })
150                    },
151                    |_, _| Ok(()),
152                )?
153            }
154            Err(error) => {
155                ensure(
156                    matches!(
157                        error.downcast_ref::<reddb_engine::storage::page::PageError>(),
158                        Some(reddb_engine::storage::page::PageError::ChecksumMismatch { .. })
159                    ),
160                    "collection root failure is not a checksum mismatch",
161                )?;
162                ensure(
163                    guard.raw_page(finding.root_page, false)?.page_type()? == PageType::BTreeLeaf,
164                    "only leaf-root collection damage is supported",
165                )?;
166                vec![finding.root_page]
167            }
168        };
169        ensure(!skipped_pages.is_empty(), "no checksum-damaged leaf found")?;
170        collections.push(PagedCollectionLoss {
171            collection: finding.collection,
172            root_page: finding.root_page,
173            skipped_pages,
174        });
175    }
176    ensure(
177        !collections.is_empty(),
178        "no damaged collection root to recover",
179    )?;
180    let report = PagedCollectionSalvageReport { collections };
181    compact_paged_inner(source, destination, None, Some(&report), false)?;
182    Ok(report)
183}
184
185pub(super) fn verify_supported_source(source: &Path, guard: &Source) -> Result<()> {
186    guard.verify_superblocks()?;
187    verify_standalone_sidecars(source)?;
188    let physical = guard.header.physical;
189    for (page_id, expected) in [
190        (physical.manifest_page, physical.manifest_checksum),
191        (
192            physical.collection_roots_page,
193            physical.collection_roots_checksum,
194        ),
195        (physical.registry_page, physical.registry_checksum),
196        (physical.recovery_page, physical.recovery_checksum),
197        (physical.catalog_page, physical.catalog_checksum),
198        (
199            physical.metadata_state_page,
200            physical.metadata_state_checksum,
201        ),
202        (
203            physical.vector_artifact_page,
204            physical.vector_artifact_checksum,
205        ),
206    ] {
207        if page_id == 0 {
208            continue;
209        }
210        let page = guard.raw_page(page_id, true)?;
211        ensure(
212            page.page_type()? == PageType::NativeMeta,
213            "invalid physical metadata page",
214        )?;
215        // The published checksum covers the encoded payload, not the zero
216        // padding to the page boundary. Its length is not stored separately.
217        // Accept only a checksum matching a prefix with exclusively zero
218        // bytes after it; the compactor also decodes each payload below.
219        let content = page.content();
220        let minimum = content
221            .iter()
222            .rposition(|byte| *byte != 0)
223            .map_or(0, |position| position + 1);
224        let mut checksum = crc32fast::Hasher::new();
225        checksum.update(&content[..minimum]);
226        let mut matches = u64::from(checksum.clone().finalize()) == expected;
227        for byte in &content[minimum..] {
228            checksum.update(std::slice::from_ref(byte));
229            matches |= u64::from(checksum.clone().finalize()) == expected;
230        }
231        ensure(
232            matches,
233            "physical metadata differs from its published checksum",
234        )?;
235    }
236    verify_vault(source, guard)?;
237    Ok(())
238}
239
240pub(super) fn verify_standalone_sidecars(source: &Path) -> Result<()> {
241    let operational = source.with_file_name(format!("{}.ops", f::data_file_name(source)));
242    if operational.exists() {
243        validate_operational(&operational)?;
244        f::OperationalManifest::for_db_path(source).verify_marker_only_for_recovery()?;
245    }
246    for path in [
247        f::logical_wal_path(source),
248        f::legacy_logical_slots_path(source),
249        f::legacy_audit_log_path(source),
250    ] {
251        match std::fs::symlink_metadata(path) {
252            Ok(metadata) => ensure(
253                metadata.is_file() && metadata.len() == 0,
254                "logical WAL, slot or audit data requires separate recovery verification",
255            )?,
256            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
257            Err(error) => return Err(error.into()),
258        }
259    }
260    Ok(())
261}
262
263pub(super) fn verify_vault(source: &Path, guard: &Source) -> Result<()> {
264    let vault = guard.raw_page(2, false)?;
265    if !vault.as_bytes().iter().all(|byte| *byte == 0) {
266        ensure(vault.page_type()? == PageType::Vault, "invalid vault page")?;
267        if vault.content().iter().all(|byte| *byte == 0) {
268            vault.verify_checksum()?;
269            return Ok(());
270        }
271        let content = vault.content();
272        ensure(
273            &content[..4] == b"RDVT" && matches!(content[4], 2 | 3),
274            "unsupported vault header",
275        )?;
276        let payload = u32::from_le_bytes(content[21..25].try_into()?);
277        ensure(
278            payload <= 64 * 1024 * 1024,
279            "vault exceeds verification budget",
280        )?;
281        let pager = Pager::open(
282            source,
283            PagerConfig {
284                read_only: true,
285                create: false,
286                ..PagerConfig::default()
287            },
288        )?;
289        let vault =
290            crate::auth::vault::Vault::open(&pager).map_err(|_| "vault authentication failed")?;
291        ensure(
292            matches!(vault.load(&pager), Ok(Some(_))),
293            "vault authentication failed",
294        )?;
295    }
296    Ok(())
297}