Diffinery

homeflare/celldpublic

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