Skip to main content

mito2/
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
15//! Mito region.
16
17pub mod catchup;
18pub mod opener;
19pub mod options;
20pub mod utils;
21pub(crate) mod version;
22
23use std::cell::OnceCell;
24use std::collections::hash_map::Entry;
25use std::collections::{HashMap, HashSet};
26use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
27use std::sync::{Arc, Mutex, RwLock};
28use std::time::{Duration, Instant};
29
30use common_base::hash::partition_expr_version;
31use common_recordbatch::adapter::RegionQueryStatCounters;
32use common_recordbatch::filter::MetadataFilter;
33use common_telemetry::{error, info, warn};
34use common_time::timestamp::TimeUnit;
35use crossbeam_utils::atomic::AtomicCell;
36use datafusion_common::ScalarValue;
37use futures::stream::{BoxStream, StreamExt};
38use partition::expr::PartitionExpr;
39use snafu::{OptionExt, ResultExt, ensure};
40use store_api::ManifestVersion;
41use store_api::codec::PrimaryKeyEncoding;
42use store_api::logstore::provider::Provider;
43use store_api::metadata::RegionMetadataRef;
44use store_api::metrics::{REGION_QUERY_CPU_TIME, REGION_QUERY_SCANNED_BYTES};
45use store_api::region_engine::{
46    RegionManifestInfo, RegionRole, RegionStatistic, SettableRegionRoleState,
47};
48use store_api::region_info::RegionInfoEntry;
49use store_api::region_request::{PathType, StagingPartitionDirective};
50use store_api::sst_entry::{self, ManifestSstEntry};
51use store_api::storage::{FileId, RegionId, SequenceNumber};
52use tokio::sync::RwLockWriteGuard;
53pub use utils::*;
54
55use crate::access_layer::AccessLayerRef;
56use crate::compaction::CompactionStateRef;
57use crate::engine::region_hook::{PendingManifestHook, RegionHookRef};
58use crate::error::{
59    EndStagingSnafu, Error, FlushableRegionStateSnafu, InvalidPartitionExprSnafu,
60    InvalidRequestSnafu, RegionBusySnafu, RegionLeaseExpiredSnafu, RegionLeaseNotReceivedSnafu,
61    RegionNotFoundSnafu, RegionStateSnafu, RegionStoppedSnafu, RegionTruncatedSnafu, Result,
62    UnexpectedSnafu, UpdateManifestSnafu,
63};
64use crate::lease::{Deadline, NodeLease, lease_nanos};
65use crate::manifest::action::{
66    PendingTail, RegionChange, RegionEdit, RegionManifest, RegionMetaAction, RegionMetaActionList,
67};
68use crate::manifest::manager::RegionManifestManager;
69use crate::memtable::MemtableId;
70use crate::metrics::manifest_size::RegionManifestSizeMetric;
71use crate::region::version::{VersionControlRef, VersionRef};
72use crate::request::{OnFailure, OptionOutputTx};
73use crate::sst::file::{self, FileMeta};
74use crate::sst::file_purger::FilePurgerRef;
75use crate::sst::location::index_file_path;
76use crate::time_provider::TimeProviderRef;
77
78/// This is the approximate factor to estimate the size of wal.
79const ESTIMATED_WAL_FACTOR: f32 = 0.42825;
80
81/// Region status include region id, memtable usage, sst usage, wal usage and manifest usage.
82#[derive(Debug)]
83pub struct RegionUsage {
84    pub region_id: RegionId,
85    pub wal_usage: u64,
86    pub sst_usage: u64,
87    pub manifest_usage: u64,
88}
89
90impl RegionUsage {
91    pub fn disk_usage(&self) -> u64 {
92        self.wal_usage + self.sst_usage + self.manifest_usage
93    }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum RegionLeaderState {
98    /// The region is opened and is writable.
99    Writable,
100    /// The region is in staging mode - writable but no checkpoint/compaction/flush.
101    Staging,
102    /// The region is entering staging mode. - write requests will be stalled.
103    EnteringStaging,
104    /// The region is committing its staged edits in `end_staging`. Writes stall until
105    /// `StagingEnded` has the worker handle them, after the region leaves this state. `set_role`
106    /// ignores role changes, since `leave_ending_staging` works out the next state from the
107    /// commit result, a downgrade begun meanwhile and the Leader lease. Graceful role changes
108    /// wait for the manifest lock, which `end_staging` holds until the region leaves.
109    EndingStaging,
110    /// The region is altering.
111    Altering,
112    /// The region is dropping.
113    Dropping,
114    /// The region is truncating.
115    Truncating,
116    /// The region is handling a region edit.
117    Editing,
118    /// The region is stepping down.
119    Downgrading,
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum RegionRoleState {
124    Leader(RegionLeaderState),
125    Follower,
126}
127
128impl RegionRoleState {
129    /// Returns whether a region in this state can replay pending tails: a leader that is
130    /// Writable, Altering or Editing. A region with pending tails cannot enter staging; a
131    /// downgrading one is leaving.
132    pub(crate) fn can_replay_tails(self) -> bool {
133        matches!(
134            self,
135            RegionRoleState::Leader(
136                RegionLeaderState::Writable
137                    | RegionLeaderState::Altering
138                    | RegionLeaderState::Editing
139            )
140        )
141    }
142
143    /// Converts the region role state to leader state if it is a leader state.
144    pub fn into_leader_state(self) -> Option<RegionLeaderState> {
145        match self {
146            RegionRoleState::Leader(leader_state) => Some(leader_state),
147            RegionRoleState::Follower => None,
148        }
149    }
150
151    /// Returns whether a region in this state is admitted to flush.
152    pub(crate) fn is_flushable(self) -> bool {
153        matches!(
154            self,
155            Self::Leader(RegionLeaderState::Writable)
156                | Self::Leader(RegionLeaderState::Staging)
157                | Self::Leader(RegionLeaderState::Downgrading)
158        )
159    }
160
161    /// Returns whether the region is staging or ending staging. A staged edit belongs to the
162    /// session too, which only [MitoRegion::in_staging_session] can tell.
163    pub(crate) fn in_staging_session(self) -> bool {
164        self == Self::Leader(RegionLeaderState::Staging)
165            || self == Self::Leader(RegionLeaderState::EndingStaging)
166    }
167
168    pub(crate) fn as_str(&self) -> &'static str {
169        match self {
170            RegionRoleState::Follower => "Follower",
171            RegionRoleState::Leader(RegionLeaderState::Writable) => "Leader(Writable)",
172            RegionRoleState::Leader(RegionLeaderState::Staging) => "Leader(Staging)",
173            RegionRoleState::Leader(RegionLeaderState::EnteringStaging) => {
174                "Leader(EnteringStaging)"
175            }
176            RegionRoleState::Leader(RegionLeaderState::EndingStaging) => "Leader(EndingStaging)",
177            RegionRoleState::Leader(RegionLeaderState::Altering) => "Leader(Altering)",
178            RegionRoleState::Leader(RegionLeaderState::Dropping) => "Leader(Dropping)",
179            RegionRoleState::Leader(RegionLeaderState::Truncating) => "Leader(Truncating)",
180            RegionRoleState::Leader(RegionLeaderState::Editing) => "Leader(Editing)",
181            RegionRoleState::Leader(RegionLeaderState::Downgrading) => "Leader(Downgrading)",
182        }
183    }
184}
185
186/// Metadata and runtime status of a region.
187///
188/// Writing and reading a region follow a single-writer-multi-reader rule:
189/// - Only the region worker thread this region belongs to can modify the metadata.
190/// - Multiple reader threads are allowed to read a specific `version` of a region.
191#[derive(Debug)]
192pub struct MitoRegion {
193    /// Id of this region.
194    ///
195    /// Accessing region id from the version control is inconvenient so
196    /// we also store it here.
197    pub(crate) region_id: RegionId,
198    /// Live compaction state shared with readers without routing through the worker.
199    pub(crate) compaction_state: CompactionStateRef,
200
201    /// Version controller for this region.
202    ///
203    /// We MUST update the version control inside the write lock of the region manifest manager.
204    pub(crate) version_control: VersionControlRef,
205    /// SSTs accessor for this region.
206    pub(crate) access_layer: AccessLayerRef,
207    /// Context to maintain manifest for this region.
208    pub(crate) manifest_ctx: ManifestContextRef,
209    /// SST file purger.
210    pub(crate) file_purger: FilePurgerRef,
211    /// The provider of log store.
212    pub(crate) provider: Provider,
213    /// Last flush time in millis.
214    last_flush_millis: AtomicI64,
215    /// Last schedule compaction time in millis.
216    last_schedule_compaction_millis: AtomicI64,
217    /// Provider to get current time.
218    time_provider: TimeProviderRef,
219    /// The topic's latest entry id since the region's last flushing.
220    /// **Only used for remote WAL pruning.**
221    ///
222    /// The value will be updated to the latest offset of the topic
223    /// if region receives a flush request or schedules a periodic flush task
224    /// and the region's memtable is empty.
225    ///
226    /// There are no WAL entries in range [flushed_entry_id, topic_latest_entry_id] for current region,
227    /// which means these WAL entries maybe able to be pruned up to `topic_latest_entry_id`.
228    pub(crate) topic_latest_entry_id: AtomicU64,
229    /// Region stats.
230    pub(crate) region_stats: RegionStats,
231    /// manifest stats
232    stats: ManifestStats,
233}
234
235/// Runtime statistics of a region.
236#[derive(Debug)]
237pub(crate) struct RegionStats {
238    /// The total bytes written to the region.
239    pub(crate) written_bytes: Arc<AtomicU64>,
240    /// Parquet bytes committed by flushes since this region instance was opened.
241    pub(crate) ingested_parquet_bytes: AtomicU64,
242    /// The total query CPU time of the region in nanoseconds.
243    pub(crate) query_cpu_time: Arc<AtomicU64>,
244    /// The total scanned bytes of the region.
245    pub(crate) query_scanned_bytes: Arc<AtomicU64>,
246}
247
248impl RegionStats {
249    pub(crate) fn new() -> Self {
250        Self {
251            written_bytes: Arc::new(AtomicU64::new(0)),
252            ingested_parquet_bytes: AtomicU64::new(0),
253            query_cpu_time: Arc::new(AtomicU64::new(0)),
254            query_scanned_bytes: Arc::new(AtomicU64::new(0)),
255        }
256    }
257
258    pub(crate) fn query_stat_counters(&self) -> RegionQueryStatCounters {
259        RegionQueryStatCounters {
260            query_cpu_time: self.query_cpu_time.clone(),
261            query_scanned_bytes: self.query_scanned_bytes.clone(),
262        }
263    }
264}
265
266pub type MitoRegionRef = Arc<MitoRegion>;
267
268#[derive(Debug, Clone)]
269pub(crate) struct StagingPartitionInfo {
270    pub(crate) partition_directive: StagingPartitionDirective,
271    pub(crate) partition_rule_version: u64,
272}
273
274impl StagingPartitionInfo {
275    /// Returns the partition expression carried by the staging directive, if any.
276    pub(crate) fn partition_expr(&self) -> Option<&str> {
277        self.partition_directive.partition_expr()
278    }
279
280    /// Builds staging partition info from a directive and derives its version marker.
281    pub(crate) fn from_partition_directive(partition_directive: StagingPartitionDirective) -> Self {
282        let partition_rule_version = match &partition_directive {
283            StagingPartitionDirective::UpdatePartitionExpr(expr) => {
284                partition_expr_version(Some(expr))
285            }
286            StagingPartitionDirective::RejectAllWrites => 0,
287        };
288        Self {
289            partition_directive,
290            partition_rule_version,
291        }
292    }
293}
294
295impl MitoRegion {
296    /// Publishes the current size when this instance enters the live map.
297    pub(crate) fn activate_region_manifest_size_metric(&self) {
298        if let Some(metric) = self.stats.metric() {
299            metric.activate(&self.stats.total_manifest_size);
300        }
301    }
302
303    /// Injects a metric threshold for lifecycle tests without changing process env.
304    #[cfg(test)]
305    pub(crate) fn set_manifest_size_metric_threshold(&self, threshold: u64) {
306        let metric = self.stats.metric().unwrap();
307        metric.set_test_threshold(threshold);
308        metric.publish(self.stats.total_manifest_size());
309    }
310
311    /// Revokes publication before removal or replacement of this instance.
312    pub(crate) fn deactivate_region_manifest_size_metric(&self) {
313        if let Some(metric) = self.stats.metric() {
314            metric.deactivate();
315        }
316    }
317
318    fn remove_region_metrics(&self) {
319        let region_id = self.region_id.as_u64().to_string();
320        let labels = &[region_id.as_str()];
321        let _ = REGION_QUERY_CPU_TIME.remove_label_values(labels);
322        let _ = REGION_QUERY_SCANNED_BYTES.remove_label_values(labels);
323    }
324
325    /// Stops background managers for this region and fences off further promotions.
326    pub(crate) async fn stop(&self) {
327        self.manifest_ctx.promotion_fence.lock().unwrap().stopped = true;
328        self.manifest_ctx
329            .manifest_manager
330            .write()
331            .await
332            .stop()
333            .await;
334
335        info!(
336            "Stopped region manifest manager, region_id: {}",
337            self.region_id
338        );
339    }
340
341    /// Returns current metadata of the region.
342    pub fn metadata(&self) -> RegionMetadataRef {
343        let version_data = self.version_control.current();
344        version_data.version.metadata.clone()
345    }
346
347    /// Returns primary key encoding of the region.
348    pub(crate) fn primary_key_encoding(&self) -> PrimaryKeyEncoding {
349        let version_data = self.version_control.current();
350        version_data.version.metadata.primary_key_encoding
351    }
352
353    /// Returns current version of the region.
354    pub(crate) fn version(&self) -> VersionRef {
355        let version_data = self.version_control.current();
356        version_data.version
357    }
358
359    /// Installs an edit reported by a completed manifest publication. Callers
360    /// must be outside the manifest lock.
361    pub(crate) async fn apply_published_edit(
362        &self,
363        mut edit: RegionEdit,
364        memtables_to_remove: &[MemtableId],
365    ) {
366        let ssts = self.version().ssts.clone();
367        let conflicts = |file: &FileMeta| {
368            ssts.levels()
369                .iter()
370                .filter_map(|level| level.files.get(&file.file_id))
371                .any(|visible| {
372                    visible.file_id() == file.file_id()
373                        && visible.dedup_marker_trusted() != file.dedup_marker_trusted
374                })
375        };
376        // An edit can publish while an earlier writer is still firing its manifest hook.
377        // When their proof differs, install the current metadata under the manifest lock.
378        let manifest_guard = if edit.files_to_add.iter().any(&conflicts) {
379            Some(self.manifest_ctx.manifest_manager.read().await)
380        } else {
381            None
382        };
383        if let Some(manager) = &manifest_guard {
384            let manifest = manager.manifest();
385            edit.files_to_add.retain_mut(|file| {
386                if !conflicts(file) {
387                    return true;
388                }
389                let Some(current) = manifest.files.get(&file.file_id) else {
390                    return false;
391                };
392                if current.file_id() != file.file_id() || current.level != file.level {
393                    return false;
394                }
395                *file = current.as_ref().clone();
396                true
397            });
398        }
399        self.version_control
400            .apply_edit(Some(edit), memtables_to_remove, self.file_purger.clone());
401    }
402
403    /// Returns whether writes to this region should skip WAL.
404    pub(crate) fn skip_wal(&self) -> bool {
405        self.provider == Provider::Noop || self.version().options.skip_wal
406    }
407
408    /// Returns last flush timestamp in millis.
409    pub(crate) fn last_flush_millis(&self) -> i64 {
410        self.last_flush_millis.load(Ordering::Relaxed)
411    }
412
413    /// Update flush time to current time.
414    pub(crate) fn update_flush_millis(&self) {
415        let now = self.time_provider.current_time_millis();
416        self.last_flush_millis.store(now, Ordering::Relaxed);
417    }
418
419    /// Returns last schedule compaction timestamp in millis.
420    pub(crate) fn last_schedule_compaction_millis(&self) -> i64 {
421        self.last_schedule_compaction_millis.load(Ordering::Relaxed)
422    }
423
424    /// Update schedule compaction time to current time.
425    pub(crate) fn update_schedule_compaction_millis(&self) {
426        let now = self.time_provider.current_time_millis();
427        self.last_schedule_compaction_millis
428            .store(now, Ordering::Relaxed);
429    }
430
431    /// Returns the table dir.
432    pub(crate) fn table_dir(&self) -> &str {
433        self.access_layer.table_dir()
434    }
435
436    /// Returns the path type of the region.
437    pub(crate) fn path_type(&self) -> PathType {
438        self.access_layer.path_type()
439    }
440
441    /// Returns whether the region is writable.
442    pub(crate) fn is_writable(&self) -> bool {
443        matches!(
444            self.manifest_ctx.state.load(),
445            RegionRoleState::Leader(RegionLeaderState::Writable)
446                | RegionRoleState::Leader(RegionLeaderState::Staging)
447        )
448    }
449
450    /// Returns whether the region is flushable.
451    pub(crate) fn is_flushable(&self) -> bool {
452        self.manifest_ctx.state.load().is_flushable()
453    }
454
455    /// Returns whether the region should abort index building.
456    pub(crate) fn should_abort_index(&self) -> bool {
457        let state = self.manifest_ctx.state.load();
458        state.in_staging_session()
459            || matches!(
460                state,
461                RegionRoleState::Follower
462                    | RegionRoleState::Leader(RegionLeaderState::Dropping)
463                    | RegionRoleState::Leader(RegionLeaderState::Truncating)
464                    | RegionRoleState::Leader(RegionLeaderState::Downgrading)
465            )
466    }
467
468    /// Returns whether the region is downgrading.
469    pub(crate) fn is_downgrading(&self) -> bool {
470        matches!(
471            self.manifest_ctx.state.load(),
472            RegionRoleState::Leader(RegionLeaderState::Downgrading)
473        )
474    }
475
476    /// Returns whether the region is in staging mode.
477    pub(crate) fn is_staging(&self) -> bool {
478        self.manifest_ctx.state.load() == RegionRoleState::Leader(RegionLeaderState::Staging)
479    }
480
481    /// Returns whether background flush triggers must skip the region: a staging region keeps
482    /// its rows in the WAL until staging ends, and a region that awaits its Leader lease cannot
483    /// commit a flush yet.
484    pub(crate) fn defers_background_flush(&self) -> bool {
485        self.is_staging() || self.manifest_ctx.awaits_leader_lease()
486    }
487
488    /// Returns whether the region is in a staging session: staging, ending staging, or in a
489    /// staged edit.
490    pub(crate) fn in_staging_session(&self) -> bool {
491        match self.manifest_ctx.state.load() {
492            state if state.in_staging_session() => true,
493            RegionRoleState::Leader(RegionLeaderState::Editing) => {
494                self.manifest_ctx.staging_partition_info().is_some()
495            }
496            _ => false,
497        }
498    }
499
500    /// Returns whether the region is entering staging mode.
501    pub(crate) fn is_enter_staging(&self) -> bool {
502        self.manifest_ctx.state.load()
503            == RegionRoleState::Leader(RegionLeaderState::EnteringStaging)
504    }
505
506    /// Returns whether the region is truncating.
507    pub(crate) fn is_truncating(&self) -> bool {
508        self.manifest_ctx.state.load() == RegionRoleState::Leader(RegionLeaderState::Truncating)
509    }
510
511    /// Returns whether the region can replay pending tails (see
512    /// [RegionRoleState::can_replay_tails]).
513    pub(crate) fn can_replay_tails(&self) -> bool {
514        self.manifest_ctx.state.load().can_replay_tails()
515    }
516
517    pub fn region_id(&self) -> RegionId {
518        self.region_id
519    }
520
521    pub fn find_committed_sequence(&self) -> SequenceNumber {
522        self.version_control.committed_sequence()
523    }
524
525    /// Returns the latest sequence that has already been persisted into SSTs.
526    ///
527    /// Incremental memtable-only reads must use a cursor greater than or equal to
528    /// this boundary; older cursors are stale because the corresponding updates may
529    /// already have been flushed out of memtables.
530    pub fn flushed_sequence(&self) -> SequenceNumber {
531        self.version_control.current().version.flushed_sequence
532    }
533
534    /// Returns whether the region is readonly.
535    pub fn is_follower(&self) -> bool {
536        self.manifest_ctx.state.load() == RegionRoleState::Follower
537    }
538
539    /// Returns the state of the region.
540    pub(crate) fn state(&self) -> RegionRoleState {
541        self.manifest_ctx.state.load()
542    }
543
544    /// Sets the region role state. Returns the state this call replaced, None if it left the
545    /// state unchanged.
546    pub(crate) fn set_role(&self, next_role: RegionRole) -> Option<RegionRoleState> {
547        self.manifest_ctx.set_role(next_role, self.region_id)
548    }
549
550    pub(crate) fn region_role(&self) -> RegionRole {
551        match self.state() {
552            RegionRoleState::Follower => RegionRole::Follower,
553            state if state.in_staging_session() => RegionRole::StagingLeader,
554            RegionRoleState::Leader(RegionLeaderState::Downgrading) => {
555                RegionRole::DowngradingLeader
556            }
557            RegionRoleState::Leader(_) => RegionRole::Leader,
558        }
559    }
560
561    /// Returns whether the region is a leader that no longer awaits its Leader lease, see
562    /// [ManifestContext::is_confirmed_leader].
563    pub(crate) fn is_confirmed_leader(&self) -> bool {
564        self.manifest_ctx.is_confirmed_leader()
565    }
566
567    /// Sets the altering state.
568    /// You should call this method in the worker loop.
569    pub(crate) fn set_altering(&self) -> Result<()> {
570        self.compare_exchange_state(
571            RegionLeaderState::Writable,
572            RegionRoleState::Leader(RegionLeaderState::Altering),
573        )
574    }
575
576    /// Sets the dropping state.
577    /// You should call this method in the worker loop.
578    pub(crate) fn set_dropping(&self, expect: RegionLeaderState) -> Result<()> {
579        self.compare_exchange_state(expect, RegionRoleState::Leader(RegionLeaderState::Dropping))
580    }
581
582    /// Sets the truncating state.
583    /// You should call this method in the worker loop.
584    pub(crate) fn set_truncating(&self) -> Result<()> {
585        self.compare_exchange_state(
586            RegionLeaderState::Writable,
587            RegionRoleState::Leader(RegionLeaderState::Truncating),
588        )
589    }
590
591    /// Sets the editing state.
592    /// You should call this method in the worker loop.
593    pub(crate) fn set_editing(&self, expect: RegionLeaderState) -> Result<()> {
594        self.compare_exchange_state(expect, RegionRoleState::Leader(RegionLeaderState::Editing))
595    }
596
597    /// Sets the staging state.
598    ///
599    /// You should call this method in the worker loop.
600    /// Transitions from Writable to Staging state.
601    /// Cleans any existing staging manifests before entering staging mode.
602    pub(crate) async fn set_staging(
603        &self,
604        manager: &mut RwLockWriteGuard<'_, RegionManifestManager>,
605    ) -> Result<()> {
606        manager.clear_staging_manifest_and_dir().await?;
607
608        self.compare_exchange_state(
609            RegionLeaderState::Writable,
610            RegionRoleState::Leader(RegionLeaderState::Staging),
611        )
612    }
613
614    /// Sets the entering staging state.
615    pub(crate) fn set_entering_staging(&self) -> Result<()> {
616        self.compare_exchange_state(
617            RegionLeaderState::Writable,
618            RegionRoleState::Leader(RegionLeaderState::EnteringStaging),
619        )
620    }
621
622    /// Exits the staging state back to writable.
623    ///
624    /// You should call this method in the worker loop.
625    /// Transitions from Staging to Writable state.
626    pub fn exit_staging(&self) -> Result<()> {
627        self.manifest_ctx.exit_staging(
628            self.region_id,
629            RegionRoleState::Leader(RegionLeaderState::Writable),
630        )
631    }
632
633    /// Leaves staging without committing it, abandoning a staged edit in progress.
634    ///
635    /// You should call this method in the worker loop, which is what restores the state of an
636    /// edit, and only when [Self::in_staging_session] holds.
637    pub(crate) fn abort_staging(&self) {
638        let aborted = self
639            .manifest_ctx
640            .state
641            .fetch_update(|state| {
642                matches!(
643                    state,
644                    RegionRoleState::Leader(
645                        RegionLeaderState::Staging | RegionLeaderState::Editing
646                    )
647                )
648                .then_some(RegionRoleState::Leader(RegionLeaderState::Writable))
649            })
650            .is_ok();
651        if aborted {
652            self.manifest_ctx.clear_staging_partition_info();
653        }
654    }
655
656    /// Sets the region role state gracefully. This acquires the manifest write lock, and releases
657    /// it while a change to follower or downgrading leader waits for the pending checkpoint.
658    ///
659    /// Ending staging awaits `drain_stalled_writes` (see [Self::end_staging]); other changes
660    /// drop it.
661    pub(crate) async fn set_role_state_gracefully(
662        &self,
663        state: SettableRegionRoleState,
664        drain_stalled_writes: impl Future<Output = ()>,
665    ) -> Result<()> {
666        let mut manager: RwLockWriteGuard<'_, RegionManifestManager> =
667            self.manifest_ctx.manifest_manager.write().await;
668        // Another writer advanced the manifest of a region waiting for a reload, so a migration
669        // from its last entry id could skip the rows still in its memtable.
670        if matches!(
671            state,
672            SettableRegionRoleState::Follower | SettableRegionRoleState::DowngradingLeader
673        ) && self.manifest_ctx.is_reload_pending()
674        {
675            return RegionBusySnafu {
676                region_id: self.region_id,
677            }
678            .fail();
679        }
680        let current_state = self.state();
681        let mut wait_for_checkpoint = false;
682
683        let hook_payload: Option<PendingManifestHook> = match state {
684            SettableRegionRoleState::Leader => {
685                // Exit staging mode and return to normal writable leader
686                // Only allowed from staging state
687                match current_state {
688                    RegionRoleState::Leader(RegionLeaderState::Staging) => {
689                        info!("Exiting staging mode for region {}", self.region_id);
690                        let pending = self.end_staging(manager, drain_stalled_writes).await?;
691                        manager = self.manifest_ctx.manifest_manager.write().await;
692                        pending
693                    }
694                    RegionRoleState::Leader(RegionLeaderState::Writable) => {
695                        // Already in desired state - no-op
696                        info!("Region {} already in normal leader mode", self.region_id);
697                        None
698                    }
699                    _ => {
700                        // Only staging -> leader transition is allowed
701                        return Err(RegionStateSnafu {
702                            region_id: self.region_id,
703                            state: current_state,
704                            expect: RegionRoleState::Leader(RegionLeaderState::Staging),
705                        }
706                        .build());
707                    }
708                }
709            }
710
711            SettableRegionRoleState::StagingLeader => {
712                // Enter staging mode from normal writable leader
713                // Only allowed from writable leader state
714                match current_state {
715                    RegionRoleState::Leader(RegionLeaderState::Writable) => {
716                        self.version().ensure_no_pending_tails()?;
717                        info!("Entering staging mode for region {}", self.region_id);
718                        self.set_staging(&mut manager).await?;
719                    }
720                    RegionRoleState::Leader(RegionLeaderState::Staging) => {
721                        // Already in desired state - no-op
722                        info!("Region {} already in staging mode", self.region_id);
723                    }
724                    _ => {
725                        return Err(RegionStateSnafu {
726                            region_id: self.region_id,
727                            state: current_state,
728                            expect: RegionRoleState::Leader(RegionLeaderState::Writable),
729                        }
730                        .build());
731                    }
732                }
733                None
734            }
735
736            SettableRegionRoleState::Follower => {
737                // Make this region a follower
738                match current_state {
739                    RegionRoleState::Leader(RegionLeaderState::Staging) => {
740                        info!(
741                            "Exiting staging and demoting region {} to follower",
742                            self.region_id
743                        );
744                        self.exit_staging()?;
745                        self.set_role(RegionRole::Follower);
746                        wait_for_checkpoint = true;
747                    }
748                    RegionRoleState::Leader(_) => {
749                        info!("Demoting region {} from leader to follower", self.region_id);
750                        self.set_role(RegionRole::Follower);
751                        wait_for_checkpoint = true;
752                    }
753                    RegionRoleState::Follower => {
754                        // Already in desired state. The change that made it a follower may
755                        // still wait for the checkpoint.
756                        info!("Region {} already in follower mode", self.region_id);
757                        wait_for_checkpoint = true;
758                    }
759                }
760                None
761            }
762
763            SettableRegionRoleState::DowngradingLeader => {
764                // downgrade this region to downgrading leader
765                match current_state {
766                    RegionRoleState::Leader(RegionLeaderState::Staging) => {
767                        info!(
768                            "Exiting staging and entering downgrade for region {}",
769                            self.region_id
770                        );
771                        self.exit_staging()?;
772                        self.set_role(RegionRole::DowngradingLeader);
773                        wait_for_checkpoint = true;
774                    }
775                    RegionRoleState::Leader(RegionLeaderState::Writable) => {
776                        info!("Starting downgrade for region {}", self.region_id);
777                        self.set_role(RegionRole::DowngradingLeader);
778                        wait_for_checkpoint = true;
779                    }
780                    RegionRoleState::Leader(RegionLeaderState::Downgrading) => {
781                        // Already in desired state - no-op
782                        info!("Region {} already in downgrading mode", self.region_id);
783                        wait_for_checkpoint = true;
784                    }
785                    RegionRoleState::Follower => {
786                        warn!(
787                            "Cannot start downgrade for region {} from state {:?}",
788                            self.region_id, current_state
789                        );
790                        wait_for_checkpoint = true;
791                    }
792                    RegionRoleState::Leader(_) => {
793                        // The region may become writable again when the
794                        // current operation, such as an ALTER, finishes. Fail
795                        // with a retryable error instead of reporting a
796                        // downgrade that does not fence writes.
797                        return Err(RegionStateSnafu {
798                            region_id: self.region_id,
799                            state: current_state,
800                            expect: RegionRoleState::Leader(RegionLeaderState::Writable),
801                        }
802                        .build());
803                    }
804                }
805                None
806            }
807        };
808
809        // The checkpoint task is taken under the lock after the state change, so every commit
810        // that could start a checkpoint has registered it: a follower's commit starts none, and a
811        // commit of a downgrading leader starts no checkpoint. The wait holds no lock, so the
812        // worker and other users of the manifest are not blocked while the checkpoint finishes.
813        if wait_for_checkpoint {
814            let checkpoint_done = manager.pending_checkpoint_completion();
815            drop(manager);
816            checkpoint_done.await;
817            manager = self.manifest_ctx.manifest_manager.write().await;
818        }
819
820        // Hack(zhongzc): If we have just become leader (writable), persist any backfilled metadata.
821        let backfill_hook_payload = self.persist_backfilled_metadata_locked(&mut manager).await;
822
823        drop(manager);
824
825        // Merge both payloads so consumers see the complete set of actions in
826        // one notification. The lock is released, so it's safe to fire.
827        let merged = match (hook_payload, backfill_hook_payload) {
828            (Some(staging), Some(backfill)) => Some(staging.merge(backfill)),
829            (Some(payload), None) => Some(payload),
830            (None, Some(payload)) => Some(payload),
831            (None, None) => None,
832        };
833
834        if let Some(pending) = merged {
835            pending.fire().await;
836        }
837
838        Ok(())
839    }
840
841    /// Persists the metadata backfilled when the region was opened if the manifest lacks it.
842    /// A catchup cannot do it for a region that [awaits its Leader
843    /// lease](ManifestContext::awaits_leader_lease), so the worker does once the region is a
844    /// writable leader with its lease. Returns false if it found the region not a writable
845    /// leader with its Leader lease, so it could not tell whether the metadata needs persisting.
846    pub(crate) async fn persist_backfilled_metadata(&self) -> bool {
847        let mut manager = self.manifest_ctx.manifest_manager.write().await;
848        if !self.may_finish_deferred_lease_work() {
849            return false;
850        }
851        // Checked once: a change the worker starts now cannot commit before the lock is dropped.
852        let pending = self.commit_backfilled_metadata_locked(&mut manager).await;
853        // The hook may read the manifest.
854        drop(manager);
855        if let Some(pending) = pending {
856            pending.fire().await;
857        }
858        true
859    }
860
861    /// Returns whether the region is a writable leader with its Leader lease, which may run the
862    /// work due once it is one.
863    pub(crate) fn may_finish_deferred_lease_work(&self) -> bool {
864        self.state() == RegionRoleState::Leader(RegionLeaderState::Writable)
865            && !self.manifest_ctx.awaits_leader_lease()
866    }
867
868    /// Persists the backfilled metadata of a writable leader that may commit, under the
869    /// caller's manifest lock. Returns the hook to fire after the lock is dropped.
870    async fn persist_backfilled_metadata_locked(
871        &self,
872        manager: &mut RwLockWriteGuard<'_, RegionManifestManager>,
873    ) -> Option<PendingManifestHook> {
874        if !self.may_finish_deferred_lease_work() {
875            return None;
876        }
877        self.commit_backfilled_metadata_locked(manager).await
878    }
879
880    /// Commits the backfilled metadata if the manifest lacks it, under the caller's manifest lock,
881    /// without checking the state. Returns the hook to fire after the lock is dropped.
882    async fn commit_backfilled_metadata_locked(
883        &self,
884        manager: &mut RwLockWriteGuard<'_, RegionManifestManager>,
885    ) -> Option<PendingManifestHook> {
886        // Persist backfilled metadata if manifest is missing fields (e.g., partition_expr).
887        // Only the metadata and the format are kept, so the memtables of the version are not
888        // pinned across the write below.
889        let (current_meta, sst_format) = {
890            let current_version = self.version();
891            (
892                current_version.metadata.clone(),
893                current_version.options.sst_format.unwrap_or_default(),
894            )
895        };
896        if manager.manifest().metadata.partition_expr.is_some()
897            || current_meta.partition_expr.is_none()
898        {
899            return None;
900        }
901        let action = RegionMetaAction::Change(RegionChange {
902            metadata: current_meta,
903            sst_format,
904            append_mode: None,
905        });
906        let action_list = RegionMetaActionList::with_action(action);
907        match self
908            .manifest_ctx
909            .update_locked(manager, action_list, false)
910            .await
911        {
912            Ok(pending) => {
913                info!(
914                    "Successfully persisted backfilled metadata for region {}, version: {}",
915                    self.region_id,
916                    pending.version()
917                );
918                Some(pending)
919            }
920            Err(e) => {
921                warn!(e; "Failed to persist backfilled metadata for region {}", self.region_id);
922                None
923            }
924        }
925    }
926
927    /// Switches the region state to `RegionRoleState::Leader(RegionLeaderState::Writable)` if the current state is `expect`.
928    /// Otherwise, logs an error.
929    pub(crate) fn switch_state_to_writable(&self, expect: RegionLeaderState) {
930        if let Err(e) = self
931            .compare_exchange_state(expect, RegionRoleState::Leader(RegionLeaderState::Writable))
932        {
933            error!(e; "failed to switch region state to writable, expect state is {:?}", expect);
934        }
935    }
936
937    /// Switches the region state to `RegionRoleState::Leader(RegionLeaderState::Staging)` if the current state is `expect`.
938    /// Otherwise, logs an error.
939    pub(crate) fn switch_state_to_staging(&self, expect: RegionLeaderState) {
940        if let Err(e) =
941            self.compare_exchange_state(expect, RegionRoleState::Leader(RegionLeaderState::Staging))
942        {
943            error!(e; "failed to switch region state to staging, expect state is {:?}", expect);
944        }
945    }
946
947    /// Returns the current manifest byte count without computing other region statistics.
948    pub(crate) fn manifest_size(&self) -> u64 {
949        self.stats.total_manifest_size()
950    }
951
952    /// Returns the region statistic.
953    pub(crate) fn region_statistic(&self) -> RegionStatistic {
954        let version = self.version();
955        let memtables = &version.memtables;
956        let memtable_usage = (memtables.mutable_usage() + memtables.immutables_usage()) as u64;
957
958        let sst_usage = version.ssts.owned_sst_usage(self.region_id);
959        let index_usage = version.ssts.owned_index_usage(self.region_id);
960        let flushed_entry_id = version.flushed_entry_id;
961
962        let wal_usage = self.estimated_wal_usage(memtables.decoded_bytes() as u64);
963        let manifest_usage = self.manifest_size();
964        let num_rows = version.ssts.owned_num_rows(self.region_id) + version.memtables.num_rows();
965        let num_files = version.ssts.owned_num_files(self.region_id);
966        let manifest_version = self.stats.manifest_version();
967        let file_removed_cnt = self.stats.file_removed_cnt();
968
969        let time_range = match (version.ssts.time_range(), version.memtables.time_range()) {
970            (Some((sst_min, sst_max)), Some((mem_min, mem_max))) => {
971                Some((sst_min.min(mem_min), sst_max.max(mem_max)))
972            }
973            (range, None) | (None, range) => range,
974        };
975
976        let topic_latest_entry_id = self.topic_latest_entry_id.load(Ordering::Relaxed);
977        let written_bytes = self.region_stats.written_bytes.load(Ordering::Relaxed);
978        let query_cpu_time = self.region_stats.query_cpu_time.load(Ordering::Relaxed);
979        let query_scanned_bytes = self
980            .region_stats
981            .query_scanned_bytes
982            .load(Ordering::Relaxed);
983
984        RegionStatistic {
985            num_rows,
986            memtable_size: memtable_usage,
987            wal_size: wal_usage,
988            manifest_size: manifest_usage,
989            sst_size: sst_usage,
990            sst_num: num_files,
991            index_size: index_usage,
992            manifest: RegionManifestInfo::Mito {
993                manifest_version,
994                flushed_entry_id,
995                file_removed_cnt,
996            },
997            data_topic_latest_entry_id: topic_latest_entry_id,
998            metadata_topic_latest_entry_id: topic_latest_entry_id,
999            written_bytes,
1000            ingested_parquet_bytes: self
1001                .region_stats
1002                .ingested_parquet_bytes
1003                .load(Ordering::Relaxed),
1004            query_cpu_time,
1005            query_scanned_bytes,
1006            min_timestamp: time_range.map(|(min, _)| min),
1007            max_timestamp: time_range.map(|(_, max)| max),
1008            has_pending_tails: version.has_pending_tails(),
1009        }
1010    }
1011
1012    /// Estimated WAL size in bytes.
1013    /// Use the decoded size of the memtable rows to estimate the size of wal.
1014    fn estimated_wal_usage(&self, memtable_decoded_bytes: u64) -> u64 {
1015        ((memtable_decoded_bytes as f32) * ESTIMATED_WAL_FACTOR) as u64
1016    }
1017
1018    /// Sets the state of the region to given state if the current state equals to
1019    /// the expected.
1020    fn compare_exchange_state(
1021        &self,
1022        expect: RegionLeaderState,
1023        state: RegionRoleState,
1024    ) -> Result<()> {
1025        self.manifest_ctx
1026            .state
1027            .compare_exchange(RegionRoleState::Leader(expect), state)
1028            .map_err(|actual| {
1029                RegionStateSnafu {
1030                    region_id: self.region_id,
1031                    state: actual,
1032                    expect: RegionRoleState::Leader(expect),
1033                }
1034                .build()
1035            })?;
1036        Ok(())
1037    }
1038
1039    pub fn access_layer(&self) -> AccessLayerRef {
1040        self.access_layer.clone()
1041    }
1042
1043    /// Returns the region info entry of the region.
1044    pub(crate) fn region_info_entry(&self, node_id: Option<u64>) -> RegionInfoEntry {
1045        let region_id = self.region_id;
1046        let version = self.version();
1047        let state = self.state();
1048        let role = self.region_role();
1049        let region_options = serde_json::to_string(&version.options)
1050            .unwrap_or_else(|err| serde_json::json!({ "error": err.to_string() }).to_string());
1051        let sst_format = match version.options.sst_format.unwrap_or_default() {
1052            crate::sst::FormatType::Narthex => "narthex",
1053            crate::sst::FormatType::PrimaryKey => "primary_key",
1054            crate::sst::FormatType::Flat => "flat",
1055        }
1056        .to_string();
1057
1058        RegionInfoEntry {
1059            region_id,
1060            table_id: region_id.table_id(),
1061            region_number: region_id.region_number(),
1062            region_group: region_id.region_group(),
1063            region_sequence: region_id.region_sequence(),
1064            state: state.as_str().to_string(),
1065            role: role.to_string(),
1066            writable: self.is_writable(),
1067            committed_sequence: self.find_committed_sequence(),
1068            flushed_sequence: Some(self.flushed_sequence()).filter(|sequence| *sequence > 0),
1069            manifest_version: self.stats.manifest_version(),
1070            compaction_time_window: version
1071                .compaction_time_window
1072                .map(|duration| humantime::format_duration(duration).to_string()),
1073            region_options,
1074            sst_format,
1075            node_id,
1076        }
1077    }
1078
1079    /// Returns the SST entries of the region.
1080    pub(crate) async fn manifest_sst_entries(&self) -> Vec<ManifestSstEntry> {
1081        self.manifest_sst_stream(MetadataFilter::default(), ManifestSstProjection::new(None))
1082            .collect()
1083            .await
1084    }
1085
1086    /// Traverses manifest snapshots without copying the file maps. Staging metadata
1087    /// overrides the normal manifest for the same file.
1088    pub(crate) fn manifest_sst_stream(
1089        &self,
1090        filters: MetadataFilter,
1091        projection: ManifestSstProjection,
1092    ) -> BoxStream<'_, ManifestSstEntry> {
1093        Box::pin(async_stream::stream! {
1094            let table_dir = self.table_dir();
1095            let path_type = self.access_layer.path_type();
1096            let visible_files = self.manifest_visible_file_ids(projection);
1097            let (manifest, staging) = {
1098                let manager = self.manifest_ctx.manifest_manager.read().await;
1099                (manager.manifest(), manager.staging_manifest())
1100            };
1101            // A region that left staging without a commit may still hold its staged files.
1102            let staging = staging.filter(|_| self.in_staging_session());
1103            let normal_files = manifest.files.values().map(|meta| (false, meta));
1104            let staging_files = staging.iter().flat_map(|s| s.files.values()).map(|meta| (true, meta));
1105            for (index, (is_staging, meta)) in normal_files.chain(staging_files).enumerate() {
1106                // A selective filter may otherwise traverse millions of files in
1107                // a single poll without yielding any rows.
1108                if index > 0 && index % 1024 == 0 {
1109                    tokio::task::yield_now().await;
1110                }
1111                if !is_staging && staging.as_ref().is_some_and(|s| s.files.contains_key(&meta.file_id)) {
1112                    continue;
1113                }
1114                if !manifest_file_matches(meta, &filters) {
1115                    continue;
1116                }
1117                // Paths describe the creating region, not the referring region.
1118                // Construct them only when a path predicate or projection needs them.
1119                let file_path = OnceCell::new();
1120                if !filters.matches(|column| match column {
1121                    sst_entry::FILE_PATH => Some(file_path.get_or_init(|| {
1122                        ScalarValue::Utf8(Some(meta.file_path(table_dir, path_type)))
1123                    })),
1124                    _ => None,
1125                }) {
1126                    continue;
1127                }
1128                let region_id = self.region_id;
1129                let origin_region_id = meta.region_id;
1130                let (index_version, index_file_path, index_file_size) = if meta.index_file_size > 0
1131                {
1132                    let index_file_path = projection.index_file_path.then(|| index_file_path(table_dir, meta.index_id(), path_type));
1133                    (
1134                        meta.index_version,
1135                        index_file_path,
1136                        Some(meta.index_file_size),
1137                    )
1138                } else {
1139                    (0, None, None)
1140                };
1141                let visible = visible_files.as_ref().is_some_and(|files| files.contains(&meta.file_id));
1142                let file_path = if projection.file_path {
1143                    match file_path.into_inner() {
1144                        Some(ScalarValue::Utf8(Some(path))) => path,
1145                        _ => meta.file_path(table_dir, path_type),
1146                    }
1147                } else {
1148                    String::new()
1149                };
1150                yield ManifestSstEntry {
1151                    table_dir: if projection.table_dir { table_dir.to_string() } else { String::new() },
1152                    region_id,
1153                    table_id: region_id.table_id(),
1154                    region_number: region_id.region_number(),
1155                    region_group: region_id.region_group(),
1156                    region_sequence: region_id.region_sequence(),
1157                    file_id: if projection.file_id { meta.file_id.to_string() } else { String::new() },
1158                    index_version,
1159                    level: meta.level,
1160                    file_path,
1161                    file_size: meta.file_size,
1162                    max_row_group_uncompressed_size: meta.max_row_group_uncompressed_size,
1163                    index_file_path,
1164                    index_file_size,
1165                    num_rows: meta.num_rows,
1166                    num_row_groups: meta.num_row_groups,
1167                    num_series: Some(meta.num_series),
1168                    min_ts: meta.time_range.0,
1169                    max_ts: meta.time_range.1,
1170                    sequence: meta.sequence.map(|s| s.get()),
1171                    partition_expr: if projection.partition_expr { meta.partition_expr.as_ref().map(ToString::to_string) } else { None },
1172                    origin_region_id,
1173                    node_id: None,
1174                    visible,
1175                    primary_key_min: if projection.primary_key_min { meta.primary_key_min.clone() } else { None },
1176                    primary_key_max: if projection.primary_key_max { meta.primary_key_max.clone() } else { None },
1177                };
1178            }
1179        })
1180    }
1181
1182    /// Copies only file IDs so a paused inspection cannot delay SST purging.
1183    /// Hidden residual columns are included in the query's projection.
1184    fn manifest_visible_file_ids(
1185        &self,
1186        projection: ManifestSstProjection,
1187    ) -> Option<HashSet<FileId>> {
1188        projection.visible.then(|| {
1189            self.version()
1190                .ssts
1191                .levels()
1192                .iter()
1193                .flat_map(|level| level.files().map(|file| file.file_id().file_id()))
1194                .collect()
1195        })
1196    }
1197
1198    /// Returns whether the current read version contains any SSTs.
1199    pub fn has_ssts(&self) -> bool {
1200        self.version()
1201            .ssts
1202            .levels()
1203            .iter()
1204            .any(|level| !level.files.is_empty())
1205    }
1206
1207    /// Returns the file metas of the region by file ids.
1208    pub async fn file_metas(&self, file_ids: &[FileId]) -> Vec<Option<FileMeta>> {
1209        let manifest_files = self.manifest_ctx.manifest().await.files.clone();
1210
1211        file_ids
1212            .iter()
1213            .map(|file_id| {
1214                manifest_files
1215                    .get(file_id)
1216                    .map(|meta| meta.as_ref().clone())
1217            })
1218            .collect::<Vec<_>>()
1219    }
1220
1221    /// Returns all live SST file metas and the normal manifest version, merging in the staging
1222    /// manifest while the region is in a staging session.
1223    ///
1224    /// In a staging session (e.g. during region copy/migration), the authoritative live file set
1225    /// lives in the staging manifest, so this method merges both — matching the semantics of
1226    /// [`manifest_sst_entries`]. Outside a session it ignores staged files, since a region that
1227    /// left staging may still hold them.
1228    pub async fn all_manifest_files(&self) -> (Vec<FileMeta>, ManifestVersion) {
1229        let manifest = self.manifest_ctx.manifest().await;
1230        let staging = self
1231            .manifest_ctx
1232            .staging_manifest()
1233            .await
1234            .filter(|_| self.in_staging_session())
1235            .map(|m| m.files.clone());
1236
1237        let files = match staging {
1238            Some(staging_files) => {
1239                let merged = manifest
1240                    .files
1241                    .clone()
1242                    .into_iter()
1243                    .chain(staging_files)
1244                    .collect::<std::collections::HashMap<_, _>>();
1245                merged
1246                    .into_values()
1247                    .map(|meta| meta.as_ref().clone())
1248                    .collect()
1249            }
1250            None => manifest
1251                .files
1252                .values()
1253                .map(|meta| meta.as_ref().clone())
1254                .collect(),
1255        };
1256
1257        (files, manifest.manifest_version)
1258    }
1259
1260    /// Commits the staged edits as one manifest version and ends staging (see
1261    /// [Self::end_staging_locked]) under the manifest write lock `manager`, then drops the lock,
1262    /// awaits `drain_stalled_writes` and clears the staging directory. The drain waits for the
1263    /// worker to handle the writes it stalled, and the worker may be waiting for the lock, so the
1264    /// drain is never awaited under the lock.
1265    /// Returns the receipt of the commit, as [Self::end_staging_locked] does.
1266    pub(crate) async fn end_staging(
1267        &self,
1268        mut manager: RwLockWriteGuard<'_, RegionManifestManager>,
1269        drain_stalled_writes: impl Future<Output = ()>,
1270    ) -> Result<Option<PendingManifestHook>> {
1271        let result = self.end_staging_locked(&mut manager).await;
1272        drop(manager);
1273
1274        // The worker cannot be awaited under the lock, and its writes need not wait for the
1275        // slower clear of the staging directory.
1276        drain_stalled_writes.await;
1277        let pending = result?;
1278        self.clear_ended_staging().await;
1279        Ok(pending)
1280    }
1281
1282    /// Clears the staging directory after staging ended, unless the region was closed (it may be
1283    /// open again by now) or a new staging has begun.
1284    async fn clear_ended_staging(&self) {
1285        let mut manager = self.manifest_ctx.manifest_manager.write().await;
1286        if manager.is_stopped() || self.is_enter_staging() || self.in_staging_session() {
1287            return;
1288        }
1289        if let Err(e) = manager.clear_staging_manifest_and_dir().await {
1290            error!(e; "Failed to clear staging manifest dir for region {}", self.region_id);
1291        }
1292    }
1293
1294    /// Commits the staged edits as one manifest version and ends staging.
1295    ///
1296    /// The caller must hold the manifest write lock and pass it via `manager`. The commit runs in
1297    /// [RegionLeaderState::EndingStaging], which stalls writes and holds role changes back (see
1298    /// [ManifestContext::leave_ending_staging] for the state it leaves for). If the region stays
1299    /// staging, its staged edits are kept for a retry and the error is retryable; otherwise they
1300    /// are dropped.
1301    ///
1302    /// Returns `Ok(None)` when there was nothing to commit.
1303    ///
1304    /// **Important:** [`fire`](PendingManifestHook::fire) the receipt only after
1305    /// dropping the lock — the hook may read the manifest and deadlock otherwise.
1306    pub(crate) async fn end_staging_locked(
1307        &self,
1308        manager: &mut RwLockWriteGuard<'_, RegionManifestManager>,
1309    ) -> Result<Option<PendingManifestHook>> {
1310        let current_state = self.manifest_ctx.current_state();
1311        ensure!(
1312            current_state == RegionRoleState::Leader(RegionLeaderState::Staging),
1313            RegionStateSnafu {
1314                region_id: self.region_id,
1315                state: current_state,
1316                expect: RegionRoleState::Leader(RegionLeaderState::Staging),
1317            }
1318        );
1319
1320        let Some(staged_actions) = manager.staged_actions() else {
1321            info!(
1322                "No staged actions for region {}, exiting staging mode without changes",
1323                self.region_id
1324            );
1325            self.exit_staging()?;
1326            return Ok(None);
1327        };
1328        let expect_change = staged_actions.actions.iter().any(|a| a.is_change());
1329        let expect_partition_expr_change = staged_actions
1330            .actions
1331            .iter()
1332            .any(|a| a.is_partition_expr_change());
1333        let expect_edit = staged_actions.actions.iter().any(|a| a.is_edit());
1334        ensure!(
1335            !(expect_change && expect_partition_expr_change),
1336            UnexpectedSnafu {
1337                reason: "unexpected both change and partition expr change actions in staged actions"
1338            }
1339        );
1340        ensure!(
1341            expect_change || expect_partition_expr_change,
1342            UnexpectedSnafu {
1343                reason: "expect a change or partition expr change action in staged actions"
1344            }
1345        );
1346        ensure!(
1347            expect_edit,
1348            UnexpectedSnafu {
1349                reason: "expect an edit action in staged actions"
1350            }
1351        );
1352
1353        if let Some(RegionMetaAction::Change(change)) =
1354            staged_actions.actions.iter().find(|a| a.is_change())
1355        {
1356            // In staging exit we only allow metadata-only updates. A `Change`
1357            // action is accepted only when column definitions are unchanged;
1358            // otherwise it is treated as a schema change and rejected.
1359            let current_column_metadatas = &self.version().metadata.column_metadatas;
1360            ensure!(
1361                change.metadata.column_metadatas == *current_column_metadatas,
1362                UnexpectedSnafu {
1363                    reason: "change action alters column metadata in staging exit"
1364                }
1365            );
1366        }
1367
1368        self.manifest_ctx
1369            .ensure_leader_lease_or_downgrading(self.region_id)?;
1370        let ending_started_at = self.manifest_ctx.begin_ending_staging(self.region_id)?;
1371        let mut result = self.manifest_ctx.commit_staged_locked(manager).await;
1372        if let Ok((pending, committed)) = &mut result {
1373            info!(
1374                "Successfully committed staged manifests for region {}, new version: {}",
1375                self.region_id,
1376                pending.version()
1377            );
1378            // Apply the committed changes to in-memory version control
1379            let (staged_partition_expr_change, staged_change, staged_edit) =
1380                std::mem::take(committed).split_region_change_and_edit();
1381            if let Some(change) = staged_partition_expr_change {
1382                let mut new_metadata = self.version().metadata.as_ref().clone();
1383                new_metadata.set_partition_expr(change.partition_expr);
1384                self.version_control.alter_metadata(new_metadata.into());
1385            }
1386            if let Some(change) = staged_change {
1387                self.version_control.alter_metadata(change.metadata);
1388            }
1389            self.version_control
1390                .apply_edit(Some(staged_edit), &[], self.file_purger.clone());
1391        }
1392        let result = result.map(|(pending, _)| pending);
1393        let next_state =
1394            self.manifest_ctx
1395                .leave_ending_staging(self.region_id, ending_started_at, &result);
1396        if next_state != RegionRoleState::Leader(RegionLeaderState::Staging) {
1397            // Only a retry commits the staged actions. The listings gate on the state and do not
1398            // rely on this.
1399            manager.unset_staging_manifest();
1400        }
1401
1402        match result {
1403            // A retry of the request commits the kept edits.
1404            Err(e) if next_state == RegionRoleState::Leader(RegionLeaderState::Staging) => {
1405                Err(Arc::new(e)).context(EndStagingSnafu {
1406                    region_id: self.region_id,
1407                })
1408            }
1409            result => result.map(Some),
1410        }
1411    }
1412
1413    pub fn expected_partition_expr_version(&self) -> u64 {
1414        if self.is_staging() {
1415            self.manifest_ctx
1416                .staging_partition_info()
1417                .as_ref()
1418                .map(|info| info.partition_rule_version)
1419                .unwrap_or_default()
1420        } else {
1421            self.version().metadata.partition_expr_version
1422        }
1423    }
1424
1425    /// Returns whether writes should be rejected for this region in staging mode.
1426    pub(crate) fn reject_all_writes_in_staging(&self) -> bool {
1427        if !self.is_staging() {
1428            return false;
1429        }
1430        self.manifest_ctx
1431            .staging_partition_info()
1432            .as_ref()
1433            .map(|info| {
1434                matches!(
1435                    info.partition_directive,
1436                    StagingPartitionDirective::RejectAllWrites
1437                )
1438            })
1439            .unwrap_or(false)
1440    }
1441}
1442
1443impl Drop for MitoRegion {
1444    fn drop(&mut self) {
1445        self.remove_region_metrics();
1446    }
1447}
1448
1449/// Result of publishing rebuilt index metadata to the manifest.
1450#[derive(Debug)]
1451pub(crate) enum IndexPublication {
1452    /// The index metadata was committed.
1453    Committed {
1454        manifest_version: ManifestVersion,
1455        file_meta: FileMeta,
1456    },
1457    /// The build no longer matches the current manifest.
1458    Stale(IndexPublicationStale),
1459}
1460
1461/// Result of publishing an edit of the pending tails, a replay's result or a discard, to the
1462/// manifest.
1463#[derive(Debug, PartialEq, Eq)]
1464pub(crate) enum TailPublication {
1465    /// The edit was committed.
1466    Committed(ManifestVersion),
1467    /// The region is altering or applying an edit, or, without conditional publication, a
1468    /// replay's earlier update may be saved without being applied.
1469    Busy,
1470    /// The region is no longer a writable leader, or its manifest no longer records the
1471    /// expected tails.
1472    Stale,
1473}
1474
1475/// Who publishes an edit of the pending tails.
1476#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1477pub(crate) enum TailsEditor {
1478    /// A tail replay, which commits its own uncertain update again.
1479    Replay,
1480    /// A discard of one node's tails.
1481    Discard,
1482}
1483
1484/// Why an index publication became stale.
1485#[derive(Debug, PartialEq, Eq)]
1486pub(crate) enum IndexPublicationStale {
1487    /// The source SST or region incarnation is no longer publishable.
1488    SourceChanged,
1489    /// The SST still matches, but the schema generation changed.
1490    SchemaChanged,
1491}
1492
1493/// Manifest state an index build is based on.
1494///
1495/// Both fields must still match when the rebuilt index is published. The file
1496/// metadata identifies the exact SST generation, while the schema version
1497/// identifies the exact index definition used by the builder.
1498#[derive(Clone, Debug, PartialEq, Eq)]
1499pub(crate) struct IndexBuildSource {
1500    pub(crate) file_meta: FileMeta,
1501    pub(crate) schema_version: u64,
1502}
1503
1504impl IndexBuildSource {
1505    pub(crate) fn new(file_meta: FileMeta, schema_version: u64) -> Self {
1506        Self {
1507            file_meta,
1508            schema_version,
1509        }
1510    }
1511}
1512
1513/// What [ManifestContext::promote_unless_downgrade_started_after] did with a Leader lease.
1514pub(crate) struct LeaderLeasePromotion {
1515    /// Whether the promotion applied; see the function.
1516    pub(crate) promoted: bool,
1517    /// How long the region awaited its Leader lease, if this lease ended the wait, as
1518    /// [ManifestContext::record_leader_lease] returns it.
1519    pub(crate) ended_wait: Option<Duration>,
1520    /// The state the promotion replaced, None if it left the state unchanged.
1521    pub(crate) replaced: Option<RegionRoleState>,
1522}
1523
1524/// What [ManifestContext::promote_unless_reload_pending] did.
1525struct Promotion {
1526    /// Whether it promoted the region; see the function.
1527    promoted: bool,
1528    /// The state the promotion replaced, as [ManifestContext::set_role] returns it.
1529    replaced: Option<RegionRoleState>,
1530}
1531
1532/// Context to update the region manifest.
1533#[derive(Debug)]
1534pub(crate) struct ManifestContext {
1535    /// Manager to maintain manifest for this region. Logical writes go through
1536    /// [`update_locked`](Self::update_locked) (or an [`update_manifest`](Self::update_manifest)
1537    /// variant; a replay of pending tails makes the same write unchecked, and the end of staging
1538    /// commits through [`commit_staged_locked`](Self::commit_staged_locked)) so they produce a
1539    /// [`PendingManifestHook`].
1540    pub(crate) manifest_manager: tokio::sync::RwLock<RegionManifestManager>,
1541    /// Whether [`Self::manifest_manager`] publishes the manifest by conditional create, which is
1542    /// fixed when the manager is opened.
1543    conditional_publication: bool,
1544    /// The state of the region. The region checks the state before updating
1545    /// manifest.
1546    state: AtomicCell<RegionRoleState>,
1547    /// Decides whether a promotion to Leader applies. The lock covers checking or changing it and
1548    /// the role change.
1549    promotion_fence: Mutex<PromotionFence>,
1550    /// When a catchup last made the region writable, in the unit of [Deadline], until a Leader
1551    /// lease of a heartbeat sent after it applies (or a StagingLeader lease, on a node whose
1552    /// writes need a lease); 0 otherwise. While it is set, the region keeps
1553    /// the unread part of another node's listed tails.
1554    catchup_promoted_at: AtomicU64,
1555    /// Whether a tail replay's manifest update has an uncertain result: it may be saved in
1556    /// storage without being applied to this instance's manifest. Tracked only without
1557    /// conditional publication, where a later update takes a new version instead of
1558    /// conflicting with a saved one. A value left by an ended replay task keeps discards busy
1559    /// until a replay of this instance publishes or the region is reopened.
1560    replay_publication_uncertain: AtomicBool,
1561    /// Deadline of the region's latest Leader or StagingLeader lease from the metasrv, which is how
1562    /// long the Leader role stays valid. The engine extends it from those leases, and writes check
1563    /// it.
1564    pub(crate) leader_deadline: Deadline,
1565    /// The clock of [`Self::leader_deadline`].
1566    node_lease: Arc<NodeLease>,
1567    /// Partition info of the region in staging mode.
1568    ///
1569    /// During the staging mode, the region metadata in [`VersionControlRef`] is not updated,
1570    /// so we need to store the partition info separately.
1571    staging_partition_info: Mutex<Option<StagingPartitionInfo>>,
1572    /// Optional region hook for observing manifest mutations.
1573    hook: Option<RegionHookRef>,
1574    /// Notifications that the region became writable sent to its worker.
1575    #[cfg(test)]
1576    pub(crate) writable_notifications: std::sync::atomic::AtomicUsize,
1577}
1578
1579impl ManifestContext {
1580    pub(crate) fn new(
1581        manager: RegionManifestManager,
1582        state: RegionRoleState,
1583        hook: Option<RegionHookRef>,
1584        node_lease: Arc<NodeLease>,
1585    ) -> Self {
1586        ManifestContext {
1587            conditional_publication: manager.is_conditional_publication(),
1588            manifest_manager: tokio::sync::RwLock::new(manager),
1589            state: AtomicCell::new(state),
1590            promotion_fence: Mutex::new(PromotionFence {
1591                downgrade_started_at: Instant::now(),
1592                reload_pending: false,
1593                catching_up: false,
1594                stopped: false,
1595                promoted_by: None,
1596            }),
1597            catchup_promoted_at: AtomicU64::new(0),
1598            replay_publication_uncertain: AtomicBool::new(false),
1599            leader_deadline: Deadline::default(),
1600            node_lease,
1601            staging_partition_info: Mutex::new(None),
1602            hook,
1603            #[cfg(test)]
1604            writable_notifications: std::sync::atomic::AtomicUsize::new(0),
1605        }
1606    }
1607
1608    /// Returns the region hook if one is registered.
1609    pub(crate) fn hook(&self) -> Option<RegionHookRef> {
1610        self.hook.clone()
1611    }
1612
1613    pub(crate) fn staging_partition_info(&self) -> Option<StagingPartitionInfo> {
1614        self.staging_partition_info.lock().unwrap().clone()
1615    }
1616
1617    pub(crate) fn set_staging_partition_info(&self, staging_partition_info: StagingPartitionInfo) {
1618        let mut current = self.staging_partition_info.lock().unwrap();
1619        debug_assert!(current.is_none());
1620        *current = Some(staging_partition_info);
1621    }
1622
1623    fn clear_staging_partition_info(&self) {
1624        *self.staging_partition_info.lock().unwrap() = None;
1625    }
1626
1627    pub(crate) fn exit_staging(
1628        &self,
1629        region_id: RegionId,
1630        next_state: RegionRoleState,
1631    ) -> Result<()> {
1632        self.state
1633            .compare_exchange(
1634                RegionRoleState::Leader(RegionLeaderState::Staging),
1635                next_state,
1636            )
1637            .map_err(|actual| {
1638                RegionStateSnafu {
1639                    region_id,
1640                    state: actual,
1641                    expect: RegionRoleState::Leader(RegionLeaderState::Staging),
1642                }
1643                .build()
1644            })?;
1645        self.clear_staging_partition_info();
1646        Ok(())
1647    }
1648
1649    /// Switches a staging region to [RegionLeaderState::EndingStaging] and returns the instant
1650    /// it switched.
1651    ///
1652    /// It holds the lock of [Self::begin_downgrade], so a downgrade either has left staging
1653    /// already, or begins after the returned instant.
1654    pub(crate) fn begin_ending_staging(&self, region_id: RegionId) -> Result<Instant> {
1655        let _fence = self.promotion_fence.lock().unwrap();
1656        self.state
1657            .compare_exchange(
1658                RegionRoleState::Leader(RegionLeaderState::Staging),
1659                RegionRoleState::Leader(RegionLeaderState::EndingStaging),
1660            )
1661            .map_err(|actual| {
1662                RegionStateSnafu {
1663                    region_id,
1664                    state: actual,
1665                    expect: RegionRoleState::Leader(RegionLeaderState::Staging),
1666                }
1667                .build()
1668            })?;
1669        Ok(Instant::now())
1670    }
1671
1672    /// Leaves [RegionLeaderState::EndingStaging], entered at `ending_started_at`, after the end
1673    /// commit returned `result`. Returns the state the region leaves it for, which is in order:
1674    /// - Follower if the commit conflicted with another writer or failed on an expired lease;
1675    /// - Downgrading if a downgrade began meanwhile;
1676    /// - Follower if the Leader lease has expired;
1677    /// - Writable if the commit succeeded;
1678    /// - Staging otherwise, keeping the staging partition info for a retry.
1679    pub(crate) fn leave_ending_staging<T>(
1680        &self,
1681        region_id: RegionId,
1682        ending_started_at: Instant,
1683        result: &Result<T>,
1684    ) -> RegionRoleState {
1685        let fence = self.promotion_fence.lock().unwrap();
1686        let lease_expired = self.node_lease.is_enabled() && self.is_leader_lease_expired();
1687        let next_state = match result {
1688            Err(Error::ManifestVersionConflict { .. } | Error::RegionLeaseExpired { .. }) => {
1689                RegionRoleState::Follower
1690            }
1691            _ if fence.downgrade_started_at > ending_started_at => {
1692                RegionRoleState::Leader(RegionLeaderState::Downgrading)
1693            }
1694            _ if lease_expired => RegionRoleState::Follower,
1695            Ok(_) => RegionRoleState::Leader(RegionLeaderState::Writable),
1696            Err(_) => RegionRoleState::Leader(RegionLeaderState::Staging),
1697        };
1698        // Role changes leave a region that is ending staging alone.
1699        self.state.store(next_state);
1700        if next_state != RegionRoleState::Leader(RegionLeaderState::Staging) {
1701            self.clear_staging_partition_info();
1702        }
1703        info!(
1704            "Region {} ended staging, next state: {:?}",
1705            region_id, next_state
1706        );
1707        next_state
1708    }
1709
1710    pub(crate) async fn manifest_version(&self) -> ManifestVersion {
1711        self.manifest_manager
1712            .read()
1713            .await
1714            .manifest()
1715            .manifest_version
1716    }
1717
1718    pub(crate) async fn has_update(&self) -> Result<bool> {
1719        self.manifest_manager.read().await.has_update().await
1720    }
1721
1722    /// Returns the latest manifest version in storage, at least the installed one. The listing
1723    /// runs without the manifest lock, so it does not hold up commits or a stop.
1724    pub(crate) async fn latest_stored_version(&self) -> Result<ManifestVersion> {
1725        let (store, installed) = {
1726            let manager = self.manifest_manager.read().await;
1727            (manager.store(), manager.last_version())
1728        };
1729        store.latest_version(installed).await
1730    }
1731
1732    /// Waits for the in-flight checkpoint of a stopped manager. A stopped manager starts no
1733    /// checkpoint, so this instance no longer writes the manifest directory afterwards.
1734    ///
1735    /// Callers must not hold the manifest lock: this takes its read lock, and the lock is not
1736    /// reentrant. Under the lock, use [RegionManifestManager::wait_for_pending_checkpoint]
1737    /// instead. The wait itself holds no lock.
1738    pub(crate) async fn wait_for_checkpoint_after_stop(&self) {
1739        let done = {
1740            let manager = self.manifest_manager.read().await;
1741            debug_assert!(manager.is_stopped());
1742            manager.pending_checkpoint_completion()
1743        };
1744        done.await;
1745    }
1746
1747    /// Returns the installed manifest version if the storage holds a newer one. The version is
1748    /// read under the manifest read lock, which is not held across the listing, so a caller
1749    /// rechecks it under the write lock before acting on it. It is the installed version, not
1750    /// `last_version`, which a failed commit leaves ahead of it.
1751    pub(crate) async fn installed_version_if_updated(&self) -> Result<Option<ManifestVersion>> {
1752        let (store, installed) = {
1753            let manager = self.manifest_manager.read().await;
1754            (manager.store(), manager.manifest().manifest_version)
1755        };
1756        // Lists without the read lock: held across the listing, it would let a queued writer
1757        // block every later reader.
1758        Ok(store
1759            .has_version_after(installed)
1760            .await?
1761            .then_some(installed))
1762    }
1763
1764    /// Fences the region for a reload, see [Self::fence_for_reload], if it is still a Writable
1765    /// leader at `expected_version`. Returns whether it fenced the region.
1766    pub(crate) async fn fence_for_reload_if_unchanged(
1767        &self,
1768        manager: &mut RegionManifestManager,
1769        region_id: RegionId,
1770        expected_version: ManifestVersion,
1771    ) -> bool {
1772        let state = self.state.load();
1773        let version = manager.manifest().manifest_version;
1774        if state != RegionRoleState::Leader(RegionLeaderState::Writable)
1775            || version != expected_version
1776        {
1777            info!(
1778                "Region {region_id} is {state:?} at manifest version {version}, not a writable leader at version {expected_version}, not fencing it"
1779            );
1780            return false;
1781        }
1782        self.fence_for_reload(manager, region_id).await;
1783        true
1784    }
1785
1786    /// Returns the current region role state.
1787    pub(crate) fn current_state(&self) -> RegionRoleState {
1788        self.state.load()
1789    }
1790
1791    /// Installs the manifest changes from the current version to the target version (inclusive).
1792    ///
1793    /// Returns installed [RegionManifest].
1794    /// **Note**: This function is not guaranteed to install the target version strictly.
1795    /// The installed version may be greater than the target version.
1796    pub(crate) async fn install_manifest_to(
1797        &self,
1798        version: ManifestVersion,
1799    ) -> Result<Arc<RegionManifest>> {
1800        let mut manager = self.manifest_manager.write().await;
1801        manager.install_manifest_to(version).await?;
1802
1803        Ok(manager.manifest())
1804    }
1805
1806    /// Updates the manifest if current state is `expect_state`.
1807    pub(crate) async fn update_manifest(
1808        &self,
1809        expect_state: RegionLeaderState,
1810        action_list: RegionMetaActionList,
1811        is_staging: bool,
1812    ) -> Result<ManifestVersion> {
1813        self.update_manifest_with_state_check(action_list, is_staging, |current_state, region_id| {
1814            // If expect_state is not downgrading, the current state must be either `expect_state` or downgrading.
1815            //
1816            // A downgrading leader rejects user writes but still allows
1817            // flushing the memtable and updating the manifest.
1818            if expect_state != RegionLeaderState::Downgrading {
1819                if current_state == RegionRoleState::Leader(RegionLeaderState::Downgrading) {
1820                    info!(
1821                        "Region {} is in downgrading leader state, updating manifest. Expect state is {:?}",
1822                        region_id, expect_state
1823                    );
1824                }
1825                ensure!(
1826                    current_state == RegionRoleState::Leader(expect_state)
1827                        || current_state == RegionRoleState::Leader(RegionLeaderState::Downgrading),
1828                    UpdateManifestSnafu {
1829                        region_id,
1830                        state: current_state,
1831                    }
1832                );
1833            } else {
1834                ensure!(
1835                    current_state == RegionRoleState::Leader(expect_state),
1836                    RegionStateSnafu {
1837                        region_id,
1838                        state: current_state,
1839                        expect: RegionRoleState::Leader(expect_state),
1840                    }
1841                );
1842            }
1843
1844            Ok(())
1845        })
1846        .await
1847    }
1848
1849    /// Updates the manifest for compaction.
1850    ///
1851    /// Compaction may finish while a direct external region edit is in the transient
1852    /// `Editing` state. Direct external edits can remove files both when followers
1853    /// apply sync-region metadata and when a writable leader performs a direct edit
1854    /// such as `edit_region()`. Allowing compaction to publish in `Editing` is still
1855    /// safe because publication happens under the manifest write lock and compaction
1856    /// rechecks that its input files are still valid before committing.
1857    ///
1858    /// This intentionally writes to the normal manifest path (`is_staging = false`).
1859    /// Entering staging cancels or waits for active compactions before switching the
1860    /// region to `Staging`, so a compaction that started before staging still finishes
1861    /// against the normal manifest. Even if a manual compaction is requested while the
1862    /// region is already staging, compaction only sees SSTs in the normal visible
1863    /// region version; SSTs from staging manifests are not applied to region version
1864    /// control until staging exits successfully.
1865    pub(crate) async fn update_manifest_for_compaction(
1866        &self,
1867        action_list: RegionMetaActionList,
1868    ) -> Result<ManifestVersion> {
1869        self.update_manifest_with_state_check(action_list, false, |current_state, region_id| {
1870            ensure!(
1871                matches!(
1872                    current_state,
1873                    RegionRoleState::Leader(RegionLeaderState::Writable)
1874                        | RegionRoleState::Leader(RegionLeaderState::Editing)
1875                        | RegionRoleState::Leader(RegionLeaderState::Downgrading)
1876                ),
1877                UpdateManifestSnafu {
1878                    region_id,
1879                    state: current_state,
1880                }
1881            );
1882
1883            Ok(())
1884        })
1885        .await
1886    }
1887
1888    /// Publish against the same truncate boundary and the watermarks used to select inputs.
1889    pub(crate) async fn publish_series_indexes(
1890        &self,
1891        edit: &crate::manifest::action::RegionEdit,
1892        truncated: Option<crate::wal::EntryId>,
1893        expected: &HashMap<i64, u64>,
1894    ) -> Result<()> {
1895        let mut manager = self.manifest_manager.write().await;
1896        let manifest = manager.manifest();
1897        let region_id = manifest.metadata.region_id;
1898        ensure!(
1899            !manager.is_stopped()
1900                && self.state.load() == RegionRoleState::Leader(RegionLeaderState::Writable)
1901                && manifest.truncated_entry_id == truncated
1902                && manifest.pending_tails.is_empty(),
1903            RegionBusySnafu { region_id }
1904        );
1905        // A competing merge may replace inputs without advancing the watermark.
1906        for id in &edit.series_indexes_to_remove {
1907            ensure!(
1908                manifest
1909                    .series_indexes
1910                    .get(&id.file_id())
1911                    .is_some_and(|file| file.file_id() == *id),
1912                RegionBusySnafu { region_id }
1913            );
1914        }
1915        let mut current = HashMap::<i64, u64>::new();
1916        for w in manifest
1917            .series_indexes
1918            .values()
1919            .filter_map(|f| f.series_window())
1920        {
1921            let seq = current.entry(w.start).or_default();
1922            *seq = (*seq).max(w.max_sequence);
1923        }
1924        for window in edit
1925            .series_indexes_to_add
1926            .iter()
1927            .filter_map(FileMeta::series_window)
1928        {
1929            ensure!(
1930                manifest
1931                    .series_window_seconds
1932                    .is_none_or(|width| width == window.end - window.start)
1933                    && current.get(&window.start) == expected.get(&window.start),
1934                RegionBusySnafu { region_id }
1935            );
1936        }
1937        let actions = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone()));
1938        match self.update_locked(&mut manager, actions, false).await {
1939            Ok(pending) => {
1940                self.unlock_and_fire(manager, pending).await;
1941            }
1942            Err(error) => {
1943                if error.may_have_persisted_manifest_update() {
1944                    manager.stop().await;
1945                }
1946                return Err(error);
1947            }
1948        }
1949        Ok(())
1950    }
1951
1952    /// Conditionally publishes rebuilt index metadata for `source`.
1953    ///
1954    /// The source SST and schema-generation checks share the manifest write lock
1955    /// with the update, so a concurrent compaction, schema change, or another
1956    /// index build cannot commit between them.
1957    pub(crate) async fn update_manifest_for_index(
1958        &self,
1959        source: &IndexBuildSource,
1960        updated: FileMeta,
1961    ) -> Result<IndexPublication> {
1962        let manager = self.manifest_manager.write().await;
1963        let manifest = manager.manifest();
1964        let current_state = self.state.load();
1965        if !matches!(
1966            current_state,
1967            RegionRoleState::Leader(RegionLeaderState::Writable)
1968                | RegionRoleState::Leader(RegionLeaderState::Downgrading)
1969        ) || manager.is_stopped()
1970        {
1971            return Ok(IndexPublication::Stale(
1972                IndexPublicationStale::SourceChanged,
1973            ));
1974        }
1975
1976        if manifest
1977            .files
1978            .get(&source.file_meta.file_id)
1979            .map(AsRef::as_ref)
1980            != Some(&source.file_meta)
1981        {
1982            return Ok(IndexPublication::Stale(
1983                IndexPublicationStale::SourceChanged,
1984            ));
1985        }
1986
1987        if manifest.metadata.schema_version != source.schema_version {
1988            return Ok(IndexPublication::Stale(
1989                IndexPublicationStale::SchemaChanged,
1990            ));
1991        }
1992
1993        // Only index metadata is allowed to change in this publication.
1994        let mut committed = source.file_meta.clone();
1995        committed.available_indexes = updated.available_indexes;
1996        committed.indexes = updated.indexes;
1997        committed.index_file_size = updated.index_file_size;
1998        committed.index_version = updated.index_version;
1999
2000        let edit = crate::manifest::action::RegionEdit {
2001            files_to_add: vec![committed.clone()],
2002            files_to_remove: Vec::new(),
2003            timestamp_ms: Some(chrono::Utc::now().timestamp_millis()),
2004            flushed_sequence: None,
2005            flushed_entry_id: None,
2006            committed_sequence: None,
2007            compaction_time_window: None,
2008            ..Default::default()
2009        };
2010        let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit));
2011        let manifest_version = self.update_and_fire(manager, action_list, false).await?;
2012
2013        Ok(IndexPublication::Committed {
2014            manifest_version,
2015            file_meta: committed,
2016        })
2017    }
2018
2019    /// Publishes an edit of the pending tails `expected` by `editor`, if the region is still a
2020    /// writable leader whose manifest records exactly those tails.
2021    ///
2022    /// Without conditional publication, a discard is busy while a replay's earlier update has an
2023    /// uncertain result, since it may be in storage and the discard would record the replayed
2024    /// tails again. A replay's update is uncertain from before its write until it commits; an
2025    /// attempt that fails without saving anything keeps the uncertainty of the attempts before
2026    /// it. With conditional publication the next update reuses the version of an uncertain
2027    /// one, so a discard over a saved update conflicts and the region reloads instead.
2028    pub(crate) async fn update_manifest_for_tails(
2029        &self,
2030        expected: &[PendingTail],
2031        action_list: RegionMetaActionList,
2032        editor: TailsEditor,
2033    ) -> Result<TailPublication> {
2034        let mut manager = self.manifest_manager.write().await;
2035        match self.state.load() {
2036            RegionRoleState::Leader(RegionLeaderState::Writable) => {}
2037            RegionRoleState::Leader(RegionLeaderState::Altering | RegionLeaderState::Editing) => {
2038                return Ok(TailPublication::Busy);
2039            }
2040            _ => return Ok(TailPublication::Stale),
2041        }
2042        if manager.manifest().pending_tails != expected {
2043            return Ok(TailPublication::Stale);
2044        }
2045        let tracks_uncertainty = !manager.is_conditional_publication();
2046        let was_uncertain = match editor {
2047            // Set under the lock before the write, so no discard commits between a saved write
2048            // and its error.
2049            TailsEditor::Replay if tracks_uncertainty => self
2050                .replay_publication_uncertain
2051                .swap(true, Ordering::Relaxed),
2052            TailsEditor::Discard
2053                if tracks_uncertainty
2054                    && self.replay_publication_uncertain.load(Ordering::Relaxed) =>
2055            {
2056                return Ok(TailPublication::Busy);
2057            }
2058            _ => false,
2059        };
2060        // A region that awaits its Leader lease commits a replay of its tails, not a discard.
2061        let result = match editor {
2062            TailsEditor::Replay => {
2063                match self.write_locked(&mut manager, action_list, false).await {
2064                    Ok(pending) => Ok(self.unlock_and_fire(manager, pending).await),
2065                    Err(e) => Err(e),
2066                }
2067            }
2068            TailsEditor::Discard => self.update_and_fire(manager, action_list, false).await,
2069        };
2070        if editor == TailsEditor::Replay && tracks_uncertainty {
2071            match &result {
2072                Ok(_) => self
2073                    .replay_publication_uncertain
2074                    .store(false, Ordering::Relaxed),
2075                // This attempt saved nothing, but an earlier one may have.
2076                Err(e) if !e.may_have_persisted_manifest_update() => self
2077                    .replay_publication_uncertain
2078                    .store(was_uncertain, Ordering::Relaxed),
2079                Err(_) => {}
2080            }
2081        }
2082        Ok(TailPublication::Committed(result?))
2083    }
2084
2085    /// Commits the empty edit a catchup makes before the region becomes writable, as the version
2086    /// after the manifest the region holds when it commits. A writer that committed other content
2087    /// at that version conflicts with it. Two catchups that start from the same manifest version
2088    /// commit the same content, so they are not told apart. Only a manifest published
2089    /// conditionally detects a conflict, so without conditional publication it commits nothing.
2090    ///
2091    /// The region commits as a Follower, which needs no valid Leader deadline, so the commit
2092    /// skips the deadline check. Like a commit of a region that awaits its Leader lease, it
2093    /// starts no checkpoint and applies only if no checkpoint covers its version. A conflict
2094    /// leaves the region and its manifest manager as they are: the next catchup reopens the
2095    /// region from the newer manifest. A stopped region commits nothing.
2096    ///
2097    /// Returns the receipt of the manifest hook, which the caller fires once it holds no manifest
2098    /// lock, or None if it committed nothing.
2099    pub(crate) async fn commit_catchup(&self) -> Result<Option<PendingManifestHook>> {
2100        let mut manager = self.manifest_manager.write().await;
2101        if !manager.is_conditional_publication() {
2102            return Ok(None);
2103        }
2104        self.commit_catchup_locked(&mut manager, RegionEdit::default())
2105            .await
2106            .map(Some)
2107    }
2108
2109    /// Commits the catchup of a region whose manifest is published conditionally as
2110    /// [Self::commit_catchup] does, with `edit` and under the caller's manifest write lock. The
2111    /// caller decides whether the region's worker applies `edit` to the region's version.
2112    pub(crate) async fn commit_catchup_locked(
2113        &self,
2114        manager: &mut RegionManifestManager,
2115        edit: RegionEdit,
2116    ) -> Result<PendingManifestHook> {
2117        let region_id = manager.manifest().metadata.region_id;
2118        let state = self.state.load();
2119        ensure!(
2120            state == RegionRoleState::Follower,
2121            RegionStateSnafu {
2122                region_id,
2123                state,
2124                expect: RegionRoleState::Follower,
2125            }
2126        );
2127        ensure!(!self.is_reload_pending(), RegionBusySnafu { region_id });
2128        // A stop marks the region before it waits for this lock to stop the manager.
2129        ensure!(!self.is_stopped(), RegionStoppedSnafu { region_id });
2130        let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit));
2131        let action_list_for_hook = self.hook.as_ref().map(|_| action_list.clone());
2132        let version = manager
2133            .update_with_verification(action_list, false, false, || true)
2134            .await?;
2135        let pending = PendingManifestHook::new(
2136            region_id,
2137            action_list_for_hook,
2138            version,
2139            self.hook.clone(),
2140            false,
2141        );
2142        Ok(pending)
2143    }
2144
2145    /// Performs a manifest write under a caller-held write lock and returns a
2146    /// [`PendingManifestHook`] to [`fire`](PendingManifestHook::fire) after
2147    /// dropping the lock. It is the checked entry of the shared write
2148    /// `write_locked`, which a replay of pending tails calls without the check;
2149    /// the end of staging commits through [`Self::commit_staged_locked`] instead.
2150    ///
2151    /// Fails an update that is not staged while the region [awaits its Leader
2152    /// lease](Self::awaits_leader_lease) and is not downgrading. Does not
2153    /// validate state or edit applicability — the caller must do so while still
2154    /// holding the lock (see `update_manifest_with_state_check` and
2155    /// `MitoRegion::persist_backfilled_metadata_locked`).
2156    pub(crate) async fn update_locked(
2157        &self,
2158        manager: &mut RegionManifestManager,
2159        action_list: RegionMetaActionList,
2160        is_staging: bool,
2161    ) -> Result<PendingManifestHook> {
2162        if !is_staging {
2163            self.ensure_leader_lease_or_downgrading(manager.manifest().metadata.region_id)?;
2164        }
2165        self.write_locked(manager, action_list, is_staging).await
2166    }
2167
2168    /// Performs the manifest write of [Self::update_locked] without its Leader lease check.
2169    async fn write_locked(
2170        &self,
2171        manager: &mut RegionManifestManager,
2172        action_list: RegionMetaActionList,
2173        is_staging: bool,
2174    ) -> Result<PendingManifestHook> {
2175        let region_id = manager.manifest().metadata.region_id;
2176        // Clone before `action_list` is moved into `update_with_verification`
2177        // so the hook still sees what was written.
2178        let action_list_for_hook = self.hook.as_ref().map(|_| action_list.clone());
2179        // A lease that ends the wait during the write does not lift the checks below.
2180        let awaited_leader_lease = self.awaits_leader_lease();
2181        // The final flush of a downgrading leader must not start cleanup after the downgrade
2182        // checkpoint barrier, nor may a region that awaits its Leader lease and may not own the
2183        // region yet.
2184        let allow_checkpoint = !is_staging
2185            && self.state.load() != RegionRoleState::Leader(RegionLeaderState::Downgrading)
2186            && !awaited_leader_lease;
2187        let version = self
2188            .commit_locked(manager, async |manager| {
2189                manager
2190                    .update_with_verification(action_list, is_staging, allow_checkpoint, || {
2191                        awaited_leader_lease || self.must_verify_commit()
2192                    })
2193                    .await
2194            })
2195            .await?;
2196
2197        Ok(PendingManifestHook::new(
2198            region_id,
2199            action_list_for_hook,
2200            version,
2201            self.hook.clone(),
2202            is_staging,
2203        ))
2204    }
2205
2206    /// Commits the staged actions of `manager` as one version under a caller-held write lock.
2207    /// Returns a [`PendingManifestHook`] to [`fire`](PendingManifestHook::fire) after dropping
2208    /// the lock, and the committed actions.
2209    pub(crate) async fn commit_staged_locked(
2210        &self,
2211        manager: &mut RegionManifestManager,
2212    ) -> Result<(PendingManifestHook, RegionMetaActionList)> {
2213        let region_id = manager.manifest().metadata.region_id;
2214        let (version, committed) = self
2215            .commit_locked(manager, async |manager| {
2216                manager.commit_staged(|| self.must_verify_commit()).await
2217            })
2218            .await?;
2219        let actions_for_hook = self.hook.as_ref().map(|_| committed.clone());
2220
2221        let pending = PendingManifestHook::new(
2222            region_id,
2223            actions_for_hook,
2224            version,
2225            self.hook.clone(),
2226            false,
2227        );
2228        Ok((pending, committed))
2229    }
2230
2231    /// Runs the manifest commit `commit` under a caller-held write lock. A writer past its
2232    /// Leader deadline may no longer hold the region, so in conditional publication it sends
2233    /// nothing; a commit that finds a newer manifest fences the region (see
2234    /// [Self::fence_for_reload]).
2235    async fn commit_locked<T>(
2236        &self,
2237        manager: &mut RegionManifestManager,
2238        commit: impl AsyncFnOnce(&mut RegionManifestManager) -> Result<T>,
2239    ) -> Result<T> {
2240        let region_id = manager.manifest().metadata.region_id;
2241        let result = match self.ensure_commit_deadline(manager) {
2242            Ok(()) => commit(manager).await,
2243            Err(error) => Err(error),
2244        };
2245        if let Err(e) = &result {
2246            error!(e; "Failed to update manifest, region_id: {}", region_id);
2247            if matches!(e, Error::ManifestVersionConflict { .. }) {
2248                self.fence_for_reload(manager, region_id).await;
2249            }
2250        }
2251        result
2252    }
2253
2254    /// Checks the leader deadline for a conditionally published manifest.
2255    pub(crate) fn ensure_commit_deadline(&self, manager: &RegionManifestManager) -> Result<()> {
2256        ensure!(
2257            !manager.is_conditional_publication() || !self.is_leader_lease_expired(),
2258            RegionLeaseExpiredSnafu {
2259                region_id: manager.manifest().metadata.region_id
2260            }
2261        );
2262        Ok(())
2263    }
2264
2265    /// Returns whether a commit, once written, checks that no checkpoint covers its version: a
2266    /// region past its Leader deadline may no longer hold the region, and one that [awaits its
2267    /// Leader lease](Self::awaits_leader_lease) may not hold it yet, so either may have written a
2268    /// version name that checkpoint cleanup freed.
2269    fn must_verify_commit(&self) -> bool {
2270        self.is_leader_lease_expired() || self.awaits_leader_lease()
2271    }
2272
2273    /// Returns whether the region's Leader deadline has passed. No deadline counts as passed.
2274    fn is_leader_lease_expired(&self) -> bool {
2275        self.node_lease.now() >= self.leader_deadline.get()
2276    }
2277
2278    /// Fences a region whose manifest another writer has advanced, under the caller's manifest
2279    /// lock: later commits fail, and the region stays a Follower that no promotion changes until
2280    /// the worker replaces it with an instance reloaded from the new manifest.
2281    pub(crate) async fn fence_for_reload(
2282        &self,
2283        manager: &mut RegionManifestManager,
2284        region_id: RegionId,
2285    ) {
2286        manager.stop().await;
2287        // Marked before the role change, so a promotion in between cannot make it writable again.
2288        self.promotion_fence.lock().unwrap().reload_pending = true;
2289        self.set_role(RegionRole::Follower, region_id);
2290        warn!("Region {region_id} is fenced until it is reloaded");
2291    }
2292
2293    /// Returns whether the region waits for a reload, see [Self::fence_for_reload].
2294    pub(crate) fn is_reload_pending(&self) -> bool {
2295        self.promotion_fence.lock().unwrap().reload_pending
2296    }
2297
2298    /// Returns whether a catchup runs on this instance, see [Self::begin_catchup]. An instance a
2299    /// catchup replaced keeps the flag set, so it is read on the registered instance.
2300    pub(crate) fn is_catching_up(&self) -> bool {
2301        self.promotion_fence.lock().unwrap().catching_up
2302    }
2303
2304    /// Ignores the promotions issued before now. The worker calls it on a reloaded instance, and
2305    /// on the replacement of a catchup again, when it replaces the old one, whose time a downgrade
2306    /// meanwhile raised instead.
2307    pub(crate) fn ignore_earlier_promotions(&self) {
2308        self.promotion_fence.lock().unwrap().downgrade_started_at = Instant::now();
2309    }
2310
2311    /// Updates the manifest using a caller-held write lock, releases the lock,
2312    /// and then fires the manifest hook.
2313    ///
2314    /// Callers must perform state and applicability checks before calling this
2315    /// method so the checks and update remain in the same lock critical section.
2316    async fn update_and_fire(
2317        &self,
2318        mut manager: RwLockWriteGuard<'_, RegionManifestManager>,
2319        action_list: RegionMetaActionList,
2320        is_staging: bool,
2321    ) -> Result<ManifestVersion> {
2322        let pending = self
2323            .update_locked(&mut manager, action_list, is_staging)
2324            .await?;
2325        Ok(self.unlock_and_fire(manager, pending).await)
2326    }
2327
2328    /// Releases the lock of the write that returned `pending`, then fires its hook.
2329    async fn unlock_and_fire(
2330        &self,
2331        manager: RwLockWriteGuard<'_, RegionManifestManager>,
2332        pending: PendingManifestHook,
2333    ) -> ManifestVersion {
2334        let region_id = manager.manifest().metadata.region_id;
2335        let version = pending.version();
2336
2337        // Hook implementations may read the manifest or send region requests
2338        // that acquire this lock.
2339        drop(manager);
2340
2341        if self.state.load() == RegionRoleState::Follower {
2342            warn!(
2343                "Region {} becomes follower while updating manifest which may cause inconsistency, manifest version: {version}",
2344                region_id
2345            );
2346        }
2347
2348        pending.fire().await;
2349        version
2350    }
2351
2352    async fn update_manifest_with_state_check(
2353        &self,
2354        action_list: RegionMetaActionList,
2355        is_staging: bool,
2356        check_state: impl FnOnce(RegionRoleState, RegionId) -> Result<()>,
2357    ) -> Result<ManifestVersion> {
2358        // Acquires the write lock of the manifest manager.
2359        let manager = self.manifest_manager.write().await;
2360        // Gets current manifest.
2361        let manifest = manager.manifest();
2362        // Checks state inside the lock. This is to ensure that we won't update the manifest
2363        // after `set_readonly_gracefully()` is called.
2364        let current_state = self.state.load();
2365        check_state(current_state, manifest.metadata.region_id)?;
2366
2367        for action in &action_list.actions {
2368            // Checks whether the edit is still applicable.
2369            let RegionMetaAction::Edit(edit) = &action else {
2370                continue;
2371            };
2372
2373            edit.validate_shared_reclassification(manifest.metadata.region_id)?;
2374            // Imports may add shared references, but ordinary edits must not retire
2375            // or overwrite them. Table publication performs its own locked input check.
2376            ensure!(
2377                edit.files_to_remove.iter().all(|file| {
2378                    file.level != file::LEVEL_SHARED
2379                        && manifest
2380                            .files
2381                            .get(&file.file_id)
2382                            .is_none_or(|current| current.level != file::LEVEL_SHARED)
2383                }) && edit.files_to_add.iter().all(|file| {
2384                    manifest.files.get(&file.file_id).is_none_or(|current| {
2385                        current.level != file::LEVEL_SHARED || current.as_ref() == file
2386                    })
2387                }),
2388                InvalidRequestSnafu {
2389                    region_id: manifest.metadata.region_id,
2390                    reason: "Ordinary manifest edits cannot modify shared SSTs",
2391                }
2392            );
2393
2394            // Checks whether the region is truncated.
2395            let Some(truncated_entry_id) = manifest.truncated_entry_id else {
2396                continue;
2397            };
2398
2399            // This is an edit from flush.
2400            if let Some(flushed_entry_id) = edit.flushed_entry_id {
2401                // A flush edit is valid after truncate in two cases:
2402                // 1. `flushed_entry_id` moves past `truncated_entry_id`, meaning it definitely
2403                //    flushed data newer than the truncate point.
2404                // 2. `flushed_entry_id` equals `truncated_entry_id`, but `flushed_sequence`
2405                //    increases. This happens in skip-WAL tables where entry id can stay at 0,
2406                //    while sequence still advances for post-truncate writes.
2407                //
2408                // We still reject stale flushes from before truncate:
2409                // if entry id is equal and sequence does not advance, the flush is outdated.
2410                let is_newer_entry = truncated_entry_id < flushed_entry_id;
2411                let is_same_entry_with_newer_sequence = truncated_entry_id == flushed_entry_id
2412                    && edit.flushed_sequence.is_some_and(|flushed_sequence| {
2413                        manifest.flushed_sequence < flushed_sequence
2414                    });
2415
2416                ensure!(
2417                    is_newer_entry || is_same_entry_with_newer_sequence,
2418                    RegionTruncatedSnafu {
2419                        region_id: manifest.metadata.region_id,
2420                    }
2421                );
2422            }
2423
2424            // This is an edit from compaction.
2425            if !edit.files_to_remove.is_empty() {
2426                // Input files of the compaction task has been truncated.
2427                for file in &edit.files_to_remove {
2428                    ensure!(
2429                        manifest.files.contains_key(&file.file_id),
2430                        RegionTruncatedSnafu {
2431                            region_id: manifest.metadata.region_id,
2432                        }
2433                    );
2434                }
2435            }
2436        }
2437
2438        self.update_and_fire(manager, action_list, is_staging).await
2439    }
2440
2441    /// Raises the downgrade start time to now, then marks the region downgrading.
2442    pub(crate) fn begin_downgrade(&self, region_id: RegionId) {
2443        let mut fence = self.promotion_fence.lock().unwrap();
2444        fence.downgrade_started_at = Instant::now();
2445        self.set_role(RegionRole::DowngradingLeader, region_id);
2446    }
2447
2448    /// Promotes the region to a writable leader unless a downgrade started after `issued_at`, a
2449    /// catchup runs on it, it waits for a reload or it was stopped. `promoted` is false if the
2450    /// promotion is ignored for one of these reasons; otherwise the role changes as
2451    /// [`Self::set_role`] allows.
2452    /// `ended_wait` tells whether this lease ended the region's wait for its Leader lease. A lease
2453    /// ignored for a downgrade or a catchup ends no wait.
2454    pub(crate) fn promote_unless_downgrade_started_after(
2455        &self,
2456        issued_at: Instant,
2457        region_id: RegionId,
2458    ) -> LeaderLeasePromotion {
2459        // A writable leader that received its Leader lease needs no change and takes no lock. One
2460        // that awaits it takes the lock, so a catchup either demotes it first or finds the wait
2461        // ended, see `begin_catchup`; a staging leader is promoted below.
2462        if self.state.load() == RegionRoleState::Leader(RegionLeaderState::Writable)
2463            && self.leader_lease_received()
2464        {
2465            return LeaderLeasePromotion {
2466                promoted: true,
2467                ended_wait: None,
2468                replaced: None,
2469            };
2470        }
2471        let fence = self.promotion_fence.lock().unwrap();
2472        if issued_at < fence.downgrade_started_at || fence.catching_up {
2473            return LeaderLeasePromotion {
2474                promoted: false,
2475                ended_wait: None,
2476                replaced: None,
2477            };
2478        }
2479        let ended_wait = self.record_leader_lease(issued_at);
2480        let promotion = self.promote_unless_reload_pending(&fence, region_id, false);
2481        LeaderLeasePromotion {
2482            promoted: promotion.promoted,
2483            ended_wait,
2484            replaced: promotion.replaced,
2485        }
2486    }
2487
2488    /// Promotes a region that caught up to a writable leader and ends its catchup, recording the
2489    /// catchup's `candidate_lease_id`. Returns false if the region waits for a reload or was
2490    /// stopped.
2491    pub(crate) fn promote_after_catchup(
2492        &self,
2493        region_id: RegionId,
2494        candidate_lease_id: Option<u64>,
2495    ) -> bool {
2496        let mut fence = self.promotion_fence.lock().unwrap();
2497        fence.catching_up = false;
2498        let promoted = self
2499            .promote_unless_reload_pending(&fence, region_id, true)
2500            .promoted;
2501        if promoted {
2502            fence.promoted_by = candidate_lease_id;
2503        }
2504        promoted
2505    }
2506
2507    /// Returns whether the region was stopped, so no catchup promotes it.
2508    pub(crate) fn is_stopped(&self) -> bool {
2509        self.promotion_fence.lock().unwrap().stopped
2510    }
2511
2512    /// Begins a catchup with `candidate_lease_id` unless the region is writable (a writable or
2513    /// staging leader, as [MitoRegion::is_writable]) and does not
2514    /// [await its Leader lease](Self::awaits_leader_lease), and returns whether the region awaits
2515    /// its Leader lease and, if so, whether the catchup repeats the catchup that promoted it
2516    /// ([AwaitedPromotion]), None if it begins none. Until the catchup ends, Leader leases do not
2517    /// promote the region and end no wait, see [Self::promote_after_catchup] and
2518    /// [Self::end_catchup]; the caller ends it on every path. A writable region is demoted to
2519    /// Follower and ignores the Leader leases sent before. A lease that ends the wait of a writable
2520    /// region holds the same lock.
2521    pub(crate) fn begin_catchup(
2522        &self,
2523        region_id: RegionId,
2524        candidate_lease_id: Option<u64>,
2525    ) -> Option<AwaitedPromotion> {
2526        let mut fence = self.promotion_fence.lock().unwrap();
2527        let writable = matches!(
2528            self.state.load(),
2529            RegionRoleState::Leader(RegionLeaderState::Writable | RegionLeaderState::Staging)
2530        );
2531        let awaits_leader_lease = self.awaits_leader_lease();
2532        if writable && !awaits_leader_lease {
2533            return None;
2534        }
2535        fence.catching_up = true;
2536        if writable {
2537            fence.downgrade_started_at = Instant::now();
2538            self.set_role(RegionRole::Follower, region_id);
2539        }
2540        // Registration generates a random nonzero candidate lease id. A matching id signals a
2541        // retry of the migration whose catchup promoted the region.
2542        Some(if !awaits_leader_lease {
2543            AwaitedPromotion::NoPendingPromotion
2544        } else if candidate_lease_id.is_some() && candidate_lease_id == fence.promoted_by {
2545            AwaitedPromotion::SameMigration
2546        } else {
2547            AwaitedPromotion::OtherOrUnknownMigration
2548        })
2549    }
2550
2551    /// Records a StagingLeader lease as [Self::record_leader_lease] does, unless a catchup runs on
2552    /// the region.
2553    pub(crate) fn record_staging_leader_lease(&self, issued_at: Instant) -> Option<Duration> {
2554        let fence = self.promotion_fence.lock().unwrap();
2555        if fence.catching_up {
2556            return None;
2557        }
2558        self.record_leader_lease(issued_at)
2559    }
2560
2561    /// Demotes the region to a follower for a lease the metasrv granted to it as the candidate of
2562    /// a migration, unless the region [awaits its Leader lease](Self::awaits_leader_lease) (a
2563    /// catchup of the migration promoted it, and the route switch that follows grants that lease;
2564    /// after a rollback, the lease may belong to the next migration, whose catchup carries its
2565    /// own candidate lease id, see [Self::begin_catchup]). Returns the state this call replaced,
2566    /// None if it left the state unchanged.
2567    ///
2568    /// It holds the lock of [Self::promote_after_catchup], so a promotion is either seen or
2569    /// happens after the demotion.
2570    pub(crate) fn demote_candidate(&self, region_id: RegionId) -> Option<RegionRoleState> {
2571        let _fence = self.promotion_fence.lock().unwrap();
2572        if self.awaits_leader_lease() {
2573            return None;
2574        }
2575        self.set_role(RegionRole::Follower, region_id)
2576    }
2577
2578    /// Ends a catchup that does not promote the region, so the next Leader lease promotes it.
2579    pub(crate) fn end_catchup(&self) {
2580        self.promotion_fence.lock().unwrap().catching_up = false;
2581    }
2582
2583    /// Makes the region wait for its Leader lease as a catchup on a node whose writes need a lease
2584    /// does, without a catchup: it keeps the memtable and enables the node lease the engine
2585    /// shares.
2586    #[cfg(test)]
2587    pub(crate) fn start_leader_lease_wait_for_test(
2588        &self,
2589        region_id: RegionId,
2590        candidate_lease_id: Option<u64>,
2591    ) {
2592        self.node_lease.enable();
2593        self.leader_deadline
2594            .extend(Instant::now() + Duration::from_secs(60));
2595        assert!(self.promote_after_catchup(region_id, candidate_lease_id));
2596        assert!(self.awaits_leader_lease());
2597    }
2598
2599    /// Marks the region stopped as [MitoRegion::stop] does before it stops the manifest manager.
2600    #[cfg(test)]
2601    pub(crate) fn mark_stopped_for_test(&self) {
2602        self.promotion_fence.lock().unwrap().stopped = true;
2603    }
2604
2605    /// Promotes the region unless it waits for a reload or was stopped. The caller holds the fence
2606    /// lock.
2607    fn promote_unless_reload_pending(
2608        &self,
2609        fence: &PromotionFence,
2610        region_id: RegionId,
2611        by_catchup: bool,
2612    ) -> Promotion {
2613        if fence.reload_pending || fence.stopped {
2614            return Promotion {
2615                promoted: false,
2616                replaced: None,
2617            };
2618        }
2619        if by_catchup {
2620            // Before the role, so a lease that finds the region writable compares with it.
2621            self.catchup_promoted_at
2622                .store(lease_nanos(Instant::now()).max(1), Ordering::Relaxed);
2623        }
2624        Promotion {
2625            promoted: true,
2626            replaced: self.set_role(RegionRole::Leader, region_id),
2627        }
2628    }
2629
2630    /// Counts an applied Leader lease (or StagingLeader lease, on a node whose writes need a lease)
2631    /// of a heartbeat sent at `issued_at` as received since the
2632    /// last catchup promotion. A heartbeat sent before the promotion does not count: its lease
2633    /// may have been granted before an earlier downgrade of this node, which
2634    /// [Self::record_staging_leader_lease] does not check, and the lease of the next heartbeat
2635    /// counts instead. On a node whose writes need a lease, returns how long the region
2636    /// [awaited](Self::awaits_leader_lease) its Leader lease if this lease ended the wait: of the
2637    /// leases that apply together, only the one that ends it returns it.
2638    pub(crate) fn record_leader_lease(&self, issued_at: Instant) -> Option<Duration> {
2639        let promoted_at = self.catchup_promoted_at.load(Ordering::Relaxed);
2640        if promoted_at == 0 || lease_nanos(issued_at) < promoted_at {
2641            return None;
2642        }
2643        self.end_leader_lease_wait(promoted_at)
2644    }
2645
2646    /// Ends the wait of the catchup promotion at `promoted_at` if no other lease ended it since
2647    /// it was read, and returns what [Self::record_leader_lease] returns for the lease that ends it.
2648    fn end_leader_lease_wait(&self, promoted_at: u64) -> Option<Duration> {
2649        self.catchup_promoted_at
2650            .compare_exchange(promoted_at, 0, Ordering::Relaxed, Ordering::Relaxed)
2651            .ok()?;
2652        self.node_lease
2653            .is_enabled()
2654            .then(|| Duration::from_nanos(lease_nanos(Instant::now()).saturating_sub(promoted_at)))
2655    }
2656
2657    /// Returns whether the region is a leader that no longer awaits its Leader lease. It reads both
2658    /// under the fence lock, under which a catchup demotes and promotes the region and a lease ends
2659    /// its wait. The changes made without the lock only demote the region, move it between leader
2660    /// states, skip a leader whose lease came, or promote it directly before ending its wait, so no
2661    /// read sees an instance a catchup touched as confirmed before a lease confirms it.
2662    pub(crate) fn is_confirmed_leader(&self) -> bool {
2663        let _fence = self.promotion_fence.lock().unwrap();
2664        self.state.load() != RegionRoleState::Follower && !self.awaits_leader_lease()
2665    }
2666
2667    /// Returns whether a Leader lease (or a StagingLeader lease, on a node whose writes need a
2668    /// lease) of a heartbeat sent after the last catchup promotion applied, or no catchup promoted
2669    /// the region.
2670    pub(crate) fn leader_lease_received(&self) -> bool {
2671        self.catchup_promoted_at.load(Ordering::Relaxed) == 0
2672    }
2673
2674    /// Returns whether the region, on a node whose writes need a lease, still waits for the
2675    /// Leader or StagingLeader lease that follows its catchup promotion, whatever its role is
2676    /// now. Until that lease nothing confirms that it owns the region, even if the route already
2677    /// points to it, so it commits nothing but replayed tails and what it commits while
2678    /// downgrading, and starts no work that only such a commit could finish.
2679    pub(crate) fn awaits_leader_lease(&self) -> bool {
2680        self.node_lease.is_enabled() && !self.leader_lease_received()
2681    }
2682
2683    /// Fails a manifest commit of a region that [awaits its Leader lease](Self::awaits_leader_lease),
2684    /// unless the region is downgrading: a downgrade is asked only of the leader in the route.
2685    /// A commit calls it under the manifest lock before it sends anything; a request that would
2686    /// flush first calls it before it schedules the flush, and an index build before it starts.
2687    /// It reads atomics only.
2688    pub(crate) fn ensure_leader_lease_or_downgrading(&self, region_id: RegionId) -> Result<()> {
2689        ensure!(
2690            !self.refuses_commits_awaiting_leader_lease(),
2691            RegionLeaseNotReceivedSnafu { region_id }
2692        );
2693        Ok(())
2694    }
2695
2696    /// Returns whether [Self::ensure_leader_lease_or_downgrading] fails.
2697    pub(crate) fn refuses_commits_awaiting_leader_lease(&self) -> bool {
2698        self.awaits_leader_lease()
2699            && self.state.load() != RegionRoleState::Leader(RegionLeaderState::Downgrading)
2700    }
2701
2702    /// Sets the [`RegionRole`].
2703    ///
2704    /// ```text
2705    ///                  +---------------------+
2706    ///                  |   Staging Leader    |
2707    ///                  +----------+----------+
2708    ///                             |
2709    ///                             v
2710    ///     +----------+     +------+-------+     +-------------+
2711    ///     | Follower | <-> |    Leader    | <-> | Downgrading |
2712    ///     +-----+----+     +------+-------+     +------+------+
2713    ///           ^                 ^                    |
2714    ///           +-----------------+--------------------+
2715    ///
2716    /// ```
2717    ///
2718    /// # State Transitions
2719    ///
2720    /// From `Follower`:
2721    /// - `Follower -> Leader`
2722    ///
2723    /// From `Leader`:
2724    /// - `Leader -> Follower`
2725    /// - `Leader -> Downgrading Leader`
2726    ///
2727    /// From `Staging Leader`:
2728    /// - `Staging Leader -> Leader`
2729    /// - `Staging Leader -> Follower`
2730    /// - `Staging Leader -> Downgrading Leader`
2731    ///
2732    /// From `Downgrading Leader`:
2733    /// - `Downgrading Leader -> Leader`
2734    /// - `Downgrading Leader -> Follower`
2735    ///
2736    /// A region that is ending staging keeps its state: the end of staging reads the Leader
2737    /// deadline and the downgrade start when it leaves that state.
2738    ///
2739    /// Returns the state this call replaced, None if it left the state unchanged. It comes from
2740    /// the atomic operation that replaced it.
2741    pub(crate) fn set_role(
2742        &self,
2743        next_role: RegionRole,
2744        region_id: RegionId,
2745    ) -> Option<RegionRoleState> {
2746        match next_role {
2747            RegionRole::Follower => {
2748                if self
2749                    .exit_staging(region_id, RegionRoleState::Follower)
2750                    .is_ok()
2751                {
2752                    info!(
2753                        "Convert region {} to follower, previous role state: {:?}",
2754                        region_id,
2755                        RegionRoleState::Leader(RegionLeaderState::Staging)
2756                    );
2757                    return Some(RegionRoleState::Leader(RegionLeaderState::Staging));
2758                }
2759                match self.state.fetch_update(|state| {
2760                    if !matches!(
2761                        state,
2762                        RegionRoleState::Follower
2763                            | RegionRoleState::Leader(RegionLeaderState::EndingStaging)
2764                    ) {
2765                        Some(RegionRoleState::Follower)
2766                    } else {
2767                        None
2768                    }
2769                }) {
2770                    Ok(state) => {
2771                        info!(
2772                            "Convert region {} to follower, previous role state: {:?}",
2773                            region_id, state
2774                        );
2775                        Some(state)
2776                    }
2777                    Err(state) => {
2778                        if state != RegionRoleState::Follower {
2779                            warn!(
2780                                "Failed to convert region {} to follower, current role state: {:?}",
2781                                region_id, state
2782                            )
2783                        }
2784                        None
2785                    }
2786                }
2787            }
2788            RegionRole::Leader => {
2789                if self
2790                    .exit_staging(
2791                        region_id,
2792                        RegionRoleState::Leader(RegionLeaderState::Writable),
2793                    )
2794                    .is_ok()
2795                {
2796                    info!(
2797                        "Convert region {} to leader, previous role state: {:?}",
2798                        region_id,
2799                        RegionRoleState::Leader(RegionLeaderState::Staging)
2800                    );
2801                    return Some(RegionRoleState::Leader(RegionLeaderState::Staging));
2802                }
2803                match self.state.fetch_update(|state| {
2804                    if matches!(
2805                        state,
2806                        RegionRoleState::Follower
2807                            | RegionRoleState::Leader(RegionLeaderState::Downgrading)
2808                    ) {
2809                        Some(RegionRoleState::Leader(RegionLeaderState::Writable))
2810                    } else {
2811                        None
2812                    }
2813                }) {
2814                    Ok(state) => {
2815                        info!(
2816                            "Convert region {} to leader, previous role state: {:?}",
2817                            region_id, state
2818                        );
2819                        Some(state)
2820                    }
2821                    Err(state) => {
2822                        // These states already have the leader role; keep their ongoing operation.
2823                        if !matches!(
2824                            state,
2825                            RegionRoleState::Leader(
2826                                RegionLeaderState::Writable
2827                                    | RegionLeaderState::Altering
2828                                    | RegionLeaderState::Dropping
2829                                    | RegionLeaderState::Truncating
2830                                    | RegionLeaderState::Editing
2831                                    | RegionLeaderState::EnteringStaging
2832                                    | RegionLeaderState::EndingStaging
2833                            )
2834                        ) {
2835                            warn!(
2836                                "Failed to convert region {} to leader, current role state: {:?}",
2837                                region_id, state
2838                            )
2839                        }
2840                        None
2841                    }
2842                }
2843            }
2844            RegionRole::StagingLeader => {
2845                info!(
2846                    "Ignore direct conversion of region {} to staging leader; staging requires the dedicated workflow",
2847                    region_id
2848                );
2849                None
2850            }
2851            RegionRole::DowngradingLeader => {
2852                if self
2853                    .exit_staging(
2854                        region_id,
2855                        RegionRoleState::Leader(RegionLeaderState::Downgrading),
2856                    )
2857                    .is_ok()
2858                {
2859                    info!(
2860                        "Convert region {} to downgrading region, previous role state: {:?}",
2861                        region_id,
2862                        RegionRoleState::Leader(RegionLeaderState::Staging)
2863                    );
2864                    return Some(RegionRoleState::Leader(RegionLeaderState::Staging));
2865                }
2866                match self.state.compare_exchange(
2867                    RegionRoleState::Leader(RegionLeaderState::Writable),
2868                    RegionRoleState::Leader(RegionLeaderState::Downgrading),
2869                ) {
2870                    Ok(state) => {
2871                        info!(
2872                            "Convert region {} to downgrading region, previous role state: {:?}",
2873                            region_id, state
2874                        );
2875                        Some(state)
2876                    }
2877                    Err(state) => {
2878                        if state != RegionRoleState::Leader(RegionLeaderState::Downgrading) {
2879                            warn!(
2880                                "Failed to convert region {} to downgrading leader, current role state: {:?}",
2881                                region_id, state
2882                            )
2883                        }
2884                        None
2885                    }
2886                }
2887            }
2888        }
2889    }
2890
2891    /// Returns whether the region publishes its manifest by conditional create.
2892    pub(crate) fn is_conditional_publication(&self) -> bool {
2893        self.conditional_publication
2894    }
2895
2896    /// Returns the normal manifest of the region.
2897    pub(crate) async fn manifest(&self) -> Arc<crate::manifest::action::RegionManifest> {
2898        self.manifest_manager.read().await.manifest()
2899    }
2900
2901    /// Returns the staging manifest of the region.
2902    pub(crate) async fn staging_manifest(
2903        &self,
2904    ) -> Option<Arc<crate::manifest::action::RegionManifest>> {
2905        self.manifest_manager.read().await.staging_manifest()
2906    }
2907}
2908
2909pub(crate) type ManifestContextRef = Arc<ManifestContext>;
2910
2911/// The state that decides whether a promotion to Leader applies.
2912#[derive(Debug)]
2913struct PromotionFence {
2914    /// When the region last began a downgrade. A promotion issued before it does not apply.
2915    ///
2916    /// It starts at creation time, so promotions issued before the region was opened or reopened
2917    /// do not apply. A context that replaces this one after a close or reopen is created after
2918    /// its last downgrade began. A reloaded one is created while this one is still registered, so
2919    /// it raises the time when it replaces this one.
2920    downgrade_started_at: Instant,
2921    /// Whether another writer advanced the manifest, so this instance stays a Follower until a
2922    /// reload replaces it.
2923    reload_pending: bool,
2924    /// Whether a catchup runs on this instance. Until it ends, a Leader lease does not promote
2925    /// the region: only the catchup's own promotion does.
2926    catching_up: bool,
2927    /// Whether the region was stopped (closed, dropped or its worker cleaned up), so no promotion
2928    /// applies. The manifest manager also knows it, but a promotion decides under this lock only.
2929    stopped: bool,
2930    /// The candidate lease id of the catchup that last promoted the region;
2931    /// [ManifestContext::begin_catchup] reads it only while the region awaits that promotion's
2932    /// Leader lease.
2933    promoted_by: Option<u64>,
2934}
2935
2936/// Whether a catchup that began on a region repeats the catchup whose promotion's Leader lease
2937/// the region awaits, see [ManifestContext::begin_catchup].
2938#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2939pub(crate) enum AwaitedPromotion {
2940    /// The region awaits no Leader lease.
2941    NoPendingPromotion,
2942    /// The catchup carries the candidate lease id recorded by the pending promotion.
2943    SameMigration,
2944    /// The catchup carries another id or none: one of a migration after a rolled-back one, or of
2945    /// a migration recovered after a metasrv leader change, which registers a new id.
2946    OtherOrUnknownMigration,
2947}
2948
2949/// Regions indexed by ids.
2950#[derive(Debug, Default)]
2951pub(crate) struct RegionMap {
2952    regions: RwLock<HashMap<RegionId, MitoRegionRef>>,
2953}
2954
2955impl RegionMap {
2956    /// Returns true if the region exists.
2957    pub(crate) fn is_region_exists(&self, region_id: RegionId) -> bool {
2958        let regions = self.regions.read().unwrap();
2959        regions.contains_key(&region_id)
2960    }
2961
2962    /// Inserts a new region into the map.
2963    pub(crate) fn insert_region(&self, region: MitoRegionRef) {
2964        let mut regions = self.regions.write().unwrap();
2965        regions.insert(region.region_id, region);
2966    }
2967
2968    /// Gets region by region id.
2969    pub(crate) fn get_region(&self, region_id: RegionId) -> Option<MitoRegionRef> {
2970        let regions = self.regions.read().unwrap();
2971        regions.get(&region_id).cloned()
2972    }
2973
2974    /// Gets writable region by region id.
2975    ///
2976    /// Returns error if the region does not exist or is readonly.
2977    pub(crate) fn writable_region(&self, region_id: RegionId) -> Result<MitoRegionRef> {
2978        let region = self
2979            .get_region(region_id)
2980            .context(RegionNotFoundSnafu { region_id })?;
2981        ensure!(
2982            region.is_writable(),
2983            RegionStateSnafu {
2984                region_id,
2985                state: region.state(),
2986                expect: RegionRoleState::Leader(RegionLeaderState::Writable),
2987            }
2988        );
2989        Ok(region)
2990    }
2991
2992    /// Gets readonly region by region id.
2993    ///
2994    /// Returns error if the region does not exist or is writable.
2995    pub(crate) fn follower_region(&self, region_id: RegionId) -> Result<MitoRegionRef> {
2996        let region = self
2997            .get_region(region_id)
2998            .context(RegionNotFoundSnafu { region_id })?;
2999        ensure!(
3000            region.is_follower(),
3001            RegionStateSnafu {
3002                region_id,
3003                state: region.state(),
3004                expect: RegionRoleState::Follower,
3005            }
3006        );
3007
3008        Ok(region)
3009    }
3010
3011    /// Gets region by region id.
3012    ///
3013    /// Calls the callback if the region does not exist.
3014    pub(crate) fn get_region_or<F: OnFailure>(
3015        &self,
3016        region_id: RegionId,
3017        cb: &mut F,
3018    ) -> Option<MitoRegionRef> {
3019        match self
3020            .get_region(region_id)
3021            .context(RegionNotFoundSnafu { region_id })
3022        {
3023            Ok(region) => Some(region),
3024            Err(e) => {
3025                cb.on_failure(e);
3026                None
3027            }
3028        }
3029    }
3030
3031    /// Gets writable region by region id.
3032    ///
3033    /// Calls the callback if the region does not exist or is readonly.
3034    pub(crate) fn writable_region_or<F: OnFailure>(
3035        &self,
3036        region_id: RegionId,
3037        cb: &mut F,
3038    ) -> Option<MitoRegionRef> {
3039        match self.writable_region(region_id) {
3040            Ok(region) => Some(region),
3041            Err(e) => {
3042                cb.on_failure(e);
3043                None
3044            }
3045        }
3046    }
3047
3048    /// Gets writable non-staging region by region id.
3049    ///
3050    /// Returns error if the region does not exist, is readonly, or is in staging mode.
3051    pub(crate) fn writable_non_staging_region(&self, region_id: RegionId) -> Result<MitoRegionRef> {
3052        let region = self.writable_region(region_id)?;
3053        if region.is_staging() {
3054            return Err(crate::error::RegionStateSnafu {
3055                region_id,
3056                state: region.state(),
3057                expect: RegionRoleState::Leader(RegionLeaderState::Writable),
3058            }
3059            .build());
3060        }
3061        Ok(region)
3062    }
3063
3064    /// Gets staging region by region id.
3065    ///
3066    /// Returns error if the region does not exist or is not in staging state.
3067    pub(crate) fn staging_region(&self, region_id: RegionId) -> Result<MitoRegionRef> {
3068        let region = self
3069            .get_region(region_id)
3070            .context(RegionNotFoundSnafu { region_id })?;
3071        ensure!(
3072            region.is_staging(),
3073            RegionStateSnafu {
3074                region_id,
3075                state: region.state(),
3076                expect: RegionRoleState::Leader(RegionLeaderState::Staging),
3077            }
3078        );
3079        Ok(region)
3080    }
3081
3082    /// Gets flushable region by region id.
3083    ///
3084    /// Returns error if the region does not exist or not flushable.
3085    pub(crate) fn flushable_region(&self, region_id: RegionId) -> Result<MitoRegionRef> {
3086        let region = self
3087            .get_region(region_id)
3088            .context(RegionNotFoundSnafu { region_id })?;
3089        ensure!(
3090            region.is_flushable(),
3091            FlushableRegionStateSnafu {
3092                region_id,
3093                state: region.state(),
3094            }
3095        );
3096        Ok(region)
3097    }
3098
3099    /// Remove region by id.
3100    pub(crate) fn remove_region(&self, region_id: RegionId) -> Option<MitoRegionRef> {
3101        let mut regions = self.regions.write().unwrap();
3102        regions.remove(&region_id)
3103    }
3104
3105    /// List all regions.
3106    pub(crate) fn list_regions(&self) -> Vec<MitoRegionRef> {
3107        let regions = self.regions.read().unwrap();
3108        regions.values().cloned().collect()
3109    }
3110
3111    /// Clear the map.
3112    pub(crate) fn clear(&self) {
3113        self.regions.write().unwrap().clear();
3114    }
3115}
3116
3117pub(crate) type RegionMapRef = Arc<RegionMap>;
3118
3119/// Opening regions
3120#[derive(Debug, Default)]
3121pub(crate) struct OpeningRegions {
3122    regions: RwLock<HashMap<RegionId, Vec<OptionOutputTx>>>,
3123}
3124
3125impl OpeningRegions {
3126    /// Registers `sender` for an opening region; Otherwise, it returns `None`.
3127    pub(crate) fn wait_for_opening_region(
3128        &self,
3129        region_id: RegionId,
3130        sender: OptionOutputTx,
3131    ) -> Option<OptionOutputTx> {
3132        let mut regions = self.regions.write().unwrap();
3133        match regions.entry(region_id) {
3134            Entry::Occupied(mut senders) => {
3135                senders.get_mut().push(sender);
3136                None
3137            }
3138            Entry::Vacant(_) => Some(sender),
3139        }
3140    }
3141
3142    /// Returns true if the region exists.
3143    pub(crate) fn is_region_exists(&self, region_id: RegionId) -> bool {
3144        let regions = self.regions.read().unwrap();
3145        regions.contains_key(&region_id)
3146    }
3147
3148    /// Inserts a new region into the map.
3149    pub(crate) fn insert_sender(&self, region: RegionId, sender: OptionOutputTx) {
3150        let mut regions = self.regions.write().unwrap();
3151        regions.insert(region, vec![sender]);
3152    }
3153
3154    /// Remove region by id.
3155    pub(crate) fn remove_sender(&self, region_id: RegionId) -> Vec<OptionOutputTx> {
3156        let mut regions = self.regions.write().unwrap();
3157        regions.remove(&region_id).unwrap_or_default()
3158    }
3159
3160    #[cfg(test)]
3161    pub(crate) fn sender_len(&self, region_id: RegionId) -> usize {
3162        let regions = self.regions.read().unwrap();
3163        if let Some(senders) = regions.get(&region_id) {
3164            senders.len()
3165        } else {
3166            0
3167        }
3168    }
3169}
3170
3171pub(crate) type OpeningRegionsRef = Arc<OpeningRegions>;
3172
3173/// The regions that are catching up.
3174#[derive(Debug, Default)]
3175pub(crate) struct CatchupRegions {
3176    regions: RwLock<HashSet<RegionId>>,
3177}
3178
3179impl CatchupRegions {
3180    /// Returns true if the region exists.
3181    pub(crate) fn is_region_exists(&self, region_id: RegionId) -> bool {
3182        let regions = self.regions.read().unwrap();
3183        regions.contains(&region_id)
3184    }
3185
3186    /// Inserts a new region into the set.
3187    pub(crate) fn insert_region(&self, region_id: RegionId) {
3188        let mut regions = self.regions.write().unwrap();
3189        regions.insert(region_id);
3190    }
3191
3192    /// Remove region by id.
3193    pub(crate) fn remove_region(&self, region_id: RegionId) {
3194        let mut regions = self.regions.write().unwrap();
3195        regions.remove(&region_id);
3196    }
3197}
3198
3199pub(crate) type CatchupRegionsRef = Arc<CatchupRegions>;
3200
3201/// Manifest stats.
3202#[derive(Default, Debug, Clone)]
3203pub struct ManifestStats {
3204    metric: Option<RegionManifestSizeMetric>,
3205    pub(crate) total_manifest_size: Arc<AtomicU64>,
3206    pub(crate) manifest_version: Arc<AtomicU64>,
3207    pub(crate) file_removed_cnt: Arc<AtomicU64>,
3208}
3209
3210impl ManifestStats {
3211    /// Creates an inactive descriptor; opening a region does not publish a series.
3212    pub(crate) fn with_region_metrics(region_id: RegionId) -> Self {
3213        Self {
3214            metric: Some(RegionManifestSizeMetric::new(region_id)),
3215            ..Default::default()
3216        }
3217    }
3218
3219    pub(crate) fn metric(&self) -> Option<&RegionManifestSizeMetric> {
3220        self.metric.as_ref()
3221    }
3222
3223    fn total_manifest_size(&self) -> u64 {
3224        self.total_manifest_size.load(Ordering::Relaxed)
3225    }
3226
3227    fn manifest_version(&self) -> u64 {
3228        self.manifest_version.load(Ordering::Relaxed)
3229    }
3230
3231    fn file_removed_cnt(&self) -> u64 {
3232        self.file_removed_cnt.load(Ordering::Relaxed)
3233    }
3234}
3235
3236/// Parses the partition expression from a JSON string.
3237pub fn parse_partition_expr(partition_expr_str: Option<&str>) -> Result<Option<PartitionExpr>> {
3238    match partition_expr_str {
3239        None => Ok(None),
3240        Some("") => Ok(None),
3241        Some(json_str) => {
3242            let expr = partition::expr::PartitionExpr::from_json_str(json_str)
3243                .with_context(|_| InvalidPartitionExprSnafu { expr: json_str })?;
3244            Ok(expr)
3245        }
3246    }
3247}
3248
3249/// Columns requiring allocations or snapshots during an inspection scan.
3250#[derive(Clone, Copy)]
3251pub(crate) struct ManifestSstProjection {
3252    visible: bool,
3253    table_dir: bool,
3254    file_id: bool,
3255    file_path: bool,
3256    index_file_path: bool,
3257    partition_expr: bool,
3258    primary_key_min: bool,
3259    primary_key_max: bool,
3260}
3261
3262impl ManifestSstProjection {
3263    /// Selects columns by index in [`ManifestSstEntry::schema`]; `None` selects all columns.
3264    pub(crate) fn new(projection: Option<&[usize]>) -> Self {
3265        let schema = ManifestSstEntry::schema();
3266        let included = |name: &str| {
3267            projection.is_none_or(|indices| {
3268                indices.iter().any(|index| {
3269                    schema
3270                        .column_schemas()
3271                        .get(*index)
3272                        .is_some_and(|column| column.name == name)
3273                })
3274            })
3275        };
3276        Self {
3277            visible: included(sst_entry::VISIBLE),
3278            table_dir: included(sst_entry::TABLE_DIR),
3279            file_id: included(sst_entry::FILE_ID),
3280            file_path: included(sst_entry::FILE_PATH),
3281            index_file_path: included(sst_entry::INDEX_FILE_PATH),
3282            partition_expr: included(sst_entry::PARTITION_EXPR),
3283            primary_key_min: included(sst_entry::PRIMARY_KEY_MIN),
3284            primary_key_max: included(sst_entry::PRIMARY_KEY_MAX),
3285        }
3286    }
3287}
3288
3289/// Applies supported file predicates before allocating an inspection row. Unknown
3290/// predicates and evaluation failures are left to the query's residual filter.
3291fn manifest_file_matches(meta: &FileMeta, filters: &MetadataFilter) -> bool {
3292    filters.matches(|column| {
3293        Some(match column {
3294            sst_entry::FILE_SIZE => ScalarValue::UInt64(Some(meta.file_size)),
3295            sst_entry::LEVEL => ScalarValue::UInt8(Some(meta.level)),
3296            sst_entry::NUM_ROWS => ScalarValue::UInt64(Some(meta.num_rows)),
3297            sst_entry::NUM_ROW_GROUPS => ScalarValue::UInt64(Some(meta.num_row_groups)),
3298            sst_entry::ORIGIN_REGION_ID => ScalarValue::UInt64(Some(meta.region_id.as_u64())),
3299            sst_entry::MIN_TS => ScalarValue::TimestampNanosecond(
3300                meta.time_range
3301                    .0
3302                    .convert_to(TimeUnit::Nanosecond)
3303                    .map(|ts| ts.value()),
3304                None,
3305            ),
3306            sst_entry::MAX_TS => ScalarValue::TimestampNanosecond(
3307                meta.time_range
3308                    .1
3309                    .convert_to(TimeUnit::Nanosecond)
3310                    .map(|ts| ts.value()),
3311                None,
3312            ),
3313            _ => return None,
3314        })
3315    })
3316}
3317
3318#[cfg(test)]
3319mod tests {
3320    use std::sync::Arc;
3321    use std::sync::atomic::Ordering;
3322
3323    use common_datasource::compression::CompressionType;
3324    use common_test_util::temp_dir::create_temp_dir;
3325    use crossbeam_utils::atomic::AtomicCell;
3326    use object_store::ObjectStore;
3327    use object_store::services::Fs;
3328    use store_api::logstore::provider::Provider;
3329    use store_api::region_engine::RegionRole;
3330    use store_api::region_request::{PathType, StagingPartitionDirective};
3331    use store_api::storage::{FileId, RegionId};
3332
3333    use crate::access_layer::AccessLayer;
3334    use crate::error::{Error, ManifestVersionConflictSnafu, Result, UnexpectedSnafu};
3335    use crate::manifest::action::{
3336        RegionChange, RegionEdit, RegionMetaAction, RegionMetaActionList, RegionPartitionExprChange,
3337    };
3338    use crate::manifest::manager::{RegionManifestManager, RegionManifestOptions};
3339    use crate::manifest::storage::delta_file;
3340    use crate::manifest::storage::staging::staging_manifest_path;
3341    use crate::region::{
3342        IndexBuildSource, IndexPublication, IndexPublicationStale, ManifestContext, ManifestStats,
3343        MitoRegion, PromotionFence, RegionLeaderState, RegionRoleState, RegionStats,
3344        StagingPartitionInfo, TailPublication, TailsEditor,
3345    };
3346    use crate::sst::FormatType;
3347    use crate::sst::index::intermediate::IntermediateManager;
3348    use crate::sst::index::puffin_manager::PuffinManagerFactory;
3349    use crate::test_util::scheduler_util::SchedulerEnv;
3350    use crate::test_util::version_util::VersionControlBuilder;
3351    use crate::time_provider::StdTimeProvider;
3352
3353    #[test]
3354    fn test_manifest_file_predicates() {
3355        use common_recordbatch::filter::MetadataFilter;
3356        use common_time::Timestamp;
3357        use datafusion_common::ScalarValue;
3358        use datafusion_expr::{col, lit};
3359        let meta = super::FileMeta {
3360            file_size: 100,
3361            time_range: (
3362                Timestamp::new_millisecond(10),
3363                Timestamp::new_millisecond(20),
3364            ),
3365            ..Default::default()
3366        };
3367        for (expr, expected) in [
3368            (col("file_size").lt(lit(101u64)), true),
3369            (col("file_size").lt(lit(100u64)), false),
3370            (
3371                col("min_ts").eq(lit(ScalarValue::TimestampNanosecond(
3372                    Some(10_000_000),
3373                    None,
3374                ))),
3375                true,
3376            ),
3377            (
3378                col("max_ts").lt(lit(ScalarValue::TimestampNanosecond(
3379                    Some(20_000_000),
3380                    None,
3381                ))),
3382                false,
3383            ),
3384            (col("file_id").eq(lit("unknown")), true),
3385        ] {
3386            let filter = MetadataFilter::new(std::slice::from_ref(&expr));
3387            assert_eq!(
3388                super::manifest_file_matches(&meta, &filter),
3389                expected,
3390                "{expr}"
3391            );
3392        }
3393    }
3394
3395    #[test]
3396    fn test_manifest_timestamp_overflow_is_null() {
3397        use common_recordbatch::filter::MetadataFilter;
3398        use common_time::Timestamp;
3399        use datafusion_expr::col;
3400        let meta = super::FileMeta {
3401            time_range: (
3402                Timestamp::new_second(i64::MAX),
3403                Timestamp::new_second(i64::MAX),
3404            ),
3405            ..Default::default()
3406        };
3407        let filter = MetadataFilter::new(&[col("min_ts").is_null()]);
3408        assert!(super::manifest_file_matches(&meta, &filter));
3409        let filter = MetadataFilter::new(&[col("max_ts").is_not_null()]);
3410        assert!(!super::manifest_file_matches(&meta, &filter));
3411    }
3412
3413    #[test]
3414    fn test_region_state_lock_free() {
3415        assert!(AtomicCell::<RegionRoleState>::is_lock_free());
3416    }
3417
3418    #[test]
3419    fn test_region_role_state_as_str() {
3420        assert_eq!("Follower", RegionRoleState::Follower.as_str());
3421        assert_eq!(
3422            "Leader(Writable)",
3423            RegionRoleState::Leader(RegionLeaderState::Writable).as_str()
3424        );
3425        assert_eq!(
3426            "Leader(Staging)",
3427            RegionRoleState::Leader(RegionLeaderState::Staging).as_str()
3428        );
3429        assert_eq!(
3430            "Leader(Downgrading)",
3431            RegionRoleState::Leader(RegionLeaderState::Downgrading).as_str()
3432        );
3433    }
3434
3435    async fn build_test_region(env: &SchedulerEnv) -> MitoRegion {
3436        build_test_region_with_checkpoint_distance(env, 10).await
3437    }
3438
3439    async fn build_test_region_with_checkpoint_distance(
3440        env: &SchedulerEnv,
3441        checkpoint_distance: u64,
3442    ) -> MitoRegion {
3443        let builder = VersionControlBuilder::new();
3444        let version_control = Arc::new(builder.build());
3445        let metadata = version_control.current().version.metadata.clone();
3446
3447        let manager = RegionManifestManager::new(
3448            metadata.clone(),
3449            0,
3450            RegionManifestOptions {
3451                file_metadata_interner: Default::default(),
3452                manifest_dir: "".to_string(),
3453                object_store: env.access_layer.object_store().clone(),
3454                compress_type: CompressionType::Uncompressed,
3455                checkpoint_distance,
3456                remove_file_options: Default::default(),
3457                manifest_cache: None,
3458                conditional_publication: false,
3459            },
3460            FormatType::PrimaryKey,
3461            false,
3462            &Default::default(),
3463        )
3464        .await
3465        .unwrap();
3466
3467        let manifest_ctx = Arc::new(ManifestContext::new(
3468            manager,
3469            RegionRoleState::Leader(RegionLeaderState::Writable),
3470            None,
3471            Default::default(),
3472        ));
3473
3474        MitoRegion {
3475            region_id: metadata.region_id,
3476            compaction_state: Default::default(),
3477            version_control,
3478            access_layer: env.access_layer.clone(),
3479            manifest_ctx,
3480            file_purger: crate::test_util::new_noop_file_purger(),
3481            provider: Provider::noop_provider(),
3482            last_flush_millis: Default::default(),
3483            last_schedule_compaction_millis: Default::default(),
3484            time_provider: Arc::new(StdTimeProvider),
3485            topic_latest_entry_id: Default::default(),
3486            region_stats: RegionStats::new(),
3487            stats: ManifestStats::default(),
3488        }
3489    }
3490
3491    #[tokio::test]
3492    async fn test_manifest_stream_does_not_pin_sst_handles() {
3493        use std::sync::atomic::{AtomicUsize, Ordering};
3494
3495        use common_recordbatch::filter::MetadataFilter;
3496        use datafusion_expr::{col, lit};
3497        use futures::StreamExt;
3498
3499        use super::ManifestSstProjection;
3500        use crate::sst::file::FileMeta;
3501        use crate::sst::file_purger::FilePurger;
3502
3503        #[derive(Debug, Default)]
3504        struct CountingPurger(AtomicUsize);
3505
3506        impl FilePurger for CountingPurger {
3507            fn purge_file(&self, _: FileMeta) {
3508                self.0.fetch_add(1, Ordering::SeqCst);
3509            }
3510        }
3511
3512        for include_visible in [false, true] {
3513            let env = SchedulerEnv::new().await;
3514            let region = build_test_region(&env).await;
3515            let purger = Arc::new(CountingPurger::default());
3516            let files = (0..2)
3517                .map(|_| FileMeta {
3518                    region_id: region.region_id,
3519                    file_id: FileId::random(),
3520                    ..Default::default()
3521                })
3522                .collect::<Vec<_>>();
3523            let mut edit = empty_edit();
3524            edit.files_to_add = files.clone();
3525            region
3526                .manifest_ctx
3527                .manifest_manager
3528                .write()
3529                .await
3530                .update(
3531                    RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone())),
3532                    false,
3533                )
3534                .await
3535                .unwrap();
3536            region
3537                .version_control
3538                .apply_edit(Some(edit), &[], purger.clone());
3539
3540            let schema = store_api::sst_entry::ManifestSstEntry::schema();
3541            let columns = if include_visible {
3542                vec!["file_id", "visible"]
3543            } else {
3544                vec!["file_id"]
3545            };
3546            let projection = columns
3547                .iter()
3548                .map(|name| {
3549                    schema
3550                        .column_schemas()
3551                        .iter()
3552                        .position(|column| column.name == *name)
3553                        .unwrap()
3554                })
3555                .collect::<Vec<_>>();
3556            let projection = ManifestSstProjection::new(Some(&projection));
3557            let snapshot = region.manifest_visible_file_ids(projection);
3558            assert_eq!(snapshot.is_some(), include_visible);
3559            if let Some(snapshot) = snapshot {
3560                assert_eq!(snapshot, files.iter().map(|file| file.file_id).collect());
3561            }
3562            // A direct caller may omit a residual column. The source must not
3563            // interpret an unmaterialized visible value as grounds for pruning.
3564            let filters = MetadataFilter::new(&[col("visible").eq(lit(true))]);
3565            let mut stream = region.manifest_sst_stream(filters, projection);
3566            let first = stream.next().await.unwrap();
3567            if include_visible {
3568                assert!(first.visible);
3569            }
3570            let mut removal = empty_edit();
3571            removal.files_to_remove = files;
3572            region
3573                .version_control
3574                .apply_edit(Some(removal), &[], purger.clone());
3575            // Both final FileHandles must reach the purger while the stream is
3576            // suspended at its first yield, rather than waiting for cancellation.
3577            assert_eq!(purger.0.load(Ordering::SeqCst), 2);
3578            let second = stream.next().await.unwrap();
3579            if include_visible {
3580                assert!(
3581                    second.visible,
3582                    "visibility must retain the original snapshot"
3583                );
3584            }
3585            assert!(stream.next().await.is_none());
3586        }
3587    }
3588
3589    #[tokio::test]
3590    async fn test_manifest_narthex_file_path_filter() {
3591        use common_recordbatch::filter::MetadataFilter;
3592        use datafusion_expr::{col, lit};
3593        use futures::StreamExt;
3594
3595        use super::ManifestSstProjection;
3596        use crate::sst::file::{FileFormat, FileMeta, NarthexPartMeta, NarthexSamplesMeta};
3597
3598        let env = SchedulerEnv::new().await;
3599        let region = build_test_region(&env).await;
3600        let id = FileId::random();
3601        let path = format!(
3602            "{}manifest.json",
3603            crate::sst::location::narthex_file_dir(
3604                &region.access_layer.build_region_dir(region.region_id),
3605                id
3606            )
3607        );
3608        let mut edit = empty_edit();
3609        edit.files_to_add.push(FileMeta {
3610            file_id: id,
3611            region_id: region.region_id,
3612            file_size: 2,
3613            format: FileFormat::NarthexSamples(Box::new(NarthexSamplesMeta {
3614                manifest_size: 1,
3615                parts: smallvec::smallvec![NarthexPartMeta { file_size: 1 }],
3616            })),
3617            ..Default::default()
3618        });
3619        region
3620            .manifest_ctx
3621            .manifest_manager
3622            .write()
3623            .await
3624            .update(
3625                RegionMetaActionList::with_action(RegionMetaAction::Edit(edit)),
3626                false,
3627            )
3628            .await
3629            .unwrap();
3630
3631        for filters in [
3632            MetadataFilter::new(&[]),
3633            MetadataFilter::new(&[col("file_path").eq(lit(path.as_str()))]),
3634        ] {
3635            let mut stream = region.manifest_sst_stream(filters, ManifestSstProjection::new(None));
3636            assert_eq!(stream.next().await.unwrap().file_path, path);
3637            assert!(stream.next().await.is_none());
3638        }
3639    }
3640
3641    fn empty_edit() -> RegionEdit {
3642        RegionEdit {
3643            series_indexes_to_add: Vec::new(),
3644            series_indexes_to_remove: Vec::new(),
3645            files_to_add: Vec::new(),
3646            files_to_remove: Vec::new(),
3647            timestamp_ms: None,
3648            compaction_time_window: None,
3649            flushed_entry_id: None,
3650            flushed_sequence: None,
3651            committed_sequence: None,
3652            ..Default::default()
3653        }
3654    }
3655
3656    #[tokio::test]
3657    async fn test_promoting_writable_leader_takes_no_lock() {
3658        let env = SchedulerEnv::new().await;
3659        let region = Arc::new(build_test_region(&env).await);
3660        let _promotion_fence = region.manifest_ctx.promotion_fence.lock().unwrap();
3661        let (tx, rx) = std::sync::mpsc::channel();
3662        let promoted = region.clone();
3663        std::thread::spawn(move || {
3664            let manifest_ctx = &promoted.manifest_ctx;
3665            let issued_at = std::time::Instant::now();
3666            tx.send(
3667                manifest_ctx
3668                    .promote_unless_downgrade_started_after(issued_at, promoted.region_id)
3669                    .promoted,
3670            )
3671            .unwrap();
3672        });
3673        assert!(rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap());
3674    }
3675
3676    /// Makes the test region a writable leader that awaits its Leader lease.
3677    fn await_leader_lease(region: &MitoRegion) {
3678        let manifest_ctx = &region.manifest_ctx;
3679        manifest_ctx.node_lease.enable();
3680        manifest_ctx
3681            .leader_deadline
3682            .extend(std::time::Instant::now() + std::time::Duration::from_secs(60));
3683        region.set_role(RegionRole::Follower);
3684        assert!(manifest_ctx.promote_after_catchup(region.region_id, None));
3685        assert!(region.is_writable());
3686        assert!(manifest_ctx.awaits_leader_lease());
3687    }
3688
3689    /// Runs `f` on another thread while this thread holds the fence lock, checks that `f` waits
3690    /// for the lock, then runs `under_lock` before it releases the lock and returns what `f` returns.
3691    fn run_blocked_on_fence<T: Send + 'static>(
3692        region: &Arc<MitoRegion>,
3693        f: impl FnOnce(&MitoRegion) -> T + Send + 'static,
3694        under_lock: impl FnOnce(&mut PromotionFence),
3695    ) -> T {
3696        let mut fence = region.manifest_ctx.promotion_fence.lock().unwrap();
3697        let (ready_tx, ready_rx) = std::sync::mpsc::channel();
3698        let (tx, rx) = std::sync::mpsc::channel();
3699        let blocked = region.clone();
3700        std::thread::spawn(move || {
3701            ready_tx.send(()).unwrap();
3702            tx.send(f(&blocked)).unwrap();
3703        });
3704        ready_rx
3705            .recv_timeout(std::time::Duration::from_secs(10))
3706            .unwrap();
3707        assert!(
3708            rx.recv_timeout(std::time::Duration::from_millis(200))
3709                .is_err()
3710        );
3711        under_lock(&mut fence);
3712        drop(fence);
3713        rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap()
3714    }
3715
3716    /// A Leader lease of a writable leader that awaits it takes the fence lock, so it cannot end
3717    /// the wait between a catchup's flag and its demotion.
3718    #[tokio::test]
3719    async fn test_lease_awaited_by_writable_leader_waits_for_catchup_demotion() {
3720        let env = SchedulerEnv::new().await;
3721        let region = Arc::new(build_test_region(&env).await);
3722        await_leader_lease(&region);
3723        let issued_at = std::time::Instant::now();
3724        let promotion = run_blocked_on_fence(
3725            &region,
3726            move |r| {
3727                r.manifest_ctx
3728                    .promote_unless_downgrade_started_after(issued_at, r.region_id)
3729            },
3730            // What a catchup does under the lock.
3731            |fence| {
3732                fence.catching_up = true;
3733                region
3734                    .manifest_ctx
3735                    .set_role(RegionRole::Follower, region.region_id);
3736            },
3737        );
3738        assert!(!promotion.promoted);
3739        assert!(promotion.ended_wait.is_none());
3740        assert!(region.manifest_ctx.awaits_leader_lease());
3741    }
3742
3743    /// A candidate lease reads the wait for a Leader lease under the fence lock, so it does not
3744    /// demote a region that a catchup promotes meanwhile.
3745    #[tokio::test]
3746    async fn test_candidate_demotion_sees_catchup_promotion_under_fence() {
3747        let env = SchedulerEnv::new().await;
3748        let region = Arc::new(build_test_region(&env).await);
3749        region.manifest_ctx.node_lease.enable();
3750        // A writable leader, so a demotion that misses the fence returns Some and fails below.
3751        assert!(region.is_writable());
3752        assert!(!region.manifest_ctx.awaits_leader_lease());
3753        let demoted = run_blocked_on_fence(
3754            &region,
3755            |r| r.manifest_ctx.demote_candidate(r.region_id),
3756            // What a catchup's promotion does under the lock.
3757            |fence| {
3758                assert!(
3759                    region
3760                        .manifest_ctx
3761                        .promote_unless_reload_pending(fence, region.region_id, true)
3762                        .promoted
3763                )
3764            },
3765        );
3766        assert_eq!(demoted, None);
3767        assert!(region.manifest_ctx.awaits_leader_lease());
3768        assert_eq!(
3769            region.state(),
3770            RegionRoleState::Leader(RegionLeaderState::Writable)
3771        );
3772    }
3773
3774    /// The readiness of an upgrade reads the role and the wait for a Leader lease under the fence
3775    /// lock, so it sees a change of both made under that lock as a whole.
3776    #[tokio::test]
3777    async fn test_confirmed_leader_read_waits_for_fence_lock() {
3778        let env = SchedulerEnv::new().await;
3779        let region = Arc::new(build_test_region(&env).await);
3780        await_leader_lease(&region);
3781        // A lease ends the wait under the lock; a read made before it would answer false.
3782        let confirmed = run_blocked_on_fence(
3783            &region,
3784            |r| r.is_confirmed_leader(),
3785            |_| {
3786                region
3787                    .manifest_ctx
3788                    .catchup_promoted_at
3789                    .store(0, Ordering::Relaxed)
3790            },
3791        );
3792        assert!(confirmed);
3793    }
3794
3795    /// A catchup begins on no writable leader whose wait for a Leader lease ended, and promotes no
3796    /// stopped region.
3797    #[tokio::test]
3798    async fn test_catchup_skips_confirmed_leader_and_promotes_no_stopped_region() {
3799        let env = SchedulerEnv::new().await;
3800        let region = build_test_region(&env).await;
3801        await_leader_lease(&region);
3802        let promotion = region
3803            .manifest_ctx
3804            .promote_unless_downgrade_started_after(std::time::Instant::now(), region.region_id);
3805        assert!(promotion.ended_wait.is_some());
3806        assert!(!region.manifest_ctx.awaits_leader_lease());
3807        assert_eq!(
3808            region.manifest_ctx.begin_catchup(region.region_id, None),
3809            None
3810        );
3811        assert!(region.is_writable());
3812        region.set_role(RegionRole::Follower);
3813        region.stop().await;
3814        assert!(region.manifest_ctx.is_stopped());
3815        assert!(
3816            !region
3817                .manifest_ctx
3818                .promote_after_catchup(region.region_id, None)
3819        );
3820        assert!(region.is_follower());
3821    }
3822
3823    #[tokio::test]
3824    async fn test_awaiting_leader_lease_requires_verification() {
3825        let env = SchedulerEnv::new().await;
3826        let region = build_test_region(&env).await;
3827        let manifest_ctx = &region.manifest_ctx;
3828        manifest_ctx.node_lease.enable();
3829        manifest_ctx
3830            .leader_deadline
3831            .extend(std::time::Instant::now() + std::time::Duration::from_secs(60));
3832        assert!(!manifest_ctx.must_verify_commit());
3833
3834        region.set_role(RegionRole::Follower);
3835        assert!(manifest_ctx.promote_after_catchup(region.region_id, None));
3836        assert!(manifest_ctx.must_verify_commit());
3837
3838        std::thread::sleep(std::time::Duration::from_millis(1));
3839        manifest_ctx.record_leader_lease(std::time::Instant::now());
3840        assert!(!manifest_ctx.must_verify_commit());
3841    }
3842
3843    #[tokio::test]
3844    async fn test_lease_sent_before_catchup_promotion_does_not_count() {
3845        let env = SchedulerEnv::new().await;
3846        let region = build_test_region(&env).await;
3847        let manifest_ctx = &region.manifest_ctx;
3848        let sent_before = std::time::Instant::now();
3849        region.set_role(RegionRole::Follower);
3850        std::thread::sleep(std::time::Duration::from_millis(1));
3851        assert!(manifest_ctx.promote_after_catchup(region.region_id, None));
3852
3853        assert!(
3854            manifest_ctx
3855                .promote_unless_downgrade_started_after(sent_before, region.region_id)
3856                .promoted
3857        );
3858        assert!(!manifest_ctx.leader_lease_received());
3859        let sent_after = std::time::Instant::now();
3860        assert!(
3861            manifest_ctx
3862                .promote_unless_downgrade_started_after(sent_after, region.region_id)
3863                .promoted
3864        );
3865        assert!(manifest_ctx.leader_lease_received());
3866    }
3867
3868    /// A replay of pending tails that commits while the region awaits its Leader lease starts no
3869    /// checkpoint without conditional publication too, where no verification of the commit
3870    /// turns it off.
3871    #[tokio::test]
3872    async fn test_tail_commit_awaiting_leader_lease_starts_no_checkpoint_without_conditional_publication()
3873     {
3874        let env = SchedulerEnv::new().await;
3875        let region = build_test_region_with_checkpoint_distance(&env, 1).await;
3876        let manifest_ctx = &region.manifest_ctx;
3877        manifest_ctx.start_leader_lease_wait_for_test(region.region_id, None);
3878        let action_list =
3879            RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit::default()));
3880
3881        let publication = manifest_ctx
3882            .update_manifest_for_tails(&[], action_list, TailsEditor::Replay)
3883            .await
3884            .unwrap();
3885
3886        assert!(matches!(publication, TailPublication::Committed(_)));
3887        let manager = manifest_ctx.manifest_manager.read().await;
3888        assert_eq!(0, manager.checkpointer().last_checkpoint_version());
3889        assert!(!manager.checkpointer().is_doing_checkpoint());
3890    }
3891
3892    /// Of the leases that apply together, only the one that ends the wait reports it.
3893    #[tokio::test]
3894    async fn test_only_the_lease_that_ends_the_wait_reports_it() {
3895        let env = SchedulerEnv::new().await;
3896        let region = build_test_region(&env).await;
3897        let manifest_ctx = &region.manifest_ctx;
3898        manifest_ctx.start_leader_lease_wait_for_test(region.region_id, None);
3899        // Two leases that read the same wait before either ends it.
3900        let promoted_at = manifest_ctx.catchup_promoted_at.load(Ordering::Relaxed);
3901
3902        assert!(manifest_ctx.end_leader_lease_wait(promoted_at).is_some());
3903        assert!(manifest_ctx.end_leader_lease_wait(promoted_at).is_none());
3904        assert!(!manifest_ctx.awaits_leader_lease());
3905        // A lease that reads the wait after it ended.
3906        assert!(
3907            manifest_ctx
3908                .record_leader_lease(std::time::Instant::now())
3909                .is_none()
3910        );
3911    }
3912
3913    #[tokio::test]
3914    async fn test_compaction_update_manifest_allows_editing_state() {
3915        let env = SchedulerEnv::new().await;
3916        let region = build_test_region(&env).await;
3917        region.set_editing(RegionLeaderState::Writable).unwrap();
3918
3919        let file_id = FileId::random();
3920        let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit {
3921            files_to_add: vec![crate::sst::file::FileMeta {
3922                region_id: region.region_id,
3923                file_id,
3924                level: 1,
3925                ..Default::default()
3926            }],
3927            files_to_remove: Vec::new(),
3928            timestamp_ms: None,
3929            compaction_time_window: None,
3930            flushed_entry_id: None,
3931            flushed_sequence: None,
3932            committed_sequence: None,
3933            ..Default::default()
3934        }));
3935
3936        region
3937            .manifest_ctx
3938            .update_manifest_for_compaction(action_list)
3939            .await
3940            .unwrap();
3941
3942        assert!(
3943            region
3944                .manifest_ctx
3945                .manifest()
3946                .await
3947                .files
3948                .contains_key(&file_id)
3949        );
3950    }
3951
3952    #[rstest::rstest]
3953    #[case::writable(false)]
3954    #[case::downgrading(true)]
3955    #[tokio::test]
3956    async fn test_index_publication_refused_awaiting_leader_lease_unless_downgrading(
3957        #[case] downgrading: bool,
3958    ) {
3959        let env = SchedulerEnv::new().await;
3960        let region = build_test_region(&env).await;
3961        let source = crate::sst::file::FileMeta {
3962            region_id: region.region_id,
3963            file_id: FileId::random(),
3964            level: 1,
3965            file_size: 1024,
3966            ..Default::default()
3967        };
3968        region
3969            .manifest_ctx
3970            .update_manifest(
3971                RegionLeaderState::Writable,
3972                RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit {
3973                    files_to_add: vec![source.clone()],
3974                    ..empty_edit()
3975                })),
3976                false,
3977            )
3978            .await
3979            .unwrap();
3980        let manifest_ctx = &region.manifest_ctx;
3981        manifest_ctx.start_leader_lease_wait_for_test(region.region_id, None);
3982        let index_source =
3983            IndexBuildSource::new(source.clone(), region.version().metadata.schema_version);
3984        let mut updated = source.clone();
3985        updated.index_version = 1;
3986        updated.index_file_size = 128;
3987        let publish = || manifest_ctx.update_manifest_for_index(&index_source, updated.clone());
3988
3989        if downgrading {
3990            // A downgrade is asked only of the leader in the route.
3991            manifest_ctx.begin_downgrade(region.region_id);
3992        } else {
3993            let err = publish().await.unwrap_err();
3994            assert!(
3995                matches!(err, Error::RegionLeaseNotReceived { .. }),
3996                "{err:?}"
3997            );
3998            assert_eq!(
3999                manifest_ctx
4000                    .manifest()
4001                    .await
4002                    .files
4003                    .get(&source.file_id)
4004                    .map(AsRef::as_ref),
4005                Some(&source)
4006            );
4007            manifest_ctx.record_leader_lease(std::time::Instant::now());
4008        }
4009        assert!(matches!(
4010            publish().await.unwrap(),
4011            IndexPublication::Committed { .. }
4012        ));
4013    }
4014
4015    #[tokio::test]
4016    async fn test_index_publication_rejects_older_source_generation() {
4017        let env = SchedulerEnv::new().await;
4018        let region = build_test_region(&env).await;
4019        let source = crate::sst::file::FileMeta {
4020            region_id: region.region_id,
4021            file_id: FileId::random(),
4022            level: 1,
4023            file_size: 1024,
4024            ..Default::default()
4025        };
4026        region
4027            .manifest_ctx
4028            .update_manifest(
4029                RegionLeaderState::Writable,
4030                RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit {
4031                    files_to_add: vec![source.clone()],
4032                    ..empty_edit()
4033                })),
4034                false,
4035            )
4036            .await
4037            .unwrap();
4038
4039        let mut first_update = source.clone();
4040        first_update.index_version = 1;
4041        first_update.index_file_size = 128;
4042        let schema_version = region.version().metadata.schema_version;
4043        let initial_source = IndexBuildSource::new(source.clone(), schema_version);
4044        let first_committed = match region
4045            .manifest_ctx
4046            .update_manifest_for_index(&initial_source, first_update)
4047            .await
4048            .unwrap()
4049        {
4050            IndexPublication::Committed { file_meta, .. } => file_meta,
4051            IndexPublication::Stale(_) => panic!("first index publication should commit"),
4052        };
4053
4054        let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
4055        let (release_tx, release_rx) = tokio::sync::oneshot::channel();
4056        let delayed_manifest_ctx = region.manifest_ctx.clone();
4057        let delayed_source = IndexBuildSource::new(first_committed.clone(), schema_version);
4058        let delayed_publication = tokio::spawn(async move {
4059            let mut delayed_update = delayed_source.file_meta.clone();
4060            delayed_update.index_version = 2;
4061            delayed_update.index_file_size = 128;
4062            ready_tx.send(()).unwrap();
4063            release_rx.await.unwrap();
4064            delayed_manifest_ctx
4065                .update_manifest_for_index(&delayed_source, delayed_update)
4066                .await
4067        });
4068        ready_rx.await.unwrap();
4069
4070        let mut newer_update = first_committed.clone();
4071        newer_update.index_version = 3;
4072        newer_update.index_file_size = 256;
4073        let newer_source = IndexBuildSource::new(first_committed, schema_version);
4074        let newer_committed = match region
4075            .manifest_ctx
4076            .update_manifest_for_index(&newer_source, newer_update)
4077            .await
4078            .unwrap()
4079        {
4080            IndexPublication::Committed { file_meta, .. } => file_meta,
4081            IndexPublication::Stale(_) => panic!("newer index publication should commit"),
4082        };
4083
4084        release_tx.send(()).unwrap();
4085        assert!(matches!(
4086            delayed_publication.await.unwrap().unwrap(),
4087            IndexPublication::Stale(IndexPublicationStale::SourceChanged)
4088        ));
4089        assert_eq!(
4090            region
4091                .manifest_ctx
4092                .manifest()
4093                .await
4094                .files
4095                .get(&source.file_id)
4096                .map(AsRef::as_ref),
4097            Some(&newer_committed)
4098        );
4099    }
4100
4101    #[tokio::test]
4102    async fn test_index_publication_rejects_older_schema_generation() {
4103        let env = SchedulerEnv::new().await;
4104        let region = build_test_region(&env).await;
4105        let source_meta = crate::sst::file::FileMeta {
4106            region_id: region.region_id,
4107            file_id: FileId::random(),
4108            level: 1,
4109            file_size: 1024,
4110            ..Default::default()
4111        };
4112        region
4113            .manifest_ctx
4114            .update_manifest(
4115                RegionLeaderState::Writable,
4116                RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit {
4117                    files_to_add: vec![source_meta.clone()],
4118                    ..empty_edit()
4119                })),
4120                false,
4121            )
4122            .await
4123            .unwrap();
4124
4125        let old_schema_version = region.version().metadata.schema_version;
4126        let source = IndexBuildSource::new(source_meta.clone(), old_schema_version);
4127        let mut new_metadata = region.version().metadata.as_ref().clone();
4128        new_metadata.schema_version += 1;
4129        region
4130            .manifest_ctx
4131            .update_manifest(
4132                RegionLeaderState::Writable,
4133                RegionMetaActionList::with_action(RegionMetaAction::Change(RegionChange {
4134                    metadata: Arc::new(new_metadata),
4135                    sst_format: FormatType::PrimaryKey,
4136                    append_mode: None,
4137                })),
4138                false,
4139            )
4140            .await
4141            .unwrap();
4142
4143        let mut updated = source_meta.clone();
4144        updated.index_version = 1;
4145        updated.index_file_size = 128;
4146        assert!(matches!(
4147            region
4148                .manifest_ctx
4149                .update_manifest_for_index(&source, updated)
4150                .await
4151                .unwrap(),
4152            IndexPublication::Stale(IndexPublicationStale::SchemaChanged)
4153        ));
4154
4155        let manifest = region.manifest_ctx.manifest().await;
4156        assert_eq!(manifest.metadata.schema_version, old_schema_version + 1);
4157        assert_eq!(
4158            manifest.files.get(&source_meta.file_id).map(AsRef::as_ref),
4159            Some(&source_meta)
4160        );
4161    }
4162
4163    #[tokio::test]
4164    async fn test_end_staging_partition_expr_change_and_edit_success() {
4165        let env = SchedulerEnv::new().await;
4166        let region = build_test_region(&env).await;
4167
4168        let mut manager = region.manifest_ctx.manifest_manager.write().await;
4169        region.set_staging(&mut manager).await.unwrap();
4170        let version = manager.last_version();
4171        for action in [
4172            RegionMetaAction::PartitionExprChange(RegionPartitionExprChange {
4173                partition_expr: Some("expr_a".to_string()),
4174            }),
4175            RegionMetaAction::Edit(empty_edit()),
4176        ] {
4177            manager
4178                .update(RegionMetaActionList::with_action(action), true)
4179                .await
4180                .unwrap();
4181        }
4182        // Staged actions take no version.
4183        assert_eq!(manager.last_version(), version);
4184
4185        let pending = region.end_staging_locked(&mut manager).await.unwrap();
4186        assert_eq!(pending.unwrap().version(), version + 1);
4187        assert_eq!(manager.last_version(), version + 1);
4188        assert!(manager.staged_actions().is_none());
4189        drop(manager);
4190
4191        assert_eq!(
4192            region.version().metadata.partition_expr.as_deref(),
4193            Some("expr_a")
4194        );
4195        assert_eq!(
4196            region.state(),
4197            RegionRoleState::Leader(RegionLeaderState::Writable)
4198        );
4199    }
4200
4201    #[tokio::test]
4202    async fn test_end_staging_change_with_same_columns_success() {
4203        let env = SchedulerEnv::new().await;
4204        let region = build_test_region(&env).await;
4205
4206        let mut manager = region.manifest_ctx.manifest_manager.write().await;
4207        region.set_staging(&mut manager).await.unwrap();
4208
4209        let mut changed_metadata = region.version().metadata.as_ref().clone();
4210        changed_metadata.set_partition_expr(Some("expr_b".to_string()));
4211
4212        manager
4213            .update(
4214                RegionMetaActionList::new(vec![
4215                    RegionMetaAction::Change(RegionChange {
4216                        metadata: Arc::new(changed_metadata),
4217                        sst_format: FormatType::PrimaryKey,
4218                        append_mode: None,
4219                    }),
4220                    RegionMetaAction::Edit(empty_edit()),
4221                ]),
4222                true,
4223            )
4224            .await
4225            .unwrap();
4226
4227        let _hook_payload = region.end_staging_locked(&mut manager).await.unwrap();
4228        drop(manager);
4229
4230        assert_eq!(
4231            region.version().metadata.partition_expr.as_deref(),
4232            Some("expr_b")
4233        );
4234        assert_eq!(
4235            region.state(),
4236            RegionRoleState::Leader(RegionLeaderState::Writable)
4237        );
4238    }
4239
4240    #[tokio::test]
4241    async fn test_end_staging_change_with_different_columns_fails() {
4242        let env = SchedulerEnv::new().await;
4243        let region = build_test_region(&env).await;
4244
4245        let mut manager = region.manifest_ctx.manifest_manager.write().await;
4246        region.set_staging(&mut manager).await.unwrap();
4247
4248        let mut changed_metadata = region.version().metadata.as_ref().clone();
4249        changed_metadata.column_metadatas.rotate_left(1);
4250
4251        manager
4252            .update(
4253                RegionMetaActionList::new(vec![
4254                    RegionMetaAction::Change(RegionChange {
4255                        metadata: Arc::new(changed_metadata),
4256                        sst_format: FormatType::PrimaryKey,
4257                        append_mode: None,
4258                    }),
4259                    RegionMetaAction::Edit(empty_edit()),
4260                ]),
4261                true,
4262            )
4263            .await
4264            .unwrap();
4265
4266        let result = region.end_staging_locked(&mut manager).await;
4267        assert!(matches!(result, Err(Error::Unexpected { .. })));
4268    }
4269
4270    #[tokio::test]
4271    async fn test_end_staging_partition_expr_change_and_change_conflict_fails() {
4272        let env = SchedulerEnv::new().await;
4273        let region = build_test_region(&env).await;
4274
4275        let mut manager = region.manifest_ctx.manifest_manager.write().await;
4276        region.set_staging(&mut manager).await.unwrap();
4277
4278        let mut changed_metadata = region.version().metadata.as_ref().clone();
4279        changed_metadata.set_partition_expr(Some("expr_c".to_string()));
4280
4281        manager
4282            .update(
4283                RegionMetaActionList::new(vec![
4284                    RegionMetaAction::PartitionExprChange(RegionPartitionExprChange {
4285                        partition_expr: Some("expr_c".to_string()),
4286                    }),
4287                    RegionMetaAction::Change(RegionChange {
4288                        metadata: Arc::new(changed_metadata),
4289                        sst_format: FormatType::PrimaryKey,
4290                        append_mode: None,
4291                    }),
4292                    RegionMetaAction::Edit(empty_edit()),
4293                ]),
4294                true,
4295            )
4296            .await
4297            .unwrap();
4298
4299        let result = region.end_staging_locked(&mut manager).await;
4300        assert!(matches!(result, Err(Error::Unexpected { .. })));
4301    }
4302
4303    #[tokio::test]
4304    async fn test_end_staging_ignores_files_in_staging_dir() {
4305        let env = SchedulerEnv::new().await;
4306        let region = build_test_region(&env).await;
4307
4308        let mut manager = region.manifest_ctx.manifest_manager.write().await;
4309        region.set_staging(&mut manager).await.unwrap();
4310        // A late writer leaves a delta in the staging directory.
4311        let late_file = crate::sst::file::FileMeta {
4312            file_id: FileId::random(),
4313            ..Default::default()
4314        };
4315        let late_edit = RegionEdit {
4316            files_to_add: vec![late_file.clone()],
4317            ..Default::default()
4318        };
4319        region
4320            .access_layer
4321            .object_store()
4322            .write(
4323                &format!(
4324                    "{}{}",
4325                    staging_manifest_path(manager.store().manifest_dir()),
4326                    delta_file(1)
4327                ),
4328                RegionMetaActionList::with_action(RegionMetaAction::Edit(late_edit))
4329                    .encode()
4330                    .unwrap(),
4331            )
4332            .await
4333            .unwrap();
4334        manager
4335            .update(
4336                RegionMetaActionList::new(vec![
4337                    RegionMetaAction::PartitionExprChange(RegionPartitionExprChange {
4338                        partition_expr: Some("expr_a".to_string()),
4339                    }),
4340                    RegionMetaAction::Edit(empty_edit()),
4341                ]),
4342                true,
4343            )
4344            .await
4345            .unwrap();
4346
4347        let _hook_payload = region.end_staging_locked(&mut manager).await.unwrap();
4348
4349        assert!(!manager.manifest().files.contains_key(&late_file.file_id));
4350    }
4351
4352    #[tokio::test]
4353    async fn test_ending_staging_holds_role_changes() {
4354        let env = SchedulerEnv::new().await;
4355        let version_control = VersionControlBuilder::new().build();
4356        let ctx = env
4357            .mock_manifest_context(version_control.current().version.metadata.clone())
4358            .await;
4359        let region_id = RegionId::new(1024, 0);
4360        let staging = RegionRoleState::Leader(RegionLeaderState::Staging);
4361        let committed: Result<()> = Ok(());
4362        let unknown: Result<()> = UnexpectedSnafu { reason: "mock" }.fail();
4363        let conflict: Result<()> = ManifestVersionConflictSnafu {
4364            version: 1u64,
4365            manifest_dir: "manifest/",
4366            reason: "mock",
4367        }
4368        .fail();
4369        // Ends staging with `result`, running `during` while the commit runs.
4370        let end = |result: &Result<()>, during: &dyn Fn()| {
4371            ctx.state.store(staging);
4372            if ctx.staging_partition_info().is_none() {
4373                ctx.set_staging_partition_info(StagingPartitionInfo::from_partition_directive(
4374                    StagingPartitionDirective::RejectAllWrites,
4375                ));
4376            }
4377            let started = ctx.begin_ending_staging(region_id).unwrap();
4378            during();
4379            assert_eq!(
4380                ctx.state.load(),
4381                RegionRoleState::Leader(RegionLeaderState::EndingStaging)
4382            );
4383            let state = ctx.leave_ending_staging(region_id, started, result);
4384            // Only a return to staging keeps the partition info for the retry.
4385            assert_eq!(ctx.staging_partition_info().is_some(), state == staging);
4386            state
4387        };
4388        let set_roles = || {
4389            for role in [
4390                RegionRole::Follower,
4391                RegionRole::Leader,
4392                RegionRole::StagingLeader,
4393                RegionRole::DowngradingLeader,
4394            ] {
4395                ctx.set_role(role, region_id);
4396            }
4397        };
4398
4399        assert_eq!(end(&unknown, &set_roles), staging);
4400        assert_eq!(
4401            end(&committed, &|| ctx.begin_downgrade(region_id)),
4402            RegionRoleState::Leader(RegionLeaderState::Downgrading)
4403        );
4404        assert_eq!(
4405            end(&committed, &|| {}),
4406            RegionRoleState::Leader(RegionLeaderState::Writable)
4407        );
4408        assert_eq!(end(&conflict, &|| {}), RegionRoleState::Follower);
4409        // The Leader lease expired while the commit ran; no deadline counts as expired.
4410        ctx.node_lease.enable();
4411        assert_eq!(end(&committed, &|| {}), RegionRoleState::Follower);
4412        assert_eq!(end(&unknown, &|| {}), RegionRoleState::Follower);
4413    }
4414
4415    #[tokio::test]
4416    async fn test_set_region_state() {
4417        let env = SchedulerEnv::new().await;
4418        let builder = VersionControlBuilder::new();
4419        let version_control = Arc::new(builder.build());
4420        let manifest_ctx = env
4421            .mock_manifest_context(version_control.current().version.metadata.clone())
4422            .await;
4423
4424        let region_id = RegionId::new(1024, 0);
4425        // Each call returns the state it replaced, None if it left the state unchanged.
4426        // Leader -> Follower
4427        assert_eq!(
4428            manifest_ctx.set_role(RegionRole::Follower, region_id),
4429            Some(RegionRoleState::Leader(RegionLeaderState::Writable))
4430        );
4431        assert_eq!(manifest_ctx.state.load(), RegionRoleState::Follower);
4432
4433        // Follower -> Follower
4434        assert_eq!(manifest_ctx.set_role(RegionRole::Follower, region_id), None);
4435
4436        // Follower -> Leader
4437        assert_eq!(
4438            manifest_ctx.set_role(RegionRole::Leader, region_id),
4439            Some(RegionRoleState::Follower)
4440        );
4441        assert_eq!(
4442            manifest_ctx.state.load(),
4443            RegionRoleState::Leader(RegionLeaderState::Writable)
4444        );
4445
4446        // Direct Leader -> StagingLeader should be ignored.
4447        assert_eq!(
4448            manifest_ctx.set_role(RegionRole::StagingLeader, region_id),
4449            None
4450        );
4451        assert_eq!(
4452            manifest_ctx.state.load(),
4453            RegionRoleState::Leader(RegionLeaderState::Writable)
4454        );
4455
4456        // Leader -> Downgrading Leader
4457        assert_eq!(
4458            manifest_ctx.set_role(RegionRole::DowngradingLeader, region_id),
4459            Some(RegionRoleState::Leader(RegionLeaderState::Writable))
4460        );
4461        assert_eq!(
4462            manifest_ctx.state.load(),
4463            RegionRoleState::Leader(RegionLeaderState::Downgrading)
4464        );
4465
4466        // Downgrading Leader -> Follower
4467        assert_eq!(
4468            manifest_ctx.set_role(RegionRole::Follower, region_id),
4469            Some(RegionRoleState::Leader(RegionLeaderState::Downgrading))
4470        );
4471        assert_eq!(manifest_ctx.state.load(), RegionRoleState::Follower);
4472
4473        // Can't downgrade from follower (Follower -> Downgrading Leader)
4474        assert_eq!(
4475            manifest_ctx.set_role(RegionRole::DowngradingLeader, region_id),
4476            None
4477        );
4478        assert_eq!(manifest_ctx.state.load(), RegionRoleState::Follower);
4479
4480        // Set region role too Downgrading Leader
4481        assert_eq!(
4482            manifest_ctx.set_role(RegionRole::Leader, region_id),
4483            Some(RegionRoleState::Follower)
4484        );
4485        assert_eq!(
4486            manifest_ctx.set_role(RegionRole::DowngradingLeader, region_id),
4487            Some(RegionRoleState::Leader(RegionLeaderState::Writable))
4488        );
4489        assert_eq!(
4490            manifest_ctx.state.load(),
4491            RegionRoleState::Leader(RegionLeaderState::Downgrading)
4492        );
4493
4494        assert_eq!(
4495            manifest_ctx.set_role(RegionRole::DowngradingLeader, region_id),
4496            None
4497        );
4498
4499        // Downgrading Leader -> Leader
4500        assert_eq!(
4501            manifest_ctx.set_role(RegionRole::Leader, region_id),
4502            Some(RegionRoleState::Leader(RegionLeaderState::Downgrading))
4503        );
4504        assert_eq!(
4505            manifest_ctx.state.load(),
4506            RegionRoleState::Leader(RegionLeaderState::Writable)
4507        );
4508
4509        assert_eq!(manifest_ctx.set_role(RegionRole::Leader, region_id), None);
4510
4511        // Altering Leader -> Follower
4512        let altering = RegionRoleState::Leader(RegionLeaderState::Altering);
4513        manifest_ctx.state.store(altering);
4514        assert_eq!(
4515            manifest_ctx.set_role(RegionRole::Follower, region_id),
4516            Some(altering)
4517        );
4518        assert_eq!(manifest_ctx.state.load(), RegionRoleState::Follower);
4519
4520        // Staging Leader -> Follower
4521        let staging = RegionRoleState::Leader(RegionLeaderState::Staging);
4522        manifest_ctx.state.store(staging);
4523        assert_eq!(
4524            manifest_ctx.set_role(RegionRole::Follower, region_id),
4525            Some(staging)
4526        );
4527        assert_eq!(manifest_ctx.state.load(), RegionRoleState::Follower);
4528
4529        manifest_ctx.state.store(staging);
4530        assert_eq!(
4531            manifest_ctx.set_role(RegionRole::Leader, region_id),
4532            Some(staging)
4533        );
4534        assert_eq!(
4535            manifest_ctx.state.load(),
4536            RegionRoleState::Leader(RegionLeaderState::Writable)
4537        );
4538    }
4539
4540    #[tokio::test]
4541    async fn test_staging_state_validation() {
4542        let env = SchedulerEnv::new().await;
4543        let builder = VersionControlBuilder::new();
4544        let version_control = Arc::new(builder.build());
4545
4546        // Create context with staging state using the correct pattern from SchedulerEnv
4547        let staging_ctx = {
4548            let manager = RegionManifestManager::new(
4549                version_control.current().version.metadata.clone(),
4550                0,
4551                RegionManifestOptions {
4552                    file_metadata_interner: Default::default(),
4553                    manifest_dir: "".to_string(),
4554                    object_store: env.access_layer.object_store().clone(),
4555                    compress_type: CompressionType::Uncompressed,
4556                    checkpoint_distance: 10,
4557                    remove_file_options: Default::default(),
4558                    manifest_cache: None,
4559                    conditional_publication: false,
4560                },
4561                FormatType::PrimaryKey,
4562                false,
4563                &Default::default(),
4564            )
4565            .await
4566            .unwrap();
4567            Arc::new(ManifestContext::new(
4568                manager,
4569                RegionRoleState::Leader(RegionLeaderState::Staging),
4570                None,
4571                Default::default(),
4572            ))
4573        };
4574
4575        // Test staging state behavior
4576        assert_eq!(
4577            staging_ctx.current_state(),
4578            RegionRoleState::Leader(RegionLeaderState::Staging)
4579        );
4580
4581        // Test writable context for comparison
4582        let writable_ctx = env
4583            .mock_manifest_context(version_control.current().version.metadata.clone())
4584            .await;
4585
4586        assert_eq!(
4587            writable_ctx.current_state(),
4588            RegionRoleState::Leader(RegionLeaderState::Writable)
4589        );
4590    }
4591
4592    #[tokio::test]
4593    async fn test_staging_state_transitions() {
4594        let builder = VersionControlBuilder::new();
4595        let version_control = Arc::new(builder.build());
4596        let metadata = version_control.current().version.metadata.clone();
4597
4598        // Create MitoRegion for testing state transitions
4599        let temp_dir = create_temp_dir("");
4600        let path_str = temp_dir.path().display().to_string();
4601        let fs_builder = Fs::default().root(&path_str);
4602        let object_store = ObjectStore::new(fs_builder).unwrap();
4603
4604        let index_aux_path = temp_dir.path().join("index_aux");
4605        let puffin_mgr = PuffinManagerFactory::new(&index_aux_path, 4096, None, None)
4606            .await
4607            .unwrap();
4608        let intm_mgr = IntermediateManager::init_fs(index_aux_path.to_str().unwrap())
4609            .await
4610            .unwrap();
4611
4612        let access_layer = Arc::new(AccessLayer::new(
4613            "",
4614            PathType::Bare,
4615            object_store,
4616            puffin_mgr,
4617            intm_mgr,
4618        ));
4619
4620        let manager = RegionManifestManager::new(
4621            metadata.clone(),
4622            0,
4623            RegionManifestOptions {
4624                file_metadata_interner: Default::default(),
4625                manifest_dir: "".to_string(),
4626                object_store: access_layer.object_store().clone(),
4627                compress_type: CompressionType::Uncompressed,
4628                checkpoint_distance: 10,
4629                remove_file_options: Default::default(),
4630                manifest_cache: None,
4631                conditional_publication: false,
4632            },
4633            FormatType::PrimaryKey,
4634            false,
4635            &Default::default(),
4636        )
4637        .await
4638        .unwrap();
4639
4640        let manifest_ctx = Arc::new(ManifestContext::new(
4641            manager,
4642            RegionRoleState::Leader(RegionLeaderState::Writable),
4643            None,
4644            Default::default(),
4645        ));
4646
4647        let region = MitoRegion {
4648            region_id: metadata.region_id,
4649            compaction_state: Default::default(),
4650            version_control,
4651            access_layer,
4652            manifest_ctx: manifest_ctx.clone(),
4653            file_purger: crate::test_util::new_noop_file_purger(),
4654            provider: Provider::noop_provider(),
4655            last_flush_millis: Default::default(),
4656            last_schedule_compaction_millis: Default::default(),
4657            time_provider: Arc::new(StdTimeProvider),
4658            topic_latest_entry_id: Default::default(),
4659            region_stats: RegionStats::new(),
4660            stats: ManifestStats::default(),
4661        };
4662
4663        // Test initial state
4664        assert_eq!(
4665            region.state(),
4666            RegionRoleState::Leader(RegionLeaderState::Writable)
4667        );
4668        assert!(!region.is_staging());
4669
4670        // Test transition to staging
4671        let mut manager = manifest_ctx.manifest_manager.write().await;
4672        region.set_staging(&mut manager).await.unwrap();
4673        drop(manager);
4674        assert_eq!(
4675            region.state(),
4676            RegionRoleState::Leader(RegionLeaderState::Staging)
4677        );
4678        assert!(region.is_staging());
4679
4680        // Test transition back to writable
4681        region.exit_staging().unwrap();
4682        assert_eq!(
4683            region.state(),
4684            RegionRoleState::Leader(RegionLeaderState::Writable)
4685        );
4686        assert!(!region.is_staging());
4687
4688        // Entering staging clears the staging directory and the staged actions.
4689        {
4690            let mut manager = manifest_ctx.manifest_manager.write().await;
4691            let object_store = region.access_layer.object_store().clone();
4692            // A delta that an older version staged.
4693            let stale_delta = format!(
4694                "{}{}",
4695                staging_manifest_path(manager.store().manifest_dir()),
4696                delta_file(100)
4697            );
4698            object_store
4699                .write(
4700                    &stale_delta,
4701                    RegionMetaActionList::new(vec![]).encode().unwrap(),
4702                )
4703                .await
4704                .unwrap();
4705            region.set_staging(&mut manager).await.unwrap();
4706            assert!(!object_store.exists(&stale_delta).await.unwrap());
4707
4708            manager
4709                .update(
4710                    RegionMetaActionList::with_action(RegionMetaAction::Edit(empty_edit())),
4711                    true,
4712                )
4713                .await
4714                .unwrap();
4715            assert!(manager.staged_actions().is_some());
4716            region.exit_staging().unwrap();
4717            region.set_staging(&mut manager).await.unwrap();
4718            assert!(manager.staged_actions().is_none());
4719            assert!(manager.staging_manifest().is_none());
4720
4721            // Exit staging to restore normal state for remaining tests
4722            region.exit_staging().unwrap();
4723        }
4724
4725        // Test invalid transitions
4726        let mut manager = manifest_ctx.manifest_manager.write().await;
4727        assert!(region.set_staging(&mut manager).await.is_ok()); // Writable -> Staging should work
4728        drop(manager);
4729        let mut manager = manifest_ctx.manifest_manager.write().await;
4730        assert!(region.set_staging(&mut manager).await.is_err()); // Staging -> Staging should fail
4731        drop(manager);
4732        assert!(region.exit_staging().is_ok()); // Staging -> Writable should work
4733        assert!(region.exit_staging().is_err()); // Writable -> Writable should fail
4734    }
4735}