Skip to main content

mito2/
wal.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Write ahead log of the engine.
16
17pub mod encoder;
18pub(crate) mod entry_distributor;
19pub(crate) mod entry_reader;
20pub(crate) mod raw_entry_reader;
21
22use std::collections::HashMap;
23use std::mem;
24use std::sync::{Arc, Mutex, PoisonError};
25use std::time::Duration;
26
27use api::v1::WalEntry;
28use common_error::ext::BoxedError;
29use common_telemetry::debug;
30use encoder::WalEntryEncoder;
31use entry_reader::NoopEntryReader;
32use futures::future::BoxFuture;
33use futures::stream::BoxStream;
34use futures::{StreamExt, TryStreamExt};
35use snafu::{OptionExt, ResultExt};
36use store_api::logstore::entry::Entry;
37use store_api::logstore::provider::Provider;
38use store_api::logstore::{AppendBatchResponse, LogStore, WalReadUpperBound};
39use store_api::storage::RegionId;
40use tokio::sync::watch;
41
42use crate::error::{
43    BuildEntrySnafu, CheckWalHistorySnafu, DeleteWalSnafu, HandoffWalSnafu, ReadNodeWalSnafu,
44    RemoteWalUnsupportedSnafu, ResolveWalProviderSnafu, Result, WaitWalDurableSnafu, WriteWalSnafu,
45};
46use crate::wal::entry_reader::{LogStoreEntryReader, WalEntryReader, decode_raw_entry};
47use crate::wal::raw_entry_reader::{LogStoreRawEntryReader, RegionRawEntryReader};
48
49/// WAL entry id.
50pub type EntryId = store_api::logstore::entry::Id;
51/// A stream that yields tuple of WAL entry id and corresponding entry.
52pub type WalEntryStream<'a> = BoxStream<'a, Result<(EntryId, WalEntry)>>;
53
54/// Waits until the WAL of one region is durable through an entry id.
55///
56/// A flush calls it before it records an entry id as flushed in the manifest:
57/// a log store that acknowledges an append before its entries are durable
58/// hands out entry ids that a crash can lose, and a manifest watermark that
59/// names such an id would skip the entries assigned again after a restart.
60/// A catchup from a remote WAL calls it before it replays, so the entries the
61/// region acknowledged on this node are durable before the replay reads the WAL.
62#[derive(Clone)]
63pub(crate) struct DurabilityBarrier(
64    Arc<dyn Fn(EntryId) -> BoxFuture<'static, Result<()>> + Send + Sync>,
65);
66
67impl DurabilityBarrier {
68    /// Returns once the region is durable through `entry_id`.
69    pub(crate) async fn wait(&self, entry_id: EntryId) -> Result<()> {
70        (self.0)(entry_id).await
71    }
72
73    /// A barrier that never waits, for tests without a log store.
74    #[cfg(test)]
75    pub(crate) fn noop() -> Self {
76        Self(Arc::new(|_| Box::pin(async { Ok(()) })))
77    }
78}
79
80impl std::fmt::Debug for DurabilityBarrier {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        f.write_str("DurabilityBarrier")
83    }
84}
85
86/// Write ahead log.
87///
88/// All regions in the engine shares the same WAL instance.
89#[derive(Debug)]
90pub struct Wal<S> {
91    /// The underlying log store.
92    store: Arc<S>,
93    /// One pressure snapshot shared by all workers using this WAL.
94    flush_candidates: Arc<Mutex<FlushCandidates>>,
95}
96
97impl<S> Wal<S> {
98    /// Creates a new [Wal] from the log store.
99    pub fn new(store: Arc<S>) -> Self {
100        Self {
101            store,
102            flush_candidates: Arc::default(),
103        }
104    }
105
106    pub fn store(&self) -> &Arc<S> {
107        &self.store
108    }
109}
110
111impl<S> Clone for Wal<S> {
112    fn clone(&self) -> Self {
113        Self {
114            store: Arc::clone(&self.store),
115            flush_candidates: self.flush_candidates.clone(),
116        }
117    }
118}
119
120impl<S: LogStore> Wal<S> {
121    /// Resolves persisted WAL options to this node's runtime namespace.
122    pub(crate) fn resolve_provider(
123        &self,
124        region_id: RegionId,
125        provider: Provider,
126    ) -> Result<Provider> {
127        self.store
128            .resolve_provider(provider)
129            .map_err(BoxedError::new)
130            .context(ResolveWalProviderSnafu { region_id })
131    }
132
133    /// Subscribes to shared WAL pressure snapshots. Notifications only advise
134    /// workers to check their current region state, and never wait for flush.
135    pub(crate) fn subscribe_flush_candidates(&self) -> watch::Receiver<Arc<[RegionId]>> {
136        self.flush_candidates
137            .lock()
138            .unwrap_or_else(PoisonError::into_inner)
139            .sender
140            .subscribe()
141    }
142
143    /// Refreshes and publishes candidates at most once per interval for all workers.
144    pub(crate) fn refresh_flush_candidates(&self, now: i64, interval: Duration) {
145        self.flush_candidates
146            .lock()
147            .unwrap_or_else(PoisonError::into_inner)
148            .refresh(now, interval, || self.store.flush_candidates());
149    }
150
151    /// Returns a writer to write to the WAL.
152    pub fn writer(&self) -> WalWriter<S> {
153        WalWriter {
154            store: self.store.clone(),
155            entries: Vec::new(),
156            providers: HashMap::new(),
157            encoder: WalEntryEncoder::new(),
158        }
159    }
160
161    /// Returns a [OnRegionOpened] function.
162    pub(crate) fn on_region_opened(
163        &self,
164    ) -> impl FnOnce(RegionId, EntryId, &Provider) -> BoxFuture<Result<()>> {
165        let store = self.store.clone();
166        move |region_id, last_entry_id, provider| -> BoxFuture<'_, Result<()>> {
167            if let Provider::Noop = provider {
168                debug!("Skip obsolete for region: {}", region_id);
169                return Box::pin(async move { Ok(()) });
170            }
171            Box::pin(async move {
172                store
173                    .obsolete(provider, region_id, last_entry_id)
174                    .await
175                    .map_err(BoxedError::new)
176                    .context(DeleteWalSnafu { region_id })
177            })
178        }
179    }
180
181    /// Returns the [DurabilityBarrier] of the region written through `provider`.
182    pub(crate) fn durability_barrier(
183        &self,
184        region_id: RegionId,
185        provider: &Provider,
186    ) -> DurabilityBarrier {
187        let store = self.store.clone();
188        let provider = provider.clone();
189        DurabilityBarrier(Arc::new(move |entry_id| {
190            let store = store.clone();
191            let provider = provider.clone();
192            Box::pin(async move {
193                if let Provider::Noop = provider {
194                    return Ok(());
195                }
196                store
197                    .wait_durable(&provider, entry_id)
198                    .await
199                    .map_err(BoxedError::new)
200                    .context(WaitWalDurableSnafu { region_id })
201            })
202        }))
203    }
204
205    /// Checks that the log store holds the WAL history of the region through
206    /// `entry_id`, the largest replay watermark the region persisted, before
207    /// the region is replayed from its persisted state.
208    pub(crate) async fn check_region_history(
209        &self,
210        region_id: RegionId,
211        provider: &Provider,
212        entry_id: EntryId,
213    ) -> Result<()> {
214        if let Provider::Noop = provider {
215            return Ok(());
216        }
217        self.store
218            .check_region_history(provider, entry_id)
219            .await
220            .map_err(BoxedError::new)
221            .context(CheckWalHistorySnafu { region_id })
222    }
223
224    /// Hands the region over to the log store before it becomes writable on
225    /// this node and returns the bound, see [LogStore::handoff].
226    pub(crate) async fn handoff(
227        &self,
228        region_id: RegionId,
229        provider: &Provider,
230        entry_id: EntryId,
231    ) -> Result<EntryId> {
232        if let Provider::Noop = provider {
233            return Ok(entry_id);
234        }
235        self.store
236            .handoff(provider, entry_id)
237            .await
238            .map_err(BoxedError::new)
239            .context(HandoffWalSnafu { region_id })
240    }
241
242    /// Records that the WAL history of the region starts in the log store,
243    /// as it does for a region created on it.
244    pub(crate) fn start_region_history(
245        &self,
246        region_id: RegionId,
247        provider: &Provider,
248    ) -> Result<()> {
249        if let Provider::Noop = provider {
250            return Ok(());
251        }
252        self.store
253            .start_region_history(provider)
254            .map_err(BoxedError::new)
255            .context(CheckWalHistorySnafu { region_id })
256    }
257
258    /// Returns a [WalEntryReader]
259    pub(crate) fn wal_entry_reader(
260        &self,
261        provider: &Provider,
262        region_id: RegionId,
263    ) -> Box<dyn WalEntryReader> {
264        match provider {
265            Provider::RaftEngine(_) => Box::new(LogStoreEntryReader::new(
266                LogStoreRawEntryReader::new(self.store.clone()),
267            )),
268            // Entries of many regions share one namespace, so the reader filters by region.
269            Provider::Kafka(_) | Provider::ObjectStore(_) => {
270                Box::new(LogStoreEntryReader::new(RegionRawEntryReader::new(
271                    LogStoreRawEntryReader::new(self.store.clone()),
272                    region_id,
273                )))
274            }
275            Provider::Noop => Box::new(NoopEntryReader),
276        }
277    }
278
279    /// Streams the region's entries in `(after, upper]` from the WAL of node `node_id`, which may
280    /// be this node, without writing to it.
281    pub(crate) async fn read_node(
282        &self,
283        region_id: RegionId,
284        node_id: u64,
285        after: EntryId,
286        upper: WalReadUpperBound,
287    ) -> Result<WalEntryStream<'static>> {
288        let entries = self
289            .store
290            .read_node(node_id, region_id, after, upper)
291            .await
292            .map_err(BoxedError::new)
293            .context(ReadNodeWalSnafu { region_id, node_id })?
294            .context(RemoteWalUnsupportedSnafu { region_id, node_id })?;
295        Ok(entries
296            .map(move |entries| {
297                entries
298                    .map_err(BoxedError::new)
299                    .context(ReadNodeWalSnafu { region_id, node_id })
300            })
301            .map_ok(|entries| futures::stream::iter(entries.into_iter().map(decode_raw_entry)))
302            .try_flatten()
303            .boxed())
304    }
305
306    /// Scan entries of specific region starting from `start_id` (inclusive).
307    /// Currently only used in tests.
308    pub fn scan<'a>(
309        &'a self,
310        region_id: RegionId,
311        start_id: EntryId,
312        provider: &'a Provider,
313    ) -> Result<WalEntryStream<'a>> {
314        let mut reader = self.wal_entry_reader(provider, region_id);
315        reader.read(provider, start_id)
316    }
317
318    /// Mark entries whose ids `<= last_id` as deleted.
319    pub async fn obsolete(
320        &self,
321        region_id: RegionId,
322        last_id: EntryId,
323        provider: &Provider,
324    ) -> Result<()> {
325        if let Provider::Noop = provider {
326            return Ok(());
327        }
328        self.store
329            .obsolete(provider, region_id, last_id)
330            .await
331            .map_err(BoxedError::new)
332            .context(DeleteWalSnafu { region_id })
333    }
334
335    /// Deletes all WAL entries in the namespace represented by `provider`.
336    pub async fn delete_namespace(&self, region_id: RegionId, provider: &Provider) -> Result<()> {
337        if let Provider::Noop = provider {
338            return Ok(());
339        }
340        self.store
341            .delete_namespace(provider)
342            .await
343            .map_err(BoxedError::new)
344            .context(DeleteWalSnafu { region_id })
345    }
346
347    /// Releases every WAL entry of a dropped region, see [LogStore::release_region].
348    pub async fn release_region(&self, region_id: RegionId, provider: &Provider) -> Result<()> {
349        if let Provider::Noop = provider {
350            return Ok(());
351        }
352        self.store
353            .release_region(provider, region_id)
354            .await
355            .map_err(BoxedError::new)
356            .context(DeleteWalSnafu { region_id })
357    }
358
359    /// Queues a persistent release through the region's safe recovery watermark.
360    /// Success acknowledges admission, not persistence; see [LogStore::release_entries].
361    pub async fn release_entries(
362        &self,
363        region_id: RegionId,
364        entry_id: EntryId,
365        provider: &Provider,
366    ) -> Result<()> {
367        if let Provider::Noop = provider {
368            return Ok(());
369        }
370        self.store
371            .release_entries(provider, region_id, entry_id)
372            .await
373            .map_err(BoxedError::new)
374            .context(DeleteWalSnafu { region_id })
375    }
376
377    /// Marks all WAL entries of a region as obsolete and removes its dedicated namespace when
378    /// supported by the backend.
379    pub async fn obsolete_all(&self, region_id: RegionId, provider: &Provider) -> Result<()> {
380        self.store
381            .obsolete_all(provider, region_id)
382            .await
383            .map_err(BoxedError::new)
384            .context(DeleteWalSnafu { region_id })
385    }
386}
387
388/// WAL batch writer.
389pub struct WalWriter<S: LogStore> {
390    /// Log store of the WAL.
391    store: Arc<S>,
392    /// Entries to write.
393    entries: Vec<Entry>,
394    /// Providers of regions being written into.
395    providers: HashMap<RegionId, Provider>,
396    /// Cached-size single-pass encoder, reused across entries in this batch.
397    encoder: WalEntryEncoder,
398}
399
400impl<S: LogStore> WalWriter<S> {
401    /// Add a wal entry for specific region to the writer's buffer.
402    pub fn add_entry(
403        &mut self,
404        region_id: RegionId,
405        entry_id: EntryId,
406        wal_entry: &WalEntry,
407        provider: &Provider,
408    ) -> Result<()> {
409        // Gets or inserts with a newly built provider.
410        let provider = self
411            .providers
412            .entry(region_id)
413            .or_insert_with(|| provider.clone());
414
415        let data = self.encoder.encode_to_vec(wal_entry);
416        let entry = self
417            .store
418            .entry(data, entry_id, region_id, provider)
419            .map_err(BoxedError::new)
420            .context(BuildEntrySnafu { region_id })?;
421
422        self.entries.push(entry);
423
424        Ok(())
425    }
426
427    /// Write all buffered entries to the WAL.
428    pub async fn write_to_wal(&mut self) -> Result<AppendBatchResponse> {
429        // TODO(yingwen): metrics.
430
431        let entries = mem::take(&mut self.entries);
432        self.store
433            .append_batch(entries)
434            .await
435            .map_err(BoxedError::new)
436            .context(WriteWalSnafu)
437    }
438}
439
440/// A periodically refreshed advisory snapshot. Publishing wakes every worker,
441/// so a worker whose periodic timer just ran does not wait another interval.
442#[derive(Debug)]
443struct FlushCandidates {
444    /// Wall-clock milliseconds of the last refresh, using the worker clock.
445    refreshed_at: Option<i64>,
446    /// Latest candidates; intermediate snapshots can be coalesced safely.
447    sender: watch::Sender<Arc<[RegionId]>>,
448}
449
450impl Default for FlushCandidates {
451    fn default() -> Self {
452        let (sender, _) = watch::channel(Arc::default());
453        Self {
454            refreshed_at: None,
455            sender,
456        }
457    }
458}
459
460impl FlushCandidates {
461    fn refresh(&mut self, now: i64, interval: Duration, load: impl FnOnce() -> Vec<RegionId>) {
462        if self
463            .refreshed_at
464            .is_none_or(|last| now.saturating_sub(last) >= interval.as_millis() as i64)
465        {
466            self.sender.send_replace(load().into());
467            self.refreshed_at = Some(now);
468        }
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use api::v1::helper::{tag_column_schema, time_index_column_schema};
475    use api::v1::{
476        ArrowIpc, BulkWalEntry, ColumnDataType, Mutation, OpType, Row, Rows, Value, bulk_wal_entry,
477        value,
478    };
479    use common_recordbatch::DfRecordBatch;
480    use common_test_util::flight::encode_to_flight_data;
481    use common_test_util::temp_dir::{TempDir, create_temp_dir};
482    use datatypes::arrow;
483    use datatypes::arrow::array::{ArrayRef, TimestampMillisecondArray};
484    use datatypes::arrow::datatypes::Field;
485    use datatypes::arrow_array::StringArray;
486    use futures::TryStreamExt;
487    use log_store::raft_engine::log_store::RaftEngineLogStore;
488    use log_store::test_util::log_store_util;
489    use store_api::storage::SequenceNumber;
490
491    use super::*;
492
493    #[test]
494    fn test_flush_candidates_share_refresh_and_retry_without_progress() {
495        let a = RegionId::new(1, 1);
496        let interval = Duration::from_millis(60);
497        let mut candidates = FlushCandidates::default();
498        let mut first = candidates.sender.subscribe();
499        let mut second = candidates.sender.subscribe();
500        candidates.refresh(0, interval, || vec![a]);
501        assert!(first.has_changed().unwrap());
502        assert!(second.has_changed().unwrap());
503        let first_snapshot = first.borrow_and_update().clone();
504        let second_snapshot = second.borrow_and_update().clone();
505        assert!(Arc::ptr_eq(&first_snapshot, &second_snapshot));
506        assert_eq!(&[a], first_snapshot.as_ref());
507        candidates.refresh(59, interval, || panic!("must share the snapshot"));
508        candidates.refresh(-1, interval, || panic!("clock rolled back"));
509        assert!(!first.has_changed().unwrap());
510        // A failed or skipped flush must still be retried with the same candidates.
511        candidates.refresh(60, interval, || vec![a]);
512        assert!(first.has_changed().unwrap());
513        assert_eq!(&[a], first.borrow_and_update().as_ref());
514        candidates.refresh(120, interval, Vec::new);
515        assert!(first.borrow_and_update().is_empty());
516        assert!(second.borrow_and_update().is_empty());
517    }
518
519    struct WalEnv {
520        _wal_dir: TempDir,
521        log_store: Option<Arc<RaftEngineLogStore>>,
522    }
523
524    impl WalEnv {
525        async fn new() -> WalEnv {
526            let wal_dir = create_temp_dir("");
527            let log_store =
528                log_store_util::create_tmp_local_file_log_store(wal_dir.path().to_str().unwrap())
529                    .await;
530            WalEnv {
531                _wal_dir: wal_dir,
532                log_store: Some(Arc::new(log_store)),
533            }
534        }
535
536        fn new_wal(&self) -> Wal<RaftEngineLogStore> {
537            let log_store = self.log_store.clone().unwrap();
538            Wal::new(log_store)
539        }
540    }
541
542    /// Create a new mutation from rows.
543    ///
544    /// The row format is (string, i64).
545    fn new_mutation(op_type: OpType, sequence: SequenceNumber, rows: &[(&str, i64)]) -> Mutation {
546        let rows = rows
547            .iter()
548            .map(|(str_col, int_col)| {
549                let values = vec![
550                    Value {
551                        value_data: Some(value::ValueData::StringValue(str_col.to_string())),
552                    },
553                    Value {
554                        value_data: Some(value::ValueData::TimestampMillisecondValue(*int_col)),
555                    },
556                ];
557                Row { values }
558            })
559            .collect();
560        let schema = vec![
561            tag_column_schema("tag", ColumnDataType::String),
562            time_index_column_schema("ts", ColumnDataType::TimestampMillisecond),
563        ];
564
565        Mutation {
566            op_type: op_type as i32,
567            sequence,
568            rows: Some(Rows { schema, rows }),
569            write_hint: None,
570        }
571    }
572
573    #[tokio::test]
574    async fn test_write_wal() {
575        let env = WalEnv::new().await;
576        let wal = env.new_wal();
577
578        let entry = WalEntry {
579            mutations: vec![
580                new_mutation(OpType::Put, 1, &[("k1", 1), ("k2", 2)]),
581                new_mutation(OpType::Put, 2, &[("k3", 3), ("k4", 4)]),
582            ],
583            bulk_entries: vec![],
584        };
585        let mut writer = wal.writer();
586        // Region 1 entry 1.
587        let region_id = RegionId::new(1, 1);
588        writer
589            .add_entry(
590                region_id,
591                1,
592                &entry,
593                &Provider::raft_engine_provider(region_id.as_u64()),
594            )
595            .unwrap();
596        // Region 2 entry 1.
597        let region_id = RegionId::new(1, 2);
598        writer
599            .add_entry(
600                region_id,
601                1,
602                &entry,
603                &Provider::raft_engine_provider(region_id.as_u64()),
604            )
605            .unwrap();
606        // Region 1 entry 2.
607        let region_id = RegionId::new(1, 2);
608        writer
609            .add_entry(
610                region_id,
611                2,
612                &entry,
613                &Provider::raft_engine_provider(region_id.as_u64()),
614            )
615            .unwrap();
616
617        // Test writing multiple region to wal.
618        writer.write_to_wal().await.unwrap();
619    }
620
621    fn build_record_batch(rows: &[(&str, i64)]) -> DfRecordBatch {
622        let schema = Arc::new(arrow::datatypes::Schema::new(vec![
623            Field::new("tag", arrow::datatypes::DataType::Utf8, false),
624            Field::new(
625                "ts",
626                arrow::datatypes::DataType::Timestamp(
627                    arrow::datatypes::TimeUnit::Millisecond,
628                    None,
629                ),
630                false,
631            ),
632        ]));
633
634        let tag = Arc::new(StringArray::from_iter_values(
635            rows.iter().map(|r| r.0.to_string()),
636        )) as ArrayRef;
637        let ts = Arc::new(TimestampMillisecondArray::from_iter_values(
638            rows.iter().map(|r| r.1),
639        )) as ArrayRef;
640        DfRecordBatch::try_new(schema, vec![tag, ts]).unwrap()
641    }
642
643    fn build_bulk_wal_entry(sequence_number: SequenceNumber, rows: &[(&str, i64)]) -> BulkWalEntry {
644        let rb = build_record_batch(rows);
645        let (schema, rb) = encode_to_flight_data(rb);
646        let max_ts = rows.iter().map(|r| r.1).max().unwrap();
647        let min_ts = rows.iter().map(|r| r.1).min().unwrap();
648        BulkWalEntry {
649            sequence: sequence_number,
650            max_ts,
651            min_ts,
652            timestamp_index: 1,
653            body: Some(bulk_wal_entry::Body::ArrowIpc(ArrowIpc {
654                schema: schema.data_header,
655                data_header: rb.data_header,
656                payload: rb.data_body,
657            })),
658        }
659    }
660
661    fn sample_entries() -> Vec<WalEntry> {
662        vec![
663            WalEntry {
664                mutations: vec![
665                    new_mutation(OpType::Put, 1, &[("k1", 1), ("k2", 2)]),
666                    new_mutation(OpType::Put, 2, &[("k3", 3), ("k4", 4)]),
667                ],
668                bulk_entries: vec![],
669            },
670            WalEntry {
671                mutations: vec![new_mutation(OpType::Put, 3, &[("k1", 1), ("k2", 2)])],
672                bulk_entries: vec![],
673            },
674            WalEntry {
675                mutations: vec![
676                    new_mutation(OpType::Put, 4, &[("k1", 1), ("k2", 2)]),
677                    new_mutation(OpType::Put, 5, &[("k3", 3), ("k4", 4)]),
678                ],
679                bulk_entries: vec![],
680            },
681            WalEntry {
682                mutations: vec![new_mutation(OpType::Put, 6, &[("k1", 1), ("k2", 2)])],
683                bulk_entries: vec![build_bulk_wal_entry(7, &[("k1", 8), ("k2", 9)])],
684            },
685        ]
686    }
687
688    fn check_entries(
689        expect: &[WalEntry],
690        expect_start_id: EntryId,
691        actual: &[(EntryId, WalEntry)],
692    ) {
693        for (idx, (expect_entry, (actual_id, actual_entry))) in
694            expect.iter().zip(actual.iter()).enumerate()
695        {
696            let expect_id_entry = (expect_start_id + idx as u64, expect_entry);
697            assert_eq!(expect_id_entry, (*actual_id, actual_entry));
698        }
699        assert_eq!(expect.len(), actual.len());
700    }
701
702    #[tokio::test]
703    async fn test_scan_wal() {
704        let env = WalEnv::new().await;
705        let wal = env.new_wal();
706
707        let entries = sample_entries();
708        let (id1, id2) = (RegionId::new(1, 1), RegionId::new(1, 2));
709        let ns1 = Provider::raft_engine_provider(id1.as_u64());
710        let ns2 = Provider::raft_engine_provider(id2.as_u64());
711        let mut writer = wal.writer();
712        writer.add_entry(id1, 1, &entries[0], &ns1).unwrap();
713        // Insert one entry into region2. Scan should not return this entry.
714        writer.add_entry(id2, 1, &entries[0], &ns2).unwrap();
715        writer.add_entry(id1, 2, &entries[1], &ns1).unwrap();
716        writer.add_entry(id1, 3, &entries[2], &ns1).unwrap();
717        writer.add_entry(id1, 4, &entries[3], &ns1).unwrap();
718
719        writer.write_to_wal().await.unwrap();
720
721        // Scan all contents region1
722        let stream = wal.scan(id1, 1, &ns1).unwrap();
723        let actual: Vec<_> = stream.try_collect().await.unwrap();
724        check_entries(&entries, 1, &actual);
725
726        // Scan parts of contents
727        let stream = wal.scan(id1, 2, &ns1).unwrap();
728        let actual: Vec<_> = stream.try_collect().await.unwrap();
729        check_entries(&entries[1..], 2, &actual);
730
731        // Scan out of range
732        let stream = wal.scan(id1, 5, &ns1).unwrap();
733        let actual: Vec<_> = stream.try_collect().await.unwrap();
734        assert!(actual.is_empty());
735    }
736
737    #[tokio::test]
738    async fn test_obsolete_wal() {
739        let env = WalEnv::new().await;
740        let wal = env.new_wal();
741
742        let entries = sample_entries();
743        let mut writer = wal.writer();
744        let region_id = RegionId::new(1, 1);
745        let ns = Provider::raft_engine_provider(region_id.as_u64());
746        writer.add_entry(region_id, 1, &entries[0], &ns).unwrap();
747        writer.add_entry(region_id, 2, &entries[1], &ns).unwrap();
748        writer.add_entry(region_id, 3, &entries[2], &ns).unwrap();
749
750        writer.write_to_wal().await.unwrap();
751
752        // Delete 1, 2.
753        wal.obsolete(region_id, 2, &ns).await.unwrap();
754
755        // Put 4.
756        let mut writer = wal.writer();
757        writer.add_entry(region_id, 4, &entries[3], &ns).unwrap();
758        writer.write_to_wal().await.unwrap();
759
760        // Scan all
761        let stream = wal.scan(region_id, 1, &ns).unwrap();
762        let actual: Vec<_> = stream.try_collect().await.unwrap();
763        check_entries(&entries[2..], 3, &actual);
764    }
765}