Diffinery

homeflare/celldpublic

celld/crates/ltx/src/paged.rs
546 lines · 21.3 KBRaw History
1//! paged.rs — read-on-demand paging from replica objects.
2//!
3//! The read path of paged restore, ported from Litestream's
4//! VFS. A cold cell serves a page by fetching only that page's frame from the
5//! bucket instead of downloading its whole restore chain: build a page map from
6//! each planned object's trailing page index, then range-read and decode one
7//! frame per demanded page.
8//!
9//! An LTX file ends with `[page index][8-byte index length][16-byte trailer]`,
10//! and every object celld writes carries the index (`codec::Encoder::close`),
11//! so the map reads the index tail-first and never downloads the frames it does
12//! not need.
13
14use crate::client::ReplicaClient;
15use crate::codec::{decode_page_frame_of, decode_page_index};
16use crate::error::{Error, Result};
17use crate::ltx::{FileInfo, Header, HEADER_SIZE, TRAILER_SIZE};
18use crate::ltx_file_path;
19use crate::TXID;
20use futures_util::StreamExt;
21use std::collections::BTreeSet;
22use std::collections::HashMap;
23use std::io::Read;
24use std::io::Seek;
25use std::sync::Mutex;
26
27/// Bytes fetched from the object tail first, sized to hold the whole page index
28/// of an ordinary object in one read; a larger index needs a second read. A
29/// fold of thirty 1 MB rows indexes ~8,000 pages in ~70 KiB, so 32 KiB cost
30/// every object of the 5 GB whale a second round trip: its map took 12 s on
31/// the node. Bytes are cheap on a ranged read; rounds are the cost.
32const TAIL_FETCH_BYTES: u64 = 256 * 1024;
33
34/// Width of the big-endian page-index-length field, between the index and the
35/// trailer.
36const INDEX_LEN_FIELD: u64 = 8;
37
38/// The most frame bytes one fault fetches. A fault brings its page's whole
39/// run — the consecutive pages stored as adjacent frames of the same object,
40/// which is how a snapshot or compaction lays a b-tree's leaves and a blob's
41/// overflow chain out — so a sequential read costs one round-trip per run
42/// instead of one per 4KiB page. 64 pages caps the waste on a scattered
43/// point lookup, whose interior pages sit in runs it will not read.
44pub const READAHEAD_BYTES: u64 = 1024 * 1024;
45
46/// Object page indexes fetched at once while building a map: a whale's plan
47/// of ~200 objects in a few rounds.
48const INDEX_FETCH_CONCURRENCY: usize = 32;
49
50/// Fetches and decodes one object's page index with ranged reads, without
51/// downloading the object. It reads the tail, takes the index length from the
52/// 8-byte field before the trailer, and decodes the index — a second exact
53/// read only when the index is larger than the tail fetch.
54///
55/// Returns the `(pgno, frame_offset, frame_size)` entries: each page's whole
56/// frame lives at `frame_offset` in the file, `frame_size` bytes long.
57pub async fn fetch_page_index<C: ReplicaClient>(
58 client: &C,
59 info: &FileInfo,
60) -> Result<Vec<(u32, u64, u64)>> {
61 let size = u64::try_from(info.size).map_err(|_| Error::LTXCorrupted)?;
62 let footer = INDEX_LEN_FIELD + TRAILER_SIZE as u64;
63 if size < footer {
64 return Err(Error::LTXCorrupted);
65 }
66
67 let tail_len = TAIL_FETCH_BYTES.min(size);
68 let tail_start = size - tail_len;
69 let tail = client
70 .read_range(
71 info.level,
72 info.min_txid,
73 info.max_txid,
74 tail_start,
75 tail_len,
76 )
77 .await?;
78 if (tail.len() as u64) < footer {
79 return Err(Error::LTXCorrupted);
80 }
81
82 // The index-length field sits just before the trailer; the index precedes
83 // it. Compute the index's file range from the object size, so a partial
84 // tail read still locates it.
85 let field_at = tail.len() - TRAILER_SIZE - INDEX_LEN_FIELD as usize;
86 let index_len = u64::from_be_bytes(
87 tail[field_at..field_at + INDEX_LEN_FIELD as usize]
88 .try_into()
89 .map_err(|_| Error::LTXCorrupted)?,
90 );
91 let index_end = size - footer;
92 let index_start = index_end
93 .checked_sub(index_len)
94 .ok_or(Error::LTXCorrupted)?;
95
96 if index_start >= tail_start {
97 let lo = (index_start - tail_start) as usize;
98 let hi = (index_end - tail_start) as usize;
99 decode_page_index(&tail[lo..hi])
100 } else {
101 let index_bytes = client
102 .read_range(
103 info.level,
104 info.min_txid,
105 info.max_txid,
106 index_start,
107 index_len,
108 )
109 .await?;
110 decode_page_index(&index_bytes)
111 }
112}
113
114/// Where one page's frame lives: the object that holds it and the byte range of
115/// its frame within that object.
116#[derive(Debug, Clone)]
117pub struct PageLocator {
118 pub info: FileInfo,
119 pub offset: u64,
120 pub size: u64,
121}
122
123/// An immutable per-activation view of a restore cut: which object serves each
124/// page, plus the page size and the database's page count at the cut. Built
125/// once from a plan and never updated in place, so a faulted page always comes
126/// from the pinned cut even as newer objects land.
127#[derive(Debug)]
128pub struct PageMap {
129 pub page_size: u32,
130 pub commit: u32,
131 pub pages: HashMap<u32, PageLocator>,
132}
133
134/// Builds a page map over a restore `plan` (as [`crate::replica::calc_restore_plan`]
135/// returns it, oldest object first) without downloading the objects. It fetches
136/// each object's page index and inserts its pages, so a later object in the
137/// chain overrides an earlier one — last-writer-wins, the newest version of
138/// each page. The page size and commit come from the newest object's header.
139pub async fn build_page_map<C: ReplicaClient>(client: &C, plan: &[FileInfo]) -> Result<PageMap> {
140 let newest = plan.last().ok_or(Error::TxNotAvailable)?;
141 let mut pages: HashMap<u32, PageLocator> = HashMap::new();
142 // The indexes are independent reads, so fetch them concurrently; a whale's
143 // plan of two dozen objects otherwise costs two round-trips each, in
144 // series, on the activation path. `buffered` keeps plan order for the
145 // last-writer-wins insertion below.
146 // Built as a Vec first: a closure held inside this future's state would
147 // make it higher-ranked over the plan's borrow and unspawnable.
148 let header_bytes = client
149 .read_range(
150 newest.level,
151 newest.min_txid,
152 newest.max_txid,
153 0,
154 HEADER_SIZE as u64,
155 )
156 .await?;
157 let header = Header::parse(&header_bytes)?;
158 let fetches: Vec<_> = plan
159 .iter()
160 .map(|info| fetch_page_index(client, info))
161 .collect();
162 let mut indexes = futures_util::stream::iter(fetches).buffered(INDEX_FETCH_CONCURRENCY);
163 let mut planned = plan.iter();
164 while let Some(index) = indexes.next().await {
165 let info = planned.next().expect("one index per planned object");
166 let index = index?;
167 // An older object can hold pages past the newest commit (the
168 // database shrank since); they are not part of the cut.
169 for (pgno, offset, size) in index.into_iter().filter(|(p, _, _)| *p <= header.commit) {
170 pages.insert(
171 pgno,
172 PageLocator {
173 info: info.clone(),
174 offset,
175 size,
176 },
177 );
178 }
179 }
180 Ok(PageMap {
181 page_size: header.page_size,
182 commit: header.commit,
183 pages,
184 })
185}
186
187impl PageMap {
188 /// Serves one page: range-reads its frame from the object the map points to
189 /// and decodes it. `None` when the cut has no such page (a page above the
190 /// commit, or one never written).
191 pub async fn read_page<C: ReplicaClient>(
192 &self,
193 client: &C,
194 pgno: u32,
195 ) -> Result<Option<Vec<u8>>> {
196 let Some(loc) = self.pages.get(&pgno) else {
197 return Ok(None);
198 };
199 let frame = client
200 .read_range(
201 loc.info.level,
202 loc.info.min_txid,
203 loc.info.max_txid,
204 loc.offset,
205 loc.size,
206 )
207 .await?;
208 Ok(Some(decode_page_frame_of(
209 &frame,
210 self.page_size as usize,
211 pgno,
212 )?))
213 }
214
215 /// The VFS fault path, on whatever thread SQLite called `xRead` from:
216 /// `pgno`'s page plus its run (see [`READAHEAD_BYTES`]), in one ranged
217 /// read of the object that holds them. Empty when the cut has no such
218 /// page; otherwise the first entry is `pgno`.
219 pub fn read_run_sync(
220 &self,
221 reader: &dyn RangeReader,
222 pgno: u32,
223 max_bytes: u64,
224 ) -> Result<Vec<(u32, Vec<u8>)>> {
225 let Some(first) = self.pages.get(&pgno) else {
226 return Ok(Vec::new());
227 };
228 // The cap is in decoded page bytes: frames are LZ4-compressed, and a
229 // cap on frame bytes let one fault of a compressible file bring the
230 // whole database (a 13MB fixture in a single 1MiB "run").
231 let max_pages = (max_bytes / u64::from(self.page_size)).max(1) as u32;
232 let mut end = first.offset + first.size;
233 let mut last = pgno;
234 while let Some(next) = self.pages.get(&(last + 1)) {
235 let adjacent = next.info == first.info && next.offset == end;
236 if !adjacent || last + 1 - pgno >= max_pages {
237 break;
238 }
239 end += next.size;
240 last += 1;
241 }
242 let bytes = reader.read_range(&first.info, first.offset, end - first.offset)?;
243 let mut run = Vec::with_capacity((last - pgno + 1) as usize);
244 let mut at = 0;
245 if (bytes.len() as u64) < end - first.offset {
246 return Err(Error::LTXCorrupted);
247 }
248 for pgno_ in pgno..=last {
249 let size = self.pages[&pgno_].size as usize;
250 let page = decode_page_frame_of(&bytes[at..at + size], self.page_size as usize, pgno_)?;
251 run.push((pgno_, page));
252 at += size;
253 }
254 Ok(run)
255 }
256}
257
258/// A blocking ranged read of one replica object: the fault path's I/O.
259///
260/// SQLite's `xRead` is synchronous and runs on whichever thread entered the
261/// connection — a blocking thread for the managed Db, but a tokio task's
262/// thread for the actor's own queries, since isolates are entered from tasks.
263/// Every bridge from that thread into the async client failed in one context
264/// (`block_on` on a worker, `block_in_place` on a current-thread runtime, a
265/// same-runtime spawn stuck in the worker's LIFO slot). So the fault path does
266/// its own I/O on the calling thread with a plain socket and never touches a
267/// runtime, which is correct from any thread by construction.
268pub trait RangeReader: Send + Sync {
269 /// `len` bytes of `info`'s object starting at `offset`.
270 fn read_range(&self, info: &FileInfo, offset: u64, len: u64) -> Result<Vec<u8>>;
271}
272
273/// A [`RangeReader`] over the file replica layout (`ltx_file_path`).
274pub struct FileRangeReader {
275 root: String,
276}
277
278impl FileRangeReader {
279 pub fn new(root: impl Into<String>) -> Self {
280 Self { root: root.into() }
281 }
282}
283
284// The file replica is a development and test backend, not node storage:
285// it reads the same directory the file client writes with tokio::fs, outside
286// the injected node filesystem the lint guards.
287#[allow(clippy::disallowed_methods)]
288impl RangeReader for FileRangeReader {
289 fn read_range(&self, info: &FileInfo, offset: u64, len: u64) -> Result<Vec<u8>> {
290 let path = ltx_file_path(&self.root, info.level as u32, info.min_txid, info.max_txid);
291 let mut file = std::fs::File::open(path)?;
292 file.seek(std::io::SeekFrom::Start(offset))?;
293 let mut out = vec![0; len as usize];
294 file.read_exact(&mut out)?;
295 Ok(out)
296 }
297}
298
299/// Children a fault should bring along, read off the faulted page's b-tree
300/// structure. Round-trips are the whole cost of a fault (a 4KiB and a 1MiB
301/// range cost about the same), and SQLite asks for pages one at a time, so
302/// the only way below one round-trip per page is to read the structure: an
303/// interior page names every child. Fetching the children concurrently makes
304/// a scan cost one round per tree level instead of one per leaf. A misparse
305/// can only waste bytes: every served page still comes from the map.
306///
307/// A leaf's overflow chains are deliberately not here: a chain is stored as
308/// a run, so the sequential walk SQLite does gets it in one read after the
309/// first overflow fault, while fetching every cell's chain at the leaf fault
310/// pulls the neighbours' megabytes for a single-row read.
311#[derive(Debug, Default, PartialEq, Eq)]
312pub struct Prefetch {
313 /// Child pages of an interior page, in cell order.
314 pub children: Vec<u32>,
315}
316
317/// Children fetched ahead of a fault on a child page, along the tree in
318/// page order: a scan then costs one round per window of leaves, and a
319/// point read pays for one window at most.
320const SCAN_AHEAD: usize = 64;
321
322/// Concurrent range reads while fetching ahead.
323const PREFETCH_WORKERS: usize = 64;
324
325/// Parses a decoded b-tree page for what to prefetch; page 1 carries the
326/// 100-byte file header. Anything malformed yields an empty plan.
327pub fn prefetch_plan(pgno: u32, page: &[u8]) -> Prefetch {
328 let mut plan = Prefetch::default();
329 let base = if pgno == 1 { 100 } else { 0 };
330 let Some(head) = page.get(base..base + 12) else {
331 return plan;
332 };
333 // 0x05 interior table, 0x02 interior index; leaves have no children.
334 if head[0] != 0x05 && head[0] != 0x02 {
335 return plan;
336 }
337 let cells = u16::from_be_bytes([head[3], head[4]]) as usize;
338 let ptrs = base + 12;
339 for i in 0..cells {
340 let Some(at) = page.get(ptrs + 2 * i..ptrs + 2 * i + 2) else {
341 break;
342 };
343 let at = u16::from_be_bytes([at[0], at[1]]) as usize;
344 let Some(child) = page.get(at..at + 4) else {
345 break;
346 };
347 plan.children
348 .push(u32::from_be_bytes([child[0], child[1], child[2], child[3]]));
349 }
350 plan.children
351 .push(u32::from_be_bytes([head[8], head[9], head[10], head[11]]));
352 plan
353}
354
355/// A synchronous page reader over a [`PageMap`] for the paged SQLite VFS:
356/// the pinned cut's map plus a blocking [`RangeReader`] for its objects.
357///
358/// celld's VFS faults a missing page into a local sparse main-db file, so
359/// SQLite then runs entirely normally over that file (WAL, page-1 writes,
360/// checkpoint) and the local file is the cache. This source therefore holds no
361/// cache and does not rewrite page 1: it just serves the pinned cut's bytes for
362/// a page the local file does not have yet.
363pub struct PageSource {
364 map: PageMap,
365 reader: Box<dyn RangeReader>,
366 /// B-tree child pages named by an interior page this source has decoded
367 /// and not yet delivered, and the last one that faulted: a fault on one
368 /// fetches it alone, and a fault that continues along the tree looks
369 /// ahead (see [`PageSource::read_run_blocking`]).
370 scan: Mutex<Scan>,
371 /// Faults served: every `read_run_blocking`, foreground or hydration.
372 faults: std::sync::atomic::AtomicU64,
373}
374
375#[derive(Default)]
376struct Scan {
377 children: BTreeSet<u32>,
378 last: Option<u32>,
379}
380
381impl PageSource {
382 pub fn new(map: PageMap, reader: Box<dyn RangeReader>) -> Self {
383 Self {
384 map,
385 reader,
386 scan: Mutex::new(Scan::default()),
387 faults: std::sync::atomic::AtomicU64::new(0),
388 }
389 }
390
391 /// Faults served so far. A hydrated cell's reads leave it unchanged.
392 pub fn faults(&self) -> u64 {
393 self.faults.load(std::sync::atomic::Ordering::Relaxed)
394 }
395
396 /// The database page size at the pinned cut.
397 pub fn page_size(&self) -> u32 {
398 self.map.page_size
399 }
400
401 /// The database's page count at the pinned cut. The VFS sizes the local file
402 /// to `page_size * commit`.
403 pub fn commit(&self) -> u32 {
404 self.map.commit
405 }
406
407 /// Reads `pgno`'s run on the calling thread ([`PageMap::read_run_sync`]),
408 /// then what the faulted page's structure says comes next
409 /// ([`prefetch_plan`]), concurrently: every page returned is hydrated by
410 /// the VFS, so a scan or a big-row read pays one round-trip per level.
411 pub fn read_run_blocking(&self, pgno: u32) -> Result<Vec<(u32, Vec<u8>)>> {
412 self.faults
413 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
414 // A page an interior page named is a b-tree child. Its run is its
415 // neighbours in page order — for a leaf of a big-row table, the rows'
416 // overflow chains, megabytes a scan never reads (the whale's
417 // count(*) faulted 700 MB). Fetch it alone. When the fault continues
418 // along the tree (the last child fault was the nearest one below),
419 // it is a scan: bring the next children with it, a window at a time.
420 // A point read walks one path, so it never looks ahead: its cost
421 // stays one request per level.
422 let ahead = {
423 let mut scan = self.scan.lock().unwrap();
424 scan.children.remove(&pgno).then(|| {
425 let sequential = scan.last.is_some_and(|last| {
426 last < pgno && scan.children.range(last + 1..pgno).next().is_none()
427 });
428 scan.last = Some(pgno);
429 let next: Vec<u32> = if sequential {
430 scan.children
431 .range(pgno + 1..)
432 .take(SCAN_AHEAD)
433 .copied()
434 .collect()
435 } else {
436 Vec::new()
437 };
438 for p in &next {
439 scan.children.remove(p);
440 }
441 next
442 })
443 };
444 let page = u64::from(self.map.page_size);
445 let mut run = self.map.read_run_sync(
446 &*self.reader,
447 pgno,
448 if ahead.is_some() {
449 page
450 } else {
451 READAHEAD_BYTES
452 },
453 )?;
454 if run.is_empty() {
455 return Ok(run);
456 }
457 if let Some(wanted) = ahead.filter(|w| !w.is_empty()) {
458 let fetched = std::thread::scope(|scope| {
459 let workers: Vec<_> = wanted
460 .chunks(wanted.len().div_ceil(PREFETCH_WORKERS).max(1))
461 .map(|chunk| {
462 scope.spawn(move || {
463 // Consecutive children (a small-row table's
464 // leaves) come as one run; the rest one by one.
465 let mut pages = Vec::new();
466 let mut i = 0;
467 while i < chunk.len() {
468 let first = chunk[i];
469 let mut len = 1;
470 while i + len < chunk.len() && chunk[i + len] == first + len as u32
471 {
472 len += 1;
473 }
474 let got = self
475 .map
476 .read_run_sync(&*self.reader, first, len as u64 * page)
477 .unwrap_or_default();
478 i += got.len().max(1);
479 pages.extend(got);
480 }
481 pages
482 })
483 })
484 .collect();
485 workers
486 .into_iter()
487 .filter_map(|w| w.join().ok())
488 .flatten()
489 .collect::<Vec<_>>()
490 });
491 // A child a failed fetch did not deliver goes back on the list;
492 // dropped, its own fault would come as a run of its rows.
493 let delivered: std::collections::HashSet<u32> =
494 fetched.iter().map(|(p, _)| *p).collect();
495 let mut scan = self.scan.lock().unwrap();
496 scan.children
497 .extend(wanted.iter().copied().filter(|p| !delivered.contains(p)));
498 drop(scan);
499 run.extend(fetched);
500 }
501 // Every page delivered is off the list; every interior page among
502 // them names the children the next faults fetch alone and ahead.
503 let mut scan = self.scan.lock().unwrap();
504 for (p, page) in &run {
505 scan.children.remove(p);
506 scan.children.extend(prefetch_plan(*p, page).children);
507 }
508 Ok(run)
509 }
510
511 /// Reads one page on the calling thread. `None` when the cut has no such
512 /// page.
513 pub fn read_page_blocking(&self, pgno: u32) -> Result<Option<Vec<u8>>> {
514 Ok(self
515 .read_run_blocking(pgno)?
516 .into_iter()
517 .next()
518 .map(|(_, page)| page))
519 }
520}
521
522/// Routes a fault to the epoch that holds the object, by the object's first
523/// txid, as [`crate::client::epochs::EpochChain`] routes the async reads.
524pub struct EpochChainReader {
525 spans: Vec<(TXID, Box<dyn RangeReader>)>,
526}
527
528impl EpochChainReader {
529 /// `spans` ascending by the first txid each reader serves.
530 pub fn new(spans: Vec<(TXID, Box<dyn RangeReader>)>) -> Self {
531 assert!(!spans.is_empty(), "an epoch chain has a span");
532 Self { spans }
533 }
534}
535
536impl RangeReader for EpochChainReader {
537 fn read_range(&self, info: &FileInfo, offset: u64, len: u64) -> Result<Vec<u8>> {
538 let (_, reader) = self
539 .spans
540 .iter()
541 .rev()
542 .find(|(lo, _)| *lo <= info.min_txid)
543 .unwrap_or(&self.spans[0]);
544 reader.read_range(info, offset, len)
545 }
546}