Skip to main content

mito2/
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//! Background replay of the pending WAL tails of a region into SSTs.
16
17use std::num::NonZeroU64;
18use std::sync::Arc;
19use std::sync::atomic::{AtomicUsize, Ordering};
20use std::time::Duration;
21
22use common_telemetry::{error, info, warn};
23use futures::TryStreamExt;
24use snafu::ensure;
25use store_api::logstore::{LogStore, WalReadUpperBound};
26use store_api::storage::RegionId;
27use tokio::sync::Semaphore;
28use tokio::sync::mpsc::Sender;
29
30use crate::cache::CacheManagerRef;
31use crate::config::MitoConfig;
32use crate::error::{Error, FlushCancelledSnafu, Result, TailEntryMissingSnafu, UnexpectedSnafu};
33use crate::flush::MemtableSstWriter;
34use crate::manifest::action::{
35    PendingTail, RegionEdit, RegionMetaAction, RegionMetaActionList, UptoKind, WalRecoveryEdit,
36    cap_wal_release,
37};
38use crate::memtable::time_partition::TimePartitions;
39use crate::metrics::TAIL_REPLAY_FAILURE_TOTAL;
40use crate::region::opener::replay_entry;
41use crate::region::version::{VersionBuilder, VersionControl, VersionControlRef};
42use crate::region::{MitoRegion, MitoRegionRef, TailPublication, TailsEditor};
43use crate::request::{BackgroundNotify, WorkerRequest, WorkerRequestWithTime};
44use crate::schedule::CancellableTaskState;
45use crate::sst::file::{FileMeta, UncommittedSsts};
46use crate::wal::{EntryId, Wal, WalEntryStream};
47use crate::worker::WorkerListener;
48
49/// Memtable usage at which replayed rows are written to SSTs at the latest.
50const CHUNK_MEMTABLE_USAGE: usize = 64 * 1024 * 1024;
51/// Replays that read and write at once on a node.
52const MAX_CONCURRENT_TAIL_REPLAYS: usize = 16;
53/// The replay chunks of a node may use `1 / TAIL_REPLAY_MEMORY_FACTOR` of the global write
54/// buffer size.
55const TAIL_REPLAY_MEMORY_FACTOR: usize = 8;
56/// Delay before the first retry of a failed round or an unfinished commit.
57const MIN_BACKOFF: Duration = Duration::from_secs(1);
58/// Longest delay between retries.
59const MAX_BACKOFF: Duration = Duration::from_secs(30);
60/// How often a replay checks whether the region received a Leader lease.
61const LEASE_CHECK_INTERVAL: Duration = Duration::from_millis(500);
62
63/// Returns whether the pending tails of `region` are to be replayed: it has some and
64/// [can replay them](MitoRegion::can_replay_tails).
65pub(crate) fn should_replay_tails(region: &MitoRegion) -> bool {
66    region.can_replay_tails() && region.version().has_pending_tails()
67}
68
69/// Releases the WAL of `region` on node `node_id` up to where the region now replays it on
70/// open, keeping the node's remaining tails, after an edit of its pending tails or a handover's
71/// commit, which may record only a handoff floor or nothing. A failure is only logged.
72pub(crate) async fn release_wal_to_replay_start<S: LogStore>(
73    region: &MitoRegion,
74    wal: &Wal<S>,
75    node_id: Option<u64>,
76) {
77    let entry_id = {
78        let manifest = region.manifest_ctx.manifest().await;
79        cap_wal_release(
80            &manifest.pending_tails,
81            node_id,
82            manifest.wal_replay_start(node_id),
83        )
84    };
85    if let Err(e) = wal
86        .obsolete(region.region_id, entry_id, &region.provider)
87        .await
88    {
89        error!(e; "Failed to release the WAL of region {} up to entry {}", region.region_id, entry_id);
90    }
91}
92
93/// Replays the pending tails of a region into SSTs and publishes them in one manifest edit.
94///
95/// Each round reads the tails in order and writes each into its own SSTs: an SST can give all its
96/// rows its largest sequence, so in an SST shared with a later tail, an earlier tail's rows would
97/// take the later tail's sequence and outrank rows that a leader between the two tails flushed. A
98/// tail's chunks only bound memory: writes accepted during the replay already take sequences
99/// above every tail's. A chunk is written once it reaches 64 MiB, or once it grows above its floor
100/// and the node's replay memory pool cannot cover the growth. The edit adds the SSTs, clears
101/// the tails and advances the flushed entry id and sequence. Another node's listed tail is only a
102/// bound, so until the region receives a Leader lease after a catchup made it writable, the edit
103/// keeps its unread part, which a second edit clears once a lease arrives. A failed round is
104/// retried after a back-off while [should_replay_tails] holds, unless the storage holds a newer
105/// manifest and the region is still a Writable leader at its installed version: then the task
106/// fences the region for a reload and ends. The task always reports its end to the worker.
107pub(crate) struct TailReplayTask<S> {
108    pub(crate) region: MitoRegionRef,
109    /// Id of this node, whose tails are read from `wal`.
110    pub(crate) node_id: Option<u64>,
111    pub(crate) wal: Wal<S>,
112    /// Writes the chunks, built by [TailReplayLimits::new_sst_writer].
113    pub(crate) sst_writer: MemtableSstWriter,
114    /// Test listener told of failed rounds, lease and fence checks and commits.
115    pub(crate) listener: WorkerListener,
116    /// Sends the task's results and its end to the worker.
117    pub(crate) request_sender: Sender<WorkerRequestWithTime>,
118    /// Limits of the node's tail replays.
119    pub(crate) limits: TailReplayLimits,
120    pub(crate) state: CancellableTaskState,
121}
122
123impl<S: LogStore> TailReplayTask<S> {
124    pub(crate) async fn run(self) {
125        let region_id = self.region.region_id;
126        let _ended = TailReplayEndGuard {
127            sender: self.request_sender.clone(),
128            region_id,
129        };
130        let mut backoff = MIN_BACKOFF;
131        while !self.state.is_cancelled() && should_replay_tails(&self.region) {
132            match self.replay_round().await {
133                Ok(()) => return,
134                Err(_) if self.state.is_cancelled() => break,
135                Err(e) => {
136                    error!(e; "Failed to replay the pending WAL tails of region {region_id}");
137                    TAIL_REPLAY_FAILURE_TOTAL.inc();
138                    self.listener.on_tail_replay_failed(region_id, &e);
139                    // The tails may be gone from a newer manifest, e.g. after another writer
140                    // committed them and their source released its WAL. The worker reloads the
141                    // fenced region once this task ends.
142                    match self.fence_if_manifest_updated().await {
143                        Ok(true) => break,
144                        Ok(false) => {}
145                        Err(_) if self.state.is_cancelled() => break,
146                        Err(e) => {
147                            warn!(e; "Failed to check region {region_id} for a newer manifest");
148                        }
149                    }
150                }
151            }
152            if !self.sleep(backoff).await {
153                break;
154            }
155            backoff = (backoff * 2).min(MAX_BACKOFF);
156        }
157        info!(
158            "Region {region_id} stopped replaying its pending WAL tails before they were published"
159        );
160    }
161
162    /// Fences the region for a reload if the storage holds a newer manifest and the region is
163    /// still a Writable leader at its installed version. Returns whether it fenced the region.
164    /// Cancellation ends it until it holds the manifest write lock.
165    async fn fence_if_manifest_updated(&self) -> Result<bool> {
166        let manifest_ctx = &self.region.manifest_ctx;
167        let Some(installed) = self
168            .unless_cancelled(manifest_ctx.installed_version_if_updated())
169            .await?
170        else {
171            return Ok(false);
172        };
173        let region_id = self.region.region_id;
174        info!(
175            "Region {region_id} found a manifest newer than its version {installed} after a failed replay round"
176        );
177        self.listener.on_tail_fence_begin(region_id);
178        let mut manager = self
179            .unless_cancelled(async { Ok(manifest_ctx.manifest_manager.write().await) })
180            .await?;
181        Ok(manifest_ctx
182            .fence_for_reload_if_unchanged(&mut manager, region_id, installed)
183            .await)
184    }
185
186    /// Replays the current tails and publishes the result. An error asks for another round.
187    async fn replay_round(&self) -> Result<()> {
188        let region_id = self.region.region_id;
189        let replay_semaphore = &self.limits.replay_semaphore;
190        let permit = match replay_semaphore.try_acquire() {
191            Ok(permit) => permit,
192            Err(_) => {
193                info!("Region {region_id} waits for a tail replay permit");
194                self.unless_cancelled(async {
195                    replay_semaphore.acquire().await.map_err(|error| {
196                        UnexpectedSnafu {
197                            reason: format!("failed to acquire a tail replay permit: {error}"),
198                        }
199                        .build()
200                    })
201                })
202                .await?
203            }
204        };
205        // Keeps no version past this point: it would hold the region's memtables, and their
206        // write buffer memory, after a flush released them.
207        let (tails, flushed_entry_id) = {
208            let version = self.region.version();
209            (version.pending_tails.clone(), version.flushed_entry_id)
210        };
211        let uncommitted = UncommittedSsts::new(
212            region_id,
213            self.region.access_layer.clone(),
214            Some(self.sst_writer.cache_manager().clone()),
215        );
216        let replayed = self.replay_tails(&tails, &uncommitted).await;
217        drop(permit);
218        let (files, last_entry_ids) = match replayed {
219            Ok(replayed) => replayed,
220            Err(e) => {
221                uncommitted.cleanup().await;
222                return Err(e);
223            }
224        };
225        let lease_received = self.region.manifest_ctx.leader_lease_received();
226        let remaining = tails
227            .iter()
228            .zip(&last_entry_ids)
229            .filter_map(|(tail, last_entry_id)| {
230                self.remaining_tail(tail, *last_entry_id, lease_received)
231            })
232            .collect::<Vec<_>>();
233        if !files.is_empty() || remaining != tails {
234            let last_entry_id = last_entry_ids.into_iter().flatten().max().unwrap_or(0);
235            let flushed_sequence = files
236                .iter()
237                .filter_map(|file| file.sequence)
238                .map(NonZeroU64::get)
239                .max();
240            let edit = RegionEdit {
241                flushed_sequence,
242                files_to_add: files,
243                files_to_remove: Vec::new(),
244                timestamp_ms: Some(chrono::Utc::now().timestamp_millis()),
245                compaction_time_window: None,
246                flushed_entry_id: (last_entry_id > flushed_entry_id).then_some(last_entry_id),
247                // Later writes of the region take sequences above the replayed rows.
248                committed_sequence: flushed_sequence,
249                wal_recovery: WalRecoveryEdit {
250                    pending_tails: Some(remaining.clone()),
251                    handoff_floor: None,
252                },
253                ..Default::default()
254            };
255            if !self.publish(&tails, edit, &uncommitted).await? {
256                return Ok(());
257            }
258        }
259        if remaining.is_empty() || !self.wait_for_leader_lease().await {
260            return Ok(());
261        }
262        let edit = RegionEdit {
263            timestamp_ms: Some(chrono::Utc::now().timestamp_millis()),
264            wal_recovery: WalRecoveryEdit {
265                pending_tails: Some(Vec::new()),
266                handoff_floor: None,
267            },
268            ..Default::default()
269        };
270        self.publish(&remaining, edit, &uncommitted).await?;
271        Ok(())
272    }
273
274    /// Returns what stays recorded of `tail` after a replay read it up to `last_entry_id`.
275    /// Only another node's listed tail stays, from its last entry read, and only until the
276    /// region receives a Leader lease.
277    fn remaining_tail(
278        &self,
279        tail: &PendingTail,
280        last_entry_id: Option<EntryId>,
281        lease_received: bool,
282    ) -> Option<PendingTail> {
283        if lease_received
284            || tail.upto_kind == UptoKind::Reported
285            || Some(tail.node_id) == self.node_id
286        {
287            return None;
288        }
289        let after = last_entry_id.unwrap_or(tail.after);
290        (after < tail.upto).then(|| PendingTail {
291            after,
292            ..tail.clone()
293        })
294    }
295
296    /// Replays `tails` into chunks of SSTs. Returns the SSTs and the last entry id read of
297    /// each tail.
298    async fn replay_tails(
299        &self,
300        tails: &[PendingTail],
301        uncommitted: &UncommittedSsts,
302    ) -> Result<(Vec<FileMeta>, Vec<Option<EntryId>>)> {
303        let region_id = self.region.region_id;
304        let provider = &self.region.provider;
305        let mut files = Vec::new();
306        let mut last_entry_ids = Vec::with_capacity(tails.len());
307        for tail in tails {
308            let mut entries = self.unless_cancelled(self.read_tail_entries(tail)).await?;
309            let mut chunk = self.new_chunk_version();
310            let mut reservation = self.limits.memory.chunk_reservation();
311            let mut last_entry_id = None;
312            while let Some((entry_id, entry)) = self.unless_cancelled(entries.try_next()).await? {
313                if entry_id > tail.upto {
314                    break;
315                }
316                replay_entry(provider, region_id, &chunk, entry, entry_id).await?;
317                last_entry_id = Some(entry_id);
318                let usage = chunk.current().version.memtables.mutable_usage();
319                if usage >= CHUNK_MEMTABLE_USAGE || !reservation.grow_to(usage) {
320                    files.extend(self.write_chunk_ssts(&chunk, uncommitted).await?);
321                    chunk = self.new_chunk_version();
322                    reservation.clear();
323                }
324                if entry_id == tail.upto {
325                    break;
326                }
327            }
328            ensure!(
329                last_entry_id == Some(tail.upto) || tail.upto_kind == UptoKind::Listed,
330                TailEntryMissingSnafu {
331                    region_id,
332                    node_id: tail.node_id,
333                    entry_id: tail.upto,
334                }
335            );
336            files.extend(self.write_chunk_ssts(&chunk, uncommitted).await?);
337            last_entry_ids.push(last_entry_id);
338        }
339        Ok((files, last_entry_ids))
340    }
341
342    /// Streams the region's entries of `tail`, starting after `tail.after`. This node's reported
343    /// tail comes from its own WAL, whose stream may go past `tail.upto`. Every other tail is read
344    /// up to its bound through [Wal::read_node], since a listed bound may name no entry.
345    async fn read_tail_entries(&self, tail: &PendingTail) -> Result<WalEntryStream<'static>> {
346        let (provider, region_id) = (&self.region.provider, self.region.region_id);
347        let upper = match tail.upto_kind {
348            UptoKind::Reported if Some(tail.node_id) == self.node_id => {
349                let mut reader = self.wal.wal_entry_reader(provider, region_id);
350                return reader.read(provider, tail.after + 1);
351            }
352            UptoKind::Reported => WalReadUpperBound::LastEntry(tail.upto),
353            UptoKind::Listed => WalReadUpperBound::Listed(tail.upto),
354        };
355        self.wal
356            .read_node(region_id, tail.node_id, tail.after, upper)
357            .await
358    }
359
360    /// Waits until the region receives a Leader lease, or a StagingLeader lease on a node whose
361    /// writes need a lease. Returns false if the region stops being a writable, altering or
362    /// editing leader, or the task is cancelled, first.
363    async fn wait_for_leader_lease(&self) -> bool {
364        let region_id = self.region.region_id;
365        info!(
366            "Region {region_id} waits for a lease that confirms it as the leader to clear its unread listed tails"
367        );
368        while self.region.can_replay_tails() {
369            self.listener.on_tail_lease_check(region_id);
370            if self.region.manifest_ctx.leader_lease_received() {
371                return true;
372            }
373            if !self.sleep(LEASE_CHECK_INTERVAL).await {
374                info!("Region {region_id} cancelled its tail replay while waiting for a lease");
375                return false;
376            }
377        }
378        info!("Region {region_id} can no longer replay, keeping its unread listed tails");
379        false
380    }
381
382    /// Returns a scratch version with an empty memtable for one chunk of replayed rows.
383    fn new_chunk_version(&self) -> VersionControlRef {
384        let version = self.region.version();
385        let mutable = TimePartitions::new(
386            version.metadata.clone(),
387            version.memtables.mutable.memtable_builder().clone(),
388            0,
389            Some(version.memtables.mutable.part_duration()),
390        );
391        Arc::new(VersionControl::new(
392            VersionBuilder::new(version.metadata.clone(), mutable)
393                .options(version.options.clone())
394                .build(),
395        ))
396    }
397
398    /// Writes the rows of `chunk` to SSTs.
399    async fn write_chunk_ssts(
400        &self,
401        chunk: &VersionControl,
402        uncommitted: &UncommittedSsts,
403    ) -> Result<Vec<FileMeta>> {
404        chunk.freeze_mutable()?;
405        let version = chunk.current().version;
406        if version.memtables.immutables().is_empty() {
407            return Ok(Vec::new());
408        }
409        self.sst_writer
410            .write_ssts(&version, &self.state, uncommitted)
411            .await
412    }
413
414    /// Commits `edit` for the replayed `tails`. It commits the same content again while the
415    /// result is unknown or the region is busy. Returns whether it committed; if not, the task
416    /// ends. An error asks for another round.
417    async fn publish(
418        &self,
419        tails: &[PendingTail],
420        edit: RegionEdit,
421        uncommitted: &UncommittedSsts,
422    ) -> Result<bool> {
423        let region_id = self.region.region_id;
424        let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone()));
425        let mut backoff = MIN_BACKOFF;
426        // Whether an attempt may have persisted the edit, which only the same content confirms.
427        let mut uncertain = false;
428        loop {
429            self.listener.on_tail_commit_begin(region_id).await;
430            if self.state.is_cancelled() {
431                info!("Region {region_id} cancelled its tail replay before publishing");
432                uncommitted.cleanup().await;
433                return Ok(false);
434            }
435            match self
436                .region
437                .manifest_ctx
438                .update_manifest_for_tails(tails, action_list.clone(), TailsEditor::Replay)
439                .await
440            {
441                Ok(TailPublication::Committed(manifest_version)) => {
442                    uncommitted.disarm_cleanup();
443                    info!(
444                        "Published the replayed WAL tails of region {region_id} in manifest version {manifest_version}"
445                    );
446                    release_wal_to_replay_start(&self.region, &self.wal, self.node_id).await;
447                    self.listener.on_tail_commit_end(region_id).await;
448                    let region = self.region.clone();
449                    let tails = tails.to_vec();
450                    let notify = BackgroundNotify::TailReplayCommitted {
451                        region,
452                        edit,
453                        tails,
454                    };
455                    notify_worker(&self.request_sender, region_id, notify).await;
456                    return Ok(true);
457                }
458                Ok(TailPublication::Busy) => {}
459                Ok(TailPublication::Stale) => {
460                    info!("Region {region_id} changed its role or tails, dropping the replay");
461                    uncommitted.cleanup().await;
462                    return Ok(false);
463                }
464                // The commit fenced the region, which the worker reloads once this task ends.
465                Err(e @ Error::ManifestVersionConflict { .. }) => {
466                    uncommitted.disarm_cleanup();
467                    warn!(e; "Publishing the replayed WAL tails of region {region_id} conflicted");
468                    return Ok(false);
469                }
470                Err(e) if e.may_have_persisted_manifest_update() => {
471                    uncommitted.disarm_cleanup();
472                    uncertain = true;
473                    error!(e; "Publishing the replayed WAL tails of region {region_id} may have failed, retrying");
474                }
475                Err(Error::RegionStopped { .. }) => {
476                    info!("Region {region_id} stopped, dropping the replay");
477                    uncommitted.cleanup().await;
478                    return Ok(false);
479                }
480                Err(e) if uncertain => {
481                    error!(e; "Failed to publish the replayed WAL tails of region {region_id} again, retrying");
482                }
483                Err(e) => {
484                    uncommitted.cleanup().await;
485                    return Err(e);
486                }
487            }
488            if !self.sleep(backoff).await {
489                info!(
490                    "Region {region_id} cancelled its tail replay while retrying the publication"
491                );
492                uncommitted.cleanup().await;
493                return Ok(false);
494            }
495            backoff = (backoff * 2).min(MAX_BACKOFF);
496        }
497    }
498
499    /// Awaits `future` unless the task is cancelled first.
500    async fn unless_cancelled<T>(&self, future: impl Future<Output = Result<T>>) -> Result<T> {
501        let cancellation = self.state.cancel_token();
502        tokio::select! {
503            biased;
504            _ = cancellation.cancelled() => FlushCancelledSnafu.fail(),
505            result = future => result,
506        }
507    }
508
509    /// Sleeps for `delay`. Returns false if the task is cancelled first.
510    async fn sleep(&self, delay: Duration) -> bool {
511        self.unless_cancelled(async {
512            tokio::time::sleep(delay).await;
513            Ok(())
514        })
515        .await
516        .is_ok()
517    }
518}
519
520/// Sends `notify` about the region `region_id` to its worker.
521pub(crate) async fn notify_worker(
522    sender: &Sender<WorkerRequestWithTime>,
523    region_id: RegionId,
524    notify: BackgroundNotify,
525) {
526    let request = WorkerRequest::Background { region_id, notify };
527    if sender
528        .send(WorkerRequestWithTime::new(request))
529        .await
530        .is_err()
531    {
532        warn!("The worker of region {region_id} has stopped");
533    }
534}
535
536/// Reports the end of a tail replay to the worker, however the task ends.
537struct TailReplayEndGuard {
538    sender: Sender<WorkerRequestWithTime>,
539    region_id: RegionId,
540}
541
542impl Drop for TailReplayEndGuard {
543    fn drop(&mut self) {
544        let sender = self.sender.clone();
545        let region_id = self.region_id;
546        common_runtime::spawn_global(async move {
547            notify_worker(&sender, region_id, BackgroundNotify::TailReplayEnded).await;
548        });
549    }
550}
551
552/// Bounds the tail replays of a node. They take none of the flush permits, while their chunk
553/// memtables still count in the global write buffer.
554#[derive(Clone)]
555pub(crate) struct TailReplayLimits {
556    /// Replays that read and write at once.
557    replay_semaphore: Arc<Semaphore>,
558    /// SST writes of the replays, as many as the flushes may run, so a node may write up to
559    /// `2 * max_background_flushes` level 0 SSTs at once. Writer buffers are not part of the
560    /// replay memory budget.
561    write_semaphore: Arc<Semaphore>,
562    /// Memtable memory of the replay chunks.
563    memory: Arc<TailReplayMemory>,
564}
565
566impl TailReplayLimits {
567    /// Creates the limits of a node from `config`: `MAX_CONCURRENT_TAIL_REPLAYS` replays,
568    /// `max_background_flushes` SST writes and
569    /// `global_write_buffer_size / TAIL_REPLAY_MEMORY_FACTOR` bytes of chunk memory.
570    pub(crate) fn new(config: &MitoConfig) -> Self {
571        Self {
572            replay_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_TAIL_REPLAYS)),
573            write_semaphore: Arc::new(Semaphore::new(config.max_background_flushes)),
574            memory: Arc::new(TailReplayMemory::new(
575                config.global_write_buffer_size.as_bytes() as usize / TAIL_REPLAY_MEMORY_FACTOR,
576            )),
577        }
578    }
579
580    /// Creates a writer of the `region`'s replay chunks, which takes these limits' write
581    /// permits.
582    pub(crate) fn new_sst_writer(
583        &self,
584        region: &MitoRegion,
585        engine_config: Arc<MitoConfig>,
586        cache_manager: CacheManagerRef,
587    ) -> MemtableSstWriter {
588        MemtableSstWriter::new_tail_replay(
589            region,
590            engine_config,
591            cache_manager,
592            self.write_semaphore.clone(),
593        )
594    }
595}
596
597/// Memtable memory of the replay chunks on a node, out of a `budget`. The chunks share a pool of
598/// half the budget above their floors, and each of the [MAX_CONCURRENT_TAIL_REPLAYS] replays may
599/// always use a floor of an equal share of the other half.
600struct TailReplayMemory {
601    /// Bytes each replay's chunk may always use without a reservation.
602    floor: usize,
603    /// Bytes the chunks share above their floors.
604    pool: usize,
605    /// Bytes of the pool the chunks hold.
606    reserved: AtomicUsize,
607}
608
609impl TailReplayMemory {
610    /// Splits `budget` into the floors and the pool.
611    fn new(budget: usize) -> Self {
612        Self {
613            floor: budget / (2 * MAX_CONCURRENT_TAIL_REPLAYS),
614            pool: budget / 2,
615            reserved: AtomicUsize::new(0),
616        }
617    }
618
619    /// Returns an empty reservation for one chunk.
620    fn chunk_reservation(&self) -> ChunkReservation<'_> {
621        ChunkReservation {
622            memory: self,
623            bytes: 0,
624        }
625    }
626
627    /// Reserves `bytes` of the pool. Returns false if the pool has not enough left.
628    fn try_reserve(&self, bytes: usize) -> bool {
629        self.reserved
630            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |reserved| {
631                (reserved + bytes <= self.pool).then_some(reserved + bytes)
632            })
633            .is_ok()
634    }
635
636    /// Returns `bytes` to the pool.
637    fn release(&self, bytes: usize) {
638        self.reserved.fetch_sub(bytes, Ordering::Relaxed);
639    }
640}
641
642/// The pool memory a chunk uses above its floor. It is released on drop.
643struct ChunkReservation<'a> {
644    /// Memory the reservation is taken from.
645    memory: &'a TailReplayMemory,
646    /// Bytes of the pool the chunk holds.
647    bytes: usize,
648}
649
650impl ChunkReservation<'_> {
651    /// Grows the reservation to cover a chunk using `usage` bytes. Returns false if the pool
652    /// has not enough left, in which case the reservation is unchanged.
653    fn grow_to(&mut self, usage: usize) -> bool {
654        let needed = usage.saturating_sub(self.memory.floor);
655        if needed <= self.bytes {
656            return true;
657        }
658        if !self.memory.try_reserve(needed - self.bytes) {
659            return false;
660        }
661        self.bytes = needed;
662        true
663    }
664
665    /// Releases the reservation for a new chunk.
666    fn clear(&mut self) {
667        self.memory.release(self.bytes);
668        self.bytes = 0;
669    }
670}
671
672impl Drop for ChunkReservation<'_> {
673    fn drop(&mut self) {
674        self.clear();
675    }
676}
677
678#[cfg(test)]
679mod tests {
680    use super::*;
681
682    #[test]
683    fn test_chunk_reservation_keeps_floor_when_pool_is_exhausted() {
684        // Floor 1 KiB, pool 16 KiB.
685        let memory = TailReplayMemory::new(32 * 1024);
686        let mut first = memory.chunk_reservation();
687        let mut second = memory.chunk_reservation();
688        assert!(first.grow_to(17 * 1024));
689        assert!(!first.grow_to(17 * 1024 + 1));
690        // The pool is used up, but another chunk still grows to its floor.
691        assert!(second.grow_to(1024));
692        assert!(!second.grow_to(1025));
693
694        first.clear();
695        assert!(second.grow_to(17 * 1024));
696        drop(second);
697        assert_eq!(0, memory.reserved.load(Ordering::Relaxed));
698    }
699
700    #[test]
701    fn test_chunk_reservation_grows_by_increments_and_reuses_after_clear() {
702        // Floor 1 KiB, pool 16 KiB.
703        let memory = TailReplayMemory::new(32 * 1024);
704        let reserved = || memory.reserved.load(Ordering::Relaxed);
705        let mut chunk = memory.chunk_reservation();
706        assert!(chunk.grow_to(5 * 1024));
707        assert_eq!(4 * 1024, reserved());
708        assert!(chunk.grow_to(9 * 1024));
709        assert_eq!(8 * 1024, reserved());
710
711        chunk.clear();
712        assert_eq!(0, reserved());
713        assert!(chunk.grow_to(3 * 1024));
714        assert_eq!(2 * 1024, reserved());
715        drop(chunk);
716        assert_eq!(0, reserved());
717    }
718}