Skip to main content

mito2/worker/
handle_catchup.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
15//! Handling catchup request and the end of a region's wait for its Leader lease.
16
17use std::collections::HashSet;
18use std::sync::Arc;
19
20use common_telemetry::{debug, error, info, warn};
21use futures::try_join;
22use snafu::{OptionExt, ensure};
23use store_api::ManifestVersion;
24use store_api::logstore::LogStore;
25use store_api::region_engine::SettableRegionRoleState;
26use store_api::region_request::RegionCatchupRequest;
27use store_api::storage::RegionId;
28use tokio::sync::mpsc::Sender;
29
30use crate::config::IndexBuildMode;
31use crate::error::{self, Result};
32use crate::manifest::action::RegionEdit;
33use crate::region::catchup::{
34    CandidateLease, RegionCatchupTask, TakeoverPrepared, hand_over, takeover_source,
35};
36use crate::region::opener::RegionOpener;
37use crate::region::{
38    AwaitedPromotion, CatchupRegionsRef, MitoRegion, MitoRegionRef, RegionLeaderState,
39    RegionRoleState,
40};
41use crate::request::{
42    BackgroundNotify, BuildIndexRequest, CaughtUpAgain, HandedOver, OptionOutputTx,
43    WorkerRequestWithTime,
44};
45use crate::sst::index::IndexBuildType;
46use crate::tail_replay::{notify_worker, release_wal_to_replay_start};
47#[cfg(feature = "hdfs-object-store")]
48use crate::temp_file_sweeper;
49use crate::wal::entry_distributor::WalEntryReceiver;
50use crate::worker::{
51    DeferredLeaseWork, RegionWorkerLoop, WorkerListener, drain_ended_staging, handle_reload,
52    handle_tail_replay,
53};
54
55impl<S: LogStore> RegionWorkerLoop<S> {
56    /// Catches the region up from its WAL, or, for a region whose manifest is published
57    /// conditionally and a catchup that makes it writable and carries the entry its source
58    /// reported, hands it over from that source without replaying (see [hand_over]). A region that
59    /// awaits the Leader lease of a promotion by a catchup with the same candidate lease id (a
60    /// repeat of that migration's catchup) is caught up again into a replacement instance, which
61    /// replaces it only if the replay succeeds, see [Self::catch_up_again]. The replacement holds
62    /// only the rows its WAL replays and the rows in its SSTs. Unflushed rows written with
63    /// `skip_wal` are lost on replacement. A promoting catchup from a different or unknown
64    /// migration can proceed once the awaiting region is a Follower. A transitional leader
65    /// returns RegionBusy so its downgrade flush or edit can finish under the original promotion.
66    /// A non-promoting catchup of an awaiting region takes [Self::catch_up_again] regardless
67    /// of its candidate lease id. Remote WAL replay first waits until the entries the region
68    /// acknowledged are durable.
69    ///
70    /// A catchup that makes such a region writable and names its source but no reported entry is a
71    /// takeover. `takeover` carries what the engine prepared for it (see [TakeoverPrepared]): the
72    /// manifest version it began from, when that read returned, the listed bound of the source's
73    /// WAL and the candidate lease id; or the error of the preparation, which the worker answers
74    /// unless it skips the catchup of a region that is writable and awaits no Leader lease. The
75    /// takeover waits for a lease of its candidate before it hands the region over up to that
76    /// bound. For any other catchup `takeover` is None, and a takeover without it fails.
77    pub(crate) async fn handle_catchup_request(
78        &mut self,
79        region_id: RegionId,
80        request: RegionCatchupRequest,
81        entry_receiver: Option<WalEntryReceiver>,
82        takeover: Option<Result<TakeoverPrepared>>,
83        sender: OptionOutputTx,
84    ) {
85        let Some(region) = self.regions.get_region(region_id) else {
86            sender.send(Err(error::RegionNotFoundSnafu { region_id }.build()));
87            return;
88        };
89
90        if region.is_writable() && !region.manifest_ctx.awaits_leader_lease() {
91            debug!("Region {region_id} is writable, skip catchup");
92            sender.send(Ok(0));
93            return;
94        }
95
96        // Before the demotion below, so a catchup in progress keeps the region it promotes.
97        if self.catchup_regions.is_region_exists(region_id)
98            || region.manifest_ctx.is_reload_pending()
99        {
100            warn!("Region {region_id} under catching up or waiting for a reload");
101            sender.send(Err(error::RegionBusySnafu { region_id }.build()));
102            return;
103        }
104
105        // A Leader lease may have ended the region's wait since the check above.
106        let Some(awaited) = region
107            .manifest_ctx
108            .begin_catchup(region_id, request.candidate_lease_id)
109        else {
110            debug!("Region {region_id} is writable, skip catchup");
111            sender.send(Ok(0));
112            return;
113        };
114        let takeover = match takeover_source(&request, &region)
115            .map(|_| check_takeover(region_id, takeover))
116            .transpose()
117        {
118            Ok(takeover) => takeover,
119            Err(e) => {
120                region.manifest_ctx.end_catchup();
121                sender.send(Err(e));
122                return;
123            }
124        };
125        match awaited {
126            AwaitedPromotion::NoPendingPromotion => {}
127            AwaitedPromotion::OtherOrUnknownMigration if request.set_writable => {
128                if !region.is_follower() {
129                    region.manifest_ctx.end_catchup();
130                    sender.send(Err(error::RegionBusySnafu { region_id }.build()));
131                    return;
132                }
133                // A Follower replays no tail. A handover or takeover is refused below until the
134                // replay started by the earlier promotion ends.
135                self.cancel_tail_replay(region_id);
136            }
137            // A catchup of this migration promoted the region and no Leader lease followed, so the
138            // region may lack what the leader has written since, also when a failed catchup again
139            // demoted it. A catchup that does not make the region writable is caught up again too,
140            // keeping the region if its replay fails.
141            AwaitedPromotion::SameMigration | AwaitedPromotion::OtherOrUnknownMigration => {
142                self.catch_up_again(region, request, entry_receiver, takeover, sender)
143                    .await;
144                return;
145            }
146        }
147
148        // A catchup that makes a region whose manifest is published conditionally writable, and
149        // carries the last entry its source reported, hands the region over from that source,
150        // replaying nothing. Its memtable must be empty: the hand-off floor would skip the entries
151        // of the rows it holds, and a reopen would drop them, which for rows written without the
152        // WAL is their only copy. A demoted Follower keeps those rows when refused. A retry succeeds
153        // once a Leader lease has made it writable again (the catchup is then skipped) or it was
154        // reopened without those rows. Rows written while the region awaited another promotion's
155        // Leader lease keep it refused until it is closed. A takeover is a handover whose source
156        // reported no entry: the engine prepared it, and it commits after the manifest version it
157        // began from once its candidate lease arrives.
158        let conditional = request.set_writable && region.manifest_ctx.is_conditional_publication();
159        let handover = match (request.entry_id, takeover) {
160            (_, Some(prepared)) => Some((prepared.bound, Some(prepared))),
161            (Some(entry_id), None) if conditional => Some((entry_id, None)),
162            _ => None,
163        };
164        // A tail replay of this instance that has not reported its end may still have a
165        // committed edit for the worker to apply. A handover's edit applied first changes the
166        // version's pending tails, so the worker would skip the replay's edit and leave its SSTs
167        // out of the version. The edit of a replay of an earlier instance never applies to this
168        // one (`apply_tails_edit` checks the instance), so only a replay of this instance refuses
169        // the handover.
170        if handover.is_some()
171            && (!region.version().memtables.is_empty()
172                || self
173                    .tail_replays
174                    .get(&region_id)
175                    .is_some_and(|(owner, _)| Arc::ptr_eq(owner, &region)))
176        {
177            warn!(
178                "Region {region_id} has rows in its memtable or its own running tail replay, refusing to hand it over"
179            );
180            region.manifest_ctx.end_catchup();
181            sender.send(Err(error::RegionBusySnafu { region_id }.build()));
182            return;
183        }
184        // The worker writes a region inline, so every write acknowledged so far has an entry id
185        // at or below this one.
186        let last_entry_id = region.version_control.current().last_entry_id;
187        // A takeover reopens the region only if its manifest is behind the version the engine read
188        // (see reopen_region_for_takeover); other catchups reopen it if the memtable is not empty
189        // or the manifest has an update.
190        let reopened = match handover {
191            Some((_, Some(prepared))) => {
192                self.reopen_region_for_takeover(region.clone(), prepared.version)
193                    .await
194            }
195            _ => self.reopen_region_if_needed(region.clone()).await,
196        };
197        let region = match reopened {
198            Ok(region) => region,
199            Err(e) => {
200                region.manifest_ctx.end_catchup();
201                sender.send(Err(e));
202                return;
203            }
204        };
205
206        self.catchup_regions.insert_region(region_id);
207        let finish = self.catchup_finish(region.clone(), sender);
208        let wal = self.wal.clone();
209        let allow_stale_entries = self.config.allow_stale_entries;
210        let node_lease = self.node_lease.clone();
211        let granted_leases = self.granted_leases.clone();
212        let node_id = self.file_ref_manager.node_id();
213        common_runtime::spawn_global(async move {
214            // Under conditional manifest publication, the region becomes writable only once its
215            // catchup committed the next manifest version.
216            let result = match handover {
217                Some((upto, takeover)) => {
218                    let candidate = takeover.map(|prepared| CandidateLease {
219                        prepared,
220                        leases: &granted_leases,
221                        node_lease: &node_lease,
222                    });
223                    match hand_over(
224                        &region,
225                        &wal,
226                        node_id,
227                        request.source_node_id,
228                        upto,
229                        candidate,
230                    )
231                    .await
232                    {
233                        Ok((hook, edit)) => {
234                            hook.fire().await;
235                            // The worker applies the edit and promotes the region.
236                            let notify = BackgroundNotify::HandedOver(HandedOver {
237                                region,
238                                edit,
239                                candidate_lease_id: request.candidate_lease_id,
240                                sender: finish.sender,
241                            });
242                            notify_worker(&finish.worker_sender, region_id, notify).await;
243                            return;
244                        }
245                        Err(e) => Err(e),
246                    }
247                }
248                None => {
249                    let mut task = RegionCatchupTask::new(region.clone(), wal, allow_stale_entries)
250                        .with_entry_receiver(entry_receiver)
251                        .with_expected_last_entry_id(request.entry_id)
252                        .with_set_writable(request.set_writable)
253                        .with_node_id(node_id)
254                        .with_replay_checkpoint_entry_id(request.checkpoint.map(|c| c.entry_id))
255                        .with_acknowledged_entry_id(last_entry_id);
256                    match task.run().await {
257                        Ok(_) if request.set_writable => region.manifest_ctx.commit_catchup().await,
258                        result => result.map(|()| None),
259                    }
260                }
261            };
262            match result {
263                Ok(hook) => {
264                    if let Some(hook) = hook {
265                        hook.fire().await;
266                    }
267                    let promoted = if !request.set_writable {
268                        region.manifest_ctx.end_catchup();
269                        false
270                    } else {
271                        // The region takes writes under the node lease until its next Leader
272                        // grant.
273                        node_lease.seed(&region.manifest_ctx.leader_deadline);
274                        region
275                            .manifest_ctx
276                            .promote_after_catchup(region_id, request.candidate_lease_id)
277                    };
278                    finish.run(promoted).await;
279                }
280                Err(err) => {
281                    error!(err; "Failed to catchup region {region_id}");
282                    region.manifest_ctx.end_catchup();
283                    finish.catchup_regions.remove_region(region_id);
284                    if region.manifest_ctx.is_stopped() {
285                        finish
286                            .sender
287                            .send(Err(error::RegionNotFoundSnafu { region_id }.build()));
288                    } else {
289                        finish.sender.send(Err(err));
290                    }
291                }
292            }
293        });
294    }
295
296    /// Catches a region up again that a catchup promoted and that no Leader lease followed. The
297    /// region stays registered, demoted unless it is in a transient leader state, while a
298    /// replacement opened from its manifest replays the WAL outside the worker;
299    /// [Self::handle_caught_up_again] registers the replacement only if its replay succeeded (on
300    /// a remote WAL it must reach the entries the region acknowledged), the region took no
301    /// write and made no commit meanwhile and, for a catchup that makes the region writable, the
302    /// replacement's catchup commit succeeded (under conditional manifest publication it commits
303    /// an empty edit). Otherwise the region keeps its memtable, so a later Leader lease can promote
304    /// it; one that waits for a reload is reloaded instead. A takeover, which the engine prepared,
305    /// also waits for its candidate lease during the replay, and commits only after the version
306    /// it began from and while the latest lease is still the candidate's.
307    async fn catch_up_again(
308        &mut self,
309        region: MitoRegionRef,
310        request: RegionCatchupRequest,
311        entry_receiver: Option<WalEntryReceiver>,
312        takeover: Option<TakeoverPrepared>,
313        sender: OptionOutputTx,
314    ) {
315        let region_id = region.region_id;
316        warn!("Region {region_id} awaits its Leader lease, catching it up again");
317        self.cancel_tail_replay(region_id);
318        // The worker writes a region inline, so every write acknowledged so far has an entry id
319        // at or below this one, and a later write changes the last sequence.
320        let current = region.version_control.current();
321        let (acknowledged_entry_id, last_sequence) = (current.last_entry_id, current.last_sequence);
322        let opener = match self.region_reopener(&region) {
323            Ok(opener) => opener.skip_wal_replay(true),
324            Err(e) => {
325                region.manifest_ctx.end_catchup();
326                sender.send(Err(e));
327                return;
328            }
329        };
330        let manifest_version = region.manifest_ctx.manifest_version().await;
331        self.catchup_regions.insert_region(region_id);
332        let wal = self.wal.clone();
333        let node_id = self.file_ref_manager.node_id();
334        let config = self.config.clone();
335        let worker_sender = self.sender.clone();
336        let (node_lease, granted_leases) = (self.node_lease.clone(), self.granted_leases.clone());
337        common_runtime::spawn_global(async move {
338            let candidate = takeover.map(|prepared| CandidateLease {
339                prepared,
340                leases: &granted_leases,
341                node_lease: &node_lease,
342            });
343            let result = async {
344                let replacement = opener.open(&config, &wal).await?;
345                let mut task =
346                    RegionCatchupTask::new(replacement.clone(), wal, config.allow_stale_entries)
347                        .with_entry_receiver(entry_receiver)
348                        .with_node_id(node_id)
349                        .with_expected_last_entry_id(request.entry_id)
350                        .with_set_writable(request.set_writable)
351                        .with_replay_checkpoint_entry_id(request.checkpoint.map(|c| c.entry_id))
352                        .with_acknowledged_entry_id(acknowledged_entry_id);
353                match &candidate {
354                    Some(candidate) => {
355                        try_join!(task.run(), candidate.wait(&region))?;
356                    }
357                    None => task.run().await?,
358                }
359                Ok(replacement)
360            }
361            .await;
362            let notify = BackgroundNotify::CaughtUpAgain(CaughtUpAgain {
363                old: region,
364                manifest_version,
365                last_sequence,
366                result,
367                set_writable: request.set_writable,
368                candidate_lease_id: request.candidate_lease_id,
369                takeover,
370                sender,
371            });
372            notify_worker(&worker_sender, region_id, notify).await;
373        });
374    }
375
376    /// Replaces the region with the instance its catchup again replayed into, or keeps the region
377    /// if the replay failed, the region was closed or reopened, waits for a reload or a flush,
378    /// committed or took a write since the catchup began, or the catchup commit of the
379    /// replacement failed. A takeover also keeps the region if its candidate lease did not arrive
380    /// or is no longer the latest, or the replacement is not at the version the takeover began
381    /// from. A kept region ends its catchup, so a later Leader lease can promote it
382    /// with its memtable; one that waits for a reload is reloaded instead.
383    pub(crate) async fn handle_caught_up_again(
384        &mut self,
385        region_id: RegionId,
386        caught_up: CaughtUpAgain,
387    ) {
388        let CaughtUpAgain {
389            old,
390            manifest_version,
391            last_sequence,
392            result,
393            set_writable,
394            candidate_lease_id,
395            takeover,
396            sender,
397        } = caught_up;
398        let registered = self
399            .regions
400            .get_region(region_id)
401            .is_some_and(|registered| Arc::ptr_eq(&registered, &old));
402        // Commits of the old instance wait until the replacement is registered.
403        let manager = old.manifest_ctx.manifest_manager.read().await;
404        let unchanged = !old.manifest_ctx.is_reload_pending()
405            // Its own commits only: a version that only storage has is the replacement's.
406            && manager.manifest().manifest_version == manifest_version
407            && !self.flush_scheduler.is_flush_requested(region_id)
408            // The catchup does not demote a region in a transient leader state: an edit that fails
409            // meanwhile makes it writable again, and the replay misses the writes it then
410            // acknowledges, with or without the WAL.
411            && old.version_control.current().last_sequence == last_sequence;
412        let mut catchup_hook = None;
413        let replacement = match result {
414            _ if !registered => Err(error::RegionNotFoundSnafu { region_id }.build()),
415            Ok(_) if !unchanged => Err(error::RegionBusySnafu { region_id }.build()),
416            // The replacement's own commit guards pass, as it is unregistered; the checks of the
417            // old instance above do the guarding. The old instance's commits wait on the read
418            // guard held here, so once the commit succeeds nothing below can refuse the swap.
419            // This awaits one conditional PUT and one LIST on the worker, under that guard: the
420            // commit cannot move into a spawned task, since the old instance could then commit or
421            // be fenced between it and the checks. A catchup again is rare.
422            Ok(replacement) if set_writable => {
423                let committed = match takeover {
424                    // The replacement opened the latest manifest after the takeover read its
425                    // version, so the check refuses it if a commit came in between.
426                    Some(prepared) => {
427                        async {
428                            let candidate = CandidateLease {
429                                prepared,
430                                leases: &self.granted_leases,
431                                node_lease: &self.node_lease,
432                            };
433                            let ctx = &replacement.manifest_ctx;
434                            let mut manager = ctx.manifest_manager.write().await;
435                            candidate.check(region_id, &manager)?;
436                            ctx.commit_catchup_locked(&mut manager, RegionEdit::default())
437                                .await
438                                .map(Some)
439                        }
440                        .await
441                    }
442                    None => replacement.manifest_ctx.commit_catchup().await,
443                };
444                committed.map(|hook| {
445                    catchup_hook = hook;
446                    replacement
447                })
448            }
449            result => result,
450        };
451        let replacement = match replacement {
452            Ok(replacement) => replacement,
453            Err(e) => {
454                drop(manager);
455                warn!(e; "Region {region_id} is not replaced by its catchup again");
456                self.catchup_regions.remove_region(region_id);
457                old.manifest_ctx.end_catchup();
458                sender.send(Err(e));
459                return;
460            }
461        };
462        // Preserve allocated sequences without publishing the old memtables.
463        replacement
464            .version_control
465            .update_last_sequence(old.version_control.current().last_sequence);
466        // Leases apply through the shared region map, so only those from heartbeats sent after
467        // the replacement may promote the new instance.
468        replacement.manifest_ctx.ignore_earlier_promotions();
469        // Requests waiting for the old instance are rejected as a close rejects them.
470        self.fail_region_stalled_requests_as_not_found(&region_id);
471        self.reject_region_requests_as_not_found(region_id);
472        // Leases apply through the shared region map, so a writable catchup keeps them from
473        // promoting the registered replacement before the promotion below (including while its
474        // hook runs); that promotion ends this catchup.
475        if set_writable {
476            let begun = replacement
477                .manifest_ctx
478                .begin_catchup(region_id, candidate_lease_id);
479            debug_assert_eq!(begun, Some(AwaitedPromotion::NoPendingPromotion));
480        }
481        self.register_region(replacement.clone());
482        drop(manager);
483        // A hook may read the manifest of the region, so it fires once no manifest lock is held.
484        if let Some(hook) = catchup_hook {
485            hook.fire().await;
486        }
487        if let Some(state) = &self.series_index_task_state {
488            state.wake();
489        }
490        info!("Region {region_id} is caught up again into a new instance");
491        let promoted = set_writable && {
492            // The region takes writes under the node lease until its next Leader grant.
493            self.node_lease
494                .seed(&replacement.manifest_ctx.leader_deadline);
495            replacement
496                .manifest_ctx
497                .promote_after_catchup(region_id, candidate_lease_id)
498        };
499        let finish = self.catchup_finish(replacement, sender);
500        common_runtime::spawn_global(async move {
501            finish.run(promoted).await;
502        });
503    }
504
505    /// Applies the edit a catchup committed for the handover of a region and promotes the
506    /// region, on the worker, in order with the edits of flushes and compactions. Ends the catchup
507    /// with an error if the region was replaced or stopped since; the committed edit stays in the
508    /// manifest, which the next open recovers, and this node's WAL is still released up to the
509    /// committed manifest's replay start, capped by this node's pending tails, before the reply.
510    pub(crate) fn handle_handed_over(&mut self, region_id: RegionId, handed_over: HandedOver) {
511        let HandedOver {
512            region,
513            edit,
514            candidate_lease_id,
515            sender,
516        } = handed_over;
517        let registered = self
518            .regions
519            .get_region(region_id)
520            .is_some_and(|registered| Arc::ptr_eq(&registered, &region));
521        if !registered || region.manifest_ctx.is_stopped() {
522            warn!("Region {region_id} was replaced or stopped before its handover applied");
523            region.manifest_ctx.end_catchup();
524            self.catchup_regions.remove_region(region_id);
525            let error = error::RegionNotFoundSnafu { region_id }.build();
526            // The committed handover still releases this node's entries up to where the committed
527            // manifest replays its WAL, keeping this node's pending tails.
528            let wal = self.wal.clone();
529            let node_id = self.file_ref_manager.node_id();
530            common_runtime::spawn_global(async move {
531                release_wal_to_replay_start(&region, &wal, node_id).await;
532                sender.send(Err(error));
533            });
534            return;
535        }
536        region
537            .version_control
538            .apply_edit(Some(edit), &[], region.file_purger.clone());
539        // The region takes writes under the node lease until its next Leader grant.
540        self.node_lease.seed(&region.manifest_ctx.leader_deadline);
541        let promoted = region
542            .manifest_ctx
543            .promote_after_catchup(region_id, candidate_lease_id);
544        let finish = self.catchup_finish(region.clone(), sender);
545        let wal = self.wal.clone();
546        let node_id = self.file_ref_manager.node_id();
547        // The finish drains through this worker, so it must not be awaited here.
548        common_runtime::spawn_global(async move {
549            // A handover replayed nothing, so this node's entries up to its handoff floor are
550            // released here, keeping its pending tails. The committed manifest alone decides the
551            // release, so it does not depend on the promotion.
552            release_wal_to_replay_start(&region, &wal, node_id).await;
553            finish.run(promoted).await;
554        });
555    }
556
557    /// Returns whether a manifest sync or a follower's option change of `region` is refused
558    /// with RegionBusy: the instance is in a catchup, which replays the WAL into its memtable and
559    /// reads its options and manifest outside the worker, or it is fenced while the worker holds
560    /// a catchup or reload registration for the region. A reload reopens the region with the
561    /// options it read when it began, which would drop an option change; a sync shares the
562    /// predicate.
563    pub(crate) fn is_catching_up_or_reloading(&self, region: &MitoRegion) -> bool {
564        region.manifest_ctx.is_catching_up()
565            || (self.catchup_regions.is_region_exists(region.region_id)
566                && region.manifest_ctx.is_reload_pending())
567    }
568
569    fn catchup_finish(&self, region: MitoRegionRef, sender: OptionOutputTx) -> CatchupFinish {
570        CatchupFinish {
571            region,
572            sender,
573            catchup_regions: self.catchup_regions.clone(),
574            worker_sender: self.sender.clone(),
575            #[cfg(feature = "hdfs-object-store")]
576            sweep_older_than: self.config.gc.unknown_file_lingering_time,
577            #[cfg(feature = "hdfs-object-store")]
578            sweep_limiter: self.sweep_limiter.clone(),
579        }
580    }
581
582    /// Reopens a region for its catchup, which keeps Leader leases from promoting the reopened
583    /// instance until it ends.
584    async fn reopen_region(&mut self, region: &Arc<MitoRegion>) -> Result<Arc<MitoRegion>> {
585        let region_id = region.region_id;
586        // Commits of the old instance wait until the reopened one is registered, so a conflict
587        // either fenced the old instance before the check below or happens after it is replaced.
588        let manager = region.manifest_ctx.manifest_manager.read().await;
589        ensure!(
590            !region.manifest_ctx.is_reload_pending(),
591            error::RegionBusySnafu { region_id }
592        );
593        let manifest_version = manager.manifest().manifest_version;
594        let flushed_entry_id = region.version_control.current().last_entry_id;
595        info!(
596            "Reopening the region: {region_id}, manifest version: {manifest_version}, flushed entry id: {flushed_entry_id}"
597        );
598        let reopened_region = self
599            .region_reopener(region)?
600            .skip_wal_replay(true)
601            .open(&self.config, &self.wal)
602            .await?;
603        debug_assert!(!reopened_region.is_writable());
604        // Registered below, where a Leader lease can reach it before the catchup ends.
605        let begun = reopened_region
606            .manifest_ctx
607            .begin_catchup(region.region_id, None);
608        debug_assert_eq!(begun, Some(AwaitedPromotion::NoPendingPromotion));
609        // Preserve allocated sequences without publishing the old memtables.
610        reopened_region
611            .version_control
612            .update_last_sequence(region.version_control.current().last_sequence);
613        self.register_region(reopened_region.clone());
614        drop(manager);
615        if let Some(state) = &self.series_index_task_state {
616            state.wake();
617        }
618
619        Ok(reopened_region)
620    }
621
622    /// Returns an opener of the region from its manifest, with its current options.
623    pub(crate) fn region_reopener(&self, region: &MitoRegion) -> Result<RegionOpener> {
624        RegionOpener::new(
625            region.region_id,
626            region.table_dir(),
627            region.access_layer.path_type(),
628            self.node_lease.clone(),
629            self.memtable_builder_provider.clone(),
630            self.object_store_manager.clone(),
631            self.purge_scheduler.clone(),
632            self.puffin_manager_factory.clone(),
633            self.intermediate_manager.clone(),
634            self.time_provider.clone(),
635            self.file_ref_manager.clone(),
636            self.partition_expr_fetcher.clone(),
637        )
638        .cache(Some(self.cache_manager.clone()))
639        .hook(self.plugins.get())
640        .options(region.version().options.clone())
641    }
642
643    /// Reopens the region for its takeover if its installed manifest is behind `version`, the
644    /// version the takeover began from; fails if it is past it, or if the reopened region does not
645    /// hold that version either.
646    async fn reopen_region_for_takeover(
647        &mut self,
648        region: Arc<MitoRegion>,
649        version: ManifestVersion,
650    ) -> Result<Arc<MitoRegion>> {
651        let region_id = region.region_id;
652        let installed = region.manifest_ctx.manifest_version().await;
653        ensure!(installed <= version, error::RegionBusySnafu { region_id });
654        if installed == version {
655            return Ok(region);
656        }
657        self.listener.on_catchup_reopen_begin(region_id).await;
658        let reopened = self.reopen_region(&region).await?;
659        if reopened.manifest_ctx.manifest_version().await != version {
660            // The reopened instance began its own catchup.
661            reopened.manifest_ctx.end_catchup();
662            return error::RegionBusySnafu { region_id }.fail();
663        }
664        Ok(reopened)
665    }
666
667    async fn reopen_region_if_needed(
668        &mut self,
669        region: Arc<MitoRegion>,
670    ) -> Result<Arc<MitoRegion>> {
671        // Note: Currently, We protect the split brain by ensuring the memtable table is empty.
672        // It's expensive to execute catch-up requests without `set_writable=true` multiple times.
673        let version = region.version();
674        let is_empty_memtable = version.memtables.is_empty();
675
676        // Utilizes the short circuit evaluation.
677        let region = if !is_empty_memtable || region.manifest_ctx.has_update().await? {
678            if !is_empty_memtable {
679                warn!(
680                    "Region {} memtables is not empty, which should not happen, manifest version: {}, last entry id: {}",
681                    region.region_id,
682                    region.manifest_ctx.manifest_version().await,
683                    region.version_control.current().last_entry_id
684                );
685            }
686            self.listener
687                .on_catchup_reopen_begin(region.region_id)
688                .await;
689            self.reopen_region(&region).await?
690        } else {
691            region
692        };
693
694        Ok(region)
695    }
696
697    /// Starts the work that a region deferred while it awaited its Leader lease.
698    pub(crate) async fn handle_leader_lease_wait_ended(&mut self, region_id: RegionId) {
699        let Some(region) = self.regions.get_region(region_id) else {
700            return;
701        };
702        // As for any flush, the completion of these handles the stalled writes.
703        self.maybe_flush_worker();
704        self.maybe_flush_write_regions(HashSet::from([region_id]));
705        if region.state() == RegionRoleState::Leader(RegionLeaderState::Writable) {
706            self.schedule_compaction(&region).await;
707        } else {
708            info!(
709                "Region {region_id} is {:?} when its Leader lease wait ends, starting no compaction",
710                region.state()
711            );
712        }
713        // The sweep after the batch runs it, after the requests the batch started, or once the
714        // region is a writable leader.
715        let work = self.defer_lease_work(&region);
716        work.missing_index_pass = true;
717        work.backfill = true;
718        self.listener.on_leader_lease_wait_ended(region_id);
719    }
720
721    /// Finishes the deferred work of every region that is a writable leader with its Leader
722    /// lease. The worker loop calls it after each batch, so the work runs after the requests the
723    /// batch started; a DDL that the batch queued behind a flush or a compaction has not started.
724    /// It costs one `is_empty()` per batch and, per entry, which regions rarely have, one region
725    /// lookup (a read lock of the region map) and a few atomic loads, with no I/O or await until
726    /// a region qualifies; the `Vec` of the regions that qualify allocates only once one does.
727    pub(crate) async fn sweep_deferred_lease_work(&mut self) {
728        if self.deferred_lease_work.is_empty() {
729            return;
730        }
731        let regions: Vec<_> = self
732            .deferred_lease_work
733            .keys()
734            .filter_map(|region_id| self.regions.get_region(*region_id))
735            .filter(|region| region.may_finish_deferred_lease_work())
736            .collect();
737        for region in regions {
738            self.finish_deferred_lease_work(region).await;
739        }
740    }
741
742    /// Runs the deferred work of a region that was a writable leader with its Leader lease:
743    /// builds the missing indexes, re-issues the kept index build retries and saves the
744    /// backfilled metadata. A role change since then makes each step keep its work due.
745    async fn finish_deferred_lease_work(&mut self, region: MitoRegionRef) {
746        let region_id = region.region_id;
747        let Some(work) = self.deferred_lease_work.remove(&region_id) else {
748            return;
749        };
750        self.listener.on_deferred_lease_work_begin(region_id).await;
751        if work.missing_index_pass && self.build_missing_indexes(&region).await {
752            // A role change outside the worker stopped the pass, so the region does the work
753            // once it is a writable leader again. Nothing deferred work for the region while the
754            // pass ran: it is not a retry, and the worker handles no request until it returns.
755            self.deferred_lease_work.insert(region_id, work);
756            return;
757        }
758        // A retry that the region refuses again keeps itself.
759        for request in work.retries {
760            self.handle_rebuild_index_inner(request, OptionOutputTx::new(None), true)
761                .await;
762        }
763        if work.backfill {
764            spawn_persist_backfilled_metadata(&self.listener, &self.sender, region);
765        }
766    }
767
768    /// Defers the save of the backfilled metadata that found `source` not a writable leader with
769    /// its Leader lease. A close or a drop stopped a source whose work it removed, so a later
770    /// instance does not take it over.
771    pub(crate) fn handle_backfill_deferred(&mut self, source: MitoRegionRef) {
772        let region_id = source.region_id;
773        self.listener.on_backfill_deferred(region_id);
774        if source.manifest_ctx.is_stopped() {
775            return;
776        }
777        if let Some(region) = self.regions.get_region(region_id) {
778            self.defer_lease_work(&region).backfill = true;
779        }
780    }
781
782    /// Builds the indexes of the region's files that lack them, which a region that waits does
783    /// not build. Returns true if the state of the region stopped it.
784    async fn build_missing_indexes(&mut self, region: &MitoRegionRef) -> bool {
785        if self.config.index.build_mode != IndexBuildMode::Async {
786            return false;
787        }
788        let request = BuildIndexRequest {
789            region_id: region.region_id,
790            build_type: IndexBuildType::Flush,
791            file_metas: Vec::new(),
792            result_senders: Vec::new(),
793        };
794        self.handle_rebuild_index(request, OptionOutputTx::new(None))
795            .await
796    }
797}
798
799impl<S> RegionWorkerLoop<S> {
800    /// Returns the work `region` has due once it is a writable leader with its Leader lease,
801    /// recording that some is due.
802    pub(crate) fn defer_lease_work(&mut self, region: &MitoRegionRef) -> &mut DeferredLeaseWork {
803        let region_id = region.region_id;
804        self.deferred_lease_work.entry(region_id).or_insert_with(|| {
805            if !region.may_finish_deferred_lease_work() {
806                info!(
807                    "Region {region_id} is {:?}, deferring work until it is a writable leader with its Leader lease",
808                    region.state()
809                );
810            }
811            DeferredLeaseWork::default()
812        })
813    }
814}
815
816/// Returns what the engine prepared for the takeover of `region_id`. `None` means the engine prepared
817/// nothing, as for a catchup sent to the worker directly, and fails with `InvalidRequest`;
818/// `Some(Err(e))` fails with the error of the preparation.
819fn check_takeover(
820    region_id: RegionId,
821    takeover: Option<Result<TakeoverPrepared>>,
822) -> Result<TakeoverPrepared> {
823    takeover.with_context(|| error::InvalidRequestSnafu {
824        region_id,
825        reason: "a takeover must be prepared by the engine",
826    })?
827}
828
829/// What ends a successful catchup: it finalizes the leadership of a promoted region, ends the
830/// catchup and replies.
831struct CatchupFinish {
832    region: MitoRegionRef,
833    sender: OptionOutputTx,
834    catchup_regions: CatchupRegionsRef,
835    worker_sender: Sender<WorkerRequestWithTime>,
836    #[cfg(feature = "hdfs-object-store")]
837    sweep_older_than: std::time::Duration,
838    #[cfg(feature = "hdfs-object-store")]
839    sweep_limiter: Option<Arc<tokio::sync::Semaphore>>,
840}
841
842impl CatchupFinish {
843    async fn run(self, promoted: bool) {
844        let region = self.region;
845        let region_id = region.region_id;
846        if promoted {
847            // Finalize leadership: persist backfilled metadata.
848            let drain = drain_ended_staging(&self.worker_sender, region_id);
849            match region
850                .set_role_state_gracefully(SettableRegionRoleState::Leader, drain)
851                .await
852            {
853                Ok(()) => {
854                    #[cfg(feature = "hdfs-object-store")]
855                    temp_file_sweeper::spawn_region_sweep(
856                        region.access_layer(),
857                        region_id,
858                        self.sweep_older_than,
859                        self.sweep_limiter,
860                    );
861                }
862                Err(err) => {
863                    error!(err; "Failed to set region {region_id} to leader");
864                }
865            }
866            handle_tail_replay::notify_writable(&self.worker_sender, &region);
867        }
868        self.catchup_regions.remove_region(region_id);
869        // A close during the catchup stopped the region, which no longer serves it. A commit
870        // during the catchup, including the backfill above, may have found a newer manifest.
871        if region.manifest_ctx.is_stopped() {
872            self.sender
873                .send(Err(error::RegionNotFoundSnafu { region_id }.build()));
874        } else if region.manifest_ctx.is_reload_pending() {
875            self.sender
876                .send(Err(error::RegionBusySnafu { region_id }.build()));
877        } else {
878            self.sender.send(Ok(0));
879        }
880    }
881}
882
883/// Persists the metadata the opener filled in, which the catchup of a region that waits does
884/// not, without blocking the worker. The commit runs outside the worker, so it asks for the
885/// reload of a region it fences.
886fn spawn_persist_backfilled_metadata(
887    listener: &WorkerListener,
888    sender: &Sender<WorkerRequestWithTime>,
889    region: MitoRegionRef,
890) {
891    listener.on_persist_backfilled_metadata_begin(region.region_id);
892    let listener = listener.clone();
893    let sender = sender.clone();
894    common_runtime::spawn_global(async move {
895        listener
896            .on_persist_backfilled_metadata_lock_begin(region.region_id)
897            .await;
898        persist_backfilled_metadata_and_notify_if_fenced(&sender, &region).await;
899    });
900}
901
902/// Persists the metadata the opener filled in for `region` and, if the commit fenced the region,
903/// asks its worker through `sender` for the reload. A save that finds the region not a writable
904/// leader with its Leader lease, such as in a change the worker started after it spawned the
905/// save, has the worker defer it.
906pub(crate) async fn persist_backfilled_metadata_and_notify_if_fenced(
907    sender: &Sender<WorkerRequestWithTime>,
908    region: &MitoRegionRef,
909) {
910    if !region.persist_backfilled_metadata().await {
911        let notify = BackgroundNotify::BackfillDeferred {
912            region: region.clone(),
913        };
914        notify_worker(sender, region.region_id, notify).await;
915    }
916    handle_reload::notify_if_fenced(sender, region).await;
917}
918
919/// Tells the worker that a lease ended the wait of `region` for its Leader lease, without
920/// waiting.
921pub(crate) fn notify_leader_lease_wait_ended(
922    sender: &Sender<WorkerRequestWithTime>,
923    region: &MitoRegionRef,
924) {
925    let sender = sender.clone();
926    let region_id = region.region_id;
927    common_runtime::spawn_global(async move {
928        notify_worker(&sender, region_id, BackgroundNotify::LeaderLeaseWaitEnded).await;
929    });
930}