1use std::collections::{BTreeMap, HashMap, HashSet};
16
17use crate::batch_size::estimate_batch_size;
18use crate::compaction::CompactionOutput;
19use crate::compaction::picker::PickerOutput;
20use crate::compaction::reader::MERGED_BATCH_CHANNEL_SIZE;
21use crate::read::seq_scan::compaction_input_channel_size;
22use crate::sst::file::{FileHandle, FileMeta};
23
24#[derive(Debug, Clone)]
29pub(crate) struct CompactionUnit {
30 pub(crate) inputs: Vec<FileHandle>,
32 pub(crate) outputs: Vec<CompactionOutput>,
34 pub(crate) time_window_size: i64,
36 pub(crate) max_file_size: Option<usize>,
38}
39
40impl CompactionUnit {
41 pub(crate) fn from_picker(output: PickerOutput) -> Option<Vec<Self>> {
47 let PickerOutput {
48 outputs,
49 expired_ssts,
50 time_window_size,
51 max_file_size,
52 } = output;
53 let mut parents: Vec<_> = (0..outputs.len()).collect();
54 let mut owners = HashMap::new();
55 for (index, output) in outputs.iter().enumerate() {
56 for file in &output.inputs {
57 if let Some(&previous) = owners.get(&file.file_id()) {
58 let a = root(&mut parents, previous);
59 let b = root(&mut parents, index);
60 parents[a.min(b)] = a.max(b);
62 } else {
63 owners.insert(file.file_id(), index);
64 }
65 }
66 }
67 if expired_ssts
68 .iter()
69 .any(|f| owners.contains_key(&f.file_id()))
70 {
71 return None;
72 }
73
74 let mut groups: BTreeMap<usize, Vec<CompactionOutput>> = BTreeMap::new();
75 for (index, output) in outputs.into_iter().enumerate() {
76 groups
77 .entry(root(&mut parents, index))
78 .or_default()
79 .push(output);
80 }
81 let mut units = Vec::with_capacity(groups.len() + 1);
82 if !expired_ssts.is_empty() {
83 let mut seen = HashSet::new();
84 units.push(Self {
85 inputs: expired_ssts
86 .into_iter()
87 .filter(|f| seen.insert(f.file_id()))
88 .collect(),
89 outputs: Vec::new(),
90 time_window_size,
91 max_file_size,
92 });
93 }
94 for outputs in groups.into_values().rev() {
95 let mut seen = HashSet::new();
96 let inputs: Vec<_> = outputs
97 .iter()
98 .flat_map(|o| &o.inputs)
99 .filter(|f| seen.insert(f.file_id()))
100 .cloned()
101 .collect();
102 if inputs.is_empty() {
103 continue;
104 }
105 units.push(Self {
106 inputs,
107 outputs,
108 time_window_size,
109 max_file_size,
110 });
111 }
112 Some(units)
113 }
114
115 pub(crate) fn estimated_input_bytes(&self) -> u64 {
118 if self.outputs.is_empty() {
119 return 0;
120 }
121 self.inputs
122 .iter()
123 .fold(0u64, |total, file| total.saturating_add(file.size()))
124 }
125
126 pub(crate) fn estimated_memory_bytes(
131 &self,
132 read_parallelism: usize,
133 retains_dedup_batch: bool,
134 ) -> u64 {
135 self.outputs
136 .iter()
137 .map(|output| {
138 output_memory_bytes(&output.inputs, read_parallelism, retains_dedup_batch)
139 })
140 .max()
141 .unwrap_or(0)
142 }
143}
144
145fn max_row_group_bytes(meta: &FileMeta) -> u64 {
149 meta.max_row_group_uncompressed_size
150 .max(meta.max_row_group_decoded_size)
151}
152
153struct RowGroupShape {
155 bytes: u64,
157 rows: u64,
159 num_row_groups: u64,
160}
161
162impl RowGroupShape {
163 fn of(meta: &FileMeta) -> Option<Self> {
164 let bytes = max_row_group_bytes(meta);
165 if bytes == 0 || meta.num_rows == 0 || meta.num_row_groups == 0 {
166 return None;
167 }
168 Some(Self {
169 bytes,
170 rows: (meta.num_rows / meta.num_row_groups).max(1),
171 num_row_groups: meta.num_row_groups,
172 })
173 }
174
175 fn row_width(&self) -> u64 {
176 self.bytes.div_ceil(self.rows)
177 }
178}
179
180fn output_memory_bytes(
194 inputs: &[FileHandle],
195 read_parallelism: usize,
196 retains_dedup_batch: bool,
197) -> u64 {
198 let shapes: Vec<_> = inputs
199 .iter()
200 .filter_map(|file| RowGroupShape::of(file.meta_ref()))
201 .collect();
202 let row_group_bytes = inputs.iter().fold(0u64, |total, file| {
203 total.saturating_add(max_row_group_bytes(file.meta_ref()))
204 });
205 if shapes.is_empty() {
206 return row_group_bytes;
207 }
208 let batch_rows =
212 estimate_batch_size(shapes.iter().map(|shape| (shape.rows, shape.bytes))) as u64;
213 let merges = inputs.len() > 1;
214 let batches_per_input = if read_parallelism > 1 && merges {
216 compaction_input_channel_size() as u64 + 2
217 } else {
218 1
219 };
220 let input_batch_bytes = shapes.iter().fold(0u64, |total, shape| {
221 let batch_bytes = batch_rows.min(shape.rows).saturating_mul(shape.row_width());
222 let file_bytes = shape.bytes.saturating_mul(shape.num_row_groups);
223 total.saturating_add(
224 batches_per_input
225 .saturating_mul(batch_bytes)
226 .min(file_bytes),
227 )
228 });
229 let output_batches =
233 MERGED_BATCH_CHANNEL_SIZE as u64 + 2 + u64::from(merges) + u64::from(retains_dedup_batch);
234 let rows_per_batch = if merges {
235 batch_rows
236 } else {
237 batch_rows.min(shapes[0].rows)
238 };
239 let downstream_bytes =
240 widest_rows_bytes(&shapes, output_batches.saturating_mul(rows_per_batch));
241
242 row_group_bytes
243 .saturating_add(input_batch_bytes)
244 .saturating_add(downstream_bytes)
245}
246
247fn widest_rows_bytes(shapes: &[RowGroupShape], rows: u64) -> u64 {
251 let mut by_width: Vec<_> = shapes.iter().collect();
252 by_width.sort_unstable_by_key(|shape| std::cmp::Reverse(shape.row_width()));
253 let mut remaining = rows;
254 let mut bytes = 0u64;
255 for shape in by_width {
256 let taken = remaining.min(shape.rows.saturating_mul(shape.num_row_groups));
257 bytes = bytes.saturating_add(taken.saturating_mul(shape.row_width()));
258 remaining -= taken;
259 if remaining == 0 {
260 break;
261 }
262 }
263 bytes
264}
265
266fn root(parents: &mut [usize], mut index: usize) -> usize {
268 while parents[index] != index {
269 parents[index] = parents[parents[index]];
270 index = parents[index];
271 }
272 index
273}
274
275#[cfg(test)]
276mod tests {
277 use store_api::storage::FileId;
278
279 use super::*;
280 use crate::compaction::test_util::{new_file_handle, new_file_handle_with_size_and_sequence};
281 use crate::test_util::new_noop_file_purger;
282
283 #[test]
284 fn test_estimated_memory_counts_decoded_row_groups() {
285 let file = |uncompressed, decoded| {
286 FileHandle::new(
287 crate::sst::file::FileMeta {
288 file_id: FileId::random(),
289 max_row_group_uncompressed_size: uncompressed,
290 max_row_group_decoded_size: decoded,
291 ..Default::default()
292 },
293 crate::test_util::new_noop_file_purger(),
294 )
295 };
296 let units = CompactionUnit::from_picker(PickerOutput {
299 outputs: vec![output(vec![file(1 << 20, 128 << 20), file(4 << 20, 0)])],
300 ..Default::default()
301 })
302 .unwrap();
303 assert_eq!(
304 (128 << 20) + (4 << 20),
305 units[0].estimated_memory_bytes(1, false)
306 );
307 }
308
309 fn output(inputs: Vec<FileHandle>) -> CompactionOutput {
311 CompactionOutput {
312 inputs,
313 output_level: 1,
314 filter_deleted: false,
315 output_time_range: None,
316 }
317 }
318
319 #[test]
320 fn test_compaction_unit_transitive_inputs() {
321 let files: Vec<_> = (0..3)
322 .map(|i| {
323 new_file_handle_with_size_and_sequence(FileId::random(), 0, 100, 0, 0, (i + 1) * 10)
324 })
325 .collect();
326 let units = CompactionUnit::from_picker(PickerOutput {
327 outputs: vec![
328 output(vec![files[0].clone()]),
329 output(vec![files[2].clone()]),
330 output(vec![files[1].clone()]),
331 output(vec![files[0].clone(), files[1].clone()]),
332 ],
333 time_window_size: 100,
334 max_file_size: Some(1024),
335 ..Default::default()
336 })
337 .unwrap();
338 assert_eq!(2, units.len());
339 assert_eq!(3, units[0].outputs.len());
340 assert_eq!(2, units[0].inputs.len());
341 assert_eq!(files[2].file_id(), units[1].inputs[0].file_id());
342 assert_eq!(30, units[0].estimated_input_bytes());
343 assert_eq!(30, units[1].estimated_input_bytes());
344 assert_eq!(Some(1024), units[0].max_file_size);
345 assert_eq!(100, units[1].time_window_size);
346 }
347
348 #[test]
349 fn test_compaction_unit_group_inherits_highest_output_priority() {
350 let files: Vec<_> = (0..3)
351 .map(|_| new_file_handle(FileId::random(), 0, 100, 0))
352 .collect();
353 let units = CompactionUnit::from_picker(PickerOutput {
354 outputs: [0, 1, 1, 2, 0]
355 .into_iter()
356 .map(|index| output(vec![files[index].clone()]))
357 .collect(),
358 ..Default::default()
359 })
360 .unwrap();
361 assert_eq!(
362 vec![files[0].file_id(), files[2].file_id(), files[1].file_id()],
363 units
364 .iter()
365 .map(|unit| unit.inputs[0].file_id())
366 .collect::<Vec<_>>()
367 );
368 assert_eq!(
369 vec![2, 1, 2],
370 units
371 .iter()
372 .map(|unit| unit.outputs.len())
373 .collect::<Vec<_>>()
374 );
375 }
376
377 #[test]
378 fn test_compaction_unit_expiration_precedes_merge_units() {
379 let files: Vec<_> = (0..3)
380 .map(|_| new_file_handle(FileId::random(), 0, 100, 0))
381 .collect();
382 let units = CompactionUnit::from_picker(PickerOutput {
383 outputs: vec![
384 output(vec![files[0].clone()]),
385 output(vec![files[1].clone()]),
386 ],
387 expired_ssts: vec![files[2].clone()],
388 ..Default::default()
389 })
390 .unwrap();
391
392 assert_eq!(3, units.len());
393 assert!(units[0].outputs.is_empty());
394 assert_eq!(files[2].file_id(), units[0].inputs[0].file_id());
395 assert_eq!(files[1].file_id(), units[1].inputs[0].file_id());
396 assert_eq!(files[0].file_id(), units[2].inputs[0].file_id());
397 }
398
399 #[test]
400 fn test_memory_follows_the_merge_of_each_output() {
401 const MIB: u64 = 1024 * 1024;
402 let file = |row_group_bytes: u64, rows_per_row_group: u64, num_row_groups: u64| {
403 FileHandle::new(
404 FileMeta {
405 file_id: FileId::random(),
406 max_row_group_uncompressed_size: row_group_bytes,
407 num_rows: rows_per_row_group * num_row_groups,
408 num_row_groups,
409 ..Default::default()
410 },
411 new_noop_file_purger(),
412 )
413 };
414 let unit = |outputs: Vec<CompactionOutput>| {
415 let mut units = CompactionUnit::from_picker(PickerOutput {
416 outputs,
417 ..Default::default()
418 })
419 .unwrap();
420 assert_eq!(1, units.len());
421 units.pop().unwrap()
422 };
423 let wide_groups = || file(50 * MIB, 100 * 1024, 10);
427 let (a, b, c) = (wide_groups(), wide_groups(), wide_groups());
428 let serial = 2 * 50 * MIB + 2 * 4 * MIB + 4 * MIB + 16 * MIB;
429 assert_eq!(
430 serial,
431 unit(vec![output(vec![a.clone(), b.clone()])]).estimated_memory_bytes(1, false)
432 );
433 assert_eq!(
435 serial + 4 * MIB,
436 unit(vec![output(vec![a.clone(), b.clone()])]).estimated_memory_bytes(1, true)
437 );
438 let parallel = 2 * 50 * MIB + 2 * 16 * MIB + 4 * MIB + 16 * MIB;
440 assert_eq!(
441 parallel,
442 unit(vec![output(vec![a.clone(), b.clone()])]).estimated_memory_bytes(4, false)
443 );
444 assert_eq!(
446 parallel,
447 unit(vec![output(vec![a.clone(), b]), output(vec![a, c])])
448 .estimated_memory_bytes(4, false)
449 );
450
451 let narrow_groups = || file(4 * MIB, 4, 1000);
454 let (d, e) = (narrow_groups(), narrow_groups());
455 assert_eq!(
456 2 * 4 * MIB + 2 * 16 * MIB + 64 * MIB + 4 * 64 * MIB,
457 unit(vec![output(vec![d.clone(), e])]).estimated_memory_bytes(4, false)
458 );
459 assert_eq!(
461 4 * MIB + 4 * MIB + 4 * 4 * MIB,
462 unit(vec![output(vec![d])]).estimated_memory_bytes(4, false)
463 );
464
465 let (wide_row, narrow_rows) = (file(MIB, 1, 1), file(MIB, 1024, 512));
468 assert_eq!(
469 2 * MIB + MIB + 64 * 1024 + MIB + 319 * 1024,
470 unit(vec![output(vec![wide_row, narrow_rows])]).estimated_memory_bytes(1, false)
471 );
472
473 let (f, g) = (file(8 * 1024, 1, 1), file(8 * 1024, 1, 1));
476 assert_eq!(
477 2 * 8 * 1024 + 2 * 8 * 1024 + 2 * 8 * 1024,
478 unit(vec![output(vec![f, g])]).estimated_memory_bytes(4, false)
479 );
480 }
481
482 #[test]
483 fn test_compaction_unit_expiration_inputs() {
484 let file = new_file_handle(FileId::random(), 0, 100, 0);
485 assert!(
486 CompactionUnit::from_picker(PickerOutput {
487 outputs: vec![output(vec![file.clone()])],
488 expired_ssts: vec![file.clone()],
489 ..Default::default()
490 })
491 .is_none()
492 );
493 let units = CompactionUnit::from_picker(PickerOutput {
494 expired_ssts: vec![file.clone(), file],
495 ..Default::default()
496 })
497 .unwrap();
498 assert_eq!(1, units.len());
499 assert_eq!(1, units[0].inputs.len());
500 assert!(units[0].outputs.is_empty());
501 assert_eq!(0, units[0].estimated_memory_bytes(1, false));
502 assert!(
503 CompactionUnit::from_picker(PickerOutput::default())
504 .unwrap()
505 .is_empty()
506 );
507 }
508}