Skip to main content

mito2/worker/
handle_tail_replay.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//! Starting, applying and ending background replays of pending WAL tails, and discarding
16//! pending tails without replaying them.
17
18use std::sync::Arc;
19
20use common_telemetry::{error, info, warn};
21use store_api::logstore::LogStore;
22use store_api::storage::RegionId;
23use tokio::sync::mpsc::Sender;
24
25use crate::config::IndexBuildMode;
26use crate::error::{RegionBusySnafu, RegionStateSnafu};
27use crate::manifest::action::{
28    PendingTail, RegionEdit, RegionMetaAction, RegionMetaActionList, WalRecoveryEdit,
29};
30use crate::region::{
31    MitoRegionRef, RegionLeaderState, RegionRoleState, TailPublication, TailsEditor,
32};
33use crate::request::{BackgroundNotify, BuildIndexRequest, OptionOutputTx, WorkerRequestWithTime};
34use crate::schedule::CancellableTaskState;
35use crate::sst::index::IndexBuildType;
36use crate::tail_replay::{
37    TailReplayTask, notify_worker, release_wal_to_replay_start, should_replay_tails,
38};
39use crate::worker::RegionWorkerLoop;
40use crate::worker::handle_reload::notify_if_fenced;
41
42impl<S: LogStore> RegionWorkerLoop<S> {
43    /// Starts replaying the pending tails of the region, unless a replay of the region, of this or
44    /// an earlier instance, has not reported its end.
45    pub(crate) fn maybe_replay_tails(&mut self, region_id: RegionId) {
46        let Some(region) = self.regions.get_region(region_id) else {
47            return;
48        };
49        if self.tail_replays.contains_key(&region_id) || !should_replay_tails(&region) {
50            return;
51        }
52        info!("Replaying the pending WAL tails of region {region_id}");
53        let state = CancellableTaskState::new();
54        self.tail_replays
55            .insert(region_id, (region.clone(), state.clone()));
56        let task = TailReplayTask {
57            sst_writer: self.tail_replay_limits.new_sst_writer(
58                &region,
59                self.config.clone(),
60                self.cache_manager.clone(),
61            ),
62            region,
63            node_id: self.file_ref_manager.node_id(),
64            wal: self.wal.clone(),
65            listener: self.listener.clone(),
66            request_sender: self.sender.clone(),
67            limits: self.tail_replay_limits.clone(),
68            state,
69        };
70        common_runtime::spawn_global(task.run());
71    }
72
73    /// Cancels the tail replay of the region. The replay still reports its end.
74    pub(crate) fn cancel_tail_replay(&self, region_id: RegionId) {
75        if let Some((_, state)) = self.tail_replays.get(&region_id) {
76            let _ = state.request_cancel();
77        }
78    }
79
80    /// Discards the pending tails of the region that node `node_id` wrote, without replaying
81    /// them, and sends the number of discarded tails to `sender`. A region without such tails
82    /// sends 0 and changes nothing.
83    ///
84    /// The edit removes the tails, keeps the others in order and raises the flushed entry id
85    /// to the largest `upto` of the removed tails, for a listed tail too, whose `upto` can lie
86    /// above every entry this node wrote. Replaying the WAL at open then skips this node's
87    /// entries up to the new flushed entry id, except those covered by the node's remaining
88    /// tails, which a background replay still reads.
89    ///
90    /// Where the log store checks history and does not accept missing history, opening the
91    /// region also requires this node's WAL to hold history through the new flushed entry
92    /// id. The discard checks neither condition: whoever adds a tail ensures both (see
93    /// [RegionManifest::wal_replay_start](crate::manifest::action::RegionManifest::wal_replay_start)).
94    ///
95    /// The edit is committed outside the worker against the tails the version records now, so
96    /// a replay or a sync that changed them first makes it fail as busy, and a running replay
97    /// of the region is left to find the tails changed. Without conditional publication it also
98    /// fails as busy while a replay's update has an uncertain result, see
99    /// [ManifestContext::update_manifest_for_tails](crate::region::ManifestContext::update_manifest_for_tails).
100    pub(crate) fn handle_discard_pending_tails(
101        &mut self,
102        region_id: RegionId,
103        node_id: u64,
104        sender: OptionOutputTx,
105    ) {
106        let region = match self.regions.writable_non_staging_region(region_id) {
107            Ok(region) => region,
108            Err(e) => {
109                sender.send(Err(e));
110                return;
111            }
112        };
113        let (tails, flushed_entry_id) = {
114            let version = region.version();
115            (version.pending_tails.clone(), version.flushed_entry_id)
116        };
117        let (discarded, remaining): (Vec<_>, Vec<_>) = tails
118            .iter()
119            .cloned()
120            .partition(|tail| tail.node_id == node_id);
121        let Some(upto) = discarded.iter().map(|tail| tail.upto).max() else {
122            info!("Region {region_id} has no pending tails from node {node_id}");
123            sender.send(Ok(0));
124            return;
125        };
126        warn!(
127            "Discarding the pending WAL tails of region {region_id} from node {node_id}: {discarded:?}, flushed entry id: {flushed_entry_id}"
128        );
129        let edit = RegionEdit {
130            timestamp_ms: Some(chrono::Utc::now().timestamp_millis()),
131            flushed_entry_id: (upto > flushed_entry_id).then_some(upto),
132            wal_recovery: WalRecoveryEdit {
133                pending_tails: Some(remaining),
134                handoff_floor: None,
135            },
136            ..Default::default()
137        };
138        let wal = self.wal.clone();
139        let local_node_id = self.file_ref_manager.node_id();
140        let request_sender = self.sender.clone();
141        let listener = self.listener.clone();
142        common_runtime::spawn_global(async move {
143            let action_list =
144                RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone()));
145            match region
146                .manifest_ctx
147                .update_manifest_for_tails(&tails, action_list, TailsEditor::Discard)
148                .await
149            {
150                Ok(TailPublication::Committed(manifest_version)) => {
151                    info!(
152                        "Discarded the pending WAL tails of region {region_id} from node {node_id} in manifest version {manifest_version}"
153                    );
154                    // Notifies first: the release is storage I/O, and a replay that ends
155                    // meanwhile restarts from the old tails until the worker applies the edit.
156                    let notify = BackgroundNotify::PendingTailsDiscarded {
157                        region: region.clone(),
158                        edit,
159                        tails,
160                        discarded: discarded.len(),
161                        sender,
162                    };
163                    notify_worker(&request_sender, region_id, notify).await;
164                    release_wal_to_replay_start(&region, &wal, local_node_id).await;
165                    listener.on_discarded_tails_wal_released(region_id);
166                }
167                Ok(TailPublication::Busy) => {
168                    info!(
169                        "Region {region_id} is altering or editing, or a tail replay's update has an uncertain result, not discarding the tails from node {node_id}"
170                    );
171                    sender.send(RegionBusySnafu { region_id }.fail());
172                }
173                Ok(TailPublication::Stale) => {
174                    let state = region.state();
175                    if state == RegionRoleState::Leader(RegionLeaderState::Writable) {
176                        info!(
177                            "Region {region_id} changed its pending tails, not discarding the tails from node {node_id}"
178                        );
179                        sender.send(RegionBusySnafu { region_id }.fail());
180                    } else {
181                        sender.send(
182                            RegionStateSnafu {
183                                region_id,
184                                state,
185                                expect: RegionRoleState::Leader(RegionLeaderState::Writable),
186                            }
187                            .fail(),
188                        );
189                    }
190                }
191                Err(e) => {
192                    error!(e; "Failed to discard the pending WAL tails of region {region_id} from node {node_id}");
193                    notify_if_fenced(&request_sender, &region).await;
194                    sender.send(Err(e));
195                }
196            }
197        });
198    }
199
200    /// Applies a published edit that discards pending tails, see [Self::apply_tails_edit], and
201    /// sends the number of `discarded` tails, even if the region changed since.
202    pub(crate) async fn handle_pending_tails_discarded(
203        &mut self,
204        region_id: RegionId,
205        region: MitoRegionRef,
206        edit: RegionEdit,
207        tails: Vec<PendingTail>,
208        discarded: usize,
209        sender: OptionOutputTx,
210    ) {
211        self.apply_tails_edit(region_id, &region, edit, &tails)
212            .await;
213        sender.send(Ok(discarded));
214        self.maybe_replay_tails(region_id);
215    }
216
217    /// Applies `edit`, which a tail replay or a discard published for the pending tails
218    /// `tails`, unless the instance `region` was replaced, or its version no longer records
219    /// `tails` because a sync rebuilt it from a later manifest.
220    pub(crate) async fn apply_tails_edit(
221        &mut self,
222        region_id: RegionId,
223        region: &MitoRegionRef,
224        edit: RegionEdit,
225        tails: &[PendingTail],
226    ) {
227        let registered = self.regions.get_region(region_id);
228        if !registered.is_some_and(|registered| Arc::ptr_eq(&registered, region)) {
229            info!("Region {region_id} changed after its tails were published");
230            return;
231        }
232        if region.version().pending_tails != tails {
233            info!("Region {region_id} no longer records the published tails, skipping their edit");
234            return;
235        }
236        // A truncate uses the last entry id, which must not be below the flushed entry id.
237        if let Some(flushed_entry_id) = edit.flushed_entry_id
238            && flushed_entry_id > region.version_control.current().last_entry_id
239        {
240            region.version_control.set_entry_id(flushed_entry_id);
241        }
242        let file_metas = edit.files_to_add.clone();
243        region.apply_published_edit(edit, &[]).await;
244        if self.config.index.build_mode == IndexBuildMode::Async && !file_metas.is_empty() {
245            self.handle_rebuild_index(
246                BuildIndexRequest {
247                    region_id,
248                    build_type: IndexBuildType::Flush,
249                    file_metas,
250                    result_senders: Vec::new(),
251                },
252                OptionOutputTx::new(None),
253            )
254            .await;
255        }
256        self.schedule_compaction(region).await;
257    }
258
259    /// Cancels the tail replay of the region unless `region`, the instance a role change made
260    /// unable to replay, was replaced since.
261    pub(crate) fn handle_region_cannot_replay(&self, region_id: RegionId, region: MitoRegionRef) {
262        let registered = self.regions.get_region(region_id);
263        if registered.is_some_and(|registered| Arc::ptr_eq(&registered, &region)) {
264            self.cancel_tail_replay(region_id);
265        }
266    }
267
268    /// Forgets the ended tail replay of the region and starts another if it still has tails.
269    pub(crate) fn handle_tail_replay_ended(&mut self, region_id: RegionId) {
270        self.tail_replays.remove(&region_id);
271        self.listener.on_tail_replay_ended(region_id);
272        self.maybe_replay_tails(region_id);
273    }
274}
275
276/// Tells the worker that a region became writable, so it replays the pending tails and runs the
277/// work due once the region is a writable leader with its Leader lease, without waiting.
278pub(crate) fn notify_writable(sender: &Sender<WorkerRequestWithTime>, region: &MitoRegionRef) {
279    #[cfg(test)]
280    region
281        .manifest_ctx
282        .writable_notifications
283        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
284    let sender = sender.clone();
285    let region_id = region.region_id;
286    common_runtime::spawn_global(async move {
287        notify_worker(&sender, region_id, BackgroundNotify::RegionBecameWritable).await;
288    });
289}
290
291/// Asks the worker to cancel the tail replay of a region that a role change outside the worker
292/// made unable to replay, if it has pending tails, without waiting. A replay the cancel reaches
293/// after the region became writable again ends and the worker starts another.
294pub(crate) fn notify_cannot_replay(sender: &Sender<WorkerRequestWithTime>, region: &MitoRegionRef) {
295    if !region.version().has_pending_tails() {
296        return;
297    }
298    let sender = sender.clone();
299    let region_id = region.region_id;
300    let notify = BackgroundNotify::RegionCannotReplay {
301        region: region.clone(),
302    };
303    common_runtime::spawn_global(async move {
304        notify_worker(&sender, region_id, notify).await;
305    });
306}