Skip to main content

meta_srv/procedure/region_migration/
open_candidate_region.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::any::Any;
16use std::collections::HashSet;
17use std::ops::Div;
18
19use api::v1::meta::MailboxMessage;
20use common_meta::RegionIdent;
21use common_meta::distributed_time_constants::default_distributed_time_constants;
22use common_meta::instruction::{
23    Instruction, InstructionReply, OpenRegion, OpenRegionReason, SimpleReply,
24};
25use common_meta::key::datanode_table::RegionInfo;
26use common_procedure::{Context as ProcedureContext, Status};
27use common_telemetry::info;
28use common_telemetry::tracing_context::TracingContext;
29use serde::{Deserialize, Serialize};
30use snafu::{OptionExt, ResultExt, ensure};
31use store_api::region_request::RegionRequirements;
32use tokio::time::Instant;
33
34use crate::error::{self, Result};
35use crate::handler::HeartbeatMailbox;
36use crate::procedure::region_migration::flush_leader_region::PreFlushRegion;
37use crate::procedure::region_migration::{Context, RegionMigrationTriggerReason, State, utils};
38use crate::procedure::utils::instruction_error_result;
39use crate::service::mailbox::Channel;
40
41#[derive(Debug, Serialize, Deserialize)]
42pub struct OpenCandidateRegion;
43
44#[async_trait::async_trait]
45#[typetag::serde]
46impl State for OpenCandidateRegion {
47    async fn next(
48        &mut self,
49        ctx: &mut Context,
50        procedure_ctx: &ProcedureContext,
51    ) -> Result<(Box<dyn State>, Status)> {
52        let trigger_reason = ctx.trigger_reason(procedure_ctx.event_context.as_ref());
53        let instruction = self
54            .build_open_region_instruction(ctx, trigger_reason)
55            .await?;
56        let now = Instant::now();
57        self.open_candidate_region(ctx, instruction).await?;
58        ctx.update_open_candidate_region_elapsed(now);
59
60        Ok((Box::new(PreFlushRegion), Status::executing(false)))
61    }
62
63    fn as_any(&self) -> &dyn Any {
64        self
65    }
66}
67
68impl OpenCandidateRegion {
69    /// Builds open region instructions
70    ///
71    /// Abort(non-retry):
72    /// - Datanode Table is not found.
73    async fn build_open_region_instruction(
74        &self,
75        ctx: &mut Context,
76        trigger_reason: RegionMigrationTriggerReason,
77    ) -> Result<Instruction> {
78        let region_ids = ctx.persistent_ctx.region_ids.clone();
79        let from_peer_id = ctx.persistent_ctx.from_peer.id;
80        let to_peer_id = ctx.persistent_ctx.to_peer.id;
81        let reason = match trigger_reason {
82            RegionMigrationTriggerReason::Failover => OpenRegionReason::RegionFailover,
83            _ => OpenRegionReason::RegionMigration,
84        };
85        let datanode_table_values = ctx.get_from_peer_datanode_table_values().await?;
86        let mut open_regions = Vec::with_capacity(region_ids.len());
87
88        for region_id in region_ids {
89            let table_id = region_id.table_id();
90            let region_number = region_id.region_number();
91            let datanode_table_value = datanode_table_values.get(&table_id).context(
92                error::DatanodeTableNotFoundSnafu {
93                    table_id,
94                    datanode_id: from_peer_id,
95                },
96            )?;
97            let RegionInfo {
98                region_storage_path,
99                region_options,
100                region_wal_options,
101                engine,
102            } = datanode_table_value.region_info.clone();
103
104            open_regions.push(OpenRegion::new(
105                RegionIdent {
106                    datanode_id: to_peer_id,
107                    table_id,
108                    region_number,
109                    engine,
110                },
111                &region_storage_path,
112                region_options,
113                region_wal_options,
114                true,
115                Some(reason),
116                RegionRequirements::object_storage(),
117            ));
118        }
119
120        Ok(Instruction::OpenRegions(open_regions))
121    }
122
123    /// Opens the candidate region.
124    ///
125    /// Abort(non-retry):
126    /// - The Datanode is unreachable(e.g., Candidate pusher is not found).
127    /// - Unexpected instruction reply.
128    /// - Another procedure is opening the candidate region.
129    /// - The candidate is a follower of one of the migrated regions.
130    /// - The table route of a migrated region is not physical.
131    ///
132    /// Retry:
133    /// - Failed to retrieve the metadata of table.
134    /// - Exceeded deadline of open instruction.
135    /// - Datanode failed to open the candidate region.
136    async fn open_candidate_region(
137        &self,
138        ctx: &mut Context,
139        open_instruction: Instruction,
140    ) -> Result<()> {
141        let pc = &ctx.persistent_ctx;
142        let vc = &mut ctx.volatile_ctx;
143        let region_ids = &pc.region_ids;
144        let candidate = &pc.to_peer;
145
146        // This method might be invoked multiple times.
147        // Only registers the guard if `opening_region_guard` is absent.
148        if vc.opening_region_guards.is_empty() {
149            for region_id in region_ids {
150                // Registers the opening region.
151                let guard = ctx
152                    .opening_region_keeper
153                    .register_candidate_region(candidate.id, *region_id)
154                    .context(error::RegionOperatingRaceSnafu {
155                        peer_id: candidate.id,
156                        region_id: *region_id,
157                    })?;
158                vc.opening_region_guards.push(guard);
159            }
160        }
161
162        // A follower can be added on the candidate after the submission checked the routes, so
163        // every attempt checks them while it holds the candidate registrations.
164        {
165            let region_id_set = region_ids.iter().collect::<HashSet<_>>();
166            let table_routes = ctx.get_table_route_values().await?;
167            for (table_id, table_route) in &table_routes {
168                let region_routes = table_route.region_routes().with_context(|_| {
169                    error::UnexpectedLogicalRouteTableSnafu {
170                        err_msg: format!(
171                            "TableRoute({table_id:?}) is a non-physical TableRouteValue."
172                        ),
173                    }
174                })?;
175                for region_route in region_routes
176                    .iter()
177                    .filter(|region_route| region_id_set.contains(&region_route.region.id))
178                {
179                    ensure!(
180                        !utils::has_peer_conflict(region_route, candidate.id),
181                        error::MigrationAbortSnafu {
182                            reason: format!(
183                                "The candidate peer {} is already a follower of region {}",
184                                candidate.id, region_route.region.id
185                            ),
186                        }
187                    );
188                }
189            }
190        }
191
192        let tracing_ctx = TracingContext::from_current_span();
193        let msg = MailboxMessage::json_message(
194            &format!("Open candidate regions: {:?}", region_ids),
195            &format!("Metasrv@{}", ctx.server_addr()),
196            &format!("Datanode-{}@{}", candidate.id, candidate.addr),
197            common_time::util::current_time_millis(),
198            &open_instruction,
199            Some(tracing_ctx.to_w3c()),
200        )
201        .with_context(|_| error::SerializeToJsonSnafu {
202            input: open_instruction.to_string(),
203        })?;
204
205        let operation_timeout =
206            ctx.next_operation_timeout()
207                .context(error::ExceededDeadlineSnafu {
208                    operation: "Open candidate region",
209                })?;
210        let operation_timeout = operation_timeout
211            .div(2)
212            .max(default_distributed_time_constants().region_lease);
213        let ch = Channel::Datanode(candidate.id);
214        let now = Instant::now();
215        let receiver = ctx.mailbox.send(&ch, msg, operation_timeout).await?;
216
217        match receiver.await {
218            Ok(msg) => {
219                let reply = HeartbeatMailbox::json_reply(&msg)?;
220                info!(
221                    "Received open region reply: {:?}, region: {:?}, elapsed: {:?}",
222                    reply,
223                    region_ids,
224                    now.elapsed()
225                );
226                let InstructionReply::OpenRegions(SimpleReply { result, error }) = reply else {
227                    return error::UnexpectedInstructionReplySnafu {
228                        mailbox_message: msg.to_string(),
229                        reason: "expect open region reply",
230                    }
231                    .fail();
232                };
233
234                if result {
235                    Ok(())
236                } else if let Some(error) = error {
237                    instruction_error_result(
238                        &error,
239                        format!(
240                            "Region {region_ids:?} is not opened by datanode {:?}, error: {error:?}, elapsed: {:?}",
241                            candidate,
242                            now.elapsed()
243                        ),
244                    )
245                } else {
246                    error::UnexpectedSnafu {
247                        violated: format!(
248                            "Region {region_ids:?} is not opened by datanode {:?}, but error is absent, elapsed: {:?}",
249                            candidate,
250                            now.elapsed()
251                        ),
252                    }
253                    .fail()
254                }
255            }
256            Err(error::Error::MailboxTimeout { .. }) => {
257                let reason = format!(
258                    "Mailbox received timeout for open candidate region {region_ids:?} on datanode {:?}, elapsed: {:?}",
259                    candidate,
260                    now.elapsed()
261                );
262                error::RetryLaterSnafu { reason }.fail()
263            }
264            Err(e) => Err(e),
265        }
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use std::assert_matches;
272    use std::collections::{HashMap, HashSet};
273
274    use common_catalog::consts::MITO2_ENGINE;
275    use common_error::ext::RetryHint;
276    use common_error::status_code::StatusCode;
277    use common_meta::DatanodeId;
278    use common_meta::instruction::InstructionError;
279    use common_meta::key::table_route::TableRouteValue;
280    use common_meta::key::test_utils::new_test_table_info;
281    use common_meta::peer::Peer;
282    use common_meta::rpc::router::{Region, RegionRoute};
283    use store_api::region_engine::RegionRole;
284    use store_api::storage::RegionId;
285
286    use super::*;
287    use crate::error::Error;
288    use crate::procedure::region_migration::test_util::{self, TestingEnv, new_procedure_context};
289    use crate::procedure::region_migration::{ContextFactory, PersistentContext};
290    use crate::procedure::test_util::{
291        new_close_region_reply, new_open_region_reply, new_open_region_reply_with_error,
292        send_mock_reply,
293    };
294
295    fn new_persistent_context() -> PersistentContext {
296        test_util::new_persistent_context(1, 2, RegionId::new(1024, 1))
297    }
298
299    fn new_mock_open_instruction(datanode_id: DatanodeId, region_id: RegionId) -> Instruction {
300        Instruction::OpenRegions(vec![OpenRegion::new(
301            RegionIdent {
302                datanode_id,
303                table_id: region_id.table_id(),
304                region_number: region_id.region_number(),
305                engine: MITO2_ENGINE.to_string(),
306            },
307            "/bar/foo/region/",
308            Default::default(),
309            Default::default(),
310            true,
311            Some(OpenRegionReason::RegionMigration),
312            RegionRequirements::object_storage(),
313        )])
314    }
315
316    #[tokio::test]
317    async fn test_datanode_table_is_not_found_error() {
318        let state = OpenCandidateRegion;
319        let persistent_context = new_persistent_context();
320        let env = TestingEnv::new();
321        let mut ctx = env.context_factory().new_context(persistent_context);
322
323        let err = state
324            .build_open_region_instruction(&mut ctx, RegionMigrationTriggerReason::Unknown)
325            .await
326            .unwrap_err();
327
328        assert_matches!(err, Error::DatanodeTableNotFound { .. });
329        assert!(!err.is_retryable());
330    }
331
332    #[tokio::test]
333    async fn test_build_open_region_instruction_reason() {
334        let state = OpenCandidateRegion;
335        let persistent_context = new_persistent_context();
336        let from_peer_id = persistent_context.from_peer.id;
337        let region_id = persistent_context.region_ids[0];
338        let env = TestingEnv::new();
339
340        let table_info = new_test_table_info(1024);
341        let region_routes = vec![RegionRoute {
342            region: Region::new_test(region_id),
343            leader_peer: Some(Peer::empty(from_peer_id)),
344            ..Default::default()
345        }];
346        env.table_metadata_manager()
347            .create_table_metadata(
348                table_info,
349                TableRouteValue::physical(region_routes),
350                HashMap::default(),
351            )
352            .await
353            .unwrap();
354
355        let mut ctx = env
356            .context_factory()
357            .new_context(persistent_context.clone());
358        let instruction = state
359            .build_open_region_instruction(&mut ctx, RegionMigrationTriggerReason::Unknown)
360            .await
361            .unwrap();
362        let open_regions = instruction.into_open_regions().unwrap();
363        assert_eq!(
364            Some(OpenRegionReason::RegionMigration),
365            open_regions[0].reason
366        );
367        assert_eq!(
368            RegionRequirements::object_storage(),
369            open_regions[0].requirements
370        );
371
372        let mut ctx = env.context_factory().new_context(persistent_context);
373        let instruction = state
374            .build_open_region_instruction(&mut ctx, RegionMigrationTriggerReason::Failover)
375            .await
376            .unwrap();
377        let open_regions = instruction.into_open_regions().unwrap();
378        assert_eq!(
379            Some(OpenRegionReason::RegionFailover),
380            open_regions[0].reason
381        );
382        assert_eq!(
383            RegionRequirements::object_storage(),
384            open_regions[0].requirements
385        );
386    }
387
388    #[tokio::test]
389    async fn test_datanode_is_unreachable() {
390        let state = OpenCandidateRegion;
391        // from_peer: 1
392        // to_peer: 2
393        let persistent_context = new_persistent_context();
394        let region_id = persistent_context.region_ids[0];
395        let to_peer_id = persistent_context.to_peer.id;
396        let env = TestingEnv::new();
397        let mut ctx = env.context_factory().new_context(persistent_context);
398
399        let open_instruction = new_mock_open_instruction(to_peer_id, region_id);
400        let err = state
401            .open_candidate_region(&mut ctx, open_instruction)
402            .await
403            .unwrap_err();
404
405        assert_matches!(err, Error::PusherNotFound { .. });
406        assert!(!err.is_retryable());
407    }
408
409    #[tokio::test]
410    async fn test_candidate_region_opening_error() {
411        let state = OpenCandidateRegion;
412        // from_peer: 1
413        // to_peer: 2
414        let persistent_context = new_persistent_context();
415        let region_id = persistent_context.region_ids[0];
416        let to_peer_id = persistent_context.to_peer.id;
417
418        let env = TestingEnv::new();
419        let mut ctx = env.context_factory().new_context(persistent_context);
420        let opening_region_keeper = env.opening_region_keeper();
421        let _guard = opening_region_keeper
422            .register_with_role(to_peer_id, region_id, RegionRole::Follower)
423            .unwrap();
424
425        let open_instruction = new_mock_open_instruction(to_peer_id, region_id);
426        let err = state
427            .open_candidate_region(&mut ctx, open_instruction)
428            .await
429            .unwrap_err();
430
431        assert_matches!(err, Error::RegionOperatingRace { .. });
432        assert!(!err.is_retryable());
433    }
434
435    #[tokio::test]
436    async fn test_candidate_is_follower_error() {
437        let state = OpenCandidateRegion;
438        let mut persistent_context = new_persistent_context();
439        let region_id = persistent_context.region_ids[0];
440        let follower_region_id = RegionId::new(1024, 2);
441        persistent_context.region_ids.push(follower_region_id);
442        let from_peer_id = persistent_context.from_peer.id;
443        let to_peer_id = persistent_context.to_peer.id;
444        let mut env = TestingEnv::new();
445        let mut region_routes = [region_id, follower_region_id]
446            .map(|region_id| RegionRoute {
447                region: Region::new_test(region_id),
448                leader_peer: Some(Peer::empty(from_peer_id)),
449                ..Default::default()
450            })
451            .to_vec();
452        env.create_physical_table_metadata(new_test_table_info(1024), region_routes.clone())
453            .await;
454        let mut ctx = env.context_factory().new_context(persistent_context);
455        let mailbox_ctx = env.mailbox_context();
456        let mailbox = mailbox_ctx.mailbox().clone();
457        let (tx, mut rx) = tokio::sync::mpsc::channel(1);
458        mailbox_ctx
459            .insert_heartbeat_response_receiver(Channel::Datanode(to_peer_id), tx)
460            .await;
461
462        // The first attempt sends the open instruction, which times out.
463        let open_instruction = state
464            .build_open_region_instruction(&mut ctx, RegionMigrationTriggerReason::Unknown)
465            .await
466            .unwrap();
467        let (result, _) = tokio::join!(
468            state.open_candidate_region(&mut ctx, open_instruction),
469            async {
470                let response = rx.recv().await.unwrap().unwrap();
471                let id = response.mailbox_message.unwrap().id;
472                mailbox
473                    .on_recv(id, Err(error::MailboxTimeoutSnafu { id }.build()))
474                    .await
475                    .unwrap();
476            }
477        );
478        assert!(result.unwrap_err().is_retryable());
479
480        // A follower is added on the candidate before the retry, which holds the registrations.
481        let current = ctx.get_table_route_value(1024).await.unwrap();
482        let region_info = ctx
483            .get_from_peer_datanode_table_value(1024)
484            .await
485            .unwrap()
486            .region_info;
487        region_routes[1]
488            .follower_peers
489            .push(Peer::empty(to_peer_id));
490        env.table_metadata_manager()
491            .update_table_route(
492                1024,
493                region_info.clone(),
494                &current,
495                region_routes,
496                &region_info.region_options,
497                &region_info.region_wal_options,
498            )
499            .await
500            .unwrap();
501        assert!(!ctx.volatile_ctx.opening_region_guards.is_empty());
502        let open_instruction = state
503            .build_open_region_instruction(&mut ctx, RegionMigrationTriggerReason::Unknown)
504            .await
505            .unwrap();
506        let err = state
507            .open_candidate_region(&mut ctx, open_instruction)
508            .await
509            .unwrap_err();
510        assert_matches!(err, Error::MigrationAbort { .. });
511        assert!(!err.is_retryable());
512        assert!(rx.try_recv().is_err());
513
514        // A first attempt, as after a recovery, registers the regions again before it aborts.
515        ctx.volatile_ctx.opening_region_guards.clear();
516        let open_instruction = state
517            .build_open_region_instruction(&mut ctx, RegionMigrationTriggerReason::Unknown)
518            .await
519            .unwrap();
520        let err = state
521            .open_candidate_region(&mut ctx, open_instruction)
522            .await
523            .unwrap_err();
524        assert_matches!(err, Error::MigrationAbort { .. });
525        assert_eq!(ctx.volatile_ctx.opening_region_guards.len(), 2);
526        assert!(rx.try_recv().is_err());
527    }
528
529    #[tokio::test]
530    async fn test_unexpected_instruction_reply() {
531        let state = OpenCandidateRegion;
532        // from_peer: 1
533        // to_peer: 2
534        let persistent_context = new_persistent_context();
535        let region_id = persistent_context.region_ids[0];
536        let to_peer_id = persistent_context.to_peer.id;
537
538        let mut env = TestingEnv::new();
539        let mut ctx = env.context_factory().new_context(persistent_context);
540        let mailbox_ctx = env.mailbox_context();
541        let mailbox = mailbox_ctx.mailbox().clone();
542
543        let (tx, rx) = tokio::sync::mpsc::channel(1);
544
545        mailbox_ctx
546            .insert_heartbeat_response_receiver(Channel::Datanode(to_peer_id), tx)
547            .await;
548
549        // Sends an incorrect reply.
550        send_mock_reply(mailbox, rx, |id| Ok(new_close_region_reply(id)));
551
552        let open_instruction = new_mock_open_instruction(to_peer_id, region_id);
553        let err = state
554            .open_candidate_region(&mut ctx, open_instruction)
555            .await
556            .unwrap_err();
557
558        assert_matches!(err, Error::UnexpectedInstructionReply { .. });
559        assert!(!err.is_retryable());
560    }
561
562    #[tokio::test]
563    async fn test_instruction_exceeded_deadline() {
564        let state = OpenCandidateRegion;
565        // from_peer: 1
566        // to_peer: 2
567        let persistent_context = new_persistent_context();
568        let region_id = persistent_context.region_ids[0];
569        let to_peer_id = persistent_context.to_peer.id;
570
571        let mut env = TestingEnv::new();
572        let mut ctx = env.context_factory().new_context(persistent_context);
573        let mailbox_ctx = env.mailbox_context();
574        let mailbox = mailbox_ctx.mailbox().clone();
575
576        let (tx, rx) = tokio::sync::mpsc::channel(1);
577
578        mailbox_ctx
579            .insert_heartbeat_response_receiver(Channel::Datanode(to_peer_id), tx)
580            .await;
581
582        // Sends an timeout error.
583        send_mock_reply(mailbox, rx, |id| {
584            Err(error::MailboxTimeoutSnafu { id }.build())
585        });
586
587        let open_instruction = new_mock_open_instruction(to_peer_id, region_id);
588        let err = state
589            .open_candidate_region(&mut ctx, open_instruction)
590            .await
591            .unwrap_err();
592
593        assert_matches!(err, Error::RetryLater { .. });
594        assert!(err.is_retryable());
595    }
596
597    #[tokio::test]
598    async fn test_open_candidate_region_failed() {
599        let state = OpenCandidateRegion;
600        // from_peer: 1
601        // to_peer: 2
602        let persistent_context = new_persistent_context();
603        let region_id = persistent_context.region_ids[0];
604        let to_peer_id = persistent_context.to_peer.id;
605        let mut env = TestingEnv::new();
606
607        let mut ctx = env.context_factory().new_context(persistent_context);
608        let mailbox_ctx = env.mailbox_context();
609        let mailbox = mailbox_ctx.mailbox().clone();
610
611        let (tx, rx) = tokio::sync::mpsc::channel(1);
612
613        mailbox_ctx
614            .insert_heartbeat_response_receiver(Channel::Datanode(to_peer_id), tx)
615            .await;
616
617        send_mock_reply(mailbox, rx, |id| {
618            Ok(new_open_region_reply_with_error(
619                id,
620                false,
621                Some(InstructionError {
622                    code: StatusCode::StorageUnavailable,
623                    message: "test mocked".to_string(),
624                    retry_hint: RetryHint::Retryable,
625                }),
626            ))
627        });
628
629        let open_instruction = new_mock_open_instruction(to_peer_id, region_id);
630        let err = state
631            .open_candidate_region(&mut ctx, open_instruction)
632            .await
633            .unwrap_err();
634
635        assert_matches!(err, Error::RetryLater { .. });
636        assert!(err.is_retryable());
637        assert!(format!("{err:?}").contains("test mocked"));
638    }
639
640    #[tokio::test]
641    async fn test_open_candidate_region_non_retryable_instruction_error() {
642        let state = OpenCandidateRegion;
643        let persistent_context = new_persistent_context();
644        let region_id = persistent_context.region_ids[0];
645        let to_peer_id = persistent_context.to_peer.id;
646        let mut env = TestingEnv::new();
647
648        let mut ctx = env.context_factory().new_context(persistent_context);
649        let mailbox_ctx = env.mailbox_context();
650        let mailbox = mailbox_ctx.mailbox().clone();
651
652        let (tx, rx) = tokio::sync::mpsc::channel(1);
653
654        mailbox_ctx
655            .insert_heartbeat_response_receiver(Channel::Datanode(to_peer_id), tx)
656            .await;
657
658        send_mock_reply(mailbox, rx, |id| {
659            Ok(new_open_region_reply_with_error(
660                id,
661                false,
662                Some(InstructionError {
663                    code: StatusCode::Internal,
664                    message: "non retryable mocked".to_string(),
665                    retry_hint: RetryHint::NonRetryable,
666                }),
667            ))
668        });
669
670        let open_instruction = new_mock_open_instruction(to_peer_id, region_id);
671        let err = state
672            .open_candidate_region(&mut ctx, open_instruction)
673            .await
674            .unwrap_err();
675
676        assert_matches!(err, Error::Unexpected { .. });
677        assert!(!err.is_retryable());
678        assert!(format!("{err:?}").contains("non retryable mocked"));
679    }
680
681    #[tokio::test]
682    async fn test_open_candidate_region_false_without_error_is_unexpected() {
683        let state = OpenCandidateRegion;
684        let persistent_context = new_persistent_context();
685        let region_id = persistent_context.region_ids[0];
686        let to_peer_id = persistent_context.to_peer.id;
687        let mut env = TestingEnv::new();
688
689        let mut ctx = env.context_factory().new_context(persistent_context);
690        let mailbox_ctx = env.mailbox_context();
691        let mailbox = mailbox_ctx.mailbox().clone();
692
693        let (tx, rx) = tokio::sync::mpsc::channel(1);
694
695        mailbox_ctx
696            .insert_heartbeat_response_receiver(Channel::Datanode(to_peer_id), tx)
697            .await;
698
699        send_mock_reply(mailbox, rx, |id| {
700            Ok(new_open_region_reply_with_error(id, false, None))
701        });
702
703        let open_instruction = new_mock_open_instruction(to_peer_id, region_id);
704        let err = state
705            .open_candidate_region(&mut ctx, open_instruction)
706            .await
707            .unwrap_err();
708
709        assert_matches!(err, Error::Unexpected { .. });
710        assert!(!err.is_retryable());
711    }
712
713    #[tokio::test]
714    async fn test_next_flush_leader_region_state() {
715        let mut state = Box::new(OpenCandidateRegion);
716        // from_peer: 1
717        // to_peer: 2
718        let persistent_context = new_persistent_context();
719        let from_peer_id = persistent_context.from_peer.id;
720        let region_id = persistent_context.region_ids[0];
721        let to_peer_id = persistent_context.to_peer.id;
722        let mut env = TestingEnv::new();
723
724        // Prepares table
725        let table_info = new_test_table_info(1024);
726        let region_routes = vec![
727            RegionRoute {
728                region: Region::new_test(region_id),
729                leader_peer: Some(Peer::empty(from_peer_id)),
730                ..Default::default()
731            },
732            // A region outside the migration may have a follower on the candidate.
733            RegionRoute {
734                region: Region::new_test(RegionId::new(1024, 2)),
735                leader_peer: Some(Peer::empty(from_peer_id)),
736                follower_peers: vec![Peer::empty(to_peer_id)],
737                ..Default::default()
738            },
739        ];
740
741        env.table_metadata_manager()
742            .create_table_metadata(
743                table_info,
744                TableRouteValue::physical(region_routes),
745                HashMap::default(),
746            )
747            .await
748            .unwrap();
749
750        let mut ctx = env.context_factory().new_context(persistent_context);
751        let mailbox_ctx = env.mailbox_context();
752        let mailbox = mailbox_ctx.mailbox().clone();
753
754        let (tx, rx) = tokio::sync::mpsc::channel(1);
755
756        mailbox_ctx
757            .insert_heartbeat_response_receiver(Channel::Datanode(to_peer_id), tx)
758            .await;
759
760        send_mock_reply(mailbox, rx, |id| Ok(new_open_region_reply(id, true, None)));
761        let procedure_ctx = new_procedure_context();
762        let (next, _) = state.next(&mut ctx, &procedure_ctx).await.unwrap();
763        let candidate_lease_id = {
764            let vc = &ctx.volatile_ctx;
765            assert_eq!(vc.opening_region_guards[0].info(), (to_peer_id, region_id));
766            vc.opening_region_guards[0].candidate_lease_id()
767        };
768        assert!(candidate_lease_id.is_some_and(|id| id != 0));
769        let regions = HashSet::from([region_id]);
770        let registered = |ctx: &Context| {
771            ctx.opening_region_keeper
772                .extract_operating_regions(to_peer_id, &regions)[&region_id]
773                .candidate_lease_id
774        };
775        assert_eq!(registered(&ctx), candidate_lease_id);
776
777        // A retry of the step keeps the registration and its id.
778        state.next(&mut ctx, &procedure_ctx).await.unwrap();
779        assert_eq!(ctx.volatile_ctx.opening_region_guards.len(), 1);
780        assert_eq!(registered(&ctx), candidate_lease_id);
781
782        let flush_leader_region = next.as_any().downcast_ref::<PreFlushRegion>().unwrap();
783        assert_matches!(flush_leader_region, PreFlushRegion);
784    }
785}