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. Preserve the database and its recovery files; restore from a \
90                 verified backup",
91                path.display()
92            ),
93            Self::Io(err) => write!(f, "io error: {err}"),
94        }
95    }
96}
97
98impl std::error::Error for ZoneMigrationError {}
99
100impl From<std::io::Error> for ZoneMigrationError {
101    fn from(err: std::io::Error) -> Self {
102        Self::Io(err)
103    }
104}
105
106type Result<T> = std::result::Result<T, ZoneMigrationError>;
107
108/// The retained rollback point for `data_path`.
109pub fn backup_path_for(data_path: &Path) -> PathBuf {
110    let mut path = data_path.as_os_str().to_os_string();
111    path.push(".");
112    path.push(BACKUP_SUFFIX);
113    PathBuf::from(path)
114}
115
116/// Convert a legacy sidecar-backed store at `data_path` into the zoned form.
117///
118/// The store must be closed. On success the data file carries a superblock
119/// ping-pong pair, the retired sidecars are gone, and the pre-migration file is
120/// retained at [`ZoneMigrationReport::backup_path`]. On any failure before the
121/// sidecars are unlinked the source store is left exactly as it was.
122pub fn migrate_to_zoned(data_path: &Path) -> Result<ZoneMigrationReport> {
123    if !data_path.exists() {
124        return Err(ZoneMigrationError::MissingStore(data_path.to_path_buf()));
125    }
126    let sidecars = present_sidecars(data_path);
127    if sidecars.is_empty() {
128        return Err(ZoneMigrationError::NotALegacyStore(data_path.to_path_buf()));
129    }
130    if has_valid_superblock_zone(data_path)? {
131        return Err(ZoneMigrationError::AlreadyZoned(data_path.to_path_buf()));
132    }
133
134    let backup_path = backup_path_for(data_path);
135    fs::copy(data_path, &backup_path)?;
136
137    let page_zero = read_page(data_path, 0)?;
138    // Page 0 is authoritative unless it is the torn one โ€” which is exactly the
139    // case the `rdb-hdr` shadow existed to cover.
140    let (header_image, header_recovered_from_shadow) =
141        if reddb_file::database_header_magic_matches(&page_zero) {
142            (page_zero, false)
143        } else {
144            let shadow = read_sidecar_page(&retired::pager_header_shadow_path_v0(data_path))?
145                .filter(|page| reddb_file::database_header_magic_matches(page))
146                .ok_or_else(|| ZoneMigrationError::HeaderUnrecoverable(data_path.to_path_buf()))?;
147            (shadow, true)
148        };
149
150    let manifest_recovered_from_shadow = restore_manifest_page_if_torn(data_path)?;
151
152    // Seed both superblock copies so the ping-pong invariant holds from the
153    // migrated store's very first update.
154    let mut slot = [0u8; SLOT_SIZE];
155    slot.copy_from_slice(&header_image[..SLOT_SIZE]);
156    let mut file = OpenOptions::new().read(true).write(true).open(data_path)?;
157    for (copy_index, generation) in [(0usize, 1u64), (1usize, 2u64)] {
158        reddb_file::seal_paged_superblock_slot(&mut slot, copy_index, generation)
159            .map_err(|err| std::io::Error::other(err.to_string()))?;
160        write_at(&mut file, superblock_offset(copy_index), &slot)?;
161    }
162    file.sync_all()?;
163    drop(file);
164
165    // The file is durable in its zoned form; only now is it safe to drop the
166    // sidecars. A crash before this point leaves a store the old engine reads.
167    for sidecar in &sidecars {
168        fs::remove_file(sidecar)?;
169    }
170
171    Ok(ZoneMigrationReport {
172        data_path: data_path.to_path_buf(),
173        backup_path,
174        removed_sidecars: sidecars,
175        header_recovered_from_shadow,
176        manifest_recovered_from_shadow,
177    })
178}
179
180/// Walk a migration back: rebuild page 0 as a plain checksummed header page and
181/// re-create the retired sidecars beside it.
182///
183/// This is a true inverse of [`migrate_to_zoned`], not a backup restore, so a
184/// store that was migrated and then written to still reverts to a coherent
185/// legacy store. The retained `.pre-migration` file, if one is still around, is
186/// dropped last: once the legacy shape is durable it has nothing left to roll
187/// back to.
188pub fn revert_to_sidecars(data_path: &Path) -> Result<ZoneMigrationReport> {
189    if !data_path.exists() {
190        return Err(ZoneMigrationError::MissingStore(data_path.to_path_buf()));
191    }
192
193    let image = newest_superblock_image(data_path)?
194        .ok_or_else(|| ZoneMigrationError::HeaderUnrecoverable(data_path.to_path_buf()))?;
195
196    // Strip the slot trailer and restore the whole-page checksum: this is
197    // byte-for-byte the page 0 the sidecar-era pager wrote.
198    let mut header_page = [0u8; PAGE_SIZE];
199    header_page[..SLOT_SIZE].copy_from_slice(&image);
200    header_page[SUPERBLOCK_TRAILER_OFFSET..SLOT_SIZE].fill(0);
201    reddb_file::clear_paged_page_checksum(&mut header_page);
202    let checksum = crate::storage::engine::crc32::crc32(&header_page);
203    reddb_file::set_paged_page_checksum(&mut header_page, checksum);
204
205    let manifest_page = read_page(data_path, 1)?;
206
207    let mut file = OpenOptions::new().read(true).write(true).open(data_path)?;
208    write_at(&mut file, 0, &header_page)?;
209    file.sync_all()?;
210    drop(file);
211
212    write_sidecar_page(
213        &retired::pager_header_shadow_path_v0(data_path),
214        &header_page,
215    )?;
216    write_sidecar_page(
217        &retired::pager_meta_shadow_path_v0(data_path),
218        &manifest_page,
219    )?;
220
221    let backup_path = backup_path_for(data_path);
222    if backup_path.exists() {
223        fs::remove_file(&backup_path)?;
224    }
225
226    Ok(ZoneMigrationReport {
227        data_path: data_path.to_path_buf(),
228        backup_path,
229        removed_sidecars: Vec::new(),
230        header_recovered_from_shadow: false,
231        manifest_recovered_from_shadow: false,
232    })
233}
234
235/// The newest valid superblock slot image, or `None` when the zone is absent
236/// or unrecoverable.
237fn newest_superblock_image(data_path: &Path) -> Result<Option<[u8; SLOT_SIZE]>> {
238    let zone = read_superblock_zone(data_path)?;
239    let Some(selection) = reddb_file::select_paged_superblock(&zone) else {
240        return Ok(None);
241    };
242    let start = selection.copy_index * SLOT_SIZE;
243    let mut image = [0u8; SLOT_SIZE];
244    image.copy_from_slice(&zone[start..start + SLOT_SIZE]);
245    Ok(Some(image))
246}
247
248fn read_superblock_zone(data_path: &Path) -> Result<[u8; ZONE_SIZE]> {
249    let mut zone = [0u8; ZONE_SIZE];
250    let mut file = File::open(data_path)?;
251    let len = file.metadata()?.len().min(ZONE_SIZE as u64) as usize;
252    if len > 0 {
253        file.read_exact(&mut zone[..len])?;
254    }
255    Ok(zone)
256}
257
258fn present_sidecars(data_path: &Path) -> Vec<PathBuf> {
259    let mut seen: Vec<PathBuf> = Vec::new();
260    for candidate in retired::phase1_sidecar_paths(data_path) {
261        if candidate.exists() && !seen.contains(&candidate) {
262            seen.push(candidate);
263        }
264    }
265    seen
266}
267
268fn has_valid_superblock_zone(data_path: &Path) -> Result<bool> {
269    let zone = read_superblock_zone(data_path)?;
270    Ok(reddb_file::select_paged_superblock(&zone).is_some())
271}
272
273/// Overwrite page 1 from the `rdb-meta` shadow when the in-file page fails its
274/// checksum. Returns whether the shadow was used.
275fn restore_manifest_page_if_torn(data_path: &Path) -> Result<bool> {
276    let page_one = read_page(data_path, 1)?;
277    if page_checksum_valid(&page_one) {
278        return Ok(false);
279    }
280    let Some(shadow) = read_sidecar_page(&retired::pager_meta_shadow_path_v0(data_path))? else {
281        return Ok(false);
282    };
283    if !page_checksum_valid(&shadow) {
284        return Ok(false);
285    }
286    let mut file = OpenOptions::new().read(true).write(true).open(data_path)?;
287    write_at(&mut file, PAGE_SIZE as u64, &shadow)?;
288    file.sync_all()?;
289    Ok(true)
290}
291
292/// Verify a page's own CRC the way the pager's `Page::verify_checksum` does:
293/// CRC over the page with the checksum field zeroed.
294fn page_checksum_valid(page: &[u8; PAGE_SIZE]) -> bool {
295    let stored = reddb_file::paged_page_checksum(page);
296    let mut scratch = *page;
297    reddb_file::clear_paged_page_checksum(&mut scratch);
298    stored == crate::storage::engine::crc32::crc32(&scratch)
299}
300
301fn superblock_offset(copy_index: usize) -> u64 {
302    reddb_file::paged_superblock_slot_offset(copy_index)
303}
304
305fn read_page(path: &Path, page_id: u64) -> Result<[u8; PAGE_SIZE]> {
306    let mut file = File::open(path)?;
307    let mut page = [0u8; PAGE_SIZE];
308    file.seek(SeekFrom::Start(page_id * PAGE_SIZE as u64))?;
309    file.read_exact(&mut page)?;
310    Ok(page)
311}
312
313fn read_sidecar_page(path: &Path) -> Result<Option<[u8; PAGE_SIZE]>> {
314    if !path.exists() {
315        return Ok(None);
316    }
317    let mut file = File::open(path)?;
318    let mut page = [0u8; PAGE_SIZE];
319    match file.read_exact(&mut page) {
320        Ok(()) => Ok(Some(page)),
321        // A shadow shorter than a page is itself torn: it recovers nothing.
322        Err(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => Ok(None),
323        Err(err) => Err(err.into()),
324    }
325}
326
327fn write_sidecar_page(path: &Path, page: &[u8; PAGE_SIZE]) -> Result<()> {
328    let mut file = File::create(path)?;
329    file.write_all(page)?;
330    file.sync_all()?;
331    Ok(())
332}
333
334fn write_at(file: &mut File, offset: u64, bytes: &[u8]) -> Result<()> {
335    file.seek(SeekFrom::Start(offset))?;
336    file.write_all(bytes)?;
337    Ok(())
338}