1use std::collections::{HashMap, HashSet};
16use std::sync::Arc;
17
18use partition::expr::PartitionExpr;
19use snafu::{OptionExt, ResultExt, ensure};
20use store_api::storage::RegionId;
21
22use crate::error;
23pub use crate::error::{Error, Result};
24use crate::manifest::action::{RegionManifest, RemovedFilesRecord};
25
26pub struct RemapManifest {
28 old_manifests: HashMap<RegionId, RegionManifest>,
30 new_partition_exprs: HashMap<RegionId, PartitionExpr>,
32 region_mapping: HashMap<RegionId, Vec<RegionId>>,
34 new_manifests: HashMap<RegionId, RegionManifest>,
36}
37
38impl RemapManifest {
39 pub fn new(
40 old_manifests: HashMap<RegionId, RegionManifest>,
41 new_partition_exprs: HashMap<RegionId, PartitionExpr>,
42 region_mapping: HashMap<RegionId, Vec<RegionId>>,
43 ) -> Self {
44 Self {
45 old_manifests,
46 new_partition_exprs,
47 region_mapping,
48 new_manifests: HashMap::new(),
49 }
50 }
51
52 pub fn remap_manifests(&mut self) -> Result<RemapResult> {
57 self.initialize_new_manifests()?;
59
60 self.do_remap()?;
62
63 self.finalize_manifests()?;
65
66 let stats = self.compute_stats();
68 self.validate_result(&stats)?;
69
70 let new_manifests = std::mem::take(&mut self.new_manifests);
71
72 Ok(RemapResult {
73 new_manifests,
74 stats,
75 })
76 }
77
78 fn initialize_new_manifests(&mut self) -> Result<()> {
80 let mut new_manifests = HashMap::new();
81
82 let template_manifest = self
84 .old_manifests
85 .values()
86 .next()
87 .context(error::NoOldManifestsSnafu)?;
88 let template_metadata = (*template_manifest.metadata).clone();
89 let sst_format = template_manifest.sst_format;
90
91 for region_id in self.new_partition_exprs.keys() {
93 let mut new_metadata = template_metadata.clone();
95
96 new_metadata.region_id = *region_id;
97 let new_partition_expr = self
98 .new_partition_exprs
99 .get(region_id)
100 .context(error::MissingPartitionExprSnafu {
101 region_id: *region_id,
102 })?
103 .as_json_str()
104 .context(error::SerializePartitionExprSnafu)?;
105 new_metadata.partition_expr = Some(new_partition_expr);
106
107 let manifest = RegionManifest {
108 metadata: Arc::new(new_metadata),
109 files: HashMap::new(),
110 removed_files: RemovedFilesRecord::default(),
111 flushed_entry_id: 0,
112 flushed_sequence: 0,
113 committed_sequence: None,
114 manifest_version: 0,
115 truncated_entry_id: None,
116 compaction_time_window: None,
117 sst_format,
118 };
119
120 new_manifests.insert(*region_id, manifest);
121 }
122
123 self.new_manifests = new_manifests;
124
125 Ok(())
126 }
127
128 fn do_remap(&mut self) -> Result<()> {
130 for (&from_region_id, target_region_ids) in &self.region_mapping {
132 let from_manifest = self.old_manifests.get(&from_region_id).context(
134 error::MissingOldManifestSnafu {
135 region_id: from_region_id,
136 },
137 )?;
138
139 for &to_region_id in target_region_ids {
141 let target_manifest = self.new_manifests.get_mut(&to_region_id).context(
142 error::MissingNewManifestSnafu {
143 region_id: to_region_id,
144 },
145 )?;
146
147 Self::copy_files_to_region(from_manifest, target_manifest)?;
148 }
149 }
150
151 Ok(())
152 }
153
154 fn copy_files_to_region(
156 source_manifest: &RegionManifest,
157 target_manifest: &mut RegionManifest,
158 ) -> Result<()> {
159 for (file_id, file_meta) in &source_manifest.files {
160 let file_meta_clone = file_meta.clone();
161
162 use std::collections::hash_map::Entry;
165 match target_manifest.files.entry(*file_id) {
166 Entry::Vacant(e) => {
167 e.insert(file_meta_clone);
168 }
169 #[cfg(debug_assertions)]
170 Entry::Occupied(e) => {
171 Self::verify_file_consistency(e.get(), &file_meta_clone)?;
173 }
174 #[cfg(not(debug_assertions))]
175 Entry::Occupied(_) => {}
176 }
177 }
178
179 Ok(())
180 }
181
182 #[cfg(debug_assertions)]
184 fn verify_file_consistency(
185 existing: &crate::sst::file::FileMeta,
186 new: &crate::sst::file::FileMeta,
187 ) -> Result<()> {
188 ensure!(
192 existing.region_id == new.region_id,
193 error::InconsistentFileSnafu {
194 file_id: existing.file_id,
195 reason: "region_id mismatch",
196 }
197 );
198
199 ensure!(
200 existing.file_id == new.file_id,
201 error::InconsistentFileSnafu {
202 file_id: existing.file_id,
203 reason: "file_id mismatch",
204 }
205 );
206
207 ensure!(
208 existing.time_range == new.time_range,
209 error::InconsistentFileSnafu {
210 file_id: existing.file_id,
211 reason: "time_range mismatch",
212 }
213 );
214
215 ensure!(
216 existing.level == new.level,
217 error::InconsistentFileSnafu {
218 file_id: existing.file_id,
219 reason: "level mismatch",
220 }
221 );
222
223 ensure!(
224 existing.file_size == new.file_size,
225 error::InconsistentFileSnafu {
226 file_id: existing.file_id,
227 reason: "file_size mismatch",
228 }
229 );
230
231 ensure!(
232 existing.partition_expr == new.partition_expr,
233 error::InconsistentFileSnafu {
234 file_id: existing.file_id,
235 reason: "partition_expr mismatch",
236 }
237 );
238
239 Ok(())
240 }
241
242 fn finalize_manifests(&mut self) -> Result<()> {
244 for (region_id, manifest) in self.new_manifests.iter_mut() {
245 if let Some(previous_manifest) = self.old_manifests.get(region_id) {
246 manifest.flushed_entry_id = previous_manifest.flushed_entry_id;
247 manifest.flushed_sequence = previous_manifest.flushed_sequence;
248 manifest.manifest_version = previous_manifest.manifest_version;
249 manifest.truncated_entry_id = previous_manifest.truncated_entry_id;
250 manifest.compaction_time_window = previous_manifest.compaction_time_window;
251 manifest.committed_sequence = previous_manifest.committed_sequence;
252 } else {
253 manifest.flushed_entry_id = 0;
255 manifest.flushed_sequence = 0;
256 manifest.manifest_version = 0;
257 manifest.truncated_entry_id = None;
258 manifest.compaction_time_window = None;
259 manifest.committed_sequence = None;
260 }
261
262 manifest.removed_files = RemovedFilesRecord::default();
264 }
265
266 Ok(())
267 }
268
269 fn compute_stats(&self) -> RemapStats {
271 let mut files_per_region = HashMap::with_capacity(self.new_manifests.len());
272 let mut total_file_refs = 0;
273 let mut empty_regions = Vec::new();
274 let mut all_files = HashSet::new();
275
276 for (®ion_id, manifest) in &self.new_manifests {
277 let file_count = manifest.files.len();
278 files_per_region.insert(region_id, file_count);
279 total_file_refs += file_count;
280
281 if file_count == 0 {
282 empty_regions.push(region_id);
283 }
284
285 for file_id in manifest.files.keys() {
286 all_files.insert(*file_id);
287 }
288 }
289
290 RemapStats {
291 files_per_region,
292 total_file_refs,
293 empty_regions,
294 unique_files: all_files.len(),
295 }
296 }
297
298 fn validate_result(&self, stats: &RemapStats) -> Result<()> {
300 for region_id in self.new_partition_exprs.keys() {
302 ensure!(
303 self.new_manifests.contains_key(region_id),
304 error::MissingNewManifestSnafu {
305 region_id: *region_id
306 }
307 );
308 }
309
310 let mut old_unique_files = HashSet::new();
313 for manifest in self.old_manifests.values() {
314 for file_id in manifest.files.keys() {
315 old_unique_files.insert(*file_id);
316 }
317 }
318
319 ensure!(
320 stats.unique_files >= old_unique_files.len(),
321 error::FilesLostSnafu {
322 old_count: old_unique_files.len(),
323 new_count: stats.unique_files,
324 }
325 );
326
327 if !stats.empty_regions.is_empty() {
329 common_telemetry::warn!(
330 "Repartition resulted in {} empty regions: {:?}, new partition exprs: {:?}",
331 stats.empty_regions.len(),
332 stats.empty_regions,
333 self.new_partition_exprs.keys().collect::<Vec<_>>()
334 );
335 }
336
337 Ok(())
338 }
339}
340
341#[derive(Debug)]
343pub struct RemapResult {
344 pub new_manifests: HashMap<RegionId, RegionManifest>,
346 pub stats: RemapStats,
348}
349
350#[derive(Debug)]
352pub struct RemapStats {
353 pub files_per_region: HashMap<RegionId, usize>,
355 pub total_file_refs: usize,
357 pub empty_regions: Vec<RegionId>,
359 pub unique_files: usize,
361}
362
363#[cfg(test)]
364mod tests {
365 use std::collections::HashMap;
366 use std::num::NonZeroU64;
367 use std::sync::Arc;
368 use std::time::Duration;
369
370 use api::v1::SemanticType;
371 use datatypes::prelude::ConcreteDataType;
372 use datatypes::schema::ColumnSchema;
373 use datatypes::value::Value;
374 use partition::expr::{PartitionExpr, col};
375 use smallvec::SmallVec;
376 use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef};
377 use store_api::storage::{FileId, RegionId, SequenceNumber};
378
379 use super::*;
380 use crate::manifest::action::RegionManifest;
381 use crate::sst::FormatType;
382 use crate::sst::file::{FileMeta, FileTimeRange};
383 use crate::wal::EntryId;
384
385 fn create_region_metadata(region_id: RegionId) -> RegionMetadataRef {
387 let mut builder = RegionMetadataBuilder::new(region_id);
388 builder
389 .push_column_metadata(ColumnMetadata {
390 column_schema: ColumnSchema::new(
391 "ts",
392 ConcreteDataType::timestamp_millisecond_datatype(),
393 false,
394 ),
395 semantic_type: SemanticType::Timestamp,
396 column_id: 1,
397 })
398 .push_column_metadata(ColumnMetadata {
399 column_schema: ColumnSchema::new("pk", ConcreteDataType::int64_datatype(), false),
400 semantic_type: SemanticType::Tag,
401 column_id: 2,
402 })
403 .push_column_metadata(ColumnMetadata {
404 column_schema: ColumnSchema::new(
405 "val",
406 ConcreteDataType::float64_datatype(),
407 false,
408 ),
409 semantic_type: SemanticType::Field,
410 column_id: 3,
411 })
412 .primary_key(vec![2]);
413 Arc::new(builder.build().unwrap())
414 }
415
416 fn create_file_meta(
418 region_id: RegionId,
419 file_id: FileId,
420 partition_expr: Option<PartitionExpr>,
421 ) -> FileMeta {
422 FileMeta {
423 region_id,
424 file_id,
425 time_range: FileTimeRange::default(),
426 level: 0,
427 file_size: 1024,
428 available_indexes: SmallVec::new(),
429 index_file_size: 0,
430 index_file_id: None,
431 num_rows: 100,
432 num_row_groups: 1,
433 sequence: NonZeroU64::new(1),
434 partition_expr,
435 num_series: 1,
436 }
437 }
438
439 fn create_manifest(
441 region_id: RegionId,
442 num_files: usize,
443 partition_expr: Option<PartitionExpr>,
444 flushed_entry_id: EntryId,
445 flushed_sequence: SequenceNumber,
446 ) -> RegionManifest {
447 let mut files = HashMap::new();
448 for _ in 0..num_files {
449 let file_id = FileId::random();
450 let file_meta = create_file_meta(region_id, file_id, partition_expr.clone());
451 files.insert(file_id, file_meta);
452 }
453
454 RegionManifest {
455 metadata: create_region_metadata(region_id),
456 files,
457 removed_files: RemovedFilesRecord::default(),
458 flushed_entry_id,
459 flushed_sequence,
460 manifest_version: 1,
461 truncated_entry_id: None,
462 compaction_time_window: None,
463 committed_sequence: None,
464 sst_format: FormatType::PrimaryKey,
465 }
466 }
467
468 fn range_expr(col_name: &str, start: i64, end: i64) -> PartitionExpr {
470 col(col_name)
471 .gt_eq(Value::Int64(start))
472 .and(col(col_name).lt(Value::Int64(end)))
473 }
474
475 #[test]
476 fn test_simple_split() {
477 let old_region_id = RegionId::new(1, 1);
479 let new_region_id_1 = RegionId::new(1, 2);
480 let new_region_id_2 = RegionId::new(1, 3);
481
482 let old_expr = range_expr("x", 0, 100);
483 let new_expr_1 = range_expr("x", 0, 50);
484 let new_expr_2 = range_expr("x", 50, 100);
485
486 let old_manifest = create_manifest(old_region_id, 10, Some(old_expr.clone()), 100, 200);
487
488 let mut old_manifests = HashMap::new();
489 old_manifests.insert(old_region_id, old_manifest);
490
491 let mut new_partition_exprs = HashMap::new();
492 new_partition_exprs.insert(new_region_id_1, new_expr_1);
493 new_partition_exprs.insert(new_region_id_2, new_expr_2);
494
495 let mut region_mapping = HashMap::new();
497 region_mapping.insert(old_region_id, vec![new_region_id_1, new_region_id_2]);
498
499 let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
500
501 let result = remapper.remap_manifests().unwrap();
502
503 assert_eq!(result.new_manifests.len(), 2);
505 assert_eq!(result.new_manifests[&new_region_id_1].files.len(), 10);
506 assert_eq!(result.new_manifests[&new_region_id_2].files.len(), 10);
507 assert_eq!(result.stats.total_file_refs, 20);
508 assert_eq!(result.stats.unique_files, 10);
509 assert!(result.stats.empty_regions.is_empty());
510
511 for file_meta in result.new_manifests[&new_region_id_1].files.values() {
513 assert_eq!(file_meta.region_id, old_region_id);
514 }
515 for file_meta in result.new_manifests[&new_region_id_2].files.values() {
516 assert_eq!(file_meta.region_id, old_region_id);
517 }
518 }
519
520 #[test]
521 fn test_simple_merge() {
522 let old_region_id_1 = RegionId::new(1, 1);
524 let old_region_id_2 = RegionId::new(1, 2);
525 let new_region_id = RegionId::new(1, 3);
526
527 let old_expr_1 = range_expr("x", 0, 50);
528 let old_expr_2 = range_expr("x", 50, 100);
529 let new_expr = range_expr("x", 0, 100);
530
531 let manifest_1 = create_manifest(old_region_id_1, 5, Some(old_expr_1.clone()), 100, 200);
532 let manifest_2 = create_manifest(old_region_id_2, 5, Some(old_expr_2.clone()), 150, 250);
533
534 let mut old_manifests = HashMap::new();
535 old_manifests.insert(old_region_id_1, manifest_1);
536 old_manifests.insert(old_region_id_2, manifest_2);
537
538 let mut new_partition_exprs = HashMap::new();
539 new_partition_exprs.insert(new_region_id, new_expr);
540
541 let mut region_mapping = HashMap::new();
543 region_mapping.insert(old_region_id_1, vec![new_region_id]);
544 region_mapping.insert(old_region_id_2, vec![new_region_id]);
545
546 let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
547
548 let result = remapper.remap_manifests().unwrap();
549
550 assert_eq!(result.new_manifests.len(), 1);
552 assert_eq!(result.new_manifests[&new_region_id].files.len(), 10);
553 assert_eq!(result.stats.total_file_refs, 10);
554 assert_eq!(result.stats.unique_files, 10);
555 assert!(result.stats.empty_regions.is_empty());
556
557 let new_manifest = &result.new_manifests[&new_region_id];
559 assert_eq!(new_manifest.flushed_entry_id, 0);
560 assert_eq!(new_manifest.flushed_sequence, 0);
561 assert_eq!(new_manifest.manifest_version, 0);
562 assert_eq!(new_manifest.truncated_entry_id, None);
563 assert_eq!(new_manifest.compaction_time_window, None);
564 }
565
566 #[test]
567 fn test_metadata_preserved_for_existing_region() {
568 let old_region_id_1 = RegionId::new(1, 1);
570 let old_region_id_2 = RegionId::new(1, 2);
571 let old_region_id_3 = RegionId::new(1, 3);
572 let new_region_id = RegionId::new(1, 4);
573
574 let new_expr = range_expr("x", 0, 100);
575
576 let mut manifest_1 = create_manifest(old_region_id_1, 2, None, 10, 20);
577 manifest_1.truncated_entry_id = Some(5);
578 manifest_1.compaction_time_window = Some(Duration::from_secs(3600));
579
580 let mut manifest_2 = create_manifest(old_region_id_2, 2, None, 25, 15); manifest_2.truncated_entry_id = Some(20);
582 manifest_2.compaction_time_window = Some(Duration::from_secs(7200)); let manifest_3 = create_manifest(old_region_id_3, 2, None, 15, 30); let mut previous_manifest = create_manifest(new_region_id, 0, None, 200, 300);
586 previous_manifest.truncated_entry_id = Some(40);
587 previous_manifest.compaction_time_window = Some(Duration::from_secs(1800));
588 previous_manifest.manifest_version = 7;
589 let expected_flushed_entry_id = previous_manifest.flushed_entry_id;
590 let expected_flushed_sequence = previous_manifest.flushed_sequence;
591 let expected_truncated_entry_id = previous_manifest.truncated_entry_id;
592 let expected_compaction_window = previous_manifest.compaction_time_window;
593 let expected_manifest_version = previous_manifest.manifest_version;
594
595 let mut old_manifests = HashMap::new();
596 old_manifests.insert(old_region_id_1, manifest_1);
597 old_manifests.insert(old_region_id_2, manifest_2);
598 old_manifests.insert(old_region_id_3, manifest_3);
599 old_manifests.insert(new_region_id, previous_manifest);
600
601 let mut new_partition_exprs = HashMap::new();
602 new_partition_exprs.insert(new_region_id, new_expr);
603
604 let mut region_mapping = HashMap::new();
606 region_mapping.insert(old_region_id_1, vec![new_region_id]);
607 region_mapping.insert(old_region_id_2, vec![new_region_id]);
608 region_mapping.insert(old_region_id_3, vec![new_region_id]);
609
610 let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
611
612 let result = remapper.remap_manifests().unwrap();
613
614 let new_manifest = &result.new_manifests[&new_region_id];
615 assert_eq!(new_manifest.flushed_entry_id, expected_flushed_entry_id);
617 assert_eq!(new_manifest.flushed_sequence, expected_flushed_sequence);
618 assert_eq!(new_manifest.truncated_entry_id, expected_truncated_entry_id);
619 assert_eq!(
620 new_manifest.compaction_time_window,
621 expected_compaction_window
622 );
623 assert_eq!(new_manifest.manifest_version, expected_manifest_version);
624 }
625
626 #[test]
627 fn test_file_consistency_check() {
628 let old_region_id_1 = RegionId::new(1, 1);
630 let old_region_id_2 = RegionId::new(1, 2);
631 let new_region_id = RegionId::new(1, 3);
632
633 let new_expr = range_expr("x", 0, 100);
634
635 let shared_file_id = FileId::random();
637 let file_meta = create_file_meta(old_region_id_1, shared_file_id, None);
638
639 let mut manifest_1 = create_manifest(old_region_id_1, 0, None, 100, 200);
640 manifest_1.files.insert(shared_file_id, file_meta.clone());
641
642 let mut manifest_2 = create_manifest(old_region_id_2, 0, None, 100, 200);
643 manifest_2.files.insert(shared_file_id, file_meta);
644
645 let mut old_manifests = HashMap::new();
646 old_manifests.insert(old_region_id_1, manifest_1);
647 old_manifests.insert(old_region_id_2, manifest_2);
648
649 let mut new_partition_exprs = HashMap::new();
650 new_partition_exprs.insert(new_region_id, new_expr);
651
652 let mut region_mapping = HashMap::new();
654 region_mapping.insert(old_region_id_1, vec![new_region_id]);
655 region_mapping.insert(old_region_id_2, vec![new_region_id]);
656
657 let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
658
659 let result = remapper.remap_manifests().unwrap();
660
661 assert_eq!(result.new_manifests[&new_region_id].files.len(), 1);
663 assert_eq!(result.stats.total_file_refs, 1);
664 assert_eq!(result.stats.unique_files, 1);
665 }
666
667 #[test]
668 fn test_empty_regions() {
669 let old_region_id = RegionId::new(1, 1);
671 let new_region_id_1 = RegionId::new(1, 2);
672 let new_region_id_2 = RegionId::new(1, 3);
673
674 let old_expr = range_expr("x", 0, 50);
675 let new_expr_1 = range_expr("x", 0, 50);
676 let new_expr_2 = range_expr("x", 100, 200); let old_manifest = create_manifest(old_region_id, 5, Some(old_expr.clone()), 100, 200);
679
680 let mut old_manifests = HashMap::new();
681 old_manifests.insert(old_region_id, old_manifest);
682
683 let mut new_partition_exprs = HashMap::new();
684 new_partition_exprs.insert(new_region_id_1, new_expr_1);
685 new_partition_exprs.insert(new_region_id_2, new_expr_2);
686
687 let mut region_mapping = HashMap::new();
689 region_mapping.insert(old_region_id, vec![new_region_id_1]);
690
691 let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
692
693 let result = remapper.remap_manifests().unwrap();
694
695 assert_eq!(result.new_manifests[&new_region_id_1].files.len(), 5);
697 assert_eq!(result.new_manifests[&new_region_id_2].files.len(), 0);
698 assert_eq!(result.stats.empty_regions, vec![new_region_id_2]);
699 }
700
701 #[test]
702 fn test_n_to_m_complex_repartition() {
703 let old_region_1 = RegionId::new(1, 1);
705 let old_region_2 = RegionId::new(1, 2);
706 let new_region_1 = RegionId::new(1, 3);
707 let new_region_2 = RegionId::new(1, 4);
708 let new_region_3 = RegionId::new(1, 5);
709
710 let old_expr_1 = range_expr("u", 0, 100);
713 let old_expr_2 = range_expr("u", 100, 200);
714 let new_expr_1 = range_expr("u", 0, 50);
715 let new_expr_2 = range_expr("u", 50, 150);
716 let new_expr_3 = range_expr("u", 150, 250);
717
718 let manifest_1 = create_manifest(old_region_1, 3, Some(old_expr_1.clone()), 100, 200);
719 let manifest_2 = create_manifest(old_region_2, 4, Some(old_expr_2.clone()), 150, 250);
720
721 let mut old_manifests = HashMap::new();
722 old_manifests.insert(old_region_1, manifest_1);
723 old_manifests.insert(old_region_2, manifest_2);
724
725 let mut new_partition_exprs = HashMap::new();
726 new_partition_exprs.insert(new_region_1, new_expr_1);
727 new_partition_exprs.insert(new_region_2, new_expr_2);
728 new_partition_exprs.insert(new_region_3, new_expr_3);
729
730 let mut region_mapping = HashMap::new();
734 region_mapping.insert(old_region_1, vec![new_region_1, new_region_2]);
735 region_mapping.insert(old_region_2, vec![new_region_2, new_region_3]);
736
737 let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
738
739 let result = remapper.remap_manifests().unwrap();
740
741 assert_eq!(result.new_manifests.len(), 3);
742 assert_eq!(result.new_manifests[&new_region_1].files.len(), 3);
743 assert_eq!(result.new_manifests[&new_region_2].files.len(), 7); assert_eq!(result.new_manifests[&new_region_3].files.len(), 4);
745 assert_eq!(result.stats.total_file_refs, 14); assert_eq!(result.stats.unique_files, 7); }
748}