Skip to main content

mito2/manifest/
manager.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashSet;
16use std::sync::Arc;
17use std::sync::atomic::{AtomicU64, Ordering};
18use std::time::Instant;
19
20use common_datasource::compression::CompressionType;
21use common_telemetry::{debug, info, warn};
22use object_store::ObjectStore;
23use snafu::ensure;
24use store_api::metadata::RegionMetadataRef;
25use store_api::{MAX_VERSION, MIN_VERSION, ManifestVersion};
26
27use crate::cache::manifest_cache::ManifestCache;
28use crate::config::MitoConfig;
29use crate::error::{
30    EndStagingPendingSnafu, InstallManifestToSnafu, ManifestCheckpointAdvancedSnafu,
31    NoCheckpointSnafu, NoManifestsSnafu, RegionStoppedSnafu, Result,
32};
33use crate::manifest::action::{
34    RegionChange, RegionCheckpoint, RegionEdit, RegionManifest, RegionManifestBuilder,
35    RegionMetaAction, RegionMetaActionList, RemovedFile,
36};
37use crate::manifest::checkpointer::Checkpointer;
38use crate::manifest::storage::{ManifestObjectStore, manifest_compress_type, manifest_dir};
39use crate::metrics::MANIFEST_OP_ELAPSED;
40use crate::region::ManifestStats;
41use crate::sst::file_metadata::FileMetadataInternerRef;
42use crate::sst::{FormatType, file};
43
44/// Options for [RegionManifestManager].
45#[derive(Debug, Clone)]
46pub struct RegionManifestOptions {
47    /// Shares immutable file metadata with runtime readers in this engine.
48    pub(crate) file_metadata_interner: FileMetadataInternerRef,
49    /// Directory to store manifest.
50    pub manifest_dir: String,
51    pub object_store: ObjectStore,
52    pub compress_type: CompressionType,
53    /// Interval of version ([ManifestVersion](store_api::ManifestVersion)) between two checkpoints.
54    /// Set to 0 to disable checkpoint.
55    pub checkpoint_distance: u64,
56    pub remove_file_options: RemoveFileOptions,
57    /// Optional cache for manifest files.
58    pub manifest_cache: Option<ManifestCache>,
59    /// Whether two writers can race for a version, so that deltas are published by conditional
60    /// create under a fixed name and recovery starts from the highest listed checkpoint.
61    pub(crate) conditional_publication: bool,
62}
63
64impl RegionManifestOptions {
65    /// Creates options using the same metadata interner as the owner's runtime file views.
66    pub fn new(
67        config: &MitoConfig,
68        region_dir: &str,
69        object_store: &ObjectStore,
70        file_metadata_interner: FileMetadataInternerRef,
71    ) -> Self {
72        RegionManifestOptions {
73            file_metadata_interner,
74            manifest_dir: manifest_dir(region_dir),
75            object_store: object_store.clone(),
76            // We don't allow users to set the compression algorithm as we use it as a file suffix.
77            // Currently, the manifest storage doesn't have good support for changing compression algorithms.
78            compress_type: manifest_compress_type(config.compress_manifest),
79            checkpoint_distance: config.manifest_checkpoint_distance,
80            remove_file_options: RemoveFileOptions {
81                enable_gc: config.gc.enable,
82            },
83            manifest_cache: None,
84            conditional_publication: false,
85        }
86    }
87
88    /// Sets whether deltas are published by conditional create and recovery starts from the
89    /// highest listed checkpoint.
90    pub(crate) fn with_conditional_publication(mut self, enabled: bool) -> Self {
91        self.conditional_publication = enabled;
92        self
93    }
94}
95
96/// Options for updating `removed_files` field in [RegionManifest].
97#[derive(Debug, Clone)]
98#[cfg_attr(any(test, feature = "test"), derive(Default))]
99pub struct RemoveFileOptions {
100    /// Whether GC is enabled. If not, the removed files should always be empty when persisting manifest.
101    pub enable_gc: bool,
102}
103
104// rewrite note:
105// trait Checkpoint -> struct RegionCheckpoint
106// trait MetaAction -> struct RegionMetaActionList
107// trait MetaActionIterator -> struct MetaActionIteratorImpl
108
109#[cfg_attr(doc, aquamarine::aquamarine)]
110/// Manage region's manifest. Provide APIs to access (create/modify/recover) region's persisted
111/// metadata.
112///
113/// ```mermaid
114/// classDiagram
115/// class RegionManifestManager {
116///     -ManifestObjectStore store
117///     -RegionManifestOptions options
118///     -RegionManifest manifest
119///     +new() RegionManifestManager
120///     +open() Option~RegionManifestManager~
121///     +stop()
122///     +update(RegionMetaActionList action_list) ManifestVersion
123///     +manifest() RegionManifest
124/// }
125/// class ManifestObjectStore {
126///     -ObjectStore object_store
127/// }
128/// class RegionChange {
129///     -RegionMetadataRef metadata
130/// }
131/// class RegionEdit {
132///     -VersionNumber region_version
133///     -Vec~FileMeta~ files_to_add
134///     -Vec~FileMeta~ files_to_remove
135///     -SequenceNumber flushed_sequence
136/// }
137/// class RegionRemove {
138///     -RegionId region_id
139/// }
140/// RegionManifestManager o-- ManifestObjectStore
141/// RegionManifestManager o-- RegionManifest
142/// RegionManifestManager o-- RegionManifestOptions
143/// RegionManifestManager -- RegionMetaActionList
144/// RegionManifestManager -- RegionCheckpoint
145/// ManifestObjectStore o-- ObjectStore
146/// RegionMetaActionList o-- RegionMetaAction
147/// RegionMetaAction o-- ProtocolAction
148/// RegionMetaAction o-- RegionChange
149/// RegionMetaAction o-- RegionEdit
150/// RegionMetaAction o-- RegionRemove
151/// RegionChange o-- RegionMetadata
152/// RegionEdit o-- FileMeta
153///
154/// class RegionManifest {
155///     -RegionMetadataRef metadata
156///     -HashMap&lt;FileId, FileMeta&gt; files
157///     -ManifestVersion manifest_version
158/// }
159/// class RegionMetadata
160/// class FileMeta
161/// RegionManifest o-- RegionMetadata
162/// RegionManifest o-- FileMeta
163///
164/// class RegionCheckpoint {
165///     -ManifestVersion last_version
166///     -Option~RegionManifest~ checkpoint
167/// }
168/// RegionCheckpoint o-- RegionManifest
169/// ```
170#[derive(Debug)]
171pub struct RegionManifestManager {
172    file_metadata_interner: FileMetadataInternerRef,
173    store: ManifestObjectStore,
174    last_version: Arc<AtomicU64>,
175    checkpointer: Checkpointer,
176    manifest: Arc<RegionManifest>,
177    /// Actions of a staging region, committed as one version when staging ends.
178    staged: StagedActions,
179    stats: ManifestStats,
180    stopped: bool,
181}
182
183/// Actions appended while a region is staging. They take no version and write nothing until
184/// staging ends.
185#[derive(Debug, Default)]
186struct StagedActions {
187    actions: RegionMetaActionList,
188    /// The manifest with `actions` applied, while any are staged.
189    view: Option<Arc<RegionManifest>>,
190    /// Encoded bytes of an end commit that may have been written. A retry commits the same bytes,
191    /// and no other action is appended while they are kept.
192    attempted: Option<Vec<u8>>,
193}
194
195impl StagedActions {
196    /// Returns whether `action_list` only adds files that are already staged, as a retried
197    /// import does.
198    fn only_adds_staged_files(&self, action_list: &RegionMetaActionList) -> bool {
199        let staged: HashSet<_> = self
200            .actions
201            .actions
202            .iter()
203            .flat_map(|action| match action {
204                RegionMetaAction::Edit(edit) => edit.files_to_add.as_slice(),
205                _ => &[],
206            })
207            .map(|meta| meta.file_id)
208            .collect();
209        !action_list.actions.is_empty()
210            && action_list.actions.iter().all(|action| {
211                matches!(action, RegionMetaAction::Edit(edit)
212                    if edit.files_to_remove.is_empty()
213                        && edit.files_to_add.iter().all(|meta| staged.contains(&meta.file_id)))
214            })
215    }
216}
217
218impl RegionManifestManager {
219    /// Constructs a region's manifest and persist it.
220    pub async fn new(
221        metadata: RegionMetadataRef,
222        flushed_entry_id: u64,
223        options: RegionManifestOptions,
224        sst_format: FormatType,
225        append_mode: bool,
226        stats: &ManifestStats,
227    ) -> Result<Self> {
228        // construct storage
229        let mut store = ManifestObjectStore::new_with_metric(
230            &options.manifest_dir,
231            options.object_store.clone(),
232            options.compress_type,
233            stats.total_manifest_size.clone(),
234            stats.metric().cloned(),
235            options.manifest_cache.clone(),
236        )
237        .with_conditional_publication(options.conditional_publication)?;
238        let manifest_version = stats.manifest_version.clone();
239        let file_metadata_interner = options.file_metadata_interner.clone();
240
241        info!(
242            "Creating region manifest in {} with metadata {:?}, flushed_entry_id: {}",
243            options.manifest_dir, metadata, flushed_entry_id
244        );
245
246        let version = MIN_VERSION;
247        let mut manifest_builder = RegionManifestBuilder::new(file_metadata_interner.clone());
248        // set the initial metadata.
249        manifest_builder.apply_change(
250            version,
251            RegionChange {
252                metadata: metadata.clone(),
253                sst_format,
254                append_mode: Some(append_mode),
255            },
256        );
257        let manifest = manifest_builder.try_build()?;
258        let region_id = metadata.region_id;
259
260        debug!(
261            "Build region manifest in {}, manifest: {:?}",
262            options.manifest_dir, manifest
263        );
264
265        let mut actions = vec![RegionMetaAction::Change(RegionChange {
266            metadata,
267            sst_format,
268            append_mode: Some(append_mode),
269        })];
270        if flushed_entry_id > 0 {
271            actions.push(RegionMetaAction::Edit(RegionEdit {
272                files_to_add: vec![],
273                files_to_remove: vec![],
274                timestamp_ms: None,
275                compaction_time_window: None,
276                flushed_entry_id: Some(flushed_entry_id),
277                flushed_sequence: None,
278                committed_sequence: None,
279                ..Default::default()
280            }));
281        }
282
283        // Persist region change.
284        let action_list = RegionMetaActionList::new(actions);
285
286        store.save(version, &action_list.encode()?).await?;
287
288        let checkpointer = Checkpointer::new(region_id, options, store.clone(), MIN_VERSION);
289        manifest_version.store(version, Ordering::Relaxed);
290        manifest
291            .removed_files
292            .update_file_removed_cnt_to_stats(stats);
293        let manager = Self {
294            file_metadata_interner,
295            store,
296            last_version: manifest_version,
297            checkpointer,
298            manifest: Arc::new(manifest),
299            staged: StagedActions::default(),
300            stats: stats.clone(),
301            stopped: false,
302        };
303        Ok(manager)
304    }
305
306    /// Opens an existing manifest.
307    ///
308    /// Returns `Ok(None)` if no such manifest.
309    pub async fn open(
310        options: RegionManifestOptions,
311        stats: &ManifestStats,
312    ) -> Result<Option<Self>> {
313        let _t = MANIFEST_OP_ELAPSED
314            .with_label_values(&["open"])
315            .start_timer();
316        let open_start = Instant::now();
317
318        // construct storage
319        let mut store = ManifestObjectStore::new_with_metric(
320            &options.manifest_dir,
321            options.object_store.clone(),
322            options.compress_type,
323            stats.total_manifest_size.clone(),
324            stats.metric().cloned(),
325            options.manifest_cache.clone(),
326        )
327        .with_conditional_publication(options.conditional_publication)?;
328        let manifest_version = stats.manifest_version.clone();
329        let file_metadata_interner = options.file_metadata_interner.clone();
330
331        // recover from storage
332        // construct manifest builder
333        // calculate the manifest size from the latest checkpoint
334        let mut version = MIN_VERSION;
335        let checkpoint = Self::last_checkpoint(&mut store).await?;
336        let has_checkpoint = checkpoint.is_some();
337        let last_checkpoint_version = checkpoint
338            .as_ref()
339            .map(|checkpoint| checkpoint.last_version)
340            .unwrap_or(MIN_VERSION);
341        let mut manifest_builder = if let Some(checkpoint) = checkpoint {
342            info!(
343                "Recover region manifest {} from checkpoint version {}",
344                options.manifest_dir, checkpoint.last_version
345            );
346            version = version.max(checkpoint.last_version + 1);
347            RegionManifestBuilder::with_checkpoint(
348                checkpoint.checkpoint,
349                file_metadata_interner.clone(),
350            )
351        } else {
352            info!(
353                "Checkpoint not found in {}, build manifest from scratch",
354                options.manifest_dir
355            );
356            RegionManifestBuilder::new(file_metadata_interner.clone())
357        };
358
359        let replay_start_version = version;
360        info!(
361            "Replaying region manifest {} from version {}, last checkpoint version: {}",
362            options.manifest_dir, replay_start_version, last_checkpoint_version,
363        );
364
365        // apply actions from storage
366        let deltas = store.delta_storage();
367        let entries = if store.is_conditional_publication() {
368            let entries = store.scan_conditional(version, !has_checkpoint).await?;
369            let has_gap = (replay_start_version..)
370                .zip(&entries)
371                .any(|(expected, (found, _))| *found != expected);
372            if has_gap
373                && let Some((checkpoint_version, _)) =
374                    store.find_checkpoint(version, true, false).await?
375            {
376                return ManifestCheckpointAdvancedSnafu {
377                    checkpoint_version,
378                    replay_start_version,
379                    manifest_dir: &options.manifest_dir,
380                }
381                .fail();
382            }
383            entries
384        } else {
385            deltas.scan(version, MAX_VERSION).await?
386        };
387        let manifests = deltas.fetch_manifests_from_entries(&entries).await?;
388        // A fenced writer can recreate a listed delta before its payload is read.
389        if store.is_conditional_publication()
390            && let Some((checkpoint_version, _)) = store
391                .find_checkpoint(version, true, !has_checkpoint && manifests.is_empty())
392                .await?
393        {
394            drop(manifests);
395            if let Some(cache) = &options.manifest_cache {
396                let keys: Vec<_> = entries.iter().map(|(_, e)| e.path().to_owned()).collect();
397                cache.remove_batch(&keys).await;
398            }
399            return ManifestCheckpointAdvancedSnafu {
400                checkpoint_version,
401                replay_start_version,
402                manifest_dir: &options.manifest_dir,
403            }
404            .fail();
405        }
406        let replayed_deltas = manifests.len();
407
408        for (manifest_version, raw_action_list) in manifests {
409            let action_list = RegionMetaActionList::decode(&raw_action_list)?;
410            for action in action_list.actions {
411                match action {
412                    RegionMetaAction::Change(action) => {
413                        manifest_builder.apply_change(manifest_version, action);
414                    }
415                    RegionMetaAction::PartitionExprChange(action) => {
416                        manifest_builder.apply_partition_expr_change(manifest_version, action);
417                    }
418                    RegionMetaAction::Edit(action) => {
419                        manifest_builder.apply_edit(manifest_version, action);
420                    }
421                    RegionMetaAction::Remove(_) => {
422                        debug!(
423                            "Unhandled action in {}, action: {:?}",
424                            options.manifest_dir, action
425                        );
426                    }
427                    RegionMetaAction::Truncate(action) => {
428                        manifest_builder.apply_truncate(manifest_version, action);
429                    }
430                }
431            }
432        }
433
434        // set the initial metadata if necessary
435        if !manifest_builder.contains_metadata() {
436            debug!("No region manifest in {}", options.manifest_dir);
437            return Ok(None);
438        }
439
440        let manifest = manifest_builder.try_build()?;
441        debug!(
442            "Recovered region manifest from {}, manifest: {:?}",
443            options.manifest_dir, manifest
444        );
445        let version = manifest.manifest_version;
446
447        let manifest_dir = options.manifest_dir.clone();
448        let checkpointer = Checkpointer::new(
449            manifest.metadata.region_id,
450            options,
451            store.clone(),
452            last_checkpoint_version,
453        );
454        manifest_version.store(version, Ordering::Relaxed);
455        manifest
456            .removed_files
457            .update_file_removed_cnt_to_stats(stats);
458        info!(
459            "Opened region manifest {}, region_id: {}, start_version: {}, last_checkpoint_version: {}, replayed_deltas: {}, final_version: {}, cost: {:?}",
460            manifest_dir,
461            manifest.metadata.region_id,
462            replay_start_version,
463            last_checkpoint_version,
464            replayed_deltas,
465            version,
466            open_start.elapsed(),
467        );
468        let manager = Self {
469            file_metadata_interner,
470            store,
471            last_version: manifest_version,
472            checkpointer,
473            manifest: Arc::new(manifest),
474            staged: StagedActions::default(),
475            stats: stats.clone(),
476            stopped: false,
477        };
478        Ok(Some(manager))
479    }
480
481    /// Stops the manager. A stopped manager takes no update and starts no checkpoint, but a
482    /// checkpoint already running keeps writing the manifest directory until it ends.
483    ///
484    /// A caller that hands the storage to another instance waits for that checkpoint with
485    /// `pending_checkpoint_completion` after the stop, as engine stop and reload do. Close and
486    /// drop, which run in the region worker loop, deliberately do not.
487    pub async fn stop(&mut self) {
488        self.stopped = true;
489    }
490
491    /// Returns whether the manager has stopped accepting updates.
492    pub(crate) fn is_stopped(&self) -> bool {
493        self.stopped
494    }
495
496    /// Returns whether deltas are published by conditional create.
497    pub(crate) fn is_conditional_publication(&self) -> bool {
498        self.store.is_conditional_publication()
499    }
500
501    /// Installs the manifest changes from the current version to the target version (inclusive).
502    ///
503    /// Returns installed version.
504    /// **Note**: This function is not guaranteed to install the target version strictly.
505    /// The installed version may be greater than the target version.
506    pub async fn install_manifest_to(
507        &mut self,
508        target_version: ManifestVersion,
509    ) -> Result<ManifestVersion> {
510        let (version, loaded_checkpoint) = self.install_manifest_to_inner(target_version).await?;
511        if !loaded_checkpoint && let Err(error) = self.store.update_manifest_size(version).await {
512            warn!(error; "Failed to update manifest size after sync for region {}", self.manifest.metadata.region_id);
513        }
514        Ok(version)
515    }
516
517    async fn install_manifest_to_inner(
518        &mut self,
519        target_version: ManifestVersion,
520    ) -> Result<(ManifestVersion, bool)> {
521        let _t = MANIFEST_OP_ELAPSED
522            .with_label_values(&["install_manifest_to"])
523            .start_timer();
524
525        let last_version = self.last_version();
526        let mut loaded_checkpoint = false;
527        // Case 1: If the target version is less than the current version, return the current version.
528        if last_version >= target_version {
529            debug!(
530                "Target version {} is less than or equal to the current version {}, region: {}, skip install",
531                target_version, last_version, self.manifest.metadata.region_id
532            );
533            return Ok((last_version, false));
534        }
535
536        ensure!(
537            !self.stopped,
538            RegionStoppedSnafu {
539                region_id: self.manifest.metadata.region_id,
540            }
541        );
542
543        let region_id = self.manifest.metadata.region_id;
544        // Fetches manifests from the last version strictly.
545        let mut manifests = self
546            .store
547            // Invariant: last_version < target_version.
548            .fetch_manifests_strict_from(last_version + 1, target_version + 1, region_id)
549            .await?;
550
551        // Case 2: No manifests in range: [current_version+1, target_version+1)
552        //
553        // |---------Has been deleted------------|     [Checkpoint Version]...[Latest Version]
554        //                                                                    [Leader region]
555        // [Current Version]......[Target Version]
556        // [Follower region]
557        if manifests.is_empty() {
558            info!(
559                "Manifests are not strict from {}, region: {}, tries to install the last checkpoint",
560                last_version, self.manifest.metadata.region_id
561            );
562            let last_version = self.install_last_checkpoint().await?;
563            loaded_checkpoint = true;
564            // Case 2.1: If the installed checkpoint version is greater than or equal to the target version, return the last version.
565            if last_version >= target_version {
566                return Ok((last_version, true));
567            }
568
569            // Fetches manifests from the installed version strictly.
570            manifests = self
571                .store
572                // Invariant: last_version < target_version.
573                .fetch_manifests_strict_from(last_version + 1, target_version + 1, region_id)
574                .await?;
575        }
576
577        if manifests.is_empty() {
578            return NoManifestsSnafu {
579                region_id: self.manifest.metadata.region_id,
580                start_version: last_version + 1,
581                end_version: target_version + 1,
582                last_version,
583            }
584            .fail();
585        }
586
587        debug_assert_eq!(manifests.first().unwrap().0, last_version + 1);
588        let mut manifest_builder = RegionManifestBuilder::from_shared_manifest(
589            Some(self.manifest.as_ref().clone()),
590            self.file_metadata_interner.clone(),
591        );
592
593        for (manifest_version, raw_action_list) in manifests {
594            let action_list = RegionMetaActionList::decode(&raw_action_list)?;
595            for action in action_list.actions {
596                match action {
597                    RegionMetaAction::Change(action) => {
598                        manifest_builder.apply_change(manifest_version, action);
599                    }
600                    RegionMetaAction::PartitionExprChange(action) => {
601                        manifest_builder.apply_partition_expr_change(manifest_version, action);
602                    }
603                    RegionMetaAction::Edit(action) => {
604                        manifest_builder.apply_edit(manifest_version, action);
605                    }
606                    RegionMetaAction::Remove(_) => {
607                        debug!(
608                            "Unhandled action for region {}, action: {:?}",
609                            self.manifest.metadata.region_id, action
610                        );
611                    }
612                    RegionMetaAction::Truncate(action) => {
613                        manifest_builder.apply_truncate(manifest_version, action);
614                    }
615                }
616            }
617        }
618
619        let new_manifest = manifest_builder.try_build()?;
620        ensure!(
621            new_manifest.manifest_version >= target_version,
622            InstallManifestToSnafu {
623                region_id: self.manifest.metadata.region_id,
624                target_version,
625                available_version: new_manifest.manifest_version,
626                last_version,
627            }
628        );
629
630        let version = self.last_version();
631        new_manifest
632            .removed_files
633            .update_file_removed_cnt_to_stats(&self.stats);
634        self.manifest = Arc::new(new_manifest);
635        let last_version = self.set_version(self.manifest.manifest_version);
636        info!(
637            "Install manifest changes from {} to {}, region: {}",
638            version, last_version, self.manifest.metadata.region_id
639        );
640
641        Ok((last_version, loaded_checkpoint))
642    }
643
644    /// Installs the last checkpoint.
645    pub(crate) async fn install_last_checkpoint(&mut self) -> Result<ManifestVersion> {
646        let last_version = self.last_version();
647        let Some(checkpoint) = Self::last_checkpoint(&mut self.store).await? else {
648            return NoCheckpointSnafu {
649                region_id: self.manifest.metadata.region_id,
650                last_version,
651            }
652            .fail();
653        };
654        let builder = RegionManifestBuilder::with_checkpoint(
655            checkpoint.checkpoint,
656            self.file_metadata_interner.clone(),
657        );
658        let manifest = builder.try_build()?;
659        let last_version = self.set_version(manifest.manifest_version);
660        manifest
661            .removed_files
662            .update_file_removed_cnt_to_stats(&self.stats);
663        self.manifest = Arc::new(manifest);
664        info!(
665            "Installed region manifest from checkpoint: {}, region: {}",
666            checkpoint.last_version, self.manifest.metadata.region_id
667        );
668
669        Ok(last_version)
670    }
671
672    /// Updates the manifest. Returns the current manifest version number.
673    ///
674    /// With `is_staging`, the actions are staged in memory: they take no version and write
675    /// nothing until [Self::commit_staged] commits them when staging ends.
676    ///
677    /// The caller has no Leader deadline to show that its commit returned in time, so a normal
678    /// commit under conditional publication is always verified and starts no checkpoint.
679    pub async fn update(
680        &mut self,
681        action_list: RegionMetaActionList,
682        is_staging: bool,
683    ) -> Result<ManifestVersion> {
684        self.update_with_verification(action_list, is_staging, !is_staging, || true)
685            .await
686    }
687
688    /// Updates the manifest. Returns the current manifest version number.
689    ///
690    /// `allow_checkpoint` tells whether a normal commit may start a checkpoint. `must_verify` is
691    /// evaluated after the save returns, for a normal commit under conditional publication. If it
692    /// returns true, the commit may have landed on a name that checkpoint cleanup freed, so it
693    /// only applies when LIST finds no checkpoint that covers it, and it starts no checkpoint.
694    pub(crate) async fn update_with_verification(
695        &mut self,
696        action_list: RegionMetaActionList,
697        is_staging: bool,
698        allow_checkpoint: bool,
699        must_verify: impl FnOnce() -> bool,
700    ) -> Result<ManifestVersion> {
701        let _t = MANIFEST_OP_ELAPSED
702            .with_label_values(&["update"])
703            .start_timer();
704
705        ensure!(
706            !self.stopped,
707            RegionStoppedSnafu {
708                region_id: self.manifest.metadata.region_id,
709            }
710        );
711
712        for action in &action_list.actions {
713            if let RegionMetaAction::Edit(edit) = action {
714                for file in edit.files_to_add.iter().chain(&edit.files_to_remove) {
715                    ensure!(
716                        file::is_supported_level(file.level),
717                        crate::error::InvalidRequestSnafu {
718                            region_id: self.manifest.metadata.region_id,
719                            reason: format!("Unsupported SST level {}", file.level),
720                        }
721                    );
722                }
723            }
724        }
725        if is_staging {
726            self.stage(action_list)?;
727            return Ok(self.last_version());
728        }
729
730        let bytes = action_list.encode()?;
731        self.commit(action_list.actions, &bytes, allow_checkpoint, must_verify)
732            .await
733    }
734
735    /// Saves `bytes`, the encoded `actions`, as the next version and applies the actions.
736    async fn commit(
737        &mut self,
738        actions: Vec<RegionMetaAction>,
739        bytes: &[u8],
740        mut allow_checkpoint: bool,
741        must_verify: impl FnOnce() -> bool,
742    ) -> Result<ManifestVersion> {
743        let conditional = self.store.is_conditional_publication();
744        let version = if conditional {
745            self.last_version() + 1
746        } else {
747            self.increase_version()
748        };
749        self.store.save(version, bytes).await?;
750        if conditional {
751            if must_verify() {
752                self.store.ensure_version_not_checkpointed(version).await?;
753                allow_checkpoint = false;
754            }
755            self.set_version(version);
756        }
757
758        let mut manifest_builder = RegionManifestBuilder::from_shared_manifest(
759            Some(self.manifest.as_ref().clone()),
760            self.file_metadata_interner.clone(),
761        );
762        self.apply_actions(&mut manifest_builder, version, actions);
763        let new_manifest = manifest_builder.try_build()?;
764        new_manifest
765            .removed_files
766            .update_file_removed_cnt_to_stats(&self.stats);
767        let updated_manifest = self
768            .checkpointer
769            .update_manifest_removed_files(new_manifest)?;
770        self.manifest = Arc::new(updated_manifest);
771        if allow_checkpoint {
772            self.checkpointer
773                .maybe_do_checkpoint(self.manifest.as_ref())
774                .await;
775        }
776
777        Ok(version)
778    }
779
780    /// Commits the staged actions as one version and clears them. Returns the version and the
781    /// committed actions.
782    ///
783    /// If the commit fails with an error that may have written it, its encoded bytes are kept:
784    /// the next call commits the same bytes, and no other action is staged until the staged
785    /// actions are cleared.
786    pub(crate) async fn commit_staged(
787        &mut self,
788        must_verify: impl FnOnce() -> bool,
789    ) -> Result<(ManifestVersion, RegionMetaActionList)> {
790        let _t = MANIFEST_OP_ELAPSED
791            .with_label_values(&["update"])
792            .start_timer();
793
794        ensure!(
795            !self.stopped,
796            RegionStoppedSnafu {
797                region_id: self.manifest.metadata.region_id,
798            }
799        );
800
801        let bytes = match &self.staged.attempted {
802            Some(bytes) => bytes.clone(),
803            None => self.staged.actions.encode()?,
804        };
805        // A copy builds the new manifest; the staged list itself goes back for the region version.
806        let actions = self.staged.actions.actions.clone();
807        let result = self.commit(actions, &bytes, true, must_verify).await;
808        if let Err(e) = &result
809            && e.may_have_persisted_manifest_update()
810        {
811            self.staged.attempted = Some(bytes);
812        }
813        let version = result?;
814        let committed = std::mem::take(&mut self.staged).actions;
815        Ok((version, committed))
816    }
817
818    /// Returns the staged actions, or `None` if nothing is staged.
819    pub(crate) fn staged_actions(&self) -> Option<&RegionMetaActionList> {
820        (!self.staged.actions.actions.is_empty()).then_some(&self.staged.actions)
821    }
822
823    /// Stages `action_list` in memory.
824    fn stage(&mut self, action_list: RegionMetaActionList) -> Result<()> {
825        if self.staged.attempted.is_some() {
826            // A kept end commit must be retried with the same content: a retried import of
827            // files that are already staged changes nothing, and nothing else is staged.
828            ensure!(
829                self.staged.only_adds_staged_files(&action_list),
830                EndStagingPendingSnafu {
831                    region_id: self.manifest.metadata.region_id,
832                }
833            );
834            return Ok(());
835        }
836
837        let base = self.staged.view.as_ref().unwrap_or(&self.manifest);
838        let mut manifest_builder = RegionManifestBuilder::from_shared_manifest(
839            Some(base.as_ref().clone()),
840            self.file_metadata_interner.clone(),
841        );
842        self.apply_actions(
843            &mut manifest_builder,
844            self.last_version(),
845            action_list.actions.iter().cloned(),
846        );
847        self.staged.view = Some(Arc::new(manifest_builder.try_build()?));
848        self.staged.actions.actions.extend(action_list.actions);
849        Ok(())
850    }
851
852    /// Applies `actions` of `version` to `manifest_builder`.
853    fn apply_actions(
854        &self,
855        manifest_builder: &mut RegionManifestBuilder,
856        version: ManifestVersion,
857        actions: impl IntoIterator<Item = RegionMetaAction>,
858    ) {
859        for action in actions {
860            match action {
861                RegionMetaAction::Change(action) => {
862                    manifest_builder.apply_change(version, action);
863                }
864                RegionMetaAction::PartitionExprChange(action) => {
865                    manifest_builder.apply_partition_expr_change(version, action);
866                }
867                RegionMetaAction::Edit(action) => {
868                    manifest_builder.apply_edit(version, action);
869                }
870                RegionMetaAction::Remove(_) => {
871                    debug!(
872                        "Unhandled action for region {}, action: {:?}",
873                        self.manifest.metadata.region_id, action
874                    );
875                }
876                RegionMetaAction::Truncate(action) => {
877                    manifest_builder.apply_truncate(version, action);
878                }
879            }
880        }
881    }
882
883    /// Clears the staged actions.
884    fn clear_staged(&mut self) {
885        self.staged = StagedActions::default();
886    }
887
888    /// Waits for an in-flight checkpoint to finish, including its cleanup.
889    pub(crate) async fn wait_for_pending_checkpoint(&mut self) {
890        self.checkpointer.wait_for_pending_checkpoint().await;
891    }
892
893    /// Returns a future that resolves once the in-flight checkpoint has finished, including its
894    /// cleanup. Unlike [Self::wait_for_pending_checkpoint], which borrows the manager mutably and
895    /// reaps the task handle, this does neither.
896    pub(crate) fn pending_checkpoint_completion(&self) -> impl Future<Output = ()> + Send + use<> {
897        self.checkpointer.pending_checkpoint_completion()
898    }
899
900    /// Clear deleted files from manifest's `removed_files` field without update version. Notice if datanode exit before checkpoint then new manifest by open region may still contain these deleted files, which is acceptable for gc process.
901    pub fn clear_deleted_files(&mut self, deleted_files: Vec<RemovedFile>) {
902        let mut manifest = (*self.manifest()).clone();
903        manifest.removed_files.clear_deleted_files(deleted_files);
904        manifest
905            .removed_files
906            .update_file_removed_cnt_to_stats(&self.stats);
907        self.set_manifest(Arc::new(manifest));
908    }
909
910    pub(crate) fn set_manifest(&mut self, manifest: Arc<RegionManifest>) {
911        self.manifest = manifest;
912    }
913
914    /// Retrieves the current [RegionManifest].
915    pub fn manifest(&self) -> Arc<RegionManifest> {
916        self.manifest.clone()
917    }
918
919    /// Returns the manifest with the staged actions applied, or `None` if nothing is staged.
920    pub fn staging_manifest(&self) -> Option<Arc<RegionManifest>> {
921        self.staged.view.clone()
922    }
923
924    /// Returns total manifest size.
925    pub fn manifest_usage(&self) -> u64 {
926        self.store.total_manifest_size()
927    }
928
929    /// Returns true if a newer version manifest file is found.
930    ///
931    /// It is typically used in read-only regions to catch up with manifest.
932    /// It doesn't lock the manifest directory in the object store so the result
933    /// may be inaccurate if there are concurrent writes. A caller holds the region's manifest
934    /// `RwLock` read guard across the listing (e.g. `ManifestContext::has_update`), which
935    /// `ManifestContext::installed_version_if_updated` does not hold while it lists.
936    pub async fn has_update(&self) -> Result<bool> {
937        self.store.has_version_after(self.last_version()).await
938    }
939
940    /// Increases last version and returns the increased version.
941    fn increase_version(&mut self) -> ManifestVersion {
942        let previous = self.last_version.fetch_add(1, Ordering::Relaxed);
943        previous + 1
944    }
945
946    /// Sets the last version.
947    fn set_version(&mut self, version: ManifestVersion) -> ManifestVersion {
948        self.last_version.store(version, Ordering::Relaxed);
949        version
950    }
951
952    pub fn last_version(&self) -> ManifestVersion {
953        self.last_version.load(Ordering::Relaxed)
954    }
955
956    /// Fetches the last [RegionCheckpoint] from storage.
957    ///
958    /// If the checkpoint is not found, returns `None`.
959    /// Otherwise, returns the decoded checkpoint.
960    pub(crate) async fn last_checkpoint(
961        store: &mut ManifestObjectStore,
962    ) -> Result<Option<RegionCheckpoint>> {
963        let last_checkpoint = store.load_last_checkpoint().await?;
964
965        if let Some((_, bytes)) = last_checkpoint {
966            let checkpoint = RegionCheckpoint::decode(&bytes)?;
967            Ok(Some(checkpoint))
968        } else {
969            Ok(None)
970        }
971    }
972
973    pub fn store(&self) -> ManifestObjectStore {
974        self.store.clone()
975    }
976
977    #[cfg(test)]
978    pub(crate) fn checkpointer(&self) -> &Checkpointer {
979        &self.checkpointer
980    }
981
982    /// Clears the staged actions.
983    pub(crate) fn unset_staging_manifest(&mut self) {
984        self.clear_staged();
985    }
986
987    /// Clears the staged actions and the staging directory.
988    pub(crate) async fn clear_staging_manifest_and_dir(&mut self) -> Result<()> {
989        self.clear_staged();
990        self.store.clear_staging_manifests().await?;
991        info!(
992            "Cleared all staging manifests for region {}",
993            self.manifest.metadata.region_id
994        );
995        Ok(())
996    }
997}
998
999#[cfg(test)]
1000impl RegionManifestManager {
1001    fn validate_manifest(&self, expect: &RegionMetadataRef, last_version: ManifestVersion) {
1002        let manifest = self.manifest();
1003        assert_eq!(manifest.metadata, *expect);
1004        assert_eq!(self.manifest.manifest_version, self.last_version());
1005        assert_eq!(last_version, self.last_version());
1006    }
1007}
1008
1009#[cfg(test)]
1010mod test {
1011    use std::time::Duration;
1012
1013    use api::v1::SemanticType;
1014    use common_datasource::compression::CompressionType;
1015    use common_test_util::temp_dir::create_temp_dir;
1016    use datatypes::prelude::ConcreteDataType;
1017    use datatypes::schema::ColumnSchema;
1018    use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder};
1019
1020    use super::*;
1021    use crate::manifest::action::{RegionChange, RegionEdit};
1022    use crate::manifest::tests::utils::{basic_region_metadata, manifest_recovery_usage};
1023    use crate::test_util::TestEnv;
1024
1025    #[tokio::test]
1026    async fn create_manifest_manager() {
1027        let metadata = Arc::new(basic_region_metadata());
1028        let env = TestEnv::new().await;
1029        let manager = env
1030            .create_manifest_manager(CompressionType::Uncompressed, 10, Some(metadata.clone()))
1031            .await
1032            .unwrap()
1033            .unwrap();
1034
1035        manager.validate_manifest(&metadata, 0);
1036    }
1037
1038    #[tokio::test]
1039    async fn open_manifest_manager() {
1040        let env = TestEnv::new().await;
1041        // Try to opens an empty manifest.
1042        assert!(
1043            env.create_manifest_manager(CompressionType::Uncompressed, 10, None)
1044                .await
1045                .unwrap()
1046                .is_none()
1047        );
1048
1049        // Creates a manifest.
1050        let metadata = Arc::new(basic_region_metadata());
1051        let mut manager = env
1052            .create_manifest_manager(CompressionType::Uncompressed, 10, Some(metadata.clone()))
1053            .await
1054            .unwrap()
1055            .unwrap();
1056        // Stops it.
1057        manager.stop().await;
1058
1059        // Open it.
1060        let manager = env
1061            .create_manifest_manager(CompressionType::Uncompressed, 10, None)
1062            .await
1063            .unwrap()
1064            .unwrap();
1065
1066        manager.validate_manifest(&metadata, 0);
1067    }
1068
1069    #[tokio::test]
1070    async fn manifest_with_partition_expr_roundtrip() {
1071        let env = TestEnv::new().await;
1072        let expr_json =
1073            r#"{"Expr":{"lhs":{"Column":"a"},"op":"GtEq","rhs":{"Value":{"UInt32":10}}}}"#;
1074        let mut metadata = basic_region_metadata();
1075        metadata.set_partition_expr(Some(expr_json.to_string()));
1076        let metadata = Arc::new(metadata);
1077        let mut manager = env
1078            .create_manifest_manager(CompressionType::Uncompressed, 10, Some(metadata.clone()))
1079            .await
1080            .unwrap()
1081            .unwrap();
1082
1083        // persisted manifest should contain the same partition_expr JSON
1084        let manifest = manager.manifest();
1085        assert_eq!(manifest.metadata.partition_expr.as_deref(), Some(expr_json));
1086
1087        manager.stop().await;
1088
1089        // Reopen and check again
1090        let manager = env
1091            .create_manifest_manager(CompressionType::Uncompressed, 10, None)
1092            .await
1093            .unwrap()
1094            .unwrap();
1095        let manifest = manager.manifest();
1096        assert_eq!(manifest.metadata.partition_expr.as_deref(), Some(expr_json));
1097    }
1098
1099    #[tokio::test]
1100    async fn recover_historical_file_expression_types() {
1101        use datatypes::value::Value;
1102        use partition::expr::col;
1103        use store_api::storage::FileId;
1104
1105        use crate::sst::file::FileMeta;
1106
1107        for checkpoint_distance in [0, 1] {
1108            let env = TestEnv::new().await;
1109            let metadata = Arc::new(basic_region_metadata());
1110            let mut manager = env
1111                .create_manifest_manager(
1112                    CompressionType::Uncompressed,
1113                    checkpoint_distance,
1114                    Some(metadata.clone()),
1115                )
1116                .await
1117                .unwrap()
1118                .unwrap();
1119            let mut files = Vec::new();
1120            for value in [Value::Int32(10), Value::Int64(10)] {
1121                let file = FileMeta {
1122                    region_id: metadata.region_id,
1123                    file_id: FileId::random(),
1124                    partition_expr: Some(col("tag").lt(value).into()),
1125                    ..Default::default()
1126                };
1127                manager
1128                    .update(
1129                        RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit {
1130                            files_to_add: vec![file.clone()],
1131                            ..Default::default()
1132                        })),
1133                        false,
1134                    )
1135                    .await
1136                    .unwrap();
1137                manager.wait_for_pending_checkpoint().await;
1138                files.push(file);
1139            }
1140            assert_eq!(
1141                checkpoint_distance != 0,
1142                manager.checkpointer.last_checkpoint_version() > 0
1143            );
1144            manager.stop().await;
1145            drop(manager);
1146            // The helper supplies a fresh interner, so recovery cannot reuse old entries.
1147            let recovered = env
1148                .create_manifest_manager(CompressionType::Uncompressed, checkpoint_distance, None)
1149                .await
1150                .unwrap()
1151                .unwrap();
1152            let manifest = recovered.manifest();
1153            assert_eq!(files.len(), manifest.files.len());
1154            for file in files {
1155                assert_eq!(&file, manifest.files[&file.file_id].as_ref());
1156            }
1157        }
1158    }
1159
1160    #[tokio::test]
1161    async fn region_change_add_column() {
1162        let metadata = Arc::new(basic_region_metadata());
1163        let env = TestEnv::new().await;
1164        let mut manager = env
1165            .create_manifest_manager(CompressionType::Uncompressed, 10, Some(metadata.clone()))
1166            .await
1167            .unwrap()
1168            .unwrap();
1169
1170        let mut new_metadata_builder = RegionMetadataBuilder::from_existing((*metadata).clone());
1171        new_metadata_builder.push_column_metadata(ColumnMetadata {
1172            column_schema: ColumnSchema::new("val2", ConcreteDataType::float64_datatype(), false),
1173            semantic_type: SemanticType::Field,
1174            column_id: 252,
1175        });
1176        let new_metadata = Arc::new(new_metadata_builder.build().unwrap());
1177
1178        let action_list =
1179            RegionMetaActionList::with_action(RegionMetaAction::Change(RegionChange {
1180                metadata: new_metadata.clone(),
1181                sst_format: FormatType::PrimaryKey,
1182                append_mode: None,
1183            }));
1184
1185        let current_version = manager.update(action_list, false).await.unwrap();
1186        assert_eq!(current_version, 1);
1187        manager.validate_manifest(&new_metadata, 1);
1188
1189        // Reopen the manager.
1190        manager.stop().await;
1191        let manager = env
1192            .create_manifest_manager(CompressionType::Uncompressed, 10, None)
1193            .await
1194            .unwrap()
1195            .unwrap();
1196        manager.validate_manifest(&new_metadata, 1);
1197    }
1198
1199    #[tokio::test]
1200    async fn test_manifest_size() {
1201        let metadata = Arc::new(basic_region_metadata());
1202        let data_home = create_temp_dir("");
1203        let data_home_path = data_home.path().to_str().unwrap().to_string();
1204        let env = TestEnv::with_data_home(data_home).await;
1205
1206        let manifest_dir = format!("{}/manifest", data_home_path);
1207
1208        let mut manager = env
1209            .create_manifest_manager(CompressionType::Uncompressed, 10, Some(metadata.clone()))
1210            .await
1211            .unwrap()
1212            .unwrap();
1213
1214        let mut new_metadata_builder = RegionMetadataBuilder::from_existing((*metadata).clone());
1215        new_metadata_builder.push_column_metadata(ColumnMetadata {
1216            column_schema: ColumnSchema::new("val2", ConcreteDataType::float64_datatype(), false),
1217            semantic_type: SemanticType::Field,
1218            column_id: 252,
1219        });
1220        let new_metadata = Arc::new(new_metadata_builder.build().unwrap());
1221
1222        let action_list =
1223            RegionMetaActionList::with_action(RegionMetaAction::Change(RegionChange {
1224                metadata: new_metadata.clone(),
1225                sst_format: FormatType::PrimaryKey,
1226                append_mode: None,
1227            }));
1228
1229        let current_version = manager.update(action_list, false).await.unwrap();
1230        assert_eq!(current_version, 1);
1231        manager.validate_manifest(&new_metadata, 1);
1232
1233        // get manifest size
1234        let manifest_size = manager.manifest_usage();
1235        assert_eq!(manifest_size, manifest_recovery_usage(&manifest_dir).await);
1236
1237        // update 10 times nop_action to trigger checkpoint
1238        for _ in 0..10 {
1239            manager
1240                .update(
1241                    RegionMetaActionList::new(vec![RegionMetaAction::Edit(RegionEdit {
1242                        files_to_add: vec![],
1243                        files_to_remove: vec![],
1244                        timestamp_ms: None,
1245                        compaction_time_window: None,
1246                        flushed_entry_id: None,
1247                        flushed_sequence: None,
1248                        committed_sequence: None,
1249                        ..Default::default()
1250                    })]),
1251                    false,
1252                )
1253                .await
1254                .unwrap();
1255        }
1256
1257        while manager.checkpointer.is_doing_checkpoint() {
1258            tokio::time::sleep(Duration::from_millis(10)).await;
1259        }
1260
1261        // check manifest size again
1262        let manifest_size = manager.manifest_usage();
1263        assert_eq!(manifest_size, manifest_recovery_usage(&manifest_dir).await);
1264
1265        // Reopening reconstructs the same logical recovery set from stored bytes.
1266        manager.stop().await;
1267        let manager = env
1268            .create_manifest_manager(CompressionType::Uncompressed, 10, None)
1269            .await
1270            .unwrap()
1271            .unwrap();
1272        manager.validate_manifest(&new_metadata, 11);
1273
1274        // get manifest size again
1275        assert_eq!(
1276            manager.manifest_usage(),
1277            manifest_recovery_usage(&manifest_dir).await
1278        );
1279    }
1280}