Skip to main content

mito2/
remap_manifest.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{HashMap, HashSet};
16use std::sync::Arc;
17
18use partition::expr::PartitionExpr;
19use snafu::{OptionExt, ResultExt, ensure};
20use store_api::storage::{FileId, RegionId};
21
22use crate::error;
23pub use crate::error::{Error, Result};
24use crate::manifest::action::{RegionManifest, RemovedFilesRecord};
25use crate::sst::file::FileFormat;
26
27/// Remaps file references from old region manifests to new region manifests.
28pub struct RemapManifest {
29    /// Old region manifests indexed by region ID
30    old_manifests: HashMap<RegionId, RegionManifest>,
31    /// New partition expressions indexed by region ID
32    new_partition_exprs: HashMap<RegionId, PartitionExpr>,
33    /// For each old region, which new regions should receive its files
34    region_mapping: HashMap<RegionId, Vec<RegionId>>,
35    /// Newly generated manifests for target regions
36    new_manifests: HashMap<RegionId, RegionManifest>,
37}
38
39impl RemapManifest {
40    pub fn new(
41        old_manifests: HashMap<RegionId, RegionManifest>,
42        new_partition_exprs: HashMap<RegionId, PartitionExpr>,
43        region_mapping: HashMap<RegionId, Vec<RegionId>>,
44    ) -> Self {
45        Self {
46            old_manifests,
47            new_partition_exprs,
48            region_mapping,
49            new_manifests: HashMap::new(),
50        }
51    }
52
53    /// Remaps manifests from old regions to new regions.
54    ///
55    /// Main entry point. It copies files from old regions to new regions based on
56    /// partition expression overlaps.
57    pub fn remap_manifests(&mut self) -> Result<RemapResult> {
58        // A region may only be remapped while it holds files it produced itself.
59        self.ensure_regions_own_their_files()?;
60
61        // initialize new manifests
62        self.initialize_new_manifests()?;
63
64        // remap files
65        self.do_remap()?;
66
67        // merge and set metadata for all new manifests
68        self.finalize_manifests()?;
69
70        // validate and compute statistics
71        let stats = self.compute_stats();
72        self.validate_result(&stats)?;
73
74        let new_manifests = std::mem::take(&mut self.new_manifests);
75
76        Ok(RemapResult {
77            new_manifests,
78            stats,
79        })
80    }
81
82    /// Rejects a merge while a participant holds a file another region produced.
83    ///
84    /// A reader drops the region predicate exactly when the region's expression equals the
85    /// file's (`ScanRegion::should_skip_region_partition`), so once a holder materializes a copy
86    /// under a new file id the same row sits in the shared file and in the copy, and publishing
87    /// both reads it twice.
88    ///
89    /// The operator resolves the refusal by hand: abort the repartition (a region in a staging
90    /// session is skipped by the compaction scheduler), compact, retry. Nothing triggers that
91    /// compaction automatically.
92    ///
93    /// A split is exempt: each target receives only that source's files and no target combines
94    /// copies, so the region predicate still keeps their rows apart.
95    ///
96    /// A file that records no creator is *not* exempt. It can still hold rows of both children of
97    /// an earlier split, so it proves nothing about provenance: if both children inherited it and
98    /// only one of them compacted, the copy and the inherited file both hold that child's rows and
99    /// a merge would publish them twice. The region has to materialise (a compaction stamps its
100    /// output) before a merge.
101    fn ensure_regions_own_their_files(&self) -> Result<()> {
102        if self.is_split() {
103            return Ok(());
104        }
105
106        let mut offenders = Vec::new();
107        for &from_region_id in self.region_mapping.keys() {
108            let from_manifest = self.old_manifests.get(&from_region_id).context(
109                error::MissingOldManifestSnafu {
110                    region_id: from_region_id,
111                },
112            )?;
113            collect_foreign_files(from_region_id, from_manifest, &mut offenders)?;
114        }
115        ensure!(
116            offenders.is_empty(),
117            error::ForeignFilePartitionExprSnafu {
118                offenders: describe_offenders(&offenders),
119            }
120        );
121
122        Ok(())
123    }
124
125    /// Whether this remap publishes every target from at most one source: the shape that is
126    /// exempt from [`Self::ensure_regions_own_their_files`], because no target combines two
127    /// sources' file sets.
128    ///
129    /// The predicate is stated per target, not per source count, and the pre-publication check of
130    /// the repartition procedure reads it from the same place
131    /// ([`store_api::region_engine::sources_sharing_a_target`]), so the two stages agree on every
132    /// shape. One source feeding several targets (a split), one source feeding one target (a
133    /// one-to-one repartition, which may still hold a file an ancestor created) and several
134    /// sources feeding disjoint targets all hand each target a single source's files: the shared
135    /// object is then filtered by that target's own expression, never recombined with a copy of
136    /// itself. Only a target fed by two or more distinct sources can see both an inherited object
137    /// and a copy materialized from it, so only that shape is checked.
138    fn is_split(&self) -> bool {
139        store_api::region_engine::every_target_has_a_single_source(&self.region_mapping)
140    }
141
142    /// Initializes empty manifests for all new regions.
143    fn initialize_new_manifests(&mut self) -> Result<()> {
144        let mut new_manifests = HashMap::new();
145
146        // Get any old manifest as template (they all share the same table schema)
147        let template_manifest = self
148            .old_manifests
149            .values()
150            .next()
151            .context(error::NoOldManifestsSnafu)?;
152        let template_metadata = (*template_manifest.metadata).clone();
153        let sst_format = template_manifest.sst_format;
154
155        // Create empty manifest for each new region
156        for region_id in self.new_partition_exprs.keys() {
157            // Derive region metadata from any old manifest as template
158            let mut new_metadata = template_metadata.clone();
159
160            new_metadata.region_id = *region_id;
161            let new_partition_expr = self
162                .new_partition_exprs
163                .get(region_id)
164                .context(error::MissingPartitionExprSnafu {
165                    region_id: *region_id,
166                })?
167                .as_json_str()
168                .context(error::SerializePartitionExprSnafu)?;
169            new_metadata.set_partition_expr(Some(new_partition_expr));
170
171            let manifest = RegionManifest {
172                metadata: Arc::new(new_metadata),
173                files: HashMap::new(),
174                removed_files: RemovedFilesRecord::default(),
175                flushed_entry_id: 0,
176                flushed_sequence: 0,
177                committed_sequence: None,
178                manifest_version: 0,
179                truncated_entry_id: None,
180                compaction_time_window: None,
181                sst_format,
182                append_mode: None,
183                pending_tails: Default::default(),
184                series_indexes: Default::default(),
185                series_window_seconds: None,
186                handoff_floors: Default::default(),
187            };
188
189            new_manifests.insert(*region_id, manifest);
190        }
191
192        self.new_manifests = new_manifests;
193
194        Ok(())
195    }
196
197    /// Remaps files from old regions to new regions according to the region mapping.
198    fn do_remap(&mut self) -> Result<()> {
199        // For each old region and its target new regions
200        for (&from_region_id, target_region_ids) in &self.region_mapping {
201            // Get old manifest
202            let from_manifest = self.old_manifests.get(&from_region_id).context(
203                error::MissingOldManifestSnafu {
204                    region_id: from_region_id,
205                },
206            )?;
207
208            // Copy files to all target new regions
209            for &to_region_id in target_region_ids {
210                let target_manifest = self.new_manifests.get_mut(&to_region_id).context(
211                    error::MissingNewManifestSnafu {
212                        region_id: to_region_id,
213                    },
214                )?;
215
216                Self::copy_files_to_region(from_manifest, target_manifest)?;
217            }
218        }
219
220        Ok(())
221    }
222
223    /// Copies files from a source region to a target region.
224    fn copy_files_to_region(
225        source_manifest: &RegionManifest,
226        target_manifest: &mut RegionManifest,
227    ) -> Result<()> {
228        ensure!(
229            (source_manifest.sst_format == crate::sst::FormatType::Narthex)
230                == (target_manifest.sst_format == crate::sst::FormatType::Narthex),
231            error::InvalidRequestSnafu {
232                region_id: target_manifest.metadata.region_id,
233                reason: "Cannot remap between Parquet and Narthex regions",
234            }
235        );
236        for (file_id, file_meta) in &source_manifest.files {
237            if let Some(existing) = target_manifest.files.get(file_id)
238                && source_manifest.sst_format == crate::sst::FormatType::Narthex
239            {
240                // Admission sequences may differ by logical region; physical
241                // ownership and object inventory must still agree in all builds.
242                let same_inventory = match (&existing.format, &file_meta.format) {
243                    (FileFormat::NarthexSamples(left), FileFormat::NarthexSamples(right)) => {
244                        left.manifest_size == right.manifest_size && left.parts == right.parts
245                    }
246                    _ => false,
247                };
248                ensure!(
249                    existing.region_id == file_meta.region_id && same_inventory,
250                    error::InconsistentFileSnafu {
251                        file_id: *file_id,
252                        reason: "narthex samples identity mismatch",
253                    }
254                );
255            }
256            let file_meta_clone = file_meta.clone();
257
258            // Insert or merge into target manifest
259            // Same file might be added from multiple overlapping old regions
260            use std::collections::hash_map::Entry;
261            match target_manifest.files.entry(*file_id) {
262                Entry::Vacant(e) => {
263                    e.insert(file_meta_clone);
264                }
265                #[cfg(debug_assertions)]
266                Entry::Occupied(e) => {
267                    // File already exists - verify it's the same physical file
268                    Self::verify_file_consistency(e.get(), &file_meta_clone)?;
269                }
270                #[cfg(not(debug_assertions))]
271                Entry::Occupied(_) => {}
272            }
273        }
274
275        // The destination builds its own series coverage after admitting the samples.
276        Ok(())
277    }
278
279    /// Verifies that two file metadata entries are consistent.
280    #[cfg(debug_assertions)]
281    fn verify_file_consistency(
282        existing: &crate::sst::file::FileMeta,
283        new: &crate::sst::file::FileMeta,
284    ) -> Result<()> {
285        // When the same file appears from multiple overlapping old regions,
286        // verify they are actually the same physical file with identical metadata
287
288        ensure!(
289            existing.region_id == new.region_id,
290            error::InconsistentFileSnafu {
291                file_id: existing.file_id,
292                reason: "region_id mismatch",
293            }
294        );
295
296        ensure!(
297            existing.file_id == new.file_id,
298            error::InconsistentFileSnafu {
299                file_id: existing.file_id,
300                reason: "file_id mismatch",
301            }
302        );
303
304        ensure!(
305            existing.time_range == new.time_range,
306            error::InconsistentFileSnafu {
307                file_id: existing.file_id,
308                reason: "time_range mismatch",
309            }
310        );
311
312        ensure!(
313            existing.level == new.level,
314            error::InconsistentFileSnafu {
315                file_id: existing.file_id,
316                reason: "level mismatch",
317            }
318        );
319
320        ensure!(
321            existing.file_size == new.file_size,
322            error::InconsistentFileSnafu {
323                file_id: existing.file_id,
324                reason: "file_size mismatch",
325            }
326        );
327
328        ensure!(
329            existing.partition_expr == new.partition_expr,
330            error::InconsistentFileSnafu {
331                file_id: existing.file_id,
332                reason: "partition_expr mismatch",
333            }
334        );
335
336        Ok(())
337    }
338
339    /// Finalizes manifests by merging metadata from source regions.
340    fn finalize_manifests(&mut self) -> Result<()> {
341        for (region_id, manifest) in self.new_manifests.iter_mut() {
342            if let Some(previous_manifest) = self.old_manifests.get(region_id) {
343                manifest.flushed_entry_id = previous_manifest.flushed_entry_id;
344                manifest.flushed_sequence = previous_manifest.flushed_sequence;
345                manifest.manifest_version = previous_manifest.manifest_version;
346                manifest.truncated_entry_id = previous_manifest.truncated_entry_id;
347                manifest.compaction_time_window = previous_manifest.compaction_time_window;
348                manifest.committed_sequence = previous_manifest.committed_sequence;
349            } else {
350                // new region
351                manifest.flushed_entry_id = 0;
352                manifest.flushed_sequence = 0;
353                manifest.manifest_version = 0;
354                manifest.truncated_entry_id = None;
355                manifest.compaction_time_window = None;
356                manifest.committed_sequence = None;
357            }
358
359            // removed_files are tracked by old manifests, don't copy
360            manifest.removed_files = RemovedFilesRecord::default();
361        }
362
363        Ok(())
364    }
365
366    /// Computes statistics about the remapping.
367    fn compute_stats(&self) -> RemapStats {
368        let mut files_per_region = HashMap::with_capacity(self.new_manifests.len());
369        let mut total_file_refs = 0;
370        let mut empty_regions = Vec::new();
371        let mut all_files = HashSet::new();
372
373        for (&region_id, manifest) in &self.new_manifests {
374            let file_count = manifest.files.len();
375            files_per_region.insert(region_id, file_count);
376            total_file_refs += file_count;
377
378            if file_count == 0 {
379                empty_regions.push(region_id);
380            }
381
382            for file_id in manifest.files.keys() {
383                all_files.insert(*file_id);
384            }
385        }
386
387        RemapStats {
388            files_per_region,
389            total_file_refs,
390            empty_regions,
391            unique_files: all_files.len(),
392        }
393    }
394
395    /// Validates the remapping result.
396    fn validate_result(&self, stats: &RemapStats) -> Result<()> {
397        // all new regions have manifests
398        for region_id in self.new_partition_exprs.keys() {
399            ensure!(
400                self.new_manifests.contains_key(region_id),
401                error::MissingNewManifestSnafu {
402                    region_id: *region_id
403                }
404            );
405        }
406
407        // no unique files were lost
408        // Count unique files in old manifests (files may be duplicated across regions)
409        let mut old_unique_files = HashSet::new();
410        for manifest in self.old_manifests.values() {
411            for file_id in manifest.files.keys() {
412                old_unique_files.insert(*file_id);
413            }
414        }
415
416        ensure!(
417            stats.unique_files >= old_unique_files.len(),
418            error::FilesLostSnafu {
419                old_count: old_unique_files.len(),
420                new_count: stats.unique_files,
421            }
422        );
423
424        // 3. Log warning about empty regions (not an error)
425        if !stats.empty_regions.is_empty() {
426            common_telemetry::warn!(
427                "Repartition resulted in {} empty regions: {:?}, new partition exprs: {:?}",
428                stats.empty_regions.len(),
429                stats.empty_regions,
430                self.new_partition_exprs.keys().collect::<Vec<_>>()
431            );
432        }
433
434        Ok(())
435    }
436}
437
438/// Checks that `region_id` holds only the files it created itself.
439///
440/// This is the single comparison the ownership rule is made of, factored out of
441/// [`RemapManifest::ensure_regions_own_their_files`] so a caller can run it *before* anything is
442/// staged: it reads one persisted manifest and returns an error naming the region and every
443/// offending file. It does not need a staging region, does not write and has no side effects.
444///
445/// A split is exempt at *group* scope: the caller that runs this early only asks the sources that
446/// take part in a merge, because a one-to-many split hands each target only that source's files
447/// and combines no copies.
448pub(crate) fn ensure_region_owns_its_files(
449    region_id: RegionId,
450    manifest: &RegionManifest,
451) -> Result<()> {
452    let mut offenders = Vec::new();
453    collect_foreign_files(region_id, manifest, &mut offenders)?;
454    ensure!(
455        offenders.is_empty(),
456        error::ForeignFilePartitionExprSnafu {
457            offenders: describe_offenders(&offenders),
458        }
459    );
460
461    Ok(())
462}
463
464/// Collects the `(region, file)` pairs of `manifest` whose recorded creator is not `region_id`'s
465/// expression.
466fn collect_foreign_files(
467    region_id: RegionId,
468    manifest: &RegionManifest,
469    offenders: &mut Vec<(RegionId, FileId)>,
470) -> Result<()> {
471    let region_expr =
472        crate::region::parse_partition_expr(manifest.metadata.partition_expr.as_deref())?;
473    for (file_id, file_meta) in &manifest.files {
474        // Exact match, including the case where the region serves an expression and the file
475        // records none: such a file may hold rows either child of an earlier split wrote, so it
476        // is not evidence that this region produced it.
477        if file_meta.partition_expr.as_deref() != region_expr.as_ref() {
478            offenders.push((region_id, *file_id));
479        }
480    }
481
482    Ok(())
483}
484
485/// Number of offending files an error message lists before it summarizes the rest.
486const MAX_LISTED_OFFENDERS: usize = 8;
487
488/// Renders the offending `(region, file)` pairs an error names.
489///
490/// A repartition can be refused by many files, so the message lists the first
491/// [`MAX_LISTED_OFFENDERS`] and only counts the rest: it stays bounded while every listed entry
492/// keeps the region and the file the operator has to settle.
493fn describe_offenders(offenders: &[(RegionId, FileId)]) -> String {
494    let mut message = offenders
495        .iter()
496        .take(MAX_LISTED_OFFENDERS)
497        .map(|(region_id, file_id)| {
498            format!("region {region_id} holds file {file_id} that another region created")
499        })
500        .collect::<Vec<_>>()
501        .join("; ");
502    if let Some(rest) = offenders
503        .len()
504        .checked_sub(MAX_LISTED_OFFENDERS)
505        .filter(|rest| *rest > 0)
506    {
507        message.push_str(&format!("; and {rest} more"));
508    }
509    message
510}
511
512/// Result of manifest remapping, including new manifests and statistics.
513#[derive(Debug)]
514pub struct RemapResult {
515    /// New manifests for all new regions
516    pub new_manifests: HashMap<RegionId, RegionManifest>,
517    /// Statistics about the remapping
518    pub stats: RemapStats,
519}
520
521/// Statistical information about the manifest remapping.
522#[derive(Debug)]
523pub struct RemapStats {
524    /// Number of files per region in new manifests
525    pub files_per_region: HashMap<RegionId, usize>,
526    /// Total number of file references created across all new regions
527    pub total_file_refs: usize,
528    /// Regions that received no files (potentially empty after repartition)
529    pub empty_regions: Vec<RegionId>,
530    /// Total number of unique files processed
531    pub unique_files: usize,
532}
533
534#[cfg(test)]
535mod tests {
536    use std::collections::HashMap;
537    use std::num::NonZeroU64;
538    use std::sync::Arc;
539    use std::time::Duration;
540
541    use api::v1::SemanticType;
542    use datatypes::prelude::ConcreteDataType;
543    use datatypes::schema::ColumnSchema;
544    use datatypes::value::Value;
545    use partition::expr::{PartitionExpr, col};
546    use smallvec::SmallVec;
547    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef};
548    use store_api::storage::{FileId, RegionId, SequenceNumber};
549
550    use super::*;
551    use crate::manifest::action::RegionManifest;
552    use crate::sst::FormatType;
553    use crate::sst::file::{FileMeta, FileTimeRange};
554    use crate::wal::EntryId;
555
556    /// Helper to create a basic region metadata for testing.
557    fn create_region_metadata(region_id: RegionId) -> RegionMetadataRef {
558        let mut builder = RegionMetadataBuilder::new(region_id);
559        builder
560            .push_column_metadata(ColumnMetadata {
561                column_schema: ColumnSchema::new(
562                    "ts",
563                    ConcreteDataType::timestamp_millisecond_datatype(),
564                    false,
565                ),
566                semantic_type: SemanticType::Timestamp,
567                column_id: 1,
568            })
569            .push_column_metadata(ColumnMetadata {
570                column_schema: ColumnSchema::new("pk", ConcreteDataType::int64_datatype(), false),
571                semantic_type: SemanticType::Tag,
572                column_id: 2,
573            })
574            .push_column_metadata(ColumnMetadata {
575                column_schema: ColumnSchema::new(
576                    "val",
577                    ConcreteDataType::float64_datatype(),
578                    false,
579                ),
580                semantic_type: SemanticType::Field,
581                column_id: 3,
582            })
583            .primary_key(vec![2]);
584        Arc::new(builder.build().unwrap())
585    }
586
587    /// Helper to create a FileMeta for testing.
588    fn create_file_meta(
589        region_id: RegionId,
590        file_id: FileId,
591        partition_expr: Option<PartitionExpr>,
592    ) -> FileMeta {
593        FileMeta {
594            region_id,
595            file_id,
596            time_range: FileTimeRange::default(),
597            level: 0,
598            file_size: 1024,
599            max_row_group_uncompressed_size: 1024,
600            available_indexes: SmallVec::new(),
601            indexes: Default::default(),
602            index_file_size: 0,
603            index_version: 0,
604            num_rows: 100,
605            num_row_groups: 1,
606            sequence: NonZeroU64::new(1),
607            partition_expr: partition_expr.map(Into::into),
608            num_series: 1,
609            ..Default::default()
610        }
611    }
612
613    /// Helper to create a manifest with specified number of files.
614    fn create_manifest(
615        region_id: RegionId,
616        num_files: usize,
617        partition_expr: Option<PartitionExpr>,
618        flushed_entry_id: EntryId,
619        flushed_sequence: SequenceNumber,
620    ) -> RegionManifest {
621        let mut files = HashMap::new();
622        for _ in 0..num_files {
623            let file_id = FileId::random();
624            let file_meta = create_file_meta(region_id, file_id, partition_expr.clone());
625            files.insert(file_id, file_meta.into());
626        }
627
628        // The files are stamped with `partition_expr`, so the region serving that same
629        // expression produced them: a remap requires exactly that.
630        let mut metadata = (*create_region_metadata(region_id)).clone();
631        metadata.set_partition_expr(
632            partition_expr
633                .as_ref()
634                .map(|expr| expr.as_json_str().unwrap()),
635        );
636
637        RegionManifest {
638            metadata: Arc::new(metadata),
639            files,
640            removed_files: RemovedFilesRecord::default(),
641            flushed_entry_id,
642            flushed_sequence,
643            manifest_version: 1,
644            truncated_entry_id: None,
645            compaction_time_window: None,
646            committed_sequence: None,
647            sst_format: FormatType::PrimaryKey,
648            append_mode: None,
649            pending_tails: Default::default(),
650            series_indexes: Default::default(),
651            series_window_seconds: None,
652            handoff_floors: Default::default(),
653        }
654    }
655
656    #[rstest::rstest]
657    #[case(FormatType::Narthex, FormatType::Flat)]
658    #[case(FormatType::PrimaryKey, FormatType::Narthex)]
659    #[case(FormatType::Flat, FormatType::PrimaryKey)]
660    #[test]
661    fn test_remap_storage_format(
662        #[case] source_format: FormatType,
663        #[case] target_format: FormatType,
664    ) {
665        let mut source = create_manifest(RegionId::new(1, 0), 0, None, 0, 0);
666        let mut target = create_manifest(RegionId::new(1, 1), 0, None, 0, 0);
667        source.sst_format = source_format;
668        target.sst_format = target_format;
669        let result = RemapManifest::copy_files_to_region(&source, &mut target);
670        if source_format == FormatType::Narthex || target_format == FormatType::Narthex {
671            assert!(
672                result
673                    .unwrap_err()
674                    .to_string()
675                    .contains("Cannot remap between")
676            );
677        } else {
678            result.unwrap();
679        }
680        assert!(target.files.is_empty());
681        assert_eq!(target.sst_format, target_format);
682    }
683
684    /// Helper to create partition expression: col >= start AND col < end
685    fn range_expr(col_name: &str, start: i64, end: i64) -> PartitionExpr {
686        col(col_name)
687            .gt_eq(Value::Int64(start))
688            .and(col(col_name).lt(Value::Int64(end)))
689    }
690
691    #[test]
692    fn test_simple_split() {
693        // One region [0, 100) splits into two regions: [0, 50) and [50, 100)
694        let old_region_id = RegionId::new(1, 1);
695        let new_region_id_1 = RegionId::new(1, 2);
696        let new_region_id_2 = RegionId::new(1, 3);
697
698        let old_expr = range_expr("x", 0, 100);
699        let new_expr_1 = range_expr("x", 0, 50);
700        let new_expr_2 = range_expr("x", 50, 100);
701
702        let old_manifest = create_manifest(old_region_id, 10, Some(old_expr.clone()), 100, 200);
703
704        let mut old_manifests = HashMap::new();
705        old_manifests.insert(old_region_id, old_manifest);
706
707        let mut new_partition_exprs = HashMap::new();
708        new_partition_exprs.insert(new_region_id_1, new_expr_1);
709        new_partition_exprs.insert(new_region_id_2, new_expr_2);
710
711        // Direct mapping: old region -> both new regions
712        let mut region_mapping = HashMap::new();
713        region_mapping.insert(old_region_id, vec![new_region_id_1, new_region_id_2]);
714
715        let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
716
717        let result = remapper.remap_manifests().unwrap();
718
719        // Both new regions should have all 10 files
720        assert_eq!(result.new_manifests.len(), 2);
721        assert_eq!(result.new_manifests[&new_region_id_1].files.len(), 10);
722        assert_eq!(result.new_manifests[&new_region_id_2].files.len(), 10);
723        assert_eq!(result.stats.total_file_refs, 20);
724        assert_eq!(result.stats.unique_files, 10);
725        assert!(result.stats.empty_regions.is_empty());
726
727        // Verify FileMeta is immutable - region_id stays as old_region_id
728        for file_meta in result.new_manifests[&new_region_id_1].files.values() {
729            assert_eq!(file_meta.region_id, old_region_id);
730        }
731        for file_meta in result.new_manifests[&new_region_id_2].files.values() {
732            assert_eq!(file_meta.region_id, old_region_id);
733        }
734    }
735
736    #[test]
737    fn test_rejects_files_another_region_produced() {
738        // Both participants of the merge hold a file the whole-domain source created: merging
739        // them could publish a row of it twice once a holder materializes its own copy, and the
740        // refusal has to name every offending region and file.
741        let old_region_id_1 = RegionId::new(1, 1);
742        let old_region_id_2 = RegionId::new(1, 2);
743        let new_region_id = RegionId::new(1, 3);
744
745        let creator_expr = range_expr("x", 0, 100);
746        let mut old_manifests = HashMap::new();
747        let mut file_ids = Vec::new();
748        for old_region_id in [old_region_id_1, old_region_id_2] {
749            let own_expr = if old_region_id == old_region_id_1 {
750                range_expr("x", 0, 50)
751            } else {
752                range_expr("x", 50, 100)
753            };
754            let mut old_manifest = create_manifest(old_region_id, 1, Some(own_expr), 100, 200);
755            let file_id = *old_manifest.files.keys().next().unwrap();
756            old_manifest.files.insert(
757                file_id,
758                create_file_meta(old_region_id, file_id, Some(creator_expr.clone())).into(),
759            );
760            file_ids.push(file_id);
761            old_manifests.insert(old_region_id, old_manifest);
762        }
763
764        let mut new_partition_exprs = HashMap::new();
765        new_partition_exprs.insert(new_region_id, range_expr("x", 0, 100));
766
767        let mut region_mapping = HashMap::new();
768        region_mapping.insert(old_region_id_1, vec![new_region_id]);
769        region_mapping.insert(old_region_id_2, vec![new_region_id]);
770
771        let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
772
773        let err = remapper.remap_manifests().unwrap_err();
774        assert!(
775            matches!(&err, Error::ForeignFilePartitionExpr { .. }),
776            "unexpected error: {err:?}"
777        );
778        let message = err.to_string();
779        for (region_id, file_id) in [
780            (old_region_id_1, file_ids[0]),
781            (old_region_id_2, file_ids[1]),
782        ] {
783            assert!(message.contains(&region_id.to_string()), "{message}");
784            assert!(message.contains(&file_id.to_string()), "{message}");
785        }
786    }
787
788    #[test]
789    fn test_one_to_one_repartition_is_exempt() {
790        // A one-to-one repartition reuses the region id and may still hold a file an ancestor
791        // created (a split installs the child's expression without rewriting the files it
792        // clones). No target receives files from two sources, so nothing is combined and the
793        // remap publishes the file under the region's own expression: the shape is exempt, which
794        // is what keeps the pre-publication check and this guard from disagreeing.
795        let old_region_id = RegionId::new(1, 1);
796        let own_expr = range_expr("x", 0, 50);
797        let ancestor_expr = range_expr("x", 0, 100);
798
799        let mut old_manifest = create_manifest(old_region_id, 1, Some(own_expr.clone()), 100, 200);
800        let file_id = *old_manifest.files.keys().next().unwrap();
801        old_manifest.files.insert(
802            file_id,
803            create_file_meta(old_region_id, file_id, Some(ancestor_expr)).into(),
804        );
805
806        let mut remapper = RemapManifest::new(
807            HashMap::from([(old_region_id, old_manifest)]),
808            HashMap::from([(old_region_id, own_expr)]),
809            HashMap::from([(old_region_id, vec![old_region_id])]),
810        );
811        let result = remapper.remap_manifests().unwrap();
812        assert_eq!(result.new_manifests[&old_region_id].files.len(), 1);
813        assert!(
814            result.new_manifests[&old_region_id]
815                .files
816                .contains_key(&file_id)
817        );
818    }
819
820    #[test]
821    fn test_target_fed_by_two_sources_is_still_checked() {
822        // The predicate is per target, not per source count: here each source feeds a target of
823        // its own *and* the shared one. The shared target combines both file sets, so the guard
824        // runs and reports the file the two sources would publish twice.
825        let left_region_id = RegionId::new(1, 1);
826        let right_region_id = RegionId::new(1, 2);
827        let shared_region_id = RegionId::new(1, 3);
828        let left_only_region_id = RegionId::new(1, 4);
829
830        let left_expr = range_expr("x", 0, 50);
831        let right_expr = range_expr("x", 50, 100);
832        let shared_expr = range_expr("x", 0, 100);
833
834        let mut left_manifest =
835            create_manifest(left_region_id, 1, Some(left_expr.clone()), 100, 200);
836        let left_file = *left_manifest.files.keys().next().unwrap();
837        left_manifest.files.insert(
838            left_file,
839            create_file_meta(left_region_id, left_file, Some(shared_expr.clone())).into(),
840        );
841        let right_manifest = create_manifest(right_region_id, 1, Some(right_expr), 100, 200);
842
843        let mut remapper = RemapManifest::new(
844            HashMap::from([
845                (left_region_id, left_manifest),
846                (right_region_id, right_manifest),
847            ]),
848            HashMap::from([
849                (shared_region_id, shared_expr),
850                (left_only_region_id, left_expr),
851            ]),
852            HashMap::from([
853                (left_region_id, vec![shared_region_id, left_only_region_id]),
854                (right_region_id, vec![shared_region_id]),
855            ]),
856        );
857        let err = remapper.remap_manifests().unwrap_err();
858        assert!(
859            matches!(&err, Error::ForeignFilePartitionExpr { .. }),
860            "unexpected error: {err:?}"
861        );
862        let message = err.to_string();
863        assert!(message.contains(&left_region_id.to_string()), "{message}");
864        assert!(message.contains(&left_file.to_string()), "{message}");
865    }
866
867    #[test]
868    fn test_early_check_needs_no_staging_region() {
869        // `handle_remap` runs this predicate when the instruction asks for validation only, i.e.
870        // before any route is published and therefore before the region enters staging: it reads
871        // the ordinary manifest and reports the offenders it finds there.
872        let region_id = RegionId::new(1, 1);
873        let own_expr = range_expr("x", 0, 50);
874        let mut manifest = create_manifest(region_id, 1, Some(own_expr), 100, 200);
875        ensure_region_owns_its_files(region_id, &manifest).unwrap();
876
877        // A file another region created: the early check refuses it exactly like the remap does.
878        let foreign_expr = range_expr("x", 0, 100);
879        let file_id = *manifest.files.keys().next().unwrap();
880        manifest.files.insert(
881            file_id,
882            create_file_meta(region_id, file_id, Some(foreign_expr)).into(),
883        );
884
885        let err = ensure_region_owns_its_files(region_id, &manifest).unwrap_err();
886        assert!(
887            matches!(&err, Error::ForeignFilePartitionExpr { .. }),
888            "unexpected error: {err:?}"
889        );
890        let message = err.to_string();
891        assert!(message.contains(&region_id.to_string()), "{message}");
892        assert!(message.contains(&file_id.to_string()), "{message}");
893    }
894
895    #[test]
896    fn test_early_check_is_not_exempt_for_a_split_source() {
897        // The shape exemption belongs to the repartition procedure, which asks only about the
898        // sources of a target that two sources feed: a split maps every target from that single
899        // source, so the procedure never asks, while the per-region predicate itself - the one a
900        // checked source is judged by - reports such a file. Keeping the exemption out of this
901        // predicate is what makes the pre-publication check as strict as the remap-time guard.
902        let old_region_id = RegionId::new(1, 1);
903        let new_region_id_1 = RegionId::new(1, 2);
904        let new_region_id_2 = RegionId::new(1, 3);
905
906        let own_expr = range_expr("x", 50, 100);
907        let ancestor_expr = range_expr("x", 0, 100);
908        let mut old_manifest = create_manifest(old_region_id, 1, Some(own_expr), 100, 200);
909        let file_id = *old_manifest.files.keys().next().unwrap();
910        old_manifest.files.insert(
911            file_id,
912            create_file_meta(old_region_id, file_id, Some(ancestor_expr)).into(),
913        );
914
915        // The split itself is accepted: both children inherit the file and each keeps its own
916        // part of it visible through its own predicate.
917        let mut remapper = RemapManifest::new(
918            HashMap::from([(old_region_id, old_manifest.clone())]),
919            HashMap::from([
920                (new_region_id_1, range_expr("x", 50, 75)),
921                (new_region_id_2, range_expr("x", 75, 100)),
922            ]),
923            HashMap::from([(old_region_id, vec![new_region_id_1, new_region_id_2])]),
924        );
925        remapper.remap_manifests().unwrap();
926
927        // The predicate a merge source is checked with reports the very same file.
928        let err = ensure_region_owns_its_files(old_region_id, &old_manifest).unwrap_err();
929        assert!(
930            matches!(&err, Error::ForeignFilePartitionExpr { .. }),
931            "unexpected error: {err:?}"
932        );
933        assert!(err.to_string().contains(&file_id.to_string()), "{err}");
934    }
935
936    #[test]
937    fn test_split_is_exempt_from_the_foreign_file_rule() {
938        // The source serves [50, 100) and holds the file an ancestor [0, 100) region created.
939        // The split hands that object to both targets — [50, 75) and [75, 100), which is a real
940        // partition of the source — and stays exempt: each target keeps only its own part of the
941        // object visible through its own predicate, and no target combines file sets.
942        let old_region_id = RegionId::new(1, 1);
943        let new_region_id_1 = RegionId::new(1, 2);
944        let new_region_id_2 = RegionId::new(1, 3);
945
946        let source_expr = range_expr("x", 50, 100);
947        let mut old_manifest = create_manifest(old_region_id, 1, Some(source_expr), 100, 200);
948        let file_id = *old_manifest.files.keys().next().unwrap();
949        old_manifest.files.insert(
950            file_id,
951            // The file a wider [0, 100) region created, so the target domains are inside it.
952            create_file_meta(old_region_id, file_id, Some(range_expr("x", 0, 100))).into(),
953        );
954
955        let mut old_manifests = HashMap::new();
956        old_manifests.insert(old_region_id, old_manifest);
957
958        let left_expr = range_expr("x", 50, 75);
959        let right_expr = range_expr("x", 75, 100);
960        let mut new_partition_exprs = HashMap::new();
961        new_partition_exprs.insert(new_region_id_1, left_expr);
962        new_partition_exprs.insert(new_region_id_2, right_expr);
963
964        let mut region_mapping = HashMap::new();
965        region_mapping.insert(old_region_id, vec![new_region_id_1, new_region_id_2]);
966
967        let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
968
969        let result = remapper.remap_manifests().unwrap();
970        // Both targets inherit the shared object, so the exemption has to be what lets the pair
971        // through: the source's own file is foreign to it (creator [0, 100)).
972        for region_id in [new_region_id_1, new_region_id_2] {
973            let manifest = &result.new_manifests[&region_id];
974            assert_eq!(
975                vec![file_id],
976                manifest.files.keys().copied().collect::<Vec<_>>()
977            );
978            // The targets' expressions are strict parts of the source interval, so their union
979            // covers it and neither is the ancestry of the other.
980            let target_expr =
981                crate::region::parse_partition_expr(manifest.metadata.partition_expr.as_deref())
982                    .unwrap()
983                    .expect("a split target serves an expression");
984            assert_ne!(target_expr, range_expr("x", 50, 100));
985        }
986        assert_eq!(2, result.stats.total_file_refs);
987        assert_eq!(1, result.stats.unique_files);
988    }
989
990    #[test]
991    fn test_legacy_files_without_a_creator_are_rejected_by_a_merge() {
992        // Files written before the expression was recorded carry no creator, which proves
993        // nothing about provenance: such a file can hold rows of both children of an earlier
994        // split. The merge is refused; the region materialises first (a compaction stamps its
995        // output) exactly like it does for a file whose creator belongs to another region. A
996        // split stays exempt, so the first repartition of an upgraded table still works.
997        let old_region_id_1 = RegionId::new(1, 1);
998        let old_region_id_2 = RegionId::new(1, 2);
999        let new_region_id = RegionId::new(1, 3);
1000
1001        let mut old_manifests = HashMap::new();
1002        let mut file_ids = Vec::new();
1003        for (old_region_id, expr) in [
1004            (old_region_id_1, range_expr("x", 0, 50)),
1005            (old_region_id_2, range_expr("x", 50, 100)),
1006        ] {
1007            let mut old_manifest = create_manifest(old_region_id, 1, Some(expr), 100, 200);
1008            let file_id = *old_manifest.files.keys().next().unwrap();
1009            old_manifest.files.insert(
1010                file_id,
1011                create_file_meta(old_region_id, file_id, None).into(),
1012            );
1013            file_ids.push((old_region_id, file_id));
1014            old_manifests.insert(old_region_id, old_manifest);
1015        }
1016
1017        let mut new_partition_exprs = HashMap::new();
1018        new_partition_exprs.insert(new_region_id, range_expr("x", 0, 100));
1019
1020        let mut region_mapping = HashMap::new();
1021        region_mapping.insert(old_region_id_1, vec![new_region_id]);
1022        region_mapping.insert(old_region_id_2, vec![new_region_id]);
1023
1024        let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
1025        let err = remapper.remap_manifests().unwrap_err();
1026        assert!(
1027            matches!(&err, Error::ForeignFilePartitionExpr { .. }),
1028            "an unstamped file must not be exempt from the rule: {err:?}"
1029        );
1030        let message = err.to_string();
1031        for (region_id, file_id) in file_ids {
1032            assert!(message.contains(&region_id.to_string()), "{message}");
1033            assert!(message.contains(&file_id.to_string()), "{message}");
1034        }
1035    }
1036
1037    #[test]
1038    fn test_merge_rejects_self_stamped_sibling_and_unstamped_sibling() {
1039        // The reviewer's shape: one child of an earlier split compacted, so it holds a file it
1040        // stamped itself; its sibling still holds the unstamped ancestor object. Merging them
1041        // would publish the compacted child's rows twice — once from its own file, once from the
1042        // ancestor object the sibling inherited — so the unstamped file has to be an offender.
1043        let left_region_id = RegionId::new(1, 1);
1044        let right_region_id = RegionId::new(1, 2);
1045        let merged_region_id = RegionId::new(1, 3);
1046
1047        let left_expr = range_expr("x", 0, 50);
1048        let mut left_manifest =
1049            create_manifest(left_region_id, 1, Some(left_expr.clone()), 100, 200);
1050        let left_file = *left_manifest.files.keys().next().unwrap();
1051        // The left child materialised: its compaction output is stamped with its own expression.
1052        left_manifest.files.insert(
1053            left_file,
1054            create_file_meta(left_region_id, left_file, Some(left_expr)).into(),
1055        );
1056
1057        let right_expr = range_expr("x", 50, 100);
1058        let mut right_manifest = create_manifest(right_region_id, 1, Some(right_expr), 100, 200);
1059        let right_file = *right_manifest.files.keys().next().unwrap();
1060        // The right child still holds the ancestor's object, which records no creator.
1061        right_manifest.files.insert(
1062            right_file,
1063            create_file_meta(right_region_id, right_file, None).into(),
1064        );
1065
1066        let mut old_manifests = HashMap::new();
1067        old_manifests.insert(left_region_id, left_manifest);
1068        old_manifests.insert(right_region_id, right_manifest);
1069
1070        let mut new_partition_exprs = HashMap::new();
1071        new_partition_exprs.insert(merged_region_id, range_expr("x", 0, 100));
1072
1073        let mut region_mapping = HashMap::new();
1074        region_mapping.insert(left_region_id, vec![merged_region_id]);
1075        region_mapping.insert(right_region_id, vec![merged_region_id]);
1076
1077        let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
1078        let err = remapper.remap_manifests().unwrap_err();
1079        assert!(
1080            matches!(&err, Error::ForeignFilePartitionExpr { .. }),
1081            "unexpected error: {err:?}"
1082        );
1083        let message = err.to_string();
1084        // Only the unstamped file is an offender: the self-stamped one belongs to its region.
1085        assert!(message.contains(&right_file.to_string()), "{message}");
1086        assert!(!message.contains(&left_file.to_string()), "{message}");
1087    }
1088
1089    #[test]
1090    fn test_refusal_message_lists_a_bounded_number_of_offenders() {
1091        // A merge can be refused by many files; the message keeps the per-file detail for the
1092        // first `MAX_LISTED_OFFENDERS` and only counts the rest, so it cannot grow without bound.
1093        // The shape has to be one the guard runs on, i.e. a target fed by two sources.
1094        let old_region_id = RegionId::new(1, 1);
1095        let sibling_region_id = RegionId::new(1, 3);
1096        let new_region_id = RegionId::new(1, 2);
1097        let offender_count = MAX_LISTED_OFFENDERS + 5;
1098
1099        let mut old_manifest =
1100            create_manifest(old_region_id, 0, Some(range_expr("x", 0, 50)), 100, 200);
1101        let mut file_ids = Vec::new();
1102        for _ in 0..offender_count {
1103            let file_id = FileId::random();
1104            old_manifest.files.insert(
1105                file_id,
1106                create_file_meta(old_region_id, file_id, Some(range_expr("x", 0, 100))).into(),
1107            );
1108            file_ids.push(file_id);
1109        }
1110        // The sibling holds only its own file, so every offender comes from the region above.
1111        let sibling_manifest = create_manifest(
1112            sibling_region_id,
1113            1,
1114            Some(range_expr("x", 50, 100)),
1115            100,
1116            200,
1117        );
1118
1119        let mut old_manifests = HashMap::new();
1120        old_manifests.insert(old_region_id, old_manifest);
1121        old_manifests.insert(sibling_region_id, sibling_manifest);
1122
1123        let mut new_partition_exprs = HashMap::new();
1124        new_partition_exprs.insert(new_region_id, range_expr("x", 0, 100));
1125
1126        let mut region_mapping = HashMap::new();
1127        region_mapping.insert(old_region_id, vec![new_region_id]);
1128        region_mapping.insert(sibling_region_id, vec![new_region_id]);
1129
1130        let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
1131        let message = remapper.remap_manifests().unwrap_err().to_string();
1132        // The manifest is a map, so which files the message lists is not ordered; what matters
1133        // is that it lists exactly `MAX_LISTED_OFFENDERS` of them and only counts the rest.
1134        let listed = file_ids
1135            .iter()
1136            .filter(|file_id| message.contains(&file_id.to_string()))
1137            .count();
1138        assert_eq!(
1139            MAX_LISTED_OFFENDERS, listed,
1140            "the message has to list exactly {MAX_LISTED_OFFENDERS} offenders: {message}"
1141        );
1142        assert!(
1143            message.contains("; and 5 more"),
1144            "the message has to summarize the rest by count: {message}"
1145        );
1146    }
1147
1148    #[test]
1149    fn test_simple_merge() {
1150        // Two regions [0, 50) and [50, 100) merge into one region [0, 100)
1151        let old_region_id_1 = RegionId::new(1, 1);
1152        let old_region_id_2 = RegionId::new(1, 2);
1153        let new_region_id = RegionId::new(1, 3);
1154
1155        let old_expr_1 = range_expr("x", 0, 50);
1156        let old_expr_2 = range_expr("x", 50, 100);
1157        let new_expr = range_expr("x", 0, 100);
1158
1159        let manifest_1 = create_manifest(old_region_id_1, 5, Some(old_expr_1.clone()), 100, 200);
1160        let manifest_2 = create_manifest(old_region_id_2, 5, Some(old_expr_2.clone()), 150, 250);
1161
1162        let mut old_manifests = HashMap::new();
1163        old_manifests.insert(old_region_id_1, manifest_1);
1164        old_manifests.insert(old_region_id_2, manifest_2);
1165
1166        let mut new_partition_exprs = HashMap::new();
1167        new_partition_exprs.insert(new_region_id, new_expr);
1168
1169        // Direct mapping: both old regions -> same new region
1170        let mut region_mapping = HashMap::new();
1171        region_mapping.insert(old_region_id_1, vec![new_region_id]);
1172        region_mapping.insert(old_region_id_2, vec![new_region_id]);
1173
1174        let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
1175
1176        let result = remapper.remap_manifests().unwrap();
1177
1178        // New region should have all 10 files
1179        assert_eq!(result.new_manifests.len(), 1);
1180        assert_eq!(result.new_manifests[&new_region_id].files.len(), 10);
1181        assert_eq!(result.stats.total_file_refs, 10);
1182        assert_eq!(result.stats.unique_files, 10);
1183        assert!(result.stats.empty_regions.is_empty());
1184
1185        // Verify metadata falls back to defaults when no prior manifest exists for the region
1186        let new_manifest = &result.new_manifests[&new_region_id];
1187        assert_eq!(new_manifest.flushed_entry_id, 0);
1188        assert_eq!(new_manifest.flushed_sequence, 0);
1189        assert_eq!(new_manifest.manifest_version, 0);
1190        assert_eq!(new_manifest.truncated_entry_id, None);
1191        assert_eq!(new_manifest.compaction_time_window, None);
1192    }
1193
1194    #[test]
1195    fn test_metadata_preserved_for_existing_region() {
1196        // Test that metadata is preserved when a previous manifest exists for the same region id
1197        let old_region_id_1 = RegionId::new(1, 1);
1198        let old_region_id_2 = RegionId::new(1, 2);
1199        let old_region_id_3 = RegionId::new(1, 3);
1200        let new_region_id = RegionId::new(1, 4);
1201
1202        let new_expr = range_expr("x", 0, 100);
1203
1204        let mut manifest_1 = create_manifest(old_region_id_1, 2, None, 10, 20);
1205        manifest_1.truncated_entry_id = Some(5);
1206        manifest_1.compaction_time_window = Some(Duration::from_secs(3600));
1207
1208        let mut manifest_2 = create_manifest(old_region_id_2, 2, None, 25, 15); // Higher entry_id, lower sequence
1209        manifest_2.truncated_entry_id = Some(20);
1210        manifest_2.compaction_time_window = Some(Duration::from_secs(7200)); // Larger window
1211
1212        let manifest_3 = create_manifest(old_region_id_3, 2, None, 15, 30); // Lower entry_id, higher sequence
1213        let mut previous_manifest = create_manifest(new_region_id, 0, None, 200, 300);
1214        previous_manifest.truncated_entry_id = Some(40);
1215        previous_manifest.compaction_time_window = Some(Duration::from_secs(1800));
1216        previous_manifest.manifest_version = 7;
1217        let expected_flushed_entry_id = previous_manifest.flushed_entry_id;
1218        let expected_flushed_sequence = previous_manifest.flushed_sequence;
1219        let expected_truncated_entry_id = previous_manifest.truncated_entry_id;
1220        let expected_compaction_window = previous_manifest.compaction_time_window;
1221        let expected_manifest_version = previous_manifest.manifest_version;
1222
1223        let mut old_manifests = HashMap::new();
1224        old_manifests.insert(old_region_id_1, manifest_1);
1225        old_manifests.insert(old_region_id_2, manifest_2);
1226        old_manifests.insert(old_region_id_3, manifest_3);
1227        old_manifests.insert(new_region_id, previous_manifest);
1228
1229        let mut new_partition_exprs = HashMap::new();
1230        new_partition_exprs.insert(new_region_id, new_expr);
1231
1232        // Direct mapping: all old regions -> same new region
1233        let mut region_mapping = HashMap::new();
1234        region_mapping.insert(old_region_id_1, vec![new_region_id]);
1235        region_mapping.insert(old_region_id_2, vec![new_region_id]);
1236        region_mapping.insert(old_region_id_3, vec![new_region_id]);
1237
1238        let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
1239
1240        let result = remapper.remap_manifests().unwrap();
1241
1242        let new_manifest = &result.new_manifests[&new_region_id];
1243        // Should reuse metadata from previous manifest of the same region id
1244        assert_eq!(new_manifest.flushed_entry_id, expected_flushed_entry_id);
1245        assert_eq!(new_manifest.flushed_sequence, expected_flushed_sequence);
1246        assert_eq!(new_manifest.truncated_entry_id, expected_truncated_entry_id);
1247        assert_eq!(
1248            new_manifest.compaction_time_window,
1249            expected_compaction_window
1250        );
1251        assert_eq!(new_manifest.manifest_version, expected_manifest_version);
1252    }
1253
1254    #[test]
1255    fn test_file_consistency_check() {
1256        // Test that duplicate files are verified for consistency
1257        let old_region_id_1 = RegionId::new(1, 1);
1258        let old_region_id_2 = RegionId::new(1, 2);
1259        let new_region_id = RegionId::new(1, 3);
1260
1261        let new_expr = range_expr("x", 0, 100);
1262
1263        // Create manifests with same file (overlapping regions)
1264        let shared_file_id = FileId::random();
1265        let file_meta = create_file_meta(old_region_id_1, shared_file_id, None);
1266
1267        let mut manifest_1 = create_manifest(old_region_id_1, 0, None, 100, 200);
1268        manifest_1
1269            .files
1270            .insert(shared_file_id, file_meta.clone().into());
1271
1272        let mut manifest_2 = create_manifest(old_region_id_2, 0, None, 100, 200);
1273        manifest_2.files.insert(shared_file_id, file_meta.into());
1274
1275        let mut old_manifests = HashMap::new();
1276        old_manifests.insert(old_region_id_1, manifest_1);
1277        old_manifests.insert(old_region_id_2, manifest_2);
1278
1279        let mut new_partition_exprs = HashMap::new();
1280        new_partition_exprs.insert(new_region_id, new_expr);
1281
1282        // Direct mapping: both old regions -> same new region
1283        let mut region_mapping = HashMap::new();
1284        region_mapping.insert(old_region_id_1, vec![new_region_id]);
1285        region_mapping.insert(old_region_id_2, vec![new_region_id]);
1286
1287        let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
1288
1289        let result = remapper.remap_manifests().unwrap();
1290
1291        // Should succeed - same file is consistent
1292        assert_eq!(result.new_manifests[&new_region_id].files.len(), 1);
1293        assert_eq!(result.stats.total_file_refs, 1);
1294        assert_eq!(result.stats.unique_files, 1);
1295    }
1296
1297    #[test]
1298    fn test_empty_regions() {
1299        // Test that empty regions are detected and logged (but not an error)
1300        let old_region_id = RegionId::new(1, 1);
1301        let new_region_id_1 = RegionId::new(1, 2);
1302        let new_region_id_2 = RegionId::new(1, 3);
1303
1304        let old_expr = range_expr("x", 0, 50);
1305        let new_expr_1 = range_expr("x", 0, 50);
1306        let new_expr_2 = range_expr("x", 100, 200); // No overlap with old region
1307
1308        let old_manifest = create_manifest(old_region_id, 5, Some(old_expr.clone()), 100, 200);
1309
1310        let mut old_manifests = HashMap::new();
1311        old_manifests.insert(old_region_id, old_manifest);
1312
1313        let mut new_partition_exprs = HashMap::new();
1314        new_partition_exprs.insert(new_region_id_1, new_expr_1);
1315        new_partition_exprs.insert(new_region_id_2, new_expr_2);
1316
1317        // Direct mapping: old region -> new region 1 only (region 2 is isolated)
1318        let mut region_mapping = HashMap::new();
1319        region_mapping.insert(old_region_id, vec![new_region_id_1]);
1320
1321        let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
1322
1323        let result = remapper.remap_manifests().unwrap();
1324
1325        // Region 2 should be empty
1326        assert_eq!(result.new_manifests[&new_region_id_1].files.len(), 5);
1327        assert_eq!(result.new_manifests[&new_region_id_2].files.len(), 0);
1328        assert_eq!(result.stats.empty_regions, vec![new_region_id_2]);
1329    }
1330
1331    #[test]
1332    fn test_n_to_m_complex_repartition() {
1333        // Test complex N-to-M transition: 2 old regions -> 3 new regions
1334        let old_region_1 = RegionId::new(1, 1);
1335        let old_region_2 = RegionId::new(1, 2);
1336        let new_region_1 = RegionId::new(1, 3);
1337        let new_region_2 = RegionId::new(1, 4);
1338        let new_region_3 = RegionId::new(1, 5);
1339
1340        // Old: [0, 100), [100, 200)
1341        // New: [0, 50), [50, 150), [150, 250)
1342        let old_expr_1 = range_expr("u", 0, 100);
1343        let old_expr_2 = range_expr("u", 100, 200);
1344        let new_expr_1 = range_expr("u", 0, 50);
1345        let new_expr_2 = range_expr("u", 50, 150);
1346        let new_expr_3 = range_expr("u", 150, 250);
1347
1348        let manifest_1 = create_manifest(old_region_1, 3, Some(old_expr_1.clone()), 100, 200);
1349        let manifest_2 = create_manifest(old_region_2, 4, Some(old_expr_2.clone()), 150, 250);
1350
1351        let mut old_manifests = HashMap::new();
1352        old_manifests.insert(old_region_1, manifest_1);
1353        old_manifests.insert(old_region_2, manifest_2);
1354
1355        let mut new_partition_exprs = HashMap::new();
1356        new_partition_exprs.insert(new_region_1, new_expr_1);
1357        new_partition_exprs.insert(new_region_2, new_expr_2);
1358        new_partition_exprs.insert(new_region_3, new_expr_3);
1359
1360        // Direct mapping:
1361        // old region 1 -> new regions 1, 2
1362        // old region 2 -> new regions 2, 3
1363        let mut region_mapping = HashMap::new();
1364        region_mapping.insert(old_region_1, vec![new_region_1, new_region_2]);
1365        region_mapping.insert(old_region_2, vec![new_region_2, new_region_3]);
1366
1367        let mut remapper = RemapManifest::new(old_manifests, new_partition_exprs, region_mapping);
1368
1369        let result = remapper.remap_manifests().unwrap();
1370
1371        assert_eq!(result.new_manifests.len(), 3);
1372        assert_eq!(result.new_manifests[&new_region_1].files.len(), 3);
1373        assert_eq!(result.new_manifests[&new_region_2].files.len(), 7); // 3 + 4
1374        assert_eq!(result.new_manifests[&new_region_3].files.len(), 4);
1375        assert_eq!(result.stats.total_file_refs, 14); // 3 + 7 + 4
1376        assert_eq!(result.stats.unique_files, 7); // 3 + 4 unique
1377    }
1378}