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)?;
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))?;
182    Ok(report)
183}
184
185pub(super) fn verify_supported_source(source: &Path, guard: &Source) -> Result<()> {
186    guard.verify_superblocks()?;
187    let operational = source.with_file_name(format!("{}.ops", f::data_file_name(source)));
188    if operational.exists() {
189        validate_operational(&operational)?;
190        f::OperationalManifest::for_db_path(source).verify_marker_only_for_recovery()?;
191    }
192    for path in [
193        f::logical_wal_path(source),
194        f::legacy_logical_slots_path(source),
195        f::legacy_audit_log_path(source),
196    ] {
197        match std::fs::symlink_metadata(path) {
198            Ok(metadata) => ensure(
199                metadata.is_file() && metadata.len() == 0,
200                "logical WAL, slot or audit data requires separate recovery verification",
201            )?,
202            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
203            Err(error) => return Err(error.into()),
204        }
205    }
206    let physical = guard.header.physical;
207    for (page_id, expected) in [
208        (physical.manifest_page, physical.manifest_checksum),
209        (
210            physical.collection_roots_page,
211            physical.collection_roots_checksum,
212        ),
213        (physical.registry_page, physical.registry_checksum),
214        (physical.recovery_page, physical.recovery_checksum),
215        (physical.catalog_page, physical.catalog_checksum),
216        (
217            physical.metadata_state_page,
218            physical.metadata_state_checksum,
219        ),
220        (
221            physical.vector_artifact_page,
222            physical.vector_artifact_checksum,
223        ),
224    ] {
225        if page_id == 0 {
226            continue;
227        }
228        let page = guard.raw_page(page_id, true)?;
229        ensure(
230            page.page_type()? == PageType::NativeMeta,
231            "invalid physical metadata page",
232        )?;
233        // The published checksum covers the encoded payload, not the zero
234        // padding to the page boundary. Its length is not stored separately.
235        // Accept only a checksum matching a prefix with exclusively zero
236        // bytes after it; the compactor also decodes each payload below.
237        let content = page.content();
238        let minimum = content
239            .iter()
240            .rposition(|byte| *byte != 0)
241            .map_or(0, |position| position + 1);
242        let mut checksum = crc32fast::Hasher::new();
243        checksum.update(&content[..minimum]);
244        let mut matches = u64::from(checksum.clone().finalize()) == expected;
245        for byte in &content[minimum..] {
246            checksum.update(std::slice::from_ref(byte));
247            matches |= u64::from(checksum.clone().finalize()) == expected;
248        }
249        ensure(
250            matches,
251            "physical metadata differs from its published checksum",
252        )?;
253    }
254    verify_vault(source, guard)?;
255    Ok(())
256}
257
258pub(super) fn verify_vault(source: &Path, guard: &Source) -> Result<()> {
259    let vault = guard.raw_page(2, false)?;
260    if !vault.as_bytes().iter().all(|byte| *byte == 0) {
261        ensure(vault.page_type()? == PageType::Vault, "invalid vault page")?;
262        if vault.content().iter().all(|byte| *byte == 0) {
263            vault.verify_checksum()?;
264            return Ok(());
265        }
266        let content = vault.content();
267        ensure(
268            &content[..4] == b"RDVT" && matches!(content[4], 2 | 3),
269            "unsupported vault header",
270        )?;
271        let payload = u32::from_le_bytes(content[21..25].try_into()?);
272        ensure(
273            payload <= 64 * 1024 * 1024,
274            "vault exceeds verification budget",
275        )?;
276        let pager = Pager::open(
277            source,
278            PagerConfig {
279                read_only: true,
280                create: false,
281                ..PagerConfig::default()
282            },
283        )?;
284        let vault =
285            crate::auth::vault::Vault::open(&pager).map_err(|_| "vault authentication failed")?;
286        ensure(
287            matches!(vault.load(&pager), Ok(Some(_))),
288            "vault authentication failed",
289        )?;
290    }
291    Ok(())
292}