Skip to main content

reddb_server/
pager_zone_migration.rs

1//! Offline, reversible migration between the sidecar-backed pager layout and
2//! the zoned `.rdb` (ADR 0038 §4 phase 1).
3//!
4//! A legacy store keeps its page-0 database header in a `rdb-hdr` sidecar and
5//! its manifest page in a `rdb-meta` sidecar, each a whole-page shadow written
6//! before the in-file copy. The zoned form retires both: page 0 becomes a
7//! superblock ping-pong pair, and page 1 plus its overflow chain is the
8//! internal manifest, rooted by the superblock.
9//!
10//! Per the house no-backcompat posture the engine never reads the old form —
11//! [`crate::storage::engine::pager::Pager::open`] refuses it and names this
12//! module. Conversion is an explicit, offline step, modelled on the reversible
13//! document-body migration ([`crate::document_migration`]):
14//!
15//! 1. Copy the data file to a retained `<data>.pre-migration` rollback point.
16//! 2. Rebuild page 0's two superblock slots from the authoritative header —
17//!    preferring the in-file page 0 and falling back to the `rdb-hdr` shadow
18//!    when page 0 is the torn one (that is what the shadow was for).
19//! 3. Restore page 1 from the `rdb-meta` shadow if the in-file copy fails its
20//!    checksum, then fsync.
21//! 4. Only once the file is durable, unlink the sidecars.
22//!
23//! Every step before the unlink leaves the source readable by the *old* engine,
24//! and [`revert_to_sidecars`] walks it back. Nothing here touches the live
25//! filename contract: the retired names come from `reddb_file::layout::retired`.
26
27use std::fs::{self, File, OpenOptions};
28use std::io::{Read, Seek, SeekFrom, Write};
29use std::path::{Path, PathBuf};
30
31use reddb_file::layout::retired;
32
33const PAGE_SIZE: usize = reddb_file::PAGED_PAGE_SIZE;
34const SLOT_SIZE: usize = reddb_file::PAGED_SUPERBLOCK_SLOT_SIZE;
35const ZONE_SIZE: usize = reddb_file::PAGED_SUPERBLOCK_ZONE_SIZE;
36const SUPERBLOCK_TRAILER_OFFSET: usize = reddb_file::PAGED_SUPERBLOCK_TRAILER_OFFSET;
37
38/// Suffix for the retained pre-migration data file (the rollback point).
39const BACKUP_SUFFIX: &str = "pre-migration";
40
41/// What a migration did, so the caller can log or assert it.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct ZoneMigrationReport {
44    /// The data file that now carries the zoned layout.
45    pub data_path: PathBuf,
46    /// Retained copy of the pre-migration data file.
47    pub backup_path: PathBuf,
48    /// Retired sidecars removed by the migration, in the order they were found.
49    pub removed_sidecars: Vec<PathBuf>,
50    /// `true` when page 0 was torn and the `rdb-hdr` shadow supplied the header.
51    pub header_recovered_from_shadow: bool,
52    /// `true` when page 1 was torn and the `rdb-meta` shadow supplied the
53    /// manifest page.
54    pub manifest_recovered_from_shadow: bool,
55}
56
57#[derive(Debug)]
58pub enum ZoneMigrationError {
59    /// The data file does not exist.
60    MissingStore(PathBuf),
61    /// No retired sidecar is present, so there is nothing to migrate.
62    NotALegacyStore(PathBuf),
63    /// The store is already zoned (a valid superblock zone is present).
64    AlreadyZoned(PathBuf),
65    /// No usable database header survives in page 0 or the `rdb-hdr` shadow.
66    HeaderUnrecoverable(PathBuf),
67    Io(std::io::Error),
68}
69
70impl std::fmt::Display for ZoneMigrationError {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        match self {
73            Self::MissingStore(path) => write!(f, "no store at {}", path.display()),
74            Self::NotALegacyStore(path) => write!(
75                f,
76                "{} carries no retired rdb-hdr/rdb-meta sidecar, so there is nothing to \
77                 migrate; a zoned store opens directly",
78                path.display()
79            ),
80            Self::AlreadyZoned(path) => write!(
81                f,
82                "{} already has a valid superblock zone; migrating again would discard it",
83                path.display()
84            ),
85            Self::HeaderUnrecoverable(path) => write!(
86                f,
87                "neither page 0 of {} nor its rdb-hdr shadow holds a readable database \
88                 header, so no superblock can be seeded from this store. This is a damaged \
89                 store, not a legacy one: reach for red salvage (ADR 0074 §4)",
90                path.display()
91            ),
92            Self::Io(err) => write!(f, "io error: {err}"),
93        }
94    }
95}
96
97impl std::error::Error for ZoneMigrationError {}
98
99impl From<std::io::Error> for ZoneMigrationError {
100    fn from(err: std::io::Error) -> Self {
101        Self::Io(err)
102    }
103}
104
105type Result<T> = std::result::Result<T, ZoneMigrationError>;
106
107/// The retained rollback point for `data_path`.
108pub fn backup_path_for(data_path: &Path) -> PathBuf {
109    let mut path = data_path.as_os_str().to_os_string();
110    path.push(".");
111    path.push(BACKUP_SUFFIX);
112    PathBuf::from(path)
113}
114
115/// Convert a legacy sidecar-backed store at `data_path` into the zoned form.
116///
117/// The store must be closed. On success the data file carries a superblock
118/// ping-pong pair, the retired sidecars are gone, and the pre-migration file is
119/// retained at [`ZoneMigrationReport::backup_path`]. On any failure before the
120/// sidecars are unlinked the source store is left exactly as it was.
121pub fn migrate_to_zoned(data_path: &Path) -> Result<ZoneMigrationReport> {
122    if !data_path.exists() {
123        return Err(ZoneMigrationError::MissingStore(data_path.to_path_buf()));
124    }
125    let sidecars = present_sidecars(data_path);
126    if sidecars.is_empty() {
127        return Err(ZoneMigrationError::NotALegacyStore(data_path.to_path_buf()));
128    }
129    if has_valid_superblock_zone(data_path)? {
130        return Err(ZoneMigrationError::AlreadyZoned(data_path.to_path_buf()));
131    }
132
133    let backup_path = backup_path_for(data_path);
134    fs::copy(data_path, &backup_path)?;
135
136    let page_zero = read_page(data_path, 0)?;
137    // Page 0 is authoritative unless it is the torn one — which is exactly the
138    // case the `rdb-hdr` shadow existed to cover.
139    let (header_image, header_recovered_from_shadow) =
140        if reddb_file::database_header_magic_matches(&page_zero) {
141            (page_zero, false)
142        } else {
143            let shadow = read_sidecar_page(&retired::pager_header_shadow_path_v0(data_path))?
144                .filter(|page| reddb_file::database_header_magic_matches(page))
145                .ok_or_else(|| ZoneMigrationError::HeaderUnrecoverable(data_path.to_path_buf()))?;
146            (shadow, true)
147        };
148
149    let manifest_recovered_from_shadow = restore_manifest_page_if_torn(data_path)?;
150
151    // Seed both superblock copies so the ping-pong invariant holds from the
152    // migrated store's very first update.
153    let mut slot = [0u8; SLOT_SIZE];
154    slot.copy_from_slice(&header_image[..SLOT_SIZE]);
155    let mut file = OpenOptions::new().read(true).write(true).open(data_path)?;
156    for (copy_index, generation) in [(0usize, 1u64), (1usize, 2u64)] {
157        reddb_file::seal_paged_superblock_slot(&mut slot, copy_index, generation)
158            .map_err(|err| std::io::Error::other(err.to_string()))?;
159        write_at(&mut file, superblock_offset(copy_index), &slot)?;
160    }
161    file.sync_all()?;
162    drop(file);
163
164    // The file is durable in its zoned form; only now is it safe to drop the
165    // sidecars. A crash before this point leaves a store the old engine reads.
166    for sidecar in &sidecars {
167        fs::remove_file(sidecar)?;
168    }
169
170    Ok(ZoneMigrationReport {
171        data_path: data_path.to_path_buf(),
172        backup_path,
173        removed_sidecars: sidecars,
174        header_recovered_from_shadow,
175        manifest_recovered_from_shadow,
176    })
177}
178
179/// Walk a migration back: rebuild page 0 as a plain checksummed header page and
180/// re-create the retired sidecars beside it.
181///
182/// This is a true inverse of [`migrate_to_zoned`], not a backup restore, so a
183/// store that was migrated and then written to still reverts to a coherent
184/// legacy store. The retained `.pre-migration` file, if one is still around, is
185/// dropped last: once the legacy shape is durable it has nothing left to roll
186/// back to.
187pub fn revert_to_sidecars(data_path: &Path) -> Result<ZoneMigrationReport> {
188    if !data_path.exists() {
189        return Err(ZoneMigrationError::MissingStore(data_path.to_path_buf()));
190    }
191
192    let image = newest_superblock_image(data_path)?
193        .ok_or_else(|| ZoneMigrationError::HeaderUnrecoverable(data_path.to_path_buf()))?;
194
195    // Strip the slot trailer and restore the whole-page checksum: this is
196    // byte-for-byte the page 0 the sidecar-era pager wrote.
197    let mut header_page = [0u8; PAGE_SIZE];
198    header_page[..SLOT_SIZE].copy_from_slice(&image);
199    header_page[SUPERBLOCK_TRAILER_OFFSET..SLOT_SIZE].fill(0);
200    reddb_file::clear_paged_page_checksum(&mut header_page);
201    let checksum = crate::storage::engine::crc32::crc32(&header_page);
202    reddb_file::set_paged_page_checksum(&mut header_page, checksum);
203
204    let manifest_page = read_page(data_path, 1)?;
205
206    let mut file = OpenOptions::new().read(true).write(true).open(data_path)?;
207    write_at(&mut file, 0, &header_page)?;
208    file.sync_all()?;
209    drop(file);
210
211    write_sidecar_page(
212        &retired::pager_header_shadow_path_v0(data_path),
213        &header_page,
214    )?;
215    write_sidecar_page(
216        &retired::pager_meta_shadow_path_v0(data_path),
217        &manifest_page,
218    )?;
219
220    let backup_path = backup_path_for(data_path);
221    if backup_path.exists() {
222        fs::remove_file(&backup_path)?;
223    }
224
225    Ok(ZoneMigrationReport {
226        data_path: data_path.to_path_buf(),
227        backup_path,
228        removed_sidecars: Vec::new(),
229        header_recovered_from_shadow: false,
230        manifest_recovered_from_shadow: false,
231    })
232}
233
234/// The newest valid superblock slot image, or `None` when the zone is absent
235/// or unrecoverable.
236fn newest_superblock_image(data_path: &Path) -> Result<Option<[u8; SLOT_SIZE]>> {
237    let zone = read_superblock_zone(data_path)?;
238    let Some(selection) = reddb_file::select_paged_superblock(&zone) else {
239        return Ok(None);
240    };
241    let start = selection.copy_index * SLOT_SIZE;
242    let mut image = [0u8; SLOT_SIZE];
243    image.copy_from_slice(&zone[start..start + SLOT_SIZE]);
244    Ok(Some(image))
245}
246
247fn read_superblock_zone(data_path: &Path) -> Result<[u8; ZONE_SIZE]> {
248    let mut zone = [0u8; ZONE_SIZE];
249    let mut file = File::open(data_path)?;
250    let len = file.metadata()?.len().min(ZONE_SIZE as u64) as usize;
251    if len > 0 {
252        file.read_exact(&mut zone[..len])?;
253    }
254    Ok(zone)
255}
256
257fn present_sidecars(data_path: &Path) -> Vec<PathBuf> {
258    let mut seen: Vec<PathBuf> = Vec::new();
259    for candidate in retired::phase1_sidecar_paths(data_path) {
260        if candidate.exists() && !seen.contains(&candidate) {
261            seen.push(candidate);
262        }
263    }
264    seen
265}
266
267fn has_valid_superblock_zone(data_path: &Path) -> Result<bool> {
268    let zone = read_superblock_zone(data_path)?;
269    Ok(reddb_file::select_paged_superblock(&zone).is_some())
270}
271
272/// Overwrite page 1 from the `rdb-meta` shadow when the in-file page fails its
273/// checksum. Returns whether the shadow was used.
274fn restore_manifest_page_if_torn(data_path: &Path) -> Result<bool> {
275    let page_one = read_page(data_path, 1)?;
276    if page_checksum_valid(&page_one) {
277        return Ok(false);
278    }
279    let Some(shadow) = read_sidecar_page(&retired::pager_meta_shadow_path_v0(data_path))? else {
280        return Ok(false);
281    };
282    if !page_checksum_valid(&shadow) {
283        return Ok(false);
284    }
285    let mut file = OpenOptions::new().read(true).write(true).open(data_path)?;
286    write_at(&mut file, PAGE_SIZE as u64, &shadow)?;
287    file.sync_all()?;
288    Ok(true)
289}
290
291/// Verify a page's own CRC the way the pager's `Page::verify_checksum` does:
292/// CRC over the page with the checksum field zeroed.
293fn page_checksum_valid(page: &[u8; PAGE_SIZE]) -> bool {
294    let stored = reddb_file::paged_page_checksum(page);
295    let mut scratch = *page;
296    reddb_file::clear_paged_page_checksum(&mut scratch);
297    stored == crate::storage::engine::crc32::crc32(&scratch)
298}
299
300fn superblock_offset(copy_index: usize) -> u64 {
301    reddb_file::paged_superblock_slot_offset(copy_index)
302}
303
304fn read_page(path: &Path, page_id: u64) -> Result<[u8; PAGE_SIZE]> {
305    let mut file = File::open(path)?;
306    let mut page = [0u8; PAGE_SIZE];
307    file.seek(SeekFrom::Start(page_id * PAGE_SIZE as u64))?;
308    file.read_exact(&mut page)?;
309    Ok(page)
310}
311
312fn read_sidecar_page(path: &Path) -> Result<Option<[u8; PAGE_SIZE]>> {
313    if !path.exists() {
314        return Ok(None);
315    }
316    let mut file = File::open(path)?;
317    let mut page = [0u8; PAGE_SIZE];
318    match file.read_exact(&mut page) {
319        Ok(()) => Ok(Some(page)),
320        // A shadow shorter than a page is itself torn: it recovers nothing.
321        Err(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => Ok(None),
322        Err(err) => Err(err.into()),
323    }
324}
325
326fn write_sidecar_page(path: &Path, page: &[u8; PAGE_SIZE]) -> Result<()> {
327    let mut file = File::create(path)?;
328    file.write_all(page)?;
329    file.sync_all()?;
330    Ok(())
331}
332
333fn write_at(file: &mut File, offset: u64, bytes: &[u8]) -> Result<()> {
334    file.seek(SeekFrom::Start(offset))?;
335    file.write_all(bytes)?;
336    Ok(())
337}