Skip to main content

mito2/manifest/
storage.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
15pub(crate) mod checkpoint;
16pub(crate) mod delta;
17pub(crate) mod size_tracker;
18pub(crate) mod staging;
19pub(crate) mod utils;
20
21use std::iter::Iterator;
22use std::str::FromStr;
23use std::sync::Arc;
24use std::sync::atomic::AtomicU64;
25
26use common_datasource::compression::CompressionType;
27use common_error::ext::ErrorExt;
28use common_telemetry::{debug, warn};
29use crc32fast::Hasher;
30use futures::{TryStream, TryStreamExt};
31use lazy_static::lazy_static;
32use object_store::util::join_dir;
33use object_store::{Entry, ErrorKind, Lister, ObjectStore, util};
34use regex::Regex;
35use snafu::{OptionExt, ResultExt, ensure};
36use store_api::storage::RegionId;
37use store_api::{MIN_VERSION, ManifestVersion};
38
39use crate::cache::manifest_cache::ManifestCache;
40use crate::error::{
41    ChecksumMismatchSnafu, EmptyManifestDirSnafu, ManifestVersionConflictSnafu, OpenDalSnafu,
42    Result, UnsupportedOperationSnafu,
43};
44use crate::manifest::storage::checkpoint::CheckpointStorage;
45use crate::manifest::storage::delta::DeltaStorage;
46use crate::manifest::storage::size_tracker::{CheckpointTracker, DeltaTracker, SizeTracker};
47use crate::manifest::storage::staging::StagingStorage;
48use crate::manifest::storage::utils::remove_from_cache;
49use crate::metrics::manifest_size::RegionManifestSizeMetric;
50
51lazy_static! {
52    static ref DELTA_RE: Regex = Regex::new("^\\d+\\.json").unwrap();
53    static ref CHECKPOINT_RE: Regex = Regex::new("^\\d+\\.checkpoint").unwrap();
54}
55
56pub const LAST_CHECKPOINT_FILE: &str = "_last_checkpoint";
57const DEFAULT_MANIFEST_COMPRESSION_TYPE: CompressionType = CompressionType::Gzip;
58/// Due to backward compatibility, it is possible that the user's manifest file has not been compressed.
59/// So when we encounter problems, we need to fall back to `FALL_BACK_COMPRESS_TYPE` for processing.
60pub(crate) const FALL_BACK_COMPRESS_TYPE: CompressionType = CompressionType::Uncompressed;
61const FETCH_MANIFEST_PARALLELISM: usize = 16;
62
63/// Returns the directory to the manifest files.
64pub fn manifest_dir(region_dir: &str) -> String {
65    join_dir(region_dir, "manifest")
66}
67
68/// Returns the [CompressionType] according to whether to compress manifest files.
69pub const fn manifest_compress_type(compress: bool) -> CompressionType {
70    if compress {
71        DEFAULT_MANIFEST_COMPRESSION_TYPE
72    } else {
73        FALL_BACK_COMPRESS_TYPE
74    }
75}
76
77pub fn delta_file(version: ManifestVersion) -> String {
78    format!("{version:020}.json")
79}
80
81pub fn checkpoint_file(version: ManifestVersion) -> String {
82    format!("{version:020}.checkpoint")
83}
84
85/// Returns a lexicographic `start_after` key for an object-store `list`
86/// request over the manifest directory at `path`.
87///
88/// `path` must be the same directory prefix passed to `lister_with(path)`
89/// and must end with `/`. OpenDAL resolves `start_after` against the
90/// operator root, not relative to the listed path, so the caller must
91/// supply the full prefix — otherwise the bound is compared against keys
92/// that already share a longer prefix and is silently a no-op.
93pub(crate) fn list_start_after(path: &str, version: ManifestVersion) -> String {
94    debug_assert!(
95        path.ends_with('/'),
96        "list_start_after: path must end with '/', got {path:?}",
97    );
98    // Manifest files are named `{version:020}.{json,checkpoint}[.gz]` and sort lexicographically;
99    // `{path}{version:020}` is a strict prefix of `{path}{version:020}.{json,checkpoint}[.gz]`.
100    format!("{path}{version:020}")
101}
102
103pub fn gen_path(path: &str, file: &str, compress_type: CompressionType) -> String {
104    if compress_type == CompressionType::Uncompressed {
105        format!("{}{}", path, file)
106    } else {
107        format!("{}{}.{}", path, file, compress_type.file_extension())
108    }
109}
110
111pub(crate) fn checkpoint_checksum(data: &[u8]) -> u32 {
112    let mut hasher = Hasher::new();
113    hasher.update(data);
114    hasher.finalize()
115}
116
117pub(crate) fn verify_checksum(data: &[u8], wanted: Option<u32>) -> Result<()> {
118    if let Some(checksum) = wanted {
119        let calculated_checksum = checkpoint_checksum(data);
120        ensure!(
121            checksum == calculated_checksum,
122            ChecksumMismatchSnafu {
123                actual: calculated_checksum,
124                expected: checksum,
125            }
126        );
127    }
128    Ok(())
129}
130
131/// Return's the file manifest version from path
132///
133/// # Panics
134/// If the file path is not a valid delta or checkpoint file.
135pub fn file_version(path: &str) -> ManifestVersion {
136    let s = path.split('.').next().unwrap();
137    s.parse().unwrap_or_else(|_| panic!("Invalid file: {path}"))
138}
139
140/// Return's the file compress algorithm by file extension.
141///
142/// for example file
143/// `00000000000000000000.json.gz` -> `CompressionType::GZIP`
144pub fn file_compress_type(path: &str) -> CompressionType {
145    let s = path.rsplit('.').next().unwrap_or("");
146    CompressionType::from_str(s).unwrap_or(CompressionType::Uncompressed)
147}
148
149pub fn is_delta_file(file_name: &str) -> bool {
150    DELTA_RE.is_match(file_name)
151}
152
153pub fn is_checkpoint_file(file_name: &str) -> bool {
154    CHECKPOINT_RE.is_match(file_name)
155}
156
157#[derive(Clone, Debug)]
158pub struct ManifestObjectStore {
159    object_store: ObjectStore,
160    path: String,
161    /// Optional manifest cache for local caching.
162    manifest_cache: Option<ManifestCache>,
163    // Tracks the size of each file in the manifest directory.
164    size_tracker: SizeTracker,
165    // The checkpoint file storage.
166    checkpoint_storage: CheckpointStorage<CheckpointTracker>,
167    // The delta file storage.
168    delta_storage: DeltaStorage<DeltaTracker>,
169    /// The staging file storage.
170    staging_storage: StagingStorage,
171    /// Whether deltas are created conditionally and the last checkpoint is found by LIST.
172    conditional_publication: bool,
173}
174
175impl ManifestObjectStore {
176    pub fn new(
177        path: &str,
178        object_store: ObjectStore,
179        compress_type: CompressionType,
180        total_manifest_size: Arc<AtomicU64>,
181        manifest_cache: Option<ManifestCache>,
182    ) -> Self {
183        Self::new_with_metric(
184            path,
185            object_store,
186            compress_type,
187            total_manifest_size,
188            None,
189            manifest_cache,
190        )
191    }
192
193    /// Constructs a store sharing the region instance's publication state.
194    pub(crate) fn new_with_metric(
195        path: &str,
196        object_store: ObjectStore,
197        compress_type: CompressionType,
198        total_manifest_size: Arc<AtomicU64>,
199        metric: Option<RegionManifestSizeMetric>,
200        manifest_cache: Option<ManifestCache>,
201    ) -> Self {
202        common_telemetry::info!("Create manifest store, cache: {}", manifest_cache.is_some());
203
204        let path = util::normalize_dir(path);
205        let size_tracker = SizeTracker::new(total_manifest_size, metric);
206        let checkpoint_tracker = Arc::new(size_tracker.checkpoint_tracker());
207        let delta_tracker = Arc::new(size_tracker.manifest_tracker());
208        let checkpoint_storage = CheckpointStorage::new(
209            path.clone(),
210            object_store.clone(),
211            compress_type,
212            manifest_cache.clone(),
213            checkpoint_tracker,
214        );
215        let delta_storage = DeltaStorage::new(
216            path.clone(),
217            object_store.clone(),
218            compress_type,
219            manifest_cache.clone(),
220            delta_tracker,
221        );
222        let staging_storage = StagingStorage::new(path.clone(), object_store.clone());
223
224        Self {
225            object_store,
226            path,
227            manifest_cache,
228            size_tracker,
229            checkpoint_storage,
230            delta_storage,
231            staging_storage,
232            conditional_publication: false,
233        }
234    }
235
236    /// Sets whether this store publishes deltas by conditional create and recovers from the
237    /// highest checkpoint found by LIST.
238    ///
239    /// Returns an error if the mode is enabled on a backend without conditional create.
240    pub(crate) fn with_conditional_publication(mut self, enabled: bool) -> Result<Self> {
241        let capability = self.object_store.info().capability();
242        ensure!(
243            !enabled || capability.write_with_if_not_exists,
244            UnsupportedOperationSnafu {
245                err_msg: format!(
246                    "conditional create is required for manifest {} of a region whose writes need a lease",
247                    self.path
248                ),
249            }
250        );
251        self.conditional_publication = enabled;
252        Ok(self)
253    }
254
255    /// Returns whether this store publishes deltas by conditional create.
256    pub(crate) fn is_conditional_publication(&self) -> bool {
257        self.conditional_publication
258    }
259
260    /// Returns the manifest dir
261    pub(crate) fn manifest_dir(&self) -> &str {
262        &self.path
263    }
264
265    /// Returns whether the directory holds a delta or checkpoint of a version after
266    /// `last_version`. It reads the directory without locking it.
267    pub(crate) async fn has_version_after(&self, last_version: ManifestVersion) -> Result<bool> {
268        self.versions_after(last_version)
269            .await?
270            .try_any(|version| async move { version.is_some() })
271            .await
272            .context(OpenDalSnafu)
273    }
274
275    /// Returns the largest version of a delta or checkpoint in the directory, or `last_version`
276    /// if none is after it. It reads the directory without locking it.
277    pub(crate) async fn latest_version(
278        &self,
279        last_version: ManifestVersion,
280    ) -> Result<ManifestVersion> {
281        self.versions_after(last_version)
282            .await?
283            .try_fold(last_version, |latest, version| async move {
284                Ok(version.map_or(latest, |version| latest.max(version)))
285            })
286            .await
287            .context(OpenDalSnafu)
288    }
289
290    /// Lists the directory after `last_version`, yielding for each entry the version of a delta
291    /// or checkpoint after it, and None for other entries.
292    async fn versions_after(
293        &self,
294        last_version: ManifestVersion,
295    ) -> Result<impl TryStream<Ok = Option<ManifestVersion>, Error = object_store::Error>> {
296        // Skip older files at the object-store layer. Files for `v == last_version`
297        // may still appear (`{path}{v:020}` sorts before `{path}{v:020}.json`) but
298        // they are filtered out below by the `version > last_version` check.
299        let start_after = list_start_after(self.manifest_dir(), last_version);
300        let streamer =
301            self.manifest_lister(Some(&start_after))
302                .await?
303                .context(EmptyManifestDirSnafu {
304                    manifest_dir: self.manifest_dir(),
305                })?;
306        Ok(streamer.map_ok(move |entry| {
307            let file_name = entry.name();
308            (is_delta_file(file_name) || is_checkpoint_file(file_name))
309                .then(|| file_version(file_name))
310                .filter(|version| *version > last_version)
311        }))
312    }
313
314    /// Returns an iterator of manifests.
315    ///
316    /// `start_after` is forwarded to the lister to skip entries whose name is
317    /// lexicographically less than or equal to it.
318    pub(crate) async fn manifest_lister(
319        &self,
320        start_after: Option<&str>,
321    ) -> Result<Option<Lister>> {
322        self.delta_storage.manifest_lister(start_after).await
323    }
324
325    /// Fetches manifests in range [start_version, end_version).
326    /// This functions is guaranteed to return manifests from the `start_version` strictly (must contain `start_version`).
327    pub async fn fetch_manifests_strict_from(
328        &self,
329        start_version: ManifestVersion,
330        end_version: ManifestVersion,
331        region_id: RegionId,
332    ) -> Result<Vec<(ManifestVersion, Vec<u8>)>> {
333        self.delta_storage
334            .fetch_manifests_strict_from(start_version, end_version, region_id)
335            .await
336    }
337
338    /// Fetch all manifests in concurrent, and return the manifests in range [start_version, end_version)
339    ///
340    /// **Notes**: This function is no guarantee to return manifests from the `start_version` strictly.
341    /// Uses [fetch_manifests_strict_from](ManifestObjectStore::fetch_manifests_strict_from) to get manifests from the `start_version`.
342    pub async fn fetch_manifests(
343        &self,
344        start_version: ManifestVersion,
345        end_version: ManifestVersion,
346    ) -> Result<Vec<(ManifestVersion, Vec<u8>)>> {
347        self.delta_storage
348            .fetch_manifests(start_version, end_version)
349            .await
350    }
351
352    /// Delete manifest files that version < end.
353    /// If keep_last_checkpoint is true, the last checkpoint file will be kept.
354    /// ### Return
355    /// The number of files whose deletion was acknowledged by the object store.
356    pub async fn delete_until(
357        &self,
358        end: ManifestVersion,
359        keep_last_checkpoint: bool,
360    ) -> Result<usize> {
361        // Stores (entry, is_checkpoint, version) in a Vec.
362        //
363        // `start_after` is intentionally `None` here: a previous deletion
364        // may have been interrupted and left stale files at versions below
365        // the current checkpoint; we need the lister to surface them so
366        // cleanup can finish.
367        let entries: Vec<_> = self
368            .delta_storage
369            .get_paths(None, |entry| {
370                let file_name = entry.name();
371                let is_checkpoint = is_checkpoint_file(file_name);
372                if is_delta_file(file_name) || is_checkpoint_file(file_name) {
373                    let version = file_version(file_name);
374                    if version < end {
375                        return Some((entry, is_checkpoint, version));
376                    }
377                }
378                None
379            })
380            .await?;
381        let checkpoint_version = if keep_last_checkpoint {
382            // Note that the order of entries is unspecific.
383            entries
384                .iter()
385                .filter_map(
386                    |(_e, is_checkpoint, version)| {
387                        if *is_checkpoint { Some(version) } else { None }
388                    },
389                )
390                .max()
391        } else {
392            None
393        };
394        let del_entries: Vec<_> = entries
395            .iter()
396            .filter(|(_e, is_checkpoint, version)| {
397                if let Some(max_version) = checkpoint_version {
398                    if *is_checkpoint {
399                        // We need to keep the checkpoint file.
400                        version < max_version
401                    } else {
402                        // We can delete the log file with max_version as the checkpoint
403                        // file contains the log file's content.
404                        version <= max_version
405                    }
406                } else {
407                    true
408                }
409            })
410            .collect();
411        let paths = del_entries
412            .iter()
413            .map(|(e, _, _)| e.path().to_string())
414            .collect::<Vec<_>>();
415        let total = paths.len();
416
417        debug!(
418            "Deleting {} logs from manifest storage path {} until {}, checkpoint_version: {:?}, paths: {:?}",
419            total, self.path, end, checkpoint_version, paths,
420        );
421
422        // Remove from cache first
423        for (entry, _, _) in &del_entries {
424            remove_from_cache(self.manifest_cache.as_ref(), entry.path()).await;
425        }
426
427        // Try batch delete first. On failure, fall back to per-file deletes.
428        // This is a workaround for S3-compatible object stores that do not support batch delete. See issue #7986.
429        let mut deleted = 0;
430        match self.object_store.delete_iter(paths.clone()).await {
431            Ok(()) => deleted = total,
432            Err(batch_err) => {
433                warn!(
434                    batch_err;
435                    "Batch delete failed for manifest path {}, falling back to per-file delete for {} paths",
436                    self.path, total,
437                );
438                for (i, path) in paths.iter().enumerate() {
439                    if let Err(e) = self.object_store.delete(path).await {
440                        warn!(
441                            e;
442                            "Failed to delete manifest file {} under {}, aborting fallback, {} files will be retried on next checkpoint",
443                            path, self.path, total - i,
444                        );
445                        break;
446                    }
447                    deleted += 1;
448                }
449            }
450        }
451
452        Ok(deleted)
453    }
454
455    /// Save the delta manifest file.
456    pub async fn save(&mut self, version: ManifestVersion, bytes: &[u8]) -> Result<()> {
457        if self.conditional_publication {
458            self.delta_storage.save_conditional(version, bytes).await
459        } else {
460            self.delta_storage.save(version, bytes).await
461        }
462    }
463
464    /// Fails with a version conflict unless LIST proves that no checkpoint at or above `version`
465    /// exists.
466    ///
467    /// Cleanup deletes a delta only after a checkpoint that covers it is saved, and never deletes
468    /// the highest checkpoint. So a late create that landed on a deleted name always finds one.
469    pub(crate) async fn ensure_version_not_checkpointed(
470        &self,
471        version: ManifestVersion,
472    ) -> Result<()> {
473        let reason = match self.find_checkpoint(version, false, false).await {
474            Ok(None) => return Ok(()),
475            Ok(Some((checkpoint, _))) => format!("covered by checkpoint {checkpoint}"),
476            Err(e) => format!("cannot list the checkpoints: {}", e.output_msg()),
477        };
478        ManifestVersionConflictSnafu {
479            version,
480            manifest_dir: &self.path,
481            reason,
482        }
483        .fail()
484    }
485
486    /// Save the checkpoint manifest file.
487    pub(crate) async fn save_checkpoint(
488        &self,
489        version: ManifestVersion,
490        bytes: &[u8],
491    ) -> Result<()> {
492        self.checkpoint_storage
493            .save_checkpoint(version, bytes)
494            .await
495    }
496
497    /// Load the latest checkpoint.
498    /// Return manifest version and the raw [RegionCheckpoint](crate::manifest::action::RegionCheckpoint) content if any
499    /// Also applies the checkpoint retention rule to the tracked size.
500    pub async fn load_last_checkpoint(&mut self) -> Result<Option<(ManifestVersion, Vec<u8>)>> {
501        let checkpoint = if self.conditional_publication {
502            match self.find_checkpoint(MIN_VERSION, false, true).await? {
503                Some((version, compress_type)) => Some(
504                    self.checkpoint_storage
505                        .load_listed_checkpoint(version, compress_type)
506                        .await?,
507                ),
508                None => None,
509            }
510        } else {
511            self.checkpoint_storage.load_last_checkpoint().await?
512        };
513        if let Some((version, _)) = &checkpoint {
514            self.retain_manifest_size_after(*version);
515        }
516        Ok(checkpoint)
517    }
518
519    /// Compute the size(Byte) in manifest size map.
520    pub(crate) fn total_manifest_size(&self) -> u64 {
521        self.size_tracker.total()
522    }
523
524    /// Accounts for the latest checkpoint already covered by this follower's replay.
525    /// Only a changed or previously unaccounted checkpoint needs a stat.
526    pub(crate) async fn update_manifest_size(
527        &self,
528        replayed_version: ManifestVersion,
529    ) -> Result<()> {
530        let Some(metadata) = self
531            .checkpoint_storage
532            .read_last_checkpoint_metadata()
533            .await?
534        else {
535            return Ok(());
536        };
537        if metadata.version > replayed_version {
538            // Pruning now would stop counting deltas still in this follower's recovery set.
539            // Retention applies once replay covers this version or sync installs the checkpoint.
540            return Ok(());
541        }
542        if !self.size_tracker.contains_checkpoint(metadata.version) {
543            self.checkpoint_storage
544                .record_checkpoint_size(metadata.version)
545                .await?;
546        }
547        self.retain_manifest_size_after(metadata.version);
548        Ok(())
549    }
550
551    /// Prunes logical accounting independently of physical cleanup success.
552    pub(crate) fn retain_manifest_size_after(&self, version: ManifestVersion) {
553        self.size_tracker.retain_after(version);
554    }
555
556    /// Clear all staging manifest files.
557    pub async fn clear_staging_manifests(&mut self) -> Result<()> {
558        self.staging_storage.clear().await
559    }
560
561    /// Returns the staging storage.
562    pub(crate) fn staging_storage(&self) -> &StagingStorage {
563        &self.staging_storage
564    }
565
566    fn conditional_entries(
567        &self,
568        start: ManifestVersion,
569        mut allow_absent: bool,
570    ) -> impl futures::Stream<Item = Result<Entry>> {
571        async_stream::try_stream! {
572            let mut list = self.object_store.lister_with(&self.path);
573            if start > 0 {
574                list = list.start_after(&list_start_after(&self.path, start));
575            }
576            let mut lister = match list.await {
577                Err(e) if allow_absent && e.kind() == ErrorKind::NotFound => return,
578                result => result.context(OpenDalSnafu)?,
579            };
580            while let Some(entry) = match lister.try_next().await {
581                Err(e) if allow_absent && e.kind() == ErrorKind::NotFound => None,
582                result => result.context(OpenDalSnafu)?,
583            } {
584                allow_absent = false;
585                yield entry;
586            }
587        }
588    }
589
590    pub(crate) async fn scan_conditional(
591        &self,
592        start: ManifestVersion,
593        allow_absent: bool,
594    ) -> Result<Vec<(ManifestVersion, Entry)>> {
595        let mut lister = std::pin::pin!(self.conditional_entries(start, allow_absent));
596        let mut entries = Vec::new();
597        while let Some(entry) = lister.try_next().await? {
598            if is_delta_file(entry.name()) {
599                let version = file_version(entry.name());
600                if (start..store_api::MAX_VERSION).contains(&version) {
601                    entries.push((version, entry));
602                }
603            }
604        }
605        utils::sort_manifests(&mut entries);
606        Ok(entries)
607    }
608
609    /// Finds a checkpoint at or above `min_version`. Stops at the first match if `first_only`
610    /// is true and returns the highest match otherwise.
611    pub(crate) async fn find_checkpoint(
612        &self,
613        min_version: ManifestVersion,
614        first_only: bool,
615        allow_absent: bool,
616    ) -> Result<Option<(ManifestVersion, CompressionType)>> {
617        let mut lister = std::pin::pin!(self.conditional_entries(min_version, allow_absent));
618        let mut highest = None;
619        while let Some(entry) = lister.try_next().await? {
620            let file_name = entry.name();
621            if is_checkpoint_file(file_name) {
622                let version = file_version(file_name);
623                if version >= min_version && highest.is_none_or(|(v, _)| v < version) {
624                    highest = Some((version, file_compress_type(file_name)));
625                    if first_only {
626                        break;
627                    }
628                }
629            }
630        }
631        Ok(highest)
632    }
633
634    #[cfg(test)]
635    pub async fn read_file(&self, path: &str) -> Result<Vec<u8>> {
636        self.object_store
637            .read(path)
638            .await
639            .context(OpenDalSnafu)
640            .map(|v| v.to_vec())
641    }
642
643    #[cfg(test)]
644    pub(crate) fn checkpoint_storage(&self) -> &CheckpointStorage<CheckpointTracker> {
645        &self.checkpoint_storage
646    }
647
648    pub(crate) fn delta_storage(&self) -> &DeltaStorage<DeltaTracker> {
649        &self.delta_storage
650    }
651
652    #[cfg(test)]
653    pub(crate) fn set_compress_type(&mut self, compress_type: CompressionType) {
654        self.checkpoint_storage.set_compress_type(compress_type);
655        self.delta_storage.set_compress_type(compress_type);
656    }
657}
658
659#[cfg(test)]
660mod tests {
661    use common_test_util::temp_dir::create_temp_dir;
662    use object_store::ObjectStore;
663    use object_store::services::Fs;
664
665    use super::*;
666    use crate::manifest::storage::checkpoint::CheckpointMetadata;
667
668    fn new_test_manifest_store() -> ManifestObjectStore {
669        new_test_manifest_store_at("/")
670    }
671
672    fn new_test_manifest_store_at(path: &str) -> ManifestObjectStore {
673        common_telemetry::init_default_ut_logging();
674        let tmp_dir = create_temp_dir("test_manifest_log_store");
675        let builder = Fs::default().root(&tmp_dir.path().to_string_lossy());
676        let object_store = ObjectStore::new(builder).unwrap();
677        ManifestObjectStore::new(
678            path,
679            object_store,
680            CompressionType::Uncompressed,
681            Default::default(),
682            None,
683        )
684    }
685
686    fn new_checkpoint_metadata_with_version(version: ManifestVersion) -> CheckpointMetadata {
687        CheckpointMetadata {
688            size: 0,
689            version,
690            checksum: None,
691            extend_metadata: Default::default(),
692        }
693    }
694
695    #[test]
696    // Define this test mainly to prevent future unintentional changes may break the backward compatibility.
697    fn test_compress_file_path_generation() {
698        let path = "/foo/bar/";
699        let version: ManifestVersion = 0;
700        let file_path = gen_path(path, &delta_file(version), CompressionType::Gzip);
701        assert_eq!(file_path.as_str(), "/foo/bar/00000000000000000000.json.gz")
702    }
703
704    #[tokio::test]
705    async fn test_manifest_log_store_uncompress() {
706        let mut log_store = new_test_manifest_store();
707        log_store.set_compress_type(CompressionType::Uncompressed);
708        test_manifest_log_store_case(log_store).await;
709    }
710
711    #[tokio::test]
712    async fn test_manifest_log_store_compress() {
713        let mut log_store = new_test_manifest_store();
714        log_store.set_compress_type(CompressionType::Gzip);
715        test_manifest_log_store_case(log_store).await;
716    }
717
718    async fn test_manifest_log_store_case(mut log_store: ManifestObjectStore) {
719        for v in 0..5 {
720            log_store
721                .save(v, format!("hello, {v}").as_bytes())
722                .await
723                .unwrap();
724        }
725
726        let manifests = log_store.fetch_manifests(1, 4).await.unwrap();
727        let mut it = manifests.into_iter();
728        for v in 1..4 {
729            let (version, bytes) = it.next().unwrap();
730            assert_eq!(v, version);
731            assert_eq!(format!("hello, {v}").as_bytes(), bytes);
732        }
733        assert!(it.next().is_none());
734
735        let manifests = log_store.fetch_manifests(0, 11).await.unwrap();
736        let mut it = manifests.into_iter();
737        for v in 0..5 {
738            let (version, bytes) = it.next().unwrap();
739            assert_eq!(v, version);
740            assert_eq!(format!("hello, {v}").as_bytes(), bytes);
741        }
742        assert!(it.next().is_none());
743
744        // test checkpoint
745        assert!(log_store.load_last_checkpoint().await.unwrap().is_none());
746        log_store
747            .save_checkpoint(3, "checkpoint".as_bytes())
748            .await
749            .unwrap();
750
751        let (v, checkpoint) = log_store.load_last_checkpoint().await.unwrap().unwrap();
752        assert_eq!(checkpoint, "checkpoint".as_bytes());
753        assert_eq!(3, v);
754
755        //delete (,4) logs and keep checkpoint 3.
756        let _ = log_store.delete_until(4, true).await.unwrap();
757        let _ = log_store
758            .checkpoint_storage
759            .load_checkpoint(new_checkpoint_metadata_with_version(3))
760            .await
761            .unwrap()
762            .unwrap();
763        let _ = log_store.load_last_checkpoint().await.unwrap().unwrap();
764        let manifests = log_store.fetch_manifests(0, 11).await.unwrap();
765        let mut it = manifests.into_iter();
766
767        let (version, bytes) = it.next().unwrap();
768        assert_eq!(4, version);
769        assert_eq!("hello, 4".as_bytes(), bytes);
770        assert!(it.next().is_none());
771
772        // delete all logs and checkpoints
773        let _ = log_store.delete_until(11, false).await.unwrap();
774        assert!(
775            log_store
776                .checkpoint_storage
777                .load_checkpoint(new_checkpoint_metadata_with_version(3))
778                .await
779                .unwrap()
780                .is_none()
781        );
782        assert!(log_store.load_last_checkpoint().await.unwrap().is_none());
783        let manifests = log_store.fetch_manifests(0, 11).await.unwrap();
784        let mut it = manifests.into_iter();
785
786        assert!(it.next().is_none());
787    }
788
789    #[tokio::test]
790    // test ManifestObjectStore can read/delete previously uncompressed data correctly
791    async fn test_compress_backward_compatible() {
792        let mut log_store = new_test_manifest_store();
793
794        // write uncompress data to stimulate previously uncompressed data
795        log_store.set_compress_type(CompressionType::Uncompressed);
796        for v in 0..5 {
797            log_store
798                .save(v, format!("hello, {v}").as_bytes())
799                .await
800                .unwrap();
801        }
802        log_store
803            .save_checkpoint(5, "checkpoint_uncompressed".as_bytes())
804            .await
805            .unwrap();
806
807        // change compress type
808        log_store.set_compress_type(CompressionType::Gzip);
809
810        // test load_last_checkpoint work correctly for previously uncompressed data
811        let (v, checkpoint) = log_store.load_last_checkpoint().await.unwrap().unwrap();
812        assert_eq!(v, 5);
813        assert_eq!(checkpoint, "checkpoint_uncompressed".as_bytes());
814
815        // write compressed data to stimulate compress algorithm take effect
816        for v in 5..10 {
817            log_store
818                .save(v, format!("hello, {v}").as_bytes())
819                .await
820                .unwrap();
821        }
822        log_store
823            .save_checkpoint(10, "checkpoint_compressed".as_bytes())
824            .await
825            .unwrap();
826
827        // test data reading
828        let manifests = log_store.fetch_manifests(0, 10).await.unwrap();
829        let mut it = manifests.into_iter();
830
831        for v in 0..10 {
832            let (version, bytes) = it.next().unwrap();
833            assert_eq!(v, version);
834            assert_eq!(format!("hello, {v}").as_bytes(), bytes);
835        }
836        let (v, checkpoint) = log_store
837            .checkpoint_storage
838            .load_checkpoint(new_checkpoint_metadata_with_version(5))
839            .await
840            .unwrap()
841            .unwrap();
842        assert_eq!(v, 5);
843        assert_eq!(checkpoint, "checkpoint_uncompressed".as_bytes());
844        let (v, checkpoint) = log_store.load_last_checkpoint().await.unwrap().unwrap();
845        assert_eq!(v, 10);
846        assert_eq!(checkpoint, "checkpoint_compressed".as_bytes());
847
848        // Delete util 10, contain uncompressed/compressed data
849        // log 0, 1, 2, 7, 8, 9 will be delete
850        assert_eq!(11, log_store.delete_until(10, false).await.unwrap());
851        let manifests = log_store.fetch_manifests(0, 10).await.unwrap();
852        let mut it = manifests.into_iter();
853        assert!(it.next().is_none());
854    }
855
856    #[tokio::test]
857    async fn test_latest_version_counts_deltas_and_checkpoints() {
858        let mut store = new_test_manifest_store();
859        for v in 0..3 {
860            store.save(v, b"delta").await.unwrap();
861        }
862        assert_eq!(2, store.latest_version(0).await.unwrap());
863        assert_eq!(5, store.latest_version(5).await.unwrap());
864        store.save_checkpoint(7, b"checkpoint").await.unwrap();
865        assert_eq!(7, store.latest_version(2).await.unwrap());
866    }
867
868    #[tokio::test]
869    async fn test_file_version() {
870        let version = file_version("00000000000000000007.checkpoint");
871        assert_eq!(version, 7);
872
873        let name = delta_file(version);
874        assert_eq!(name, "00000000000000000007.json");
875
876        let name = checkpoint_file(version);
877        assert_eq!(name, "00000000000000000007.checkpoint");
878    }
879
880    #[tokio::test]
881    async fn test_uncompressed_manifest_files_size() {
882        let mut log_store = new_test_manifest_store();
883        // write 5 manifest files with uncompressed(8B per file)
884        log_store.set_compress_type(CompressionType::Uncompressed);
885        for v in 0..5 {
886            log_store
887                .save(v, format!("hello, {v}").as_bytes())
888                .await
889                .unwrap();
890        }
891        // write 1 checkpoint file with uncompressed(23B)
892        log_store
893            .save_checkpoint(5, "checkpoint_uncompressed".as_bytes())
894            .await
895            .unwrap();
896
897        // manifest files size
898        assert_eq!(log_store.total_manifest_size(), 63);
899
900        // delete 3 manifest files
901        assert_eq!(log_store.delete_until(3, false).await.unwrap(), 3);
902
903        // Physical deletion does not define the logical recovery set.
904        assert_eq!(log_store.total_manifest_size(), 63);
905        log_store.retain_manifest_size_after(5);
906        assert_eq!(log_store.total_manifest_size(), 23);
907
908        // delete all manifest files
909        assert_eq!(
910            log_store
911                .delete_until(ManifestVersion::MAX, false)
912                .await
913                .unwrap(),
914            3
915        );
916
917        assert_eq!(log_store.total_manifest_size(), 23);
918    }
919
920    #[tokio::test]
921    async fn test_compressed_manifest_files_size() {
922        let mut log_store = new_test_manifest_store();
923        // Test with compressed manifest files
924        log_store.set_compress_type(CompressionType::Gzip);
925        // write 5 manifest files
926        for v in 0..5 {
927            log_store
928                .save(v, format!("hello, {v}").as_bytes())
929                .await
930                .unwrap();
931        }
932        log_store
933            .save_checkpoint(5, "checkpoint_compressed".as_bytes())
934            .await
935            .unwrap();
936
937        // manifest files size
938        assert_eq!(log_store.total_manifest_size(), 181);
939
940        // delete 3 manifest files
941        assert_eq!(log_store.delete_until(3, false).await.unwrap(), 3);
942
943        // Physical deletion does not define the logical recovery set.
944        assert_eq!(log_store.total_manifest_size(), 181);
945        log_store.retain_manifest_size_after(5);
946        assert_eq!(log_store.total_manifest_size(), 41);
947
948        // delete all manifest files
949        assert_eq!(
950            log_store
951                .delete_until(ManifestVersion::MAX, false)
952                .await
953                .unwrap(),
954            3
955        );
956
957        assert_eq!(log_store.total_manifest_size(), 41);
958    }
959
960    #[tokio::test]
961    async fn test_scan_with_start_after_uncompress() {
962        let mut log_store = new_test_manifest_store();
963        log_store.set_compress_type(CompressionType::Uncompressed);
964        test_scan_with_start_after_case(log_store).await;
965    }
966
967    #[tokio::test]
968    async fn test_scan_with_start_after_compress() {
969        let mut log_store = new_test_manifest_store();
970        log_store.set_compress_type(CompressionType::Gzip);
971        test_scan_with_start_after_case(log_store).await;
972    }
973
974    // OpenDAL resolves `start_after` against the operator
975    // root, so the bound must embed the manifest directory prefix. Running the
976    // same assertions against a non-root path exercises that composition.
977    #[tokio::test]
978    async fn test_scan_with_start_after_nested_path() {
979        let mut log_store = new_test_manifest_store_at("/nested/region-1/");
980        log_store.set_compress_type(CompressionType::Uncompressed);
981        test_scan_with_start_after_case(log_store).await;
982    }
983
984    async fn test_scan_with_start_after_case(mut log_store: ManifestObjectStore) {
985        for v in 0..10 {
986            log_store
987                .save(v, format!("hello, {v}").as_bytes())
988                .await
989                .unwrap();
990        }
991        // A checkpoint at version 5 shares the directory; scan must still
992        // return only delta files in range.
993        log_store
994            .save_checkpoint(5, "checkpoint".as_bytes())
995            .await
996            .unwrap();
997
998        // start > 0: `start_after` must skip pre-start deltas without losing any.
999        let entries = log_store.delta_storage.scan(3, 10).await.unwrap();
1000        let versions: Vec<_> = entries.iter().map(|(v, _)| *v).collect();
1001        assert_eq!(versions, vec![3, 4, 5, 6, 7, 8, 9]);
1002
1003        // start == 0: `start_after` is skipped; every delta is returned.
1004        let entries = log_store.delta_storage.scan(0, 10).await.unwrap();
1005        let versions: Vec<_> = entries.iter().map(|(v, _)| *v).collect();
1006        assert_eq!(versions, (0..10).collect::<Vec<_>>());
1007
1008        // Upper bound exclusive.
1009        let entries = log_store.delta_storage.scan(7, 9).await.unwrap();
1010        let versions: Vec<_> = entries.iter().map(|(v, _)| *v).collect();
1011        assert_eq!(versions, vec![7, 8]);
1012
1013        // Start beyond any existing file returns empty.
1014        let entries = log_store
1015            .delta_storage
1016            .scan(10, ManifestVersion::MAX)
1017            .await
1018            .unwrap();
1019        assert!(entries.is_empty());
1020    }
1021
1022    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1023    enum CacheSource {
1024        WriteThrough,
1025        RemoteFill,
1026        LegacyDecoded,
1027        Truncated,
1028    }
1029
1030    #[derive(Debug, Clone, Copy)]
1031    enum PayloadKind {
1032        Delta,
1033        Checkpoint { checksum: bool },
1034    }
1035
1036    // Exercise both representations left by older versions, as well as new writes
1037    // and remote fills. Truncation only applies to compression envelopes.
1038    #[rstest::rstest]
1039    #[case::write_through_uncompressed(CacheSource::WriteThrough, CompressionType::Uncompressed)]
1040    #[case::write_through_gzip(CacheSource::WriteThrough, CompressionType::Gzip)]
1041    #[case::write_through_zstd(CacheSource::WriteThrough, CompressionType::Zstd)]
1042    #[case::write_through_xz(CacheSource::WriteThrough, CompressionType::Xz)]
1043    #[case::write_through_bzip2(CacheSource::WriteThrough, CompressionType::Bzip2)]
1044    #[case::remote_fill_uncompressed(CacheSource::RemoteFill, CompressionType::Uncompressed)]
1045    #[case::remote_fill_gzip(CacheSource::RemoteFill, CompressionType::Gzip)]
1046    #[case::remote_fill_zstd(CacheSource::RemoteFill, CompressionType::Zstd)]
1047    #[case::remote_fill_xz(CacheSource::RemoteFill, CompressionType::Xz)]
1048    #[case::remote_fill_bzip2(CacheSource::RemoteFill, CompressionType::Bzip2)]
1049    #[case::legacy_decoded_uncompressed(CacheSource::LegacyDecoded, CompressionType::Uncompressed)]
1050    #[case::legacy_decoded_gzip(CacheSource::LegacyDecoded, CompressionType::Gzip)]
1051    #[case::legacy_decoded_zstd(CacheSource::LegacyDecoded, CompressionType::Zstd)]
1052    #[case::legacy_decoded_xz(CacheSource::LegacyDecoded, CompressionType::Xz)]
1053    #[case::legacy_decoded_bzip2(CacheSource::LegacyDecoded, CompressionType::Bzip2)]
1054    #[case::truncated_gzip(CacheSource::Truncated, CompressionType::Gzip)]
1055    #[case::truncated_zstd(CacheSource::Truncated, CompressionType::Zstd)]
1056    #[case::truncated_xz(CacheSource::Truncated, CompressionType::Xz)]
1057    #[case::truncated_bzip2(CacheSource::Truncated, CompressionType::Bzip2)]
1058    #[tokio::test]
1059    async fn test_manifest_cache_payload(
1060        #[case] source: CacheSource,
1061        #[case] compression: CompressionType,
1062        #[values(PayloadKind::Delta, PayloadKind::Checkpoint { checksum: false }, PayloadKind::Checkpoint { checksum: true })]
1063        payload: PayloadKind,
1064    ) {
1065        use std::sync::atomic::{AtomicUsize, Ordering};
1066
1067        use common_base::readable_size::ReadableSize;
1068        use object_store::layers::mock::MockLayerBuilder;
1069
1070        let remote_dir = create_temp_dir("manifest-cache-remote");
1071        let cache_dir = create_temp_dir("manifest-cache-local");
1072        let remote =
1073            ObjectStore::new(Fs::default().root(remote_dir.path().to_str().unwrap())).unwrap();
1074        let local =
1075            ObjectStore::new(Fs::default().root(cache_dir.path().to_str().unwrap())).unwrap();
1076        let reads = Arc::new(AtomicUsize::new(0));
1077        let observed = reads.clone();
1078        let remote = remote.layer(
1079            MockLayerBuilder::default()
1080                .reader_factory(Arc::new(move |_, _, reader| {
1081                    observed.fetch_add(1, Ordering::Relaxed);
1082                    reader
1083                }))
1084                .build()
1085                .unwrap(),
1086        );
1087        let mut cache = ManifestCache::new(local.clone(), ReadableSize::mb(32), None, true).await;
1088        let mut store = ManifestObjectStore::new(
1089            "region/manifest/",
1090            remote.clone(),
1091            compression,
1092            Default::default(),
1093            (source != CacheSource::RemoteFill).then(|| cache.clone()),
1094        );
1095        let data = br#"{"manifest":"persistent cache payload"}"#;
1096        let key = gen_path(
1097            "region/manifest/",
1098            &if matches!(payload, PayloadKind::Checkpoint { .. }) {
1099                checkpoint_file(3)
1100            } else {
1101                delta_file(3)
1102            },
1103            compression,
1104        );
1105        if matches!(payload, PayloadKind::Checkpoint { .. }) {
1106            store.save_checkpoint(3, data).await.unwrap();
1107        } else {
1108            store.save(3, data).await.unwrap();
1109        }
1110        let encoded = remote.read(&key).await.unwrap().to_vec();
1111        if source == CacheSource::LegacyDecoded {
1112            cache.put_file(key.clone(), data.to_vec()).await;
1113        } else if source == CacheSource::Truncated {
1114            cache
1115                .put_file(key.clone(), encoded[..encoded.len() / 2].to_vec())
1116                .await;
1117        }
1118        drop(store);
1119        for iteration in 0..2 {
1120            drop(cache);
1121            cache = ManifestCache::new(local.clone(), ReadableSize::mb(32), None, true).await;
1122            if source != CacheSource::RemoteFill || iteration > 0 {
1123                assert!(
1124                    cache.get(&key).await.is_some(),
1125                    "cache recovery missed {key}"
1126                );
1127            }
1128            store = ManifestObjectStore::new(
1129                "region/manifest/",
1130                remote.clone(),
1131                compression,
1132                Default::default(),
1133                Some(cache.clone()),
1134            );
1135            let before = reads.load(Ordering::Relaxed);
1136            let actual = if let PayloadKind::Checkpoint { checksum } = payload {
1137                let metadata = CheckpointMetadata {
1138                    size: data.len(),
1139                    version: 3,
1140                    checksum: checksum.then(|| checkpoint_checksum(data)),
1141                    extend_metadata: Default::default(),
1142                };
1143                store
1144                    .checkpoint_storage
1145                    .load_checkpoint(metadata)
1146                    .await
1147                    .unwrap()
1148                    .unwrap()
1149            } else {
1150                let mut deltas = store.fetch_manifests(3, 4).await.unwrap();
1151                assert_eq!(1, deltas.len());
1152                deltas.remove(0)
1153            };
1154            assert_eq!((3, data.to_vec()), actual);
1155            // A successful roundtrip alone could hide a decoded refill that causes
1156            // repeated cache misses. Check both the bytes and remote read count.
1157            assert_eq!(encoded, cache.get_file(&key).await.unwrap());
1158            let must_refill = iteration == 0
1159                && (source == CacheSource::RemoteFill
1160                    || (compression != CompressionType::Uncompressed
1161                        && (source == CacheSource::LegacyDecoded
1162                            || source == CacheSource::Truncated)));
1163            assert_eq!(
1164                usize::from(must_refill),
1165                reads.load(Ordering::Relaxed) - before
1166            );
1167            drop(store);
1168        }
1169    }
1170
1171    #[rstest::rstest]
1172    #[case::checksum(false)]
1173    #[case::decompression(true)]
1174    #[tokio::test]
1175    async fn test_manifest_cache_corrupted_remote(#[case] invalid_encoding: bool) {
1176        use crate::error::Error;
1177        use common_base::readable_size::ReadableSize;
1178
1179        let remote_dir = create_temp_dir("manifest-cache-remote");
1180        let cache_dir = create_temp_dir("manifest-cache-local");
1181        let remote =
1182            ObjectStore::new(Fs::default().root(remote_dir.path().to_str().unwrap())).unwrap();
1183        let local =
1184            ObjectStore::new(Fs::default().root(cache_dir.path().to_str().unwrap())).unwrap();
1185        let cache = ManifestCache::new(local, ReadableSize::mb(32), None, true).await;
1186        let mut store = ManifestObjectStore::new(
1187            "region/",
1188            remote.clone(),
1189            CompressionType::Gzip,
1190            Default::default(),
1191            Some(cache.clone()),
1192        );
1193        store.save_checkpoint(3, b"checkpoint").await.unwrap();
1194        let key = gen_path("region/", &checkpoint_file(3), CompressionType::Gzip);
1195        let corrupted = if invalid_encoding {
1196            b"invalid gzip".to_vec()
1197        } else {
1198            CompressionType::Gzip
1199                .encode(b"other".as_slice())
1200                .await
1201                .unwrap()
1202        };
1203        remote.write(&key, corrupted).await.unwrap();
1204        // A legacy decoded cache entry must not hide the remote error on refill.
1205        cache.put_file(key.clone(), b"checkpoint".to_vec()).await;
1206        let error = store.load_last_checkpoint().await.unwrap_err();
1207        if invalid_encoding {
1208            assert!(matches!(error, Error::DecompressObject { .. }), "{error}");
1209        } else {
1210            assert!(matches!(error, Error::ChecksumMismatch { .. }), "{error}");
1211        }
1212        assert!(cache.get(&key).await.is_none());
1213    }
1214
1215    #[tokio::test]
1216    async fn test_manifest_cache_uncompressed_fallback() {
1217        use common_base::readable_size::ReadableSize;
1218
1219        let remote_dir = create_temp_dir("manifest-cache-remote");
1220        let cache_dir = create_temp_dir("manifest-cache-local");
1221        let remote =
1222            ObjectStore::new(Fs::default().root(remote_dir.path().to_str().unwrap())).unwrap();
1223        let local =
1224            ObjectStore::new(Fs::default().root(cache_dir.path().to_str().unwrap())).unwrap();
1225        let cache = ManifestCache::new(local.clone(), ReadableSize::mb(32), None, true).await;
1226        let store = ManifestObjectStore::new(
1227            "region/",
1228            remote.clone(),
1229            CompressionType::Uncompressed,
1230            Default::default(),
1231            Some(cache.clone()),
1232        );
1233        store.save_checkpoint(3, b"checkpoint").await.unwrap();
1234        drop(store);
1235        drop(cache);
1236        let cache = ManifestCache::new(local, ReadableSize::mb(32), None, true).await;
1237        assert!(
1238            cache
1239                .get("region/00000000000000000003.checkpoint")
1240                .await
1241                .is_some()
1242        );
1243        // Keep _last_checkpoint, but remove its payload to prove the fallback hit.
1244        remote
1245            .delete("region/00000000000000000003.checkpoint")
1246            .await
1247            .unwrap();
1248        let mut store = ManifestObjectStore::new(
1249            "region/",
1250            remote,
1251            CompressionType::Gzip,
1252            Default::default(),
1253            Some(cache),
1254        );
1255        assert_eq!(
1256            Some((3, b"checkpoint".to_vec())),
1257            store.load_last_checkpoint().await.unwrap()
1258        );
1259    }
1260}