| 1 | //! Additive LTX compaction through a [`ReplicaClient`]. |
| 2 | //! |
| 3 | //! This module ports the storage-independent part of Litestream v0.5.16's |
| 4 | //! `Compactor`. It creates a destination object but never deletes a source. |
| 5 | |
| 6 | use crate::client::ReplicaClient; |
| 7 | use crate::compaction_level::SNAPSHOT_LEVEL; |
| 8 | use crate::compactor::Compactor; |
| 9 | use crate::error::{Error, Result}; |
| 10 | use crate::ltx::{FileInfo, HEADER_FLAG_NO_CHECKSUM}; |
| 11 | use crate::ltx_file_path; |
| 12 | use crate::LtxHost; |
| 13 | use crate::TXID; |
| 14 | use std::io::{BufReader, BufWriter, Cursor, Read, Write}; |
| 15 | use std::path::Path; |
| 16 | use std::path::PathBuf; |
| 17 | |
| 18 | /// The immutable object and source volume from one compaction attempt. |
| 19 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 20 | pub struct CompactionOutput { |
| 21 | /// The published destination object. |
| 22 | pub info: FileInfo, |
| 23 | /// The number of source objects in the merge. |
| 24 | pub input_files: usize, |
| 25 | /// The sum of the source object sizes. |
| 26 | pub input_bytes: u64, |
| 27 | /// The number of source objects read from the local LTX directory. |
| 28 | pub local_input_files: usize, |
| 29 | } |
| 30 | |
| 31 | /// Destination coverage proved by the same attempt that selects its output. |
| 32 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 33 | pub struct CompactionResult { |
| 34 | pub covered_txid: TXID, |
| 35 | pub output: Option<CompactionOutput>, |
| 36 | } |
| 37 | |
| 38 | /// Compacts LTX objects between two adjacent replica levels. |
| 39 | pub struct ReplicaCompactor<'a, C> { |
| 40 | client: &'a C, |
| 41 | verify: bool, |
| 42 | max_files: usize, |
| 43 | max_input_bytes: u64, |
| 44 | /// The epoch's first txid. An epoch that continues a chain it paged in |
| 45 | /// starts at its cut, not at 1, so an empty destination level continues |
| 46 | /// from here rather than from the first txid that never existed here. |
| 47 | base: TXID, |
| 48 | local_path: Option<PathBuf>, |
| 49 | host: LtxHost, |
| 50 | } |
| 51 | |
| 52 | impl<'a, C: ReplicaClient> ReplicaCompactor<'a, C> { |
| 53 | pub fn new(client: &'a C) -> Self { |
| 54 | Self { |
| 55 | client, |
| 56 | verify: false, |
| 57 | max_files: usize::MAX, |
| 58 | max_input_bytes: u64::MAX, |
| 59 | base: TXID(1), |
| 60 | local_path: None, |
| 61 | host: LtxHost::default(), |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /// The txid the epoch's chain starts at (see the `base` field). |
| 66 | pub fn with_base(mut self, base: TXID) -> Self { |
| 67 | self.base = base; |
| 68 | self |
| 69 | } |
| 70 | |
| 71 | /// Checks destination continuity again after publication. Every attempt |
| 72 | /// checks the existing destination before it selects a source. |
| 73 | pub fn with_verification(mut self, verify: bool) -> Self { |
| 74 | self.verify = verify; |
| 75 | self |
| 76 | } |
| 77 | |
| 78 | /// Limits the source count and buffered input bytes. An indivisible source |
| 79 | /// above the byte budget compacts alone through scratch files. |
| 80 | pub fn with_limits(mut self, max_files: usize, max_input_bytes: u64) -> Self { |
| 81 | self.max_files = max_files; |
| 82 | self.max_input_bytes = max_input_bytes; |
| 83 | self |
| 84 | } |
| 85 | |
| 86 | /// Uses the local LTX directory before it reads an object from the replica. |
| 87 | pub fn with_local_path(mut self, path: impl AsRef<Path>) -> Self { |
| 88 | self.local_path = Some(path.as_ref().to_path_buf()); |
| 89 | self |
| 90 | } |
| 91 | |
| 92 | /// Uses an injected clock and executor host. |
| 93 | pub fn with_host(mut self, host: LtxHost) -> Self { |
| 94 | self.host = host; |
| 95 | self |
| 96 | } |
| 97 | |
| 98 | /// Compacts one new object prefix from `destination_level - 1`. |
| 99 | /// |
| 100 | /// The method returns `Ok(None)` when the destination already covers every |
| 101 | /// available source object. It publishes one immutable destination object |
| 102 | /// and leaves every source object intact. |
| 103 | pub async fn compact(&self, destination_level: i32) -> Result<Option<CompactionOutput>> { |
| 104 | Ok(self.compact_with_progress(destination_level).await?.output) |
| 105 | } |
| 106 | |
| 107 | /// Returns the proved destination bound even when no source is available. |
| 108 | /// An empty listing does not prove coverage of a concurrently durable tail. |
| 109 | pub async fn compact_with_progress(&self, destination_level: i32) -> Result<CompactionResult> { |
| 110 | if !(1..SNAPSHOT_LEVEL).contains(&destination_level) { |
| 111 | return Err(invalid("the destination compaction level is invalid")); |
| 112 | } |
| 113 | if self.max_files == 0 || self.max_input_bytes == 0 { |
| 114 | return Err(invalid("the compaction limits must be positive")); |
| 115 | } |
| 116 | |
| 117 | let destination = self.client.ltx_files(destination_level, TXID(0)).await?; |
| 118 | self.verify_files(&destination)?; |
| 119 | let previous_max = destination |
| 120 | .iter() |
| 121 | .map(|file| file.max_txid) |
| 122 | .max() |
| 123 | .unwrap_or(TXID(0)); |
| 124 | let Some(next) = previous_max.0.checked_add(1) else { |
| 125 | return Ok(CompactionResult { |
| 126 | covered_txid: previous_max, |
| 127 | output: None, |
| 128 | }); |
| 129 | }; |
| 130 | let seek = TXID(next.max(self.base.0)); |
| 131 | let source_level = destination_level - 1; |
| 132 | let mut available = self |
| 133 | .client |
| 134 | .ltx_files_bounded(source_level, seek, self.max_files) |
| 135 | .await?; |
| 136 | // The listing offset compares minimum txids. A direct drain can start |
| 137 | // before `seek` and still contain the only copy of its uncovered tail. |
| 138 | // Keep the bounded listing for ordinary rows, but search behind the |
| 139 | // offset before reporting a gap or no work. |
| 140 | if available.first().is_none_or(|file| file.min_txid != seek) { |
| 141 | available = self.client.ltx_files(source_level, TXID(0)).await?; |
| 142 | } |
| 143 | available.sort_by_key(|file| (file.min_txid, std::cmp::Reverse(file.max_txid))); |
| 144 | let mut source = Vec::new(); |
| 145 | let mut input_bytes = 0u64; |
| 146 | let mut next = seek; |
| 147 | for file in available { |
| 148 | if file.max_txid < next { |
| 149 | continue; |
| 150 | } |
| 151 | if file.min_txid > next { |
| 152 | if source.is_empty() { |
| 153 | return Err(invalid( |
| 154 | "the compaction source does not continue the destination level", |
| 155 | )); |
| 156 | } |
| 157 | break; |
| 158 | } |
| 159 | let size = u64::try_from(file.size) |
| 160 | .map_err(|_| invalid("a compaction source has a negative size"))?; |
| 161 | if source.len() == self.max_files { |
| 162 | break; |
| 163 | } |
| 164 | let total = input_bytes |
| 165 | .checked_add(size) |
| 166 | .ok_or_else(|| invalid("the compaction source size overflows"))?; |
| 167 | if total > self.max_input_bytes { |
| 168 | if source.is_empty() { |
| 169 | let output = self |
| 170 | .compact_large_source(destination_level, seek, file) |
| 171 | .await?; |
| 172 | return Ok(CompactionResult { |
| 173 | covered_txid: output.info.max_txid, |
| 174 | output: Some(output), |
| 175 | }); |
| 176 | } |
| 177 | break; |
| 178 | } |
| 179 | input_bytes = total; |
| 180 | let reaches_end = file.max_txid == TXID(u64::MAX); |
| 181 | next = TXID(file.max_txid.0.saturating_add(1)); |
| 182 | source.push(file); |
| 183 | if reaches_end { |
| 184 | break; |
| 185 | } |
| 186 | } |
| 187 | if source.is_empty() { |
| 188 | return Ok(CompactionResult { |
| 189 | covered_txid: previous_max, |
| 190 | output: None, |
| 191 | }); |
| 192 | } |
| 193 | |
| 194 | let min_txid = seek; |
| 195 | let max_txid = source |
| 196 | .iter() |
| 197 | .map(|file| file.max_txid) |
| 198 | .max() |
| 199 | .ok_or_else(|| invalid("the compaction source is empty"))?; |
| 200 | let ranges: Vec<_> = source |
| 201 | .iter() |
| 202 | .map(|file| (file.min_txid, file.max_txid)) |
| 203 | .collect(); |
| 204 | let mut readers = Vec::with_capacity(source.len()); |
| 205 | let mut local_input_files = 0usize; |
| 206 | for file in &source { |
| 207 | let bytes = match &self.local_path { |
| 208 | Some(path) => { |
| 209 | let filename = ltx_file_path( |
| 210 | &path.to_string_lossy(), |
| 211 | file.level as u32, |
| 212 | file.min_txid, |
| 213 | file.max_txid, |
| 214 | ); |
| 215 | match self.host.read_file(filename).await { |
| 216 | Ok(bytes) => { |
| 217 | local_input_files += 1; |
| 218 | bytes |
| 219 | } |
| 220 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => { |
| 221 | self.client |
| 222 | .open_ltx_file(file.level, file.min_txid, file.max_txid) |
| 223 | .await? |
| 224 | } |
| 225 | Err(error) => return Err(Error::Io(error)), |
| 226 | } |
| 227 | } |
| 228 | None => { |
| 229 | self.client |
| 230 | .open_ltx_file(file.level, file.min_txid, file.max_txid) |
| 231 | .await? |
| 232 | } |
| 233 | }; |
| 234 | readers.push(Cursor::new(bytes)); |
| 235 | } |
| 236 | |
| 237 | // The merge is pure CPU over as much as 64 MiB and must not hold a |
| 238 | // runtime worker: a restart drain runs rounds back-to-back, and on a |
| 239 | // 4-vCPU node two pegged workers starved co-owned cells' durable |
| 240 | // writes (2026-08-12 fleet roll). |
| 241 | let (header, output) = self |
| 242 | .host |
| 243 | .run_blocking(move || { |
| 244 | let mut compactor = Compactor::new(Vec::new(), readers); |
| 245 | compactor.header_flags = HEADER_FLAG_NO_CHECKSUM; |
| 246 | compactor.compact_from(min_txid, &ranges)?; |
| 247 | Ok::<_, Error>((compactor.header(), compactor.into_writer())) |
| 248 | }) |
| 249 | .await |
| 250 | .map_err(|_| invalid("the compaction merge task panicked"))??; |
| 251 | if header.min_txid != min_txid || header.max_txid != max_txid { |
| 252 | return Err(invalid( |
| 253 | "a compaction source key does not match its LTX header", |
| 254 | )); |
| 255 | } |
| 256 | let info = self |
| 257 | .client |
| 258 | .write_ltx_file(destination_level, min_txid, max_txid, &output) |
| 259 | .await?; |
| 260 | |
| 261 | if self.verify { |
| 262 | self.verify_level(destination_level).await?; |
| 263 | } |
| 264 | Ok(CompactionResult { |
| 265 | covered_txid: info.max_txid, |
| 266 | output: Some(CompactionOutput { |
| 267 | info, |
| 268 | input_files: source.len(), |
| 269 | input_bytes, |
| 270 | local_input_files, |
| 271 | }), |
| 272 | }) |
| 273 | } |
| 274 | |
| 275 | // A direct drain can produce one object larger than the entire input |
| 276 | // budget. Deferring it forever stalls the level; buffering it defeats the |
| 277 | // node's memory limit. Spool remote bytes and the output to anonymous files |
| 278 | // and merge one page at a time. The codec retains only its page index. |
| 279 | async fn compact_large_source( |
| 280 | &self, |
| 281 | destination_level: i32, |
| 282 | min: TXID, |
| 283 | source: FileInfo, |
| 284 | ) -> Result<CompactionOutput> { |
| 285 | let host = self.host.clone(); |
| 286 | let local = self.local_path.as_ref().map(|path| { |
| 287 | PathBuf::from(ltx_file_path( |
| 288 | &path.to_string_lossy(), |
| 289 | source.level as u32, |
| 290 | source.min_txid, |
| 291 | source.max_txid, |
| 292 | )) |
| 293 | }); |
| 294 | let (mut input, local_input_files) = self |
| 295 | .host |
| 296 | .run_blocking(move || match local { |
| 297 | Some(path) => match host.open(&path) { |
| 298 | Ok(file) => Ok((Some(file), 1)), |
| 299 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok((None, 0)), |
| 300 | Err(error) => Err(error), |
| 301 | }, |
| 302 | None => Ok((None, 0)), |
| 303 | }) |
| 304 | .await |
| 305 | .map_err(|_| invalid("the compaction file task panicked"))??; |
| 306 | if input.is_none() { |
| 307 | let mut scratch = self.scratch_file().await?; |
| 308 | let mut offset = 0; |
| 309 | while offset < source.size as u64 { |
| 310 | let len = (source.size as u64 - offset).min(1 << 20); |
| 311 | let bytes = self |
| 312 | .client |
| 313 | .read_range(source.level, source.min_txid, source.max_txid, offset, len) |
| 314 | .await?; |
| 315 | if bytes.len() as u64 != len { |
| 316 | return Err(invalid("a compaction source range is short")); |
| 317 | } |
| 318 | scratch = self |
| 319 | .host |
| 320 | .run_blocking(move || { |
| 321 | scratch.write_all(&bytes)?; |
| 322 | Ok::<_, Error>(scratch) |
| 323 | }) |
| 324 | .await |
| 325 | .map_err(|_| invalid("the compaction file task panicked"))??; |
| 326 | offset += len; |
| 327 | } |
| 328 | input = Some(scratch); |
| 329 | } |
| 330 | let input = input.ok_or_else(|| invalid("the compaction source is empty"))?; |
| 331 | let output = self.scratch_file().await?; |
| 332 | let expected = (source.min_txid, source.max_txid); |
| 333 | let output = self |
| 334 | .host |
| 335 | .run_blocking(move || { |
| 336 | let reader = ScratchReader::new(input)?; |
| 337 | if reader.len != source.size as u64 { |
| 338 | return Err(invalid("a compaction source size changed")); |
| 339 | } |
| 340 | // Buffered adapters avoid a syscall for every codec field. |
| 341 | let mut compactor = Compactor::new( |
| 342 | BufWriter::new(ScratchWriter(output)), |
| 343 | vec![BufReader::new(reader)], |
| 344 | ); |
| 345 | compactor.header_flags = HEADER_FLAG_NO_CHECKSUM; |
| 346 | compactor.compact_from(min, &[expected])?; |
| 347 | let output = compactor |
| 348 | .into_writer() |
| 349 | .into_inner() |
| 350 | .map_err(|error| Error::Io(error.into_error()))?; |
| 351 | Ok::<_, Error>(output.0) |
| 352 | }) |
| 353 | .await |
| 354 | .map_err(|_| invalid("the compaction merge task panicked"))??; |
| 355 | let info = self |
| 356 | .client |
| 357 | .write_ltx_file_from_file( |
| 358 | destination_level, |
| 359 | min, |
| 360 | source.max_txid, |
| 361 | output, |
| 362 | self.host.clone(), |
| 363 | ) |
| 364 | .await?; |
| 365 | if self.verify { |
| 366 | self.verify_level(destination_level).await?; |
| 367 | } |
| 368 | Ok(CompactionOutput { |
| 369 | info, |
| 370 | input_files: 1, |
| 371 | input_bytes: source.size as u64, |
| 372 | local_input_files, |
| 373 | }) |
| 374 | } |
| 375 | |
| 376 | async fn scratch_file(&self) -> Result<crate::host::HostFile> { |
| 377 | let filesystem = self.host.filesystem(); |
| 378 | let directory = self.local_path.clone(); |
| 379 | self.host |
| 380 | .run_blocking(move || filesystem.temporary_file(directory.as_deref())) |
| 381 | .await |
| 382 | .map_err(|_| invalid("the compaction file task panicked"))? |
| 383 | .map_err(Error::Io) |
| 384 | } |
| 385 | |
| 386 | /// Verifies that a destination level has neither gaps nor overlaps. |
| 387 | pub async fn verify_level(&self, level: i32) -> Result<()> { |
| 388 | let files = self.client.ltx_files(level, TXID(0)).await?; |
| 389 | self.verify_files(&files) |
| 390 | } |
| 391 | |
| 392 | fn verify_files(&self, files: &[FileInfo]) -> Result<()> { |
| 393 | if files.first().is_some_and(|file| file.min_txid != self.base) |
| 394 | || files.iter().any(|file| file.min_txid > file.max_txid) |
| 395 | { |
| 396 | return Err(invalid("the compaction level is not contiguous")); |
| 397 | } |
| 398 | for pair in files.windows(2) { |
| 399 | if pair[0].max_txid.0.checked_add(1) != Some(pair[1].min_txid.0) { |
| 400 | return Err(invalid("the compaction level is not contiguous")); |
| 401 | } |
| 402 | } |
| 403 | Ok(()) |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | fn invalid(message: &'static str) -> Error { |
| 408 | Error::Other(message.into()) |
| 409 | } |
| 410 | |
| 411 | struct ScratchReader { |
| 412 | file: crate::host::HostFile, |
| 413 | offset: u64, |
| 414 | len: u64, |
| 415 | } |
| 416 | |
| 417 | impl ScratchReader { |
| 418 | fn new(mut file: crate::host::HostFile) -> std::io::Result<Self> { |
| 419 | let len = file.file_len()?; |
| 420 | Ok(Self { |
| 421 | file, |
| 422 | offset: 0, |
| 423 | len, |
| 424 | }) |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | impl Read for ScratchReader { |
| 429 | fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> { |
| 430 | let len = (self.len - self.offset).min(bytes.len() as u64) as usize; |
| 431 | if len == 0 { |
| 432 | return Ok(0); |
| 433 | } |
| 434 | bytes[..len].copy_from_slice(&self.file.read_exact_at(self.offset, len)?); |
| 435 | self.offset += len as u64; |
| 436 | Ok(len) |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | struct ScratchWriter(crate::host::HostFile); |
| 441 | |
| 442 | impl Write for ScratchWriter { |
| 443 | fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { |
| 444 | self.0.write_all(bytes)?; |
| 445 | Ok(bytes.len()) |
| 446 | } |
| 447 | fn flush(&mut self) -> std::io::Result<()> { |
| 448 | Ok(()) |
| 449 | } |
| 450 | } |