| 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::TXID; |
| 13 | use std::io::Cursor; |
| 14 | use std::path::Path; |
| 15 | use std::path::PathBuf; |
| 16 | |
| 17 | /// The immutable object and source volume from one compaction attempt. |
| 18 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 19 | pub struct CompactionOutput { |
| 20 | /// The published destination object. |
| 21 | pub info: FileInfo, |
| 22 | /// The number of source objects in the merge. |
| 23 | pub input_files: usize, |
| 24 | /// The sum of the source object sizes. |
| 25 | pub input_bytes: u64, |
| 26 | /// The number of source objects read from the local LTX directory. |
| 27 | pub local_input_files: usize, |
| 28 | } |
| 29 | |
| 30 | /// Compacts LTX objects between two adjacent replica levels. |
| 31 | pub struct ReplicaCompactor<'a, C> { |
| 32 | client: &'a C, |
| 33 | verify: bool, |
| 34 | max_files: usize, |
| 35 | max_input_bytes: u64, |
| 36 | local_path: Option<PathBuf>, |
| 37 | } |
| 38 | |
| 39 | impl<'a, C: ReplicaClient> ReplicaCompactor<'a, C> { |
| 40 | pub fn new(client: &'a C) -> Self { |
| 41 | Self { |
| 42 | client, |
| 43 | verify: false, |
| 44 | max_files: usize::MAX, |
| 45 | max_input_bytes: u64::MAX, |
| 46 | local_path: None, |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /// Enables a destination-level continuity check after publication. |
| 51 | pub fn with_verification(mut self, verify: bool) -> Self { |
| 52 | self.verify = verify; |
| 53 | self |
| 54 | } |
| 55 | |
| 56 | /// Limits one compaction attempt to a contiguous source prefix. |
| 57 | pub fn with_limits(mut self, max_files: usize, max_input_bytes: u64) -> Self { |
| 58 | self.max_files = max_files; |
| 59 | self.max_input_bytes = max_input_bytes; |
| 60 | self |
| 61 | } |
| 62 | |
| 63 | /// Uses the local LTX directory before it reads an object from the replica. |
| 64 | pub fn with_local_path(mut self, path: impl AsRef<Path>) -> Self { |
| 65 | self.local_path = Some(path.as_ref().to_path_buf()); |
| 66 | self |
| 67 | } |
| 68 | |
| 69 | /// Compacts one new object prefix from `destination_level - 1`. |
| 70 | /// |
| 71 | /// The method returns `Ok(None)` when the destination already covers every |
| 72 | /// available source object. It publishes one immutable destination object |
| 73 | /// and leaves every source object intact. |
| 74 | pub async fn compact(&self, destination_level: i32) -> Result<Option<CompactionOutput>> { |
| 75 | if !(1..SNAPSHOT_LEVEL).contains(&destination_level) { |
| 76 | return Err(invalid("the destination compaction level is invalid")); |
| 77 | } |
| 78 | if self.max_files == 0 || self.max_input_bytes == 0 { |
| 79 | return Err(invalid("the compaction limits must be positive")); |
| 80 | } |
| 81 | |
| 82 | let destination = self.client.ltx_files(destination_level, TXID(0)).await?; |
| 83 | let previous_max = destination |
| 84 | .iter() |
| 85 | .map(|file| file.max_txid) |
| 86 | .max() |
| 87 | .unwrap_or(TXID(0)); |
| 88 | let seek = TXID(previous_max.0.wrapping_add(1)); |
| 89 | let source_level = destination_level - 1; |
| 90 | let available = self |
| 91 | .client |
| 92 | .ltx_files_bounded(source_level, seek, self.max_files) |
| 93 | .await?; |
| 94 | let mut source = Vec::new(); |
| 95 | let mut input_bytes = 0u64; |
| 96 | for file in available { |
| 97 | let size = u64::try_from(file.size) |
| 98 | .map_err(|_| invalid("a compaction source has a negative size"))?; |
| 99 | if source.len() == self.max_files { |
| 100 | break; |
| 101 | } |
| 102 | let total = input_bytes |
| 103 | .checked_add(size) |
| 104 | .ok_or_else(|| invalid("the compaction source size overflows"))?; |
| 105 | if total > self.max_input_bytes { |
| 106 | if source.is_empty() { |
| 107 | return Err(invalid("a compaction source exceeds the byte limit")); |
| 108 | } |
| 109 | break; |
| 110 | } |
| 111 | input_bytes = total; |
| 112 | source.push(file); |
| 113 | } |
| 114 | if source.is_empty() { |
| 115 | return Ok(None); |
| 116 | } |
| 117 | |
| 118 | let min_txid = source |
| 119 | .iter() |
| 120 | .map(|file| file.min_txid) |
| 121 | .min() |
| 122 | .ok_or_else(|| invalid("the compaction source is empty"))?; |
| 123 | let max_txid = source |
| 124 | .iter() |
| 125 | .map(|file| file.max_txid) |
| 126 | .max() |
| 127 | .ok_or_else(|| invalid("the compaction source is empty"))?; |
| 128 | if min_txid != seek { |
| 129 | return Err(invalid( |
| 130 | "the compaction source does not continue the destination level", |
| 131 | )); |
| 132 | } |
| 133 | let mut readers = Vec::with_capacity(source.len()); |
| 134 | let mut local_input_files = 0usize; |
| 135 | for file in &source { |
| 136 | let bytes = match &self.local_path { |
| 137 | Some(path) => { |
| 138 | let filename = ltx_file_path( |
| 139 | &path.to_string_lossy(), |
| 140 | file.level as u32, |
| 141 | file.min_txid, |
| 142 | file.max_txid, |
| 143 | ); |
| 144 | match tokio::fs::read(filename).await { |
| 145 | Ok(bytes) => { |
| 146 | local_input_files += 1; |
| 147 | bytes |
| 148 | } |
| 149 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => { |
| 150 | self.client |
| 151 | .open_ltx_file(file.level, file.min_txid, file.max_txid) |
| 152 | .await? |
| 153 | } |
| 154 | Err(error) => return Err(Error::Io(error)), |
| 155 | } |
| 156 | } |
| 157 | None => { |
| 158 | self.client |
| 159 | .open_ltx_file(file.level, file.min_txid, file.max_txid) |
| 160 | .await? |
| 161 | } |
| 162 | }; |
| 163 | readers.push(Cursor::new(bytes)); |
| 164 | } |
| 165 | |
| 166 | // The merge is pure CPU over as much as 64 MiB and must not hold a |
| 167 | // runtime worker: a restart drain runs rounds back-to-back, and on a |
| 168 | // 4-vCPU node two pegged workers starved co-owned cells' durable |
| 169 | // writes (2026-08-12 fleet roll). |
| 170 | let (header, output) = tokio::task::spawn_blocking(move || { |
| 171 | let mut compactor = Compactor::new(Vec::new(), readers); |
| 172 | compactor.header_flags = HEADER_FLAG_NO_CHECKSUM; |
| 173 | compactor.compact()?; |
| 174 | Ok::<_, Error>((compactor.header(), compactor.into_writer())) |
| 175 | }) |
| 176 | .await |
| 177 | .map_err(|_| invalid("the compaction merge task panicked"))??; |
| 178 | if header.min_txid != min_txid || header.max_txid != max_txid { |
| 179 | return Err(invalid( |
| 180 | "a compaction source key does not match its LTX header", |
| 181 | )); |
| 182 | } |
| 183 | let info = self |
| 184 | .client |
| 185 | .write_ltx_file(destination_level, min_txid, max_txid, &output) |
| 186 | .await?; |
| 187 | |
| 188 | if self.verify { |
| 189 | self.verify_level(destination_level).await?; |
| 190 | } |
| 191 | Ok(Some(CompactionOutput { |
| 192 | info, |
| 193 | input_files: source.len(), |
| 194 | input_bytes, |
| 195 | local_input_files, |
| 196 | })) |
| 197 | } |
| 198 | |
| 199 | /// Verifies that a destination level has neither gaps nor overlaps. |
| 200 | pub async fn verify_level(&self, level: i32) -> Result<()> { |
| 201 | let files = self.client.ltx_files(level, TXID(0)).await?; |
| 202 | for pair in files.windows(2) { |
| 203 | let expected = pair[0].max_txid.0.wrapping_add(1); |
| 204 | if pair[1].min_txid != TXID(expected) { |
| 205 | return Err(invalid("the compaction level is not contiguous")); |
| 206 | } |
| 207 | } |
| 208 | Ok(()) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | fn invalid(message: &'static str) -> Error { |
| 213 | Error::Other(message.into()) |
| 214 | } |
| 215 | |
| 216 | #[cfg(test)] |
| 217 | mod tests { |
| 218 | use super::*; |
| 219 | use crate::client::file::FileReplicaClient; |
| 220 | use crate::client::{make_test_ltx_file, ReplicaClient}; |
| 221 | use crate::ltx::{decode_file, decode_file_pages, PAGE_HEADER_FLAG_SIZE}; |
| 222 | |
| 223 | async fn write_l0(client: &FileReplicaClient, txid: u64, seed: u8) { |
| 224 | let data = make_test_ltx_file(TXID(txid), TXID(txid), seed); |
| 225 | client |
| 226 | .write_ltx_file(0, TXID(txid), TXID(txid), &data) |
| 227 | .await |
| 228 | .expect("write L0"); |
| 229 | } |
| 230 | |
| 231 | #[tokio::test] |
| 232 | async fn compacts_only_the_uncovered_source_tail() { |
| 233 | let directory = tempfile::tempdir().unwrap(); |
| 234 | let client = FileReplicaClient::new(directory.path().to_string_lossy().into_owned()); |
| 235 | for txid in 1..=3 { |
| 236 | write_l0(&client, txid, txid as u8).await; |
| 237 | } |
| 238 | |
| 239 | let compactor = ReplicaCompactor::new(&client).with_verification(true); |
| 240 | let first = compactor.compact(1).await.unwrap().expect("first output"); |
| 241 | assert_eq!( |
| 242 | (first.info.min_txid, first.info.max_txid), |
| 243 | (TXID(1), TXID(3)) |
| 244 | ); |
| 245 | assert_eq!(first.input_files, 3); |
| 246 | assert_eq!(first.local_input_files, 0); |
| 247 | |
| 248 | assert!(compactor.compact(1).await.unwrap().is_none()); |
| 249 | for txid in 4..=5 { |
| 250 | write_l0(&client, txid, txid as u8).await; |
| 251 | } |
| 252 | let second = compactor.compact(1).await.unwrap().expect("second output"); |
| 253 | assert_eq!( |
| 254 | (second.info.min_txid, second.info.max_txid), |
| 255 | (TXID(4), TXID(5)) |
| 256 | ); |
| 257 | |
| 258 | let level = client.ltx_files(1, TXID(0)).await.unwrap(); |
| 259 | assert_eq!(level.len(), 2); |
| 260 | assert_eq!(client.ltx_files(0, TXID(0)).await.unwrap().len(), 5); |
| 261 | |
| 262 | let bytes = client.open_ltx_file(1, TXID(1), TXID(3)).await.unwrap(); |
| 263 | let decoded = decode_file(&bytes).unwrap(); |
| 264 | assert_eq!(decoded.header.flags, HEADER_FLAG_NO_CHECKSUM); |
| 265 | assert_eq!( |
| 266 | u16::from_be_bytes([bytes[104], bytes[105]]), |
| 267 | PAGE_HEADER_FLAG_SIZE |
| 268 | ); |
| 269 | assert_eq!(decode_file_pages(&bytes).unwrap(), vec![(1, vec![3; 512])]); |
| 270 | } |
| 271 | |
| 272 | #[tokio::test] |
| 273 | async fn rejects_invalid_destinations_and_inconsistent_levels() { |
| 274 | let directory = tempfile::tempdir().unwrap(); |
| 275 | let client = FileReplicaClient::new(directory.path().to_string_lossy().into_owned()); |
| 276 | let compactor = ReplicaCompactor::new(&client); |
| 277 | assert!(compactor.compact(0).await.is_err()); |
| 278 | assert!(compactor.compact(SNAPSHOT_LEVEL).await.is_err()); |
| 279 | |
| 280 | let first = make_test_ltx_file(TXID(1), TXID(1), 1); |
| 281 | let third = make_test_ltx_file(TXID(3), TXID(3), 3); |
| 282 | client |
| 283 | .write_ltx_file(1, TXID(1), TXID(1), &first) |
| 284 | .await |
| 285 | .unwrap(); |
| 286 | client |
| 287 | .write_ltx_file(1, TXID(3), TXID(3), &third) |
| 288 | .await |
| 289 | .unwrap(); |
| 290 | assert!(compactor.verify_level(1).await.is_err()); |
| 291 | } |
| 292 | |
| 293 | #[tokio::test] |
| 294 | async fn limits_each_attempt_to_a_contiguous_source_prefix() { |
| 295 | let directory = tempfile::tempdir().unwrap(); |
| 296 | let client = FileReplicaClient::new(directory.path().to_string_lossy().into_owned()); |
| 297 | for txid in 1..=5 { |
| 298 | write_l0(&client, txid, txid as u8).await; |
| 299 | } |
| 300 | |
| 301 | let compactor = ReplicaCompactor::new(&client) |
| 302 | .with_limits(2, u64::MAX) |
| 303 | .with_verification(true); |
| 304 | let first = compactor.compact(1).await.unwrap().expect("first output"); |
| 305 | let second = compactor.compact(1).await.unwrap().expect("second output"); |
| 306 | let third = compactor.compact(1).await.unwrap().expect("third output"); |
| 307 | |
| 308 | assert_eq!( |
| 309 | (first.info.min_txid, first.info.max_txid), |
| 310 | (TXID(1), TXID(2)) |
| 311 | ); |
| 312 | assert_eq!( |
| 313 | (second.info.min_txid, second.info.max_txid), |
| 314 | (TXID(3), TXID(4)) |
| 315 | ); |
| 316 | assert_eq!( |
| 317 | (third.info.min_txid, third.info.max_txid), |
| 318 | (TXID(5), TXID(5)) |
| 319 | ); |
| 320 | assert!(compactor.compact(1).await.unwrap().is_none()); |
| 321 | assert_eq!(client.ltx_files(0, TXID(0)).await.unwrap().len(), 5); |
| 322 | } |
| 323 | |
| 324 | #[tokio::test] |
| 325 | async fn prefers_matching_local_inputs() { |
| 326 | let directory = tempfile::tempdir().unwrap(); |
| 327 | let client = FileReplicaClient::new(directory.path().to_string_lossy().into_owned()); |
| 328 | write_l0(&client, 1, 1).await; |
| 329 | write_l0(&client, 2, 2).await; |
| 330 | |
| 331 | let output = ReplicaCompactor::new(&client) |
| 332 | .with_local_path(directory.path()) |
| 333 | .compact(1) |
| 334 | .await |
| 335 | .unwrap() |
| 336 | .expect("output"); |
| 337 | assert_eq!(output.local_input_files, 2); |
| 338 | } |
| 339 | |
| 340 | #[tokio::test] |
| 341 | async fn refuses_to_publish_a_gap_after_the_destination_tail() { |
| 342 | let directory = tempfile::tempdir().unwrap(); |
| 343 | let client = FileReplicaClient::new(directory.path().to_string_lossy().into_owned()); |
| 344 | write_l0(&client, 1, 1).await; |
| 345 | let compactor = ReplicaCompactor::new(&client).with_verification(true); |
| 346 | compactor.compact(1).await.unwrap().expect("first output"); |
| 347 | |
| 348 | write_l0(&client, 3, 3).await; |
| 349 | assert!(compactor.compact(1).await.is_err()); |
| 350 | assert_eq!(client.ltx_files(1, TXID(0)).await.unwrap().len(), 1); |
| 351 | } |
| 352 | } |