Diffinery

homeflare/celldpublic

celld/crates/ltx/src/replica_compactor.rs
236 lines · 8.4 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 /// The epoch's first txid. An epoch that continues a chain it paged in
38 /// starts at its cut, not at 1, so an empty destination level continues
39 /// from here rather than from the first txid that never existed here.
40 base: TXID,
41 local_path: Option<PathBuf>,
42 host: LtxHost,
43}
44
45impl<'a, C: ReplicaClient> ReplicaCompactor<'a, C> {
46 pub fn new(client: &'a C) -> Self {
47 Self {
48 client,
49 verify: false,
50 max_files: usize::MAX,
51 max_input_bytes: u64::MAX,
52 base: TXID(1),
53 local_path: None,
54 host: LtxHost::default(),
55 }
56 }
57
58 /// Enables a destination-level continuity check after publication.
59 /// The txid the epoch's chain starts at (see the `base` field).
60 pub fn with_base(mut self, base: TXID) -> Self {
61 self.base = base;
62 self
63 }
64
65 pub fn with_verification(mut self, verify: bool) -> Self {
66 self.verify = verify;
67 self
68 }
69
70 /// Limits one compaction attempt to a contiguous source prefix.
71 pub fn with_limits(mut self, max_files: usize, max_input_bytes: u64) -> Self {
72 self.max_files = max_files;
73 self.max_input_bytes = max_input_bytes;
74 self
75 }
76
77 /// Uses the local LTX directory before it reads an object from the replica.
78 pub fn with_local_path(mut self, path: impl AsRef<Path>) -> Self {
79 self.local_path = Some(path.as_ref().to_path_buf());
80 self
81 }
82
83 /// Uses an injected clock and executor host.
84 pub fn with_host(mut self, host: LtxHost) -> Self {
85 self.host = host;
86 self
87 }
88
89 /// Compacts one new object prefix from `destination_level - 1`.
90 ///
91 /// The method returns `Ok(None)` when the destination already covers every
92 /// available source object. It publishes one immutable destination object
93 /// and leaves every source object intact.
94 pub async fn compact(&self, destination_level: i32) -> Result<Option<CompactionOutput>> {
95 if !(1..SNAPSHOT_LEVEL).contains(&destination_level) {
96 return Err(invalid("the destination compaction level is invalid"));
97 }
98 if self.max_files == 0 || self.max_input_bytes == 0 {
99 return Err(invalid("the compaction limits must be positive"));
100 }
101
102 let destination = self.client.ltx_files(destination_level, TXID(0)).await?;
103 let previous_max = destination
104 .iter()
105 .map(|file| file.max_txid)
106 .max()
107 .unwrap_or(TXID(0));
108 let seek = TXID(previous_max.0.wrapping_add(1).max(self.base.0));
109 let source_level = destination_level - 1;
110 let available = self
111 .client
112 .ltx_files_bounded(source_level, seek, self.max_files)
113 .await?;
114 let mut source = Vec::new();
115 let mut input_bytes = 0u64;
116 for file in available {
117 let size = u64::try_from(file.size)
118 .map_err(|_| invalid("a compaction source has a negative size"))?;
119 if source.len() == self.max_files {
120 break;
121 }
122 let total = input_bytes
123 .checked_add(size)
124 .ok_or_else(|| invalid("the compaction source size overflows"))?;
125 if total > self.max_input_bytes {
126 if source.is_empty() {
127 return Err(invalid("a compaction source exceeds the byte limit"));
128 }
129 break;
130 }
131 input_bytes = total;
132 source.push(file);
133 }
134 if source.is_empty() {
135 return Ok(None);
136 }
137
138 let min_txid = source
139 .iter()
140 .map(|file| file.min_txid)
141 .min()
142 .ok_or_else(|| invalid("the compaction source is empty"))?;
143 let max_txid = source
144 .iter()
145 .map(|file| file.max_txid)
146 .max()
147 .ok_or_else(|| invalid("the compaction source is empty"))?;
148 if min_txid != seek {
149 return Err(invalid(
150 "the compaction source does not continue the destination level",
151 ));
152 }
153 let mut readers = Vec::with_capacity(source.len());
154 let mut local_input_files = 0usize;
155 for file in &source {
156 let bytes = match &self.local_path {
157 Some(path) => {
158 let filename = ltx_file_path(
159 &path.to_string_lossy(),
160 file.level as u32,
161 file.min_txid,
162 file.max_txid,
163 );
164 match self.host.read_file(filename).await {
165 Ok(bytes) => {
166 local_input_files += 1;
167 bytes
168 }
169 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
170 self.client
171 .open_ltx_file(file.level, file.min_txid, file.max_txid)
172 .await?
173 }
174 Err(error) => return Err(Error::Io(error)),
175 }
176 }
177 None => {
178 self.client
179 .open_ltx_file(file.level, file.min_txid, file.max_txid)
180 .await?
181 }
182 };
183 readers.push(Cursor::new(bytes));
184 }
185
186 // The merge is pure CPU over as much as 64 MiB and must not hold a
187 // runtime worker: a restart drain runs rounds back-to-back, and on a
188 // 4-vCPU node two pegged workers starved co-owned cells' durable
189 // writes (2026-08-12 fleet roll).
190 let (header, output) = self
191 .host
192 .run_blocking(move || {
193 let mut compactor = Compactor::new(Vec::new(), readers);
194 compactor.header_flags = HEADER_FLAG_NO_CHECKSUM;
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}