Skip to main content

meta_srv/procedure/repartition/
plan.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::cmp::Ordering;
16
17use common_meta::rpc::router::RegionRoute;
18use partition::expr::PartitionExpr;
19use serde::{Deserialize, Deserializer, Serialize};
20use snafu::ResultExt;
21use store_api::storage::{RegionId, RegionNumber, TableId};
22
23use crate::error::{self, Result};
24use crate::procedure::repartition::group::GroupId;
25
26/// Metadata describing a source region involved in the plan.
27///
28/// Source regions may represent either an existing partitioned region or the
29/// default region of an unpartitioned table.
30#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
31pub enum SourceRegionDescriptor {
32    /// A regular partitioned source region.
33    Partitioned {
34        /// The region id of the source region.
35        region_id: RegionId,
36        /// The partition expression of the source region.
37        partition_expr: PartitionExpr,
38    },
39    /// The default source region of an unpartitioned table.
40    Default {
41        /// The region id of the default source region.
42        region_id: RegionId,
43    },
44}
45
46impl<'de> Deserialize<'de> for SourceRegionDescriptor {
47    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
48    where
49        D: Deserializer<'de>,
50    {
51        #[derive(Deserialize)]
52        #[serde(deny_unknown_fields)]
53        struct PartitionedSourceRegionDescriptor {
54            region_id: RegionId,
55            partition_expr: PartitionExpr,
56        }
57
58        #[derive(Deserialize)]
59        #[serde(untagged)]
60        enum SourceRegionDescriptorRepr {
61            Tagged(SourceRegionDescriptorTaggedRepr),
62            Legacy(PartitionedSourceRegionDescriptor),
63        }
64
65        #[derive(Deserialize)]
66        enum SourceRegionDescriptorTaggedRepr {
67            Partitioned {
68                region_id: RegionId,
69                partition_expr: PartitionExpr,
70            },
71            Default {
72                region_id: RegionId,
73            },
74        }
75
76        match SourceRegionDescriptorRepr::deserialize(deserializer)? {
77            SourceRegionDescriptorRepr::Tagged(SourceRegionDescriptorTaggedRepr::Partitioned {
78                region_id,
79                partition_expr,
80            }) => Ok(Self::Partitioned {
81                region_id,
82                partition_expr,
83            }),
84            SourceRegionDescriptorRepr::Tagged(SourceRegionDescriptorTaggedRepr::Default {
85                region_id,
86            }) => Ok(Self::Default { region_id }),
87            SourceRegionDescriptorRepr::Legacy(descriptor) => Ok(Self::Partitioned {
88                region_id: descriptor.region_id,
89                partition_expr: descriptor.partition_expr,
90            }),
91        }
92    }
93}
94
95impl SourceRegionDescriptor {
96    /// Creates a partitioned source region descriptor.
97    pub fn partitioned(region_id: RegionId, partition_expr: PartitionExpr) -> Self {
98        Self::Partitioned {
99            region_id,
100            partition_expr,
101        }
102    }
103
104    /// Returns the region id of this source descriptor.
105    pub fn region_id(&self) -> RegionId {
106        match self {
107            Self::Partitioned { region_id, .. } => *region_id,
108            Self::Default { region_id } => *region_id,
109        }
110    }
111
112    /// Returns the partition expression if this source is partitioned.
113    pub fn partition_expr(&self) -> Option<&PartitionExpr> {
114        match self {
115            Self::Partitioned { partition_expr, .. } => Some(partition_expr),
116            Self::Default { .. } => None,
117        }
118    }
119
120    /// Returns true if this source descriptor matches the route partition expression.
121    pub fn matches_route_expr(&self, route_expr: &str) -> Result<bool> {
122        match self {
123            Self::Partitioned { partition_expr, .. } => {
124                let expected = partition_expr
125                    .as_json_str()
126                    .context(error::SerializePartitionExprSnafu)?;
127                Ok(route_expr == expected)
128            }
129            Self::Default { .. } => Ok(route_expr.is_empty()),
130        }
131    }
132
133    /// Returns the route partition expression to restore during rollback.
134    pub fn route_expr_for_rollback(&self) -> Result<String> {
135        match self {
136            Self::Partitioned { partition_expr, .. } => partition_expr
137                .as_json_str()
138                .context(error::SerializePartitionExprSnafu),
139            Self::Default { .. } => Ok(String::new()),
140        }
141    }
142}
143
144/// Metadata describing a target region involved in the plan.
145#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
146pub struct TargetRegionDescriptor {
147    /// The region id of the target region.
148    pub region_id: RegionId,
149    /// The partition expression of the target region.
150    pub partition_expr: PartitionExpr,
151}
152
153/// A plan entry for the region allocation phase, describing source regions
154/// and target partition expressions before allocation.
155#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
156pub struct AllocationPlanEntry {
157    /// The group id for this plan entry.
158    pub group_id: GroupId,
159    /// Source region descriptors involved in the plan.
160    pub source_regions: Vec<SourceRegionDescriptor>,
161    /// The target partition expressions for the new or changed regions.
162    pub target_partition_exprs: Vec<PartitionExpr>,
163    /// For each `source_regions[k]`, the corresponding vector contains global
164    /// `target_partition_exprs` that overlap with it.
165    pub transition_map: Vec<Vec<usize>>,
166}
167
168impl AllocationPlanEntry {
169    /// Returns the target partitions that need a new region.
170    pub(super) fn targets_to_allocate(&self) -> impl ExactSizeIterator<Item = &PartitionExpr> {
171        self.target_partition_exprs
172            .iter()
173            .skip(self.source_regions.len())
174    }
175}
176
177/// A plan entry for the dispatch phase after region allocation,
178/// with concrete source and target region descriptors.
179#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
180pub struct RepartitionPlanEntry {
181    /// The group id for this plan entry.
182    pub group_id: GroupId,
183    /// The source region descriptors involved in the plan.
184    pub source_regions: Vec<SourceRegionDescriptor>,
185    /// The target region descriptors involved in the plan.
186    pub target_regions: Vec<TargetRegionDescriptor>,
187    /// The region ids of the allocated regions.
188    pub allocated_region_ids: Vec<RegionId>,
189    /// The region ids of the regions that are pending deallocation.
190    pub pending_deallocate_region_ids: Vec<RegionId>,
191    /// For each `source_regions[k]`, the corresponding vector contains global
192    /// `target_regions` that overlap with it.
193    pub transition_map: Vec<Vec<usize>>,
194    /// Pre-staging target routes persisted for parent rollback and recovery.
195    #[serde(default)]
196    pub original_target_routes: Vec<RegionRoute>,
197}
198
199impl RepartitionPlanEntry {
200    /// Returns the target regions that are newly allocated.
201    pub(crate) fn allocate_regions(&self) -> Vec<&TargetRegionDescriptor> {
202        self.target_regions
203            .iter()
204            .filter(|r| self.allocated_region_ids.contains(&r.region_id))
205            .collect()
206    }
207}
208
209/// Converts an allocation plan to a repartition plan.
210///
211/// Converts an [`AllocationPlanEntry`] (which contains abstract region allocation intents)
212/// into a [`RepartitionPlanEntry`] with concrete source and target region descriptors,
213/// plus records information on which regions are newly allocated and/or pending deallocation.
214///
215/// # Returns
216///
217/// A [`Result`] containing the [`RepartitionPlanEntry`] describing exactly the source regions,
218/// the target regions (including any that need to be newly allocated), and transition mappings.
219///
220/// # Notes
221/// - If new regions are needed, their region ids are constructed using `table_id` and incrementing
222///   from `next_region_number`.
223/// - For each target, associates the correct region descriptor; for new regions, the region id
224///   is assigned sequentially.
225pub fn convert_allocation_plan_to_repartition_plan(
226    table_id: TableId,
227    next_region_number: &mut RegionNumber,
228    plan: &AllocationPlanEntry,
229) -> RepartitionPlanEntry {
230    let AllocationPlanEntry {
231        group_id,
232        source_regions,
233        target_partition_exprs,
234        transition_map,
235    } = plan;
236    match source_regions.len().cmp(&target_partition_exprs.len()) {
237        Ordering::Less => {
238            // requires to allocate regions
239            let pending_allocate_target_partition_exprs = plan
240                .targets_to_allocate()
241                .map(|target_partition_expr| {
242                    let desc = TargetRegionDescriptor {
243                        region_id: RegionId::new(table_id, *next_region_number),
244                        partition_expr: target_partition_expr.clone(),
245                    };
246                    *next_region_number += 1;
247                    desc
248                })
249                .collect::<Vec<_>>();
250
251            let allocated_region_ids = pending_allocate_target_partition_exprs
252                .iter()
253                .map(|rd| rd.region_id)
254                .collect::<Vec<_>>();
255
256            let target_regions = source_regions
257                .iter()
258                .zip(target_partition_exprs.iter())
259                .map(
260                    |(source_region, target_partition_expr)| TargetRegionDescriptor {
261                        region_id: source_region.region_id(),
262                        partition_expr: target_partition_expr.clone(),
263                    },
264                )
265                .chain(pending_allocate_target_partition_exprs)
266                .collect::<Vec<_>>();
267
268            RepartitionPlanEntry {
269                group_id: *group_id,
270                source_regions: source_regions.clone(),
271                target_regions,
272                allocated_region_ids,
273                pending_deallocate_region_ids: vec![],
274                transition_map: transition_map.clone(),
275                original_target_routes: vec![],
276            }
277        }
278        Ordering::Equal => {
279            let target_regions = source_regions
280                .iter()
281                .zip(target_partition_exprs.iter())
282                .map(
283                    |(source_region, target_partition_expr)| TargetRegionDescriptor {
284                        region_id: source_region.region_id(),
285                        partition_expr: target_partition_expr.clone(),
286                    },
287                )
288                .collect::<Vec<_>>();
289
290            RepartitionPlanEntry {
291                group_id: *group_id,
292                source_regions: source_regions.clone(),
293                target_regions,
294                allocated_region_ids: vec![],
295                pending_deallocate_region_ids: vec![],
296                transition_map: transition_map.clone(),
297                original_target_routes: vec![],
298            }
299        }
300        Ordering::Greater => {
301            // requires to deallocate regions
302            let target_regions = source_regions
303                .iter()
304                .take(target_partition_exprs.len())
305                .zip(target_partition_exprs.iter())
306                .map(
307                    |(source_region, target_partition_expr)| TargetRegionDescriptor {
308                        region_id: source_region.region_id(),
309                        partition_expr: target_partition_expr.clone(),
310                    },
311                )
312                .collect::<Vec<_>>();
313
314            let pending_deallocate_region_ids = source_regions
315                .iter()
316                .skip(target_partition_exprs.len())
317                .map(|source_region| source_region.region_id())
318                .collect::<Vec<_>>();
319
320            RepartitionPlanEntry {
321                group_id: *group_id,
322                source_regions: source_regions.clone(),
323                target_regions,
324                allocated_region_ids: vec![],
325                pending_deallocate_region_ids,
326                transition_map: transition_map.clone(),
327                original_target_routes: vec![],
328            }
329        }
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use store_api::storage::RegionId;
336    use uuid::Uuid;
337
338    use super::*;
339    use crate::procedure::repartition::test_util::range_expr;
340
341    fn create_region_descriptor(
342        table_id: TableId,
343        region_number: u32,
344        col: &str,
345        start: i64,
346        end: i64,
347    ) -> SourceRegionDescriptor {
348        SourceRegionDescriptor::partitioned(
349            RegionId::new(table_id, region_number),
350            range_expr(col, start, end),
351        )
352    }
353
354    #[test]
355    fn test_source_region_descriptor_deserializes_legacy_partitioned_shape() {
356        let table_id = 1024;
357        let region_id = RegionId::new(table_id, 1);
358        let partition_expr = range_expr("x", 0, 100);
359        let legacy_json = serde_json::json!({
360            "region_id": region_id,
361            "partition_expr": partition_expr,
362        });
363
364        let descriptor: SourceRegionDescriptor = serde_json::from_value(legacy_json).unwrap();
365
366        assert_eq!(
367            descriptor,
368            SourceRegionDescriptor::partitioned(region_id, partition_expr)
369        );
370    }
371
372    #[test]
373    fn test_source_region_descriptor_rejects_legacy_default_shape() {
374        let region_id = RegionId::new(1024, 1);
375        let default_json = serde_json::json!({
376            "region_id": region_id,
377        });
378
379        let err = serde_json::from_value::<SourceRegionDescriptor>(default_json).unwrap_err();
380
381        assert!(err.to_string().contains("data did not match any variant"));
382    }
383
384    #[test]
385    fn test_source_region_descriptor_roundtrip_tagged_partitioned_shape() {
386        let region_id = RegionId::new(1024, 1);
387        let partition_expr = range_expr("x", 0, 100);
388        let descriptor = SourceRegionDescriptor::partitioned(region_id, partition_expr.clone());
389
390        let value = serde_json::to_value(&descriptor).unwrap();
391        let decoded = serde_json::from_value::<SourceRegionDescriptor>(value.clone()).unwrap();
392
393        assert_eq!(
394            value,
395            serde_json::json!({
396                "Partitioned": {
397                    "region_id": region_id,
398                    "partition_expr": partition_expr,
399                }
400            })
401        );
402        assert_eq!(decoded, descriptor);
403    }
404
405    #[test]
406    fn test_source_region_descriptor_roundtrip_tagged_default_shape() {
407        let region_id = RegionId::new(1024, 1);
408        let descriptor = SourceRegionDescriptor::Default { region_id };
409
410        let value = serde_json::to_value(&descriptor).unwrap();
411        let decoded = serde_json::from_value::<SourceRegionDescriptor>(value.clone()).unwrap();
412
413        assert_eq!(
414            value,
415            serde_json::json!({
416                "Default": {
417                    "region_id": region_id,
418                }
419            })
420        );
421        assert_eq!(decoded, descriptor);
422    }
423
424    #[test]
425    fn test_source_region_descriptor_rejects_invalid_partition_expr_shape() {
426        let region_id = RegionId::new(1024, 1);
427        let invalid_json = serde_json::json!({
428            "region_id": region_id,
429            "partition_expr": 42,
430        });
431
432        let err = serde_json::from_value::<SourceRegionDescriptor>(invalid_json).unwrap_err();
433
434        assert!(err.to_string().contains("data did not match any variant"));
435    }
436
437    #[test]
438    fn test_repartition_plan_entry_deserializes_legacy_source_regions() {
439        let group_id = Uuid::new_v4();
440        let table_id = 1024;
441        let source_region_id = RegionId::new(table_id, 1);
442        let target_region_id = RegionId::new(table_id, 2);
443        let source_partition_expr = range_expr("x", 0, 100);
444        let target_partition_expr = range_expr("x", 0, 50);
445        let legacy_json = serde_json::json!({
446            "group_id": group_id,
447            "source_regions": [{
448                "region_id": source_region_id,
449                "partition_expr": source_partition_expr,
450            }],
451            "target_regions": [{
452                "region_id": target_region_id,
453                "partition_expr": target_partition_expr,
454            }],
455            "allocated_region_ids": [target_region_id],
456            "pending_deallocate_region_ids": [],
457            "transition_map": [[0]],
458        });
459
460        let plan: RepartitionPlanEntry = serde_json::from_value(legacy_json).unwrap();
461
462        assert_eq!(plan.group_id, group_id);
463        assert_eq!(
464            plan.source_regions,
465            vec![SourceRegionDescriptor::partitioned(
466                source_region_id,
467                source_partition_expr
468            )]
469        );
470        assert_eq!(
471            plan.target_regions,
472            vec![TargetRegionDescriptor {
473                region_id: target_region_id,
474                partition_expr: target_partition_expr,
475            }]
476        );
477        assert_eq!(plan.allocated_region_ids, vec![target_region_id]);
478        assert!(plan.pending_deallocate_region_ids.is_empty());
479        assert_eq!(plan.transition_map, vec![vec![0]]);
480        assert!(plan.original_target_routes.is_empty());
481    }
482
483    #[test]
484    fn test_convert_plan_equal_regions() {
485        let group_id = Uuid::new_v4();
486        let table_id = 1024;
487        let mut next_region_number = 10;
488        let source_regions = vec![
489            create_region_descriptor(table_id, 1, "x", 0, 100),
490            create_region_descriptor(table_id, 2, "x", 100, 200),
491        ];
492        let target_partition_exprs = vec![range_expr("x", 0, 50), range_expr("x", 50, 200)];
493        let allocation_plan = AllocationPlanEntry {
494            group_id,
495            source_regions: source_regions.clone(),
496            target_partition_exprs: target_partition_exprs.clone(),
497            transition_map: Vec::new(),
498        };
499        let result = convert_allocation_plan_to_repartition_plan(
500            table_id,
501            &mut next_region_number,
502            &allocation_plan,
503        );
504        assert_eq!(result.group_id, group_id);
505        assert_eq!(result.source_regions, source_regions);
506        assert_eq!(result.target_regions.len(), 2);
507        assert!(result.allocated_region_ids.is_empty());
508        assert!(result.pending_deallocate_region_ids.is_empty());
509        // next_region_number should not change for equal regions
510        assert_eq!(next_region_number, 10);
511        // Verify target regions
512        assert_eq!(
513            result.target_regions[0].region_id,
514            RegionId::new(table_id, 1)
515        );
516        assert_eq!(
517            result.target_regions[0].partition_expr,
518            target_partition_exprs[0]
519        );
520        assert_eq!(
521            result.target_regions[1].region_id,
522            RegionId::new(table_id, 2)
523        );
524        assert_eq!(
525            result.target_regions[1].partition_expr,
526            target_partition_exprs[1]
527        );
528    }
529
530    #[test]
531    fn test_convert_plan_allocate_regions() {
532        let group_id = Uuid::new_v4();
533        let table_id = 1024;
534        let mut next_region_number = 10;
535
536        // 3 source regions -> 5 target partition expressions
537        let source_regions = vec![
538            create_region_descriptor(table_id, 1, "x", 0, 100),
539            create_region_descriptor(table_id, 2, "x", 100, 200),
540            create_region_descriptor(table_id, 3, "x", 200, 300),
541        ];
542        let target_partition_exprs = vec![
543            range_expr("x", 0, 50),
544            range_expr("x", 50, 100),
545            range_expr("x", 100, 150),
546            range_expr("x", 150, 200),
547            range_expr("x", 200, 300),
548        ];
549        let allocation_plan = AllocationPlanEntry {
550            group_id,
551            source_regions: source_regions.clone(),
552            target_partition_exprs: target_partition_exprs.clone(),
553            transition_map: vec![],
554        };
555        let result = convert_allocation_plan_to_repartition_plan(
556            table_id,
557            &mut next_region_number,
558            &allocation_plan,
559        );
560        assert_eq!(result.group_id, group_id);
561        assert_eq!(result.source_regions, source_regions);
562        assert_eq!(result.target_regions.len(), 5);
563        assert_eq!(result.allocated_region_ids.len(), 2);
564        assert!(result.pending_deallocate_region_ids.is_empty());
565        assert_eq!(next_region_number, 12);
566
567        // Verify first 3 target regions use source region ids with target partition exprs
568        assert_eq!(
569            result.target_regions[0].region_id,
570            RegionId::new(table_id, 1)
571        );
572        assert_eq!(
573            result.target_regions[0].partition_expr,
574            target_partition_exprs[0]
575        );
576        assert_eq!(
577            result.target_regions[1].region_id,
578            RegionId::new(table_id, 2)
579        );
580        assert_eq!(
581            result.target_regions[1].partition_expr,
582            target_partition_exprs[1]
583        );
584        assert_eq!(
585            result.target_regions[2].region_id,
586            RegionId::new(table_id, 3)
587        );
588        assert_eq!(
589            result.target_regions[2].partition_expr,
590            target_partition_exprs[2]
591        );
592
593        // Verify last 2 target regions are newly allocated
594        assert_eq!(
595            result.target_regions[3].region_id,
596            RegionId::new(table_id, 10)
597        );
598        assert_eq!(
599            result.target_regions[3].partition_expr,
600            target_partition_exprs[3]
601        );
602        assert_eq!(
603            result.target_regions[4].region_id,
604            RegionId::new(table_id, 11)
605        );
606        assert_eq!(
607            result.target_regions[4].partition_expr,
608            target_partition_exprs[4]
609        );
610
611        // Verify allocated region ids
612        assert_eq!(result.allocated_region_ids[0], RegionId::new(table_id, 10));
613        assert_eq!(result.allocated_region_ids[1], RegionId::new(table_id, 11));
614    }
615
616    #[test]
617    fn test_convert_plan_deallocate_regions() {
618        let group_id = Uuid::new_v4();
619        let table_id = 1024;
620
621        // 5 source regions -> 3 target partition expressions
622        let source_regions = vec![
623            create_region_descriptor(table_id, 1, "x", 0, 50),
624            create_region_descriptor(table_id, 2, "x", 50, 100),
625            create_region_descriptor(table_id, 3, "x", 100, 150),
626            create_region_descriptor(table_id, 4, "x", 150, 200),
627            create_region_descriptor(table_id, 5, "x", 200, 300),
628        ];
629        let target_partition_exprs = vec![
630            range_expr("x", 0, 100),
631            range_expr("x", 100, 200),
632            range_expr("x", 200, 300),
633        ];
634        let allocation_plan = AllocationPlanEntry {
635            group_id,
636            source_regions: source_regions.clone(),
637            target_partition_exprs: target_partition_exprs.clone(),
638            transition_map: vec![],
639        };
640        let mut next_region_number = 10;
641        let result = convert_allocation_plan_to_repartition_plan(
642            table_id,
643            &mut next_region_number,
644            &allocation_plan,
645        );
646        assert_eq!(next_region_number, 10);
647        assert_eq!(result.group_id, group_id);
648        assert_eq!(result.source_regions, source_regions);
649        assert_eq!(result.target_regions.len(), 3);
650        assert!(result.allocated_region_ids.is_empty());
651        assert_eq!(result.pending_deallocate_region_ids.len(), 2);
652
653        // Verify first 3 source regions are kept as target regions with new partition exprs
654        assert_eq!(
655            result.target_regions[0].region_id,
656            RegionId::new(table_id, 1)
657        );
658        assert_eq!(
659            result.target_regions[0].partition_expr,
660            target_partition_exprs[0]
661        );
662        assert_eq!(
663            result.target_regions[1].region_id,
664            RegionId::new(table_id, 2)
665        );
666        assert_eq!(
667            result.target_regions[1].partition_expr,
668            target_partition_exprs[1]
669        );
670        assert_eq!(
671            result.target_regions[2].region_id,
672            RegionId::new(table_id, 3)
673        );
674        assert_eq!(
675            result.target_regions[2].partition_expr,
676            target_partition_exprs[2]
677        );
678
679        // Verify last 2 source regions are pending deallocation
680        assert_eq!(
681            result.pending_deallocate_region_ids[0],
682            RegionId::new(table_id, 4)
683        );
684        assert_eq!(
685            result.pending_deallocate_region_ids[1],
686            RegionId::new(table_id, 5)
687        );
688    }
689
690    #[test]
691    fn test_convert_plan_allocate_single_region() {
692        let group_id = Uuid::new_v4();
693        let table_id = 1024;
694        let mut next_region_number = 5;
695        // 1 source region -> 2 target partition expressions
696        let source_regions = vec![create_region_descriptor(table_id, 1, "x", 0, 100)];
697        let target_partition_exprs = vec![range_expr("x", 0, 50), range_expr("x", 50, 100)];
698        let allocation_plan = AllocationPlanEntry {
699            group_id,
700            source_regions: source_regions.clone(),
701            target_partition_exprs: target_partition_exprs.clone(),
702            transition_map: vec![],
703        };
704
705        let result = convert_allocation_plan_to_repartition_plan(
706            table_id,
707            &mut next_region_number,
708            &allocation_plan,
709        );
710        assert_eq!(result.target_regions.len(), 2);
711        assert_eq!(result.allocated_region_ids.len(), 1);
712        assert_eq!(result.pending_deallocate_region_ids.len(), 0);
713        // First target uses source region id
714        assert_eq!(
715            result.target_regions[0].region_id,
716            RegionId::new(table_id, 1)
717        );
718        assert_eq!(
719            result.target_regions[0].partition_expr,
720            target_partition_exprs[0]
721        );
722        // Second target is newly allocated
723        assert_eq!(
724            result.target_regions[1].region_id,
725            RegionId::new(table_id, 5)
726        );
727        assert_eq!(
728            result.target_regions[1].partition_expr,
729            target_partition_exprs[1]
730        );
731        assert_eq!(next_region_number, 6);
732    }
733
734    #[test]
735    fn test_convert_plan_allocate_default_source_region() {
736        let group_id = Uuid::new_v4();
737        let table_id = 1024;
738        let mut next_region_number = 5;
739        let source_regions = vec![SourceRegionDescriptor::Default {
740            region_id: RegionId::new(table_id, 1),
741        }];
742        let target_partition_exprs = vec![range_expr("x", 0, 50), range_expr("x", 50, 100)];
743        let allocation_plan = AllocationPlanEntry {
744            group_id,
745            source_regions: source_regions.clone(),
746            target_partition_exprs: target_partition_exprs.clone(),
747            transition_map: vec![vec![0, 1]],
748        };
749
750        let result = convert_allocation_plan_to_repartition_plan(
751            table_id,
752            &mut next_region_number,
753            &allocation_plan,
754        );
755
756        assert_eq!(result.source_regions, source_regions);
757        assert_eq!(result.target_regions.len(), 2);
758        assert_eq!(
759            result.target_regions[0].region_id,
760            RegionId::new(table_id, 1)
761        );
762        assert_eq!(
763            result.target_regions[0].partition_expr,
764            target_partition_exprs[0]
765        );
766        assert_eq!(
767            result.target_regions[1].region_id,
768            RegionId::new(table_id, 5)
769        );
770        assert_eq!(
771            result.target_regions[1].partition_expr,
772            target_partition_exprs[1]
773        );
774        assert_eq!(
775            result.allocated_region_ids,
776            vec![RegionId::new(table_id, 5)]
777        );
778        assert!(result.pending_deallocate_region_ids.is_empty());
779        assert_eq!(result.transition_map, vec![vec![0, 1]]);
780        assert_eq!(next_region_number, 6);
781    }
782
783    #[test]
784    fn test_convert_plan_deallocate_to_single_region() {
785        let group_id = Uuid::new_v4();
786        let table_id = 1024;
787
788        // 3 source regions -> 1 target partition expression
789        let source_regions = vec![
790            create_region_descriptor(table_id, 1, "x", 0, 100),
791            create_region_descriptor(table_id, 2, "x", 100, 200),
792            create_region_descriptor(table_id, 3, "x", 200, 300),
793        ];
794        let target_partition_exprs = vec![range_expr("x", 0, 300)];
795        let allocation_plan = AllocationPlanEntry {
796            group_id,
797            source_regions: source_regions.clone(),
798            target_partition_exprs: target_partition_exprs.clone(),
799            transition_map: vec![],
800        };
801        let mut next_region_number = 10;
802        let result = convert_allocation_plan_to_repartition_plan(
803            table_id,
804            &mut next_region_number,
805            &allocation_plan,
806        );
807        assert_eq!(result.target_regions.len(), 1);
808        assert_eq!(result.allocated_region_ids.len(), 0);
809        assert_eq!(result.pending_deallocate_region_ids.len(), 2);
810
811        // Only first source region is kept
812        assert_eq!(
813            result.target_regions[0].region_id,
814            RegionId::new(table_id, 1)
815        );
816        assert_eq!(
817            result.target_regions[0].partition_expr,
818            target_partition_exprs[0]
819        );
820
821        // Other regions are pending deallocation
822        assert_eq!(
823            result.pending_deallocate_region_ids[0],
824            RegionId::new(table_id, 2)
825        );
826        assert_eq!(
827            result.pending_deallocate_region_ids[1],
828            RegionId::new(table_id, 3)
829        );
830    }
831}