mz_persist_client/internal/gc.rs
1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::borrow::Borrow;
11use std::collections::BTreeSet;
12use std::fmt::Debug;
13use std::marker::PhantomData;
14use std::mem;
15use std::sync::Arc;
16use std::time::Instant;
17
18use differential_dataflow::difference::Monoid;
19use differential_dataflow::lattice::Lattice;
20use futures_util::StreamExt;
21use futures_util::stream::FuturesUnordered;
22use prometheus::Counter;
23use timely::progress::Timestamp;
24use tokio::sync::mpsc::UnboundedSender;
25use tokio::sync::{Semaphore, mpsc, oneshot};
26use tracing::{Instrument, Span, debug, debug_span, warn};
27
28use crate::async_runtime::IsolatedRuntime;
29use crate::batch::{BlobDeleteStats, PartDeletes};
30use crate::cfg::{GC_BLOB_DELETE_CONCURRENCY_LIMIT, GC_REMOVE_FINALIZED_ROLLUPS};
31
32use mz_ore::cast::CastFrom;
33use mz_ore::collections::HashSet;
34use mz_ore::soft_assert_or_log;
35use mz_persist::location::{Blob, SeqNo};
36use mz_persist_types::{Codec, Codec64};
37
38use crate::ShardId;
39use crate::internal::machine::{Machine, retry_external};
40use crate::internal::maintenance::RoutineMaintenance;
41use crate::internal::metrics::{GcStepTimings, RetryMetrics};
42use crate::internal::paths::{BlobKey, PartialBlobKey, PartialRollupKey};
43use crate::internal::state::{GC_USE_ACTIVE_GC, HollowBlobRef};
44use crate::internal::state_versions::{InspectDiff, StateVersionsIter, UntypedStateVersionsIter};
45
46#[derive(Debug, Clone, PartialEq)]
47pub struct GcReq {
48 pub shard_id: ShardId,
49 pub new_seqno_since: SeqNo,
50}
51
52/// Who asked for a GC, for metrics.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum GcCaller {
55 /// A commit's maintenance.
56 Maintenance,
57 /// [Machine::finish_finalized_gc], on a dropped shard.
58 Finalize,
59}
60
61#[derive(Debug)]
62pub struct GarbageCollector<K, V, T, D> {
63 sender: UnboundedSender<(GcReq, GcCaller, oneshot::Sender<RoutineMaintenance>)>,
64 _phantom: PhantomData<fn() -> (K, V, T, D)>,
65}
66
67impl<K, V, T, D> Clone for GarbageCollector<K, V, T, D> {
68 fn clone(&self) -> Self {
69 GarbageCollector {
70 sender: self.sender.clone(),
71 _phantom: PhantomData,
72 }
73 }
74}
75
76/// Cleanup for no longer necessary blobs and consensus versions.
77///
78/// - Every read handle, snapshot, and listener is given a capability on seqno
79/// with a very long lease (allowing for infrequent heartbeats). This is a
80/// guarantee that no blobs referenced by the state at that version will be
81/// deleted (even if they've been compacted in some newer version of the
82/// state). This is called a seqno_since in the code as it has obvious
83/// parallels to how sinces work at the shard/collection level. (Is reusing
84/// "since" here a good idea? We could also call it a "seqno capability" or
85/// something else instead.)
86/// - Every state transition via apply_unbatched_cmd has the opportunity to
87/// determine that the overall seqno_since for the shard has changed. In the
88/// common case in production, this will be in response to a snapshot
89/// finishing or a listener emitting some batch.
90/// - It would be nice if this only ever happened in response to read-y things
91/// (there'd be a nice parallel to how compaction background work is only
92/// spawned by write activity), but if there are no readers, we still very
93/// much want to continue to garbage collect. Notably, if there are no
94/// readers, we naturally only need to hold a capability on the current
95/// version of state. This means that if there are only writers, a write
96/// commands will result in the seqno_since advancing immediately from the
97/// previous version of the state to the new one.
98/// - Like Compacter, GarbageCollector uses a heuristic to ignore some requests
99/// to save work. In this case, the tradeoff is between consensus traffic
100/// (plus a bit of cpu) and keeping blobs around longer than strictly
101/// necessary. This is correct because a process could always die while
102/// executing one of these requests (or be slow and still working on it when
103/// the next request is generated), so we anyway need to handle them being
104/// dropped.
105/// - GarbageCollector works by `Consensus::scan`-ing for every live version of
106/// state (ignoring what the request things the prev_state_seqno was for the
107/// reasons mentioned immediately above). It then walks through them in a
108/// loop, accumulating a BTreeSet of every referenced blob key. When it finds
109/// the version corresponding to the new_seqno_since, it removes every blob in
110/// that version of the state from the BTreeSet and exits the loop. This
111/// results in the BTreeSet containing every blob eligible for deletion. It
112/// deletes those blobs and then truncates the state to the new_seqno_since to
113/// indicate that this work doesn't need to be done again.
114/// - Note that these requests are being processed concurrently, so it's always
115/// possible that some future request has already deleted the blobs and
116/// truncated consensus. It's also possible that this is the future request.
117/// As a result, the only guarantee that we get is that the current version of
118/// head is >= new_seqno_since.
119/// - (Aside: The above also means that if Blob is not linearizable, there is a
120/// possible race where a blob gets deleted before it written and thus is
121/// leaked. We anyway always have the possibility of a write process being
122/// killed between when it writes a blob and links it into state, so this is
123/// fine; it'll be caught and fixed by the same mechanism.)
124impl<K, V, T, D> GarbageCollector<K, V, T, D>
125where
126 K: Debug + Codec,
127 V: Debug + Codec,
128 T: Timestamp + Lattice + Codec64 + Sync,
129 D: Monoid + Codec64,
130{
131 pub fn new(machine: Machine<K, V, T, D>, isolated_runtime: Arc<IsolatedRuntime>) -> Self {
132 let (gc_req_sender, mut gc_req_recv) =
133 mpsc::unbounded_channel::<(GcReq, GcCaller, oneshot::Sender<RoutineMaintenance>)>();
134
135 // spin off a single task responsible for executing GC requests.
136 // work is enqueued into the task through a channel
137 let _worker_handle = mz_ore::task::spawn(|| "PersistGcWorker", async move {
138 while let Some((req, caller, completer)) = gc_req_recv.recv().await {
139 let mut consolidated_req = req;
140 let mut consolidated_caller = caller;
141 let mut gc_completed_senders = vec![completer];
142
143 // check if any further gc requests have built up. we'll merge their requests
144 // together and run a single GC pass to satisfy all of them
145 while let Ok((req, caller, completer)) = gc_req_recv.try_recv() {
146 assert_eq!(req.shard_id, consolidated_req.shard_id);
147 gc_completed_senders.push(completer);
148 // The merged pass does the finalize's work too.
149 if caller == GcCaller::Finalize {
150 consolidated_caller = caller;
151 }
152 consolidated_req.new_seqno_since =
153 std::cmp::max(req.new_seqno_since, consolidated_req.new_seqno_since);
154 }
155
156 let merged_requests = gc_completed_senders.len() - 1;
157 if merged_requests > 0 {
158 machine
159 .applier
160 .metrics
161 .gc
162 .merged
163 .inc_by(u64::cast_from(merged_requests));
164 debug!(
165 "Merged {} gc requests together for shard {}",
166 merged_requests, consolidated_req.shard_id
167 );
168 }
169
170 let gc_span = debug_span!(parent: None, "gc_and_truncate", shard_id=%consolidated_req.shard_id);
171 gc_span.follows_from(&Span::current());
172
173 let start = Instant::now();
174 machine.applier.metrics.gc.started.inc();
175 let (mut maintenance, stats) = {
176 let name = format!("gc_and_truncate ({})", consolidated_req.shard_id);
177 let machine = machine.clone();
178 isolated_runtime
179 .spawn_named(|| name, async move {
180 Self::gc_and_truncate(&machine, consolidated_req)
181 .instrument(gc_span)
182 .await
183 })
184 .await
185 };
186 machine.applier.metrics.gc.finished.inc();
187 machine.applier.shard_metrics.gc_finished.inc();
188 if machine.applier.is_tombstone() {
189 machine
190 .applier
191 .metrics
192 .gc
193 .tombstone_deleted(consolidated_caller, stats.deleted);
194 }
195 machine
196 .applier
197 .metrics
198 .gc
199 .seconds
200 .inc_by(start.elapsed().as_secs_f64());
201
202 // inform all callers who enqueued GC reqs that their work is complete
203 for sender in gc_completed_senders {
204 // we can safely ignore errors here, it's possible the caller
205 // wasn't interested in waiting and dropped their receiver.
206 // maintenance will be somewhat-arbitrarily assigned to the first oneshot.
207 let _ = sender.send(mem::take(&mut maintenance));
208 }
209 }
210 });
211
212 GarbageCollector {
213 sender: gc_req_sender,
214 _phantom: PhantomData,
215 }
216 }
217
218 /// Enqueues a [GcReq] to be consumed by the GC background task when available.
219 ///
220 /// Returns a future that indicates when GC has cleaned up to at least [GcReq::new_seqno_since]
221 pub fn gc_and_truncate_background(
222 &self,
223 req: GcReq,
224 caller: GcCaller,
225 ) -> Option<oneshot::Receiver<RoutineMaintenance>> {
226 let (gc_completed_sender, gc_completed_receiver) = oneshot::channel();
227 let new_gc_sender = self.sender.clone();
228 let send = new_gc_sender.send((req, caller, gc_completed_sender));
229
230 if let Err(e) = send {
231 // In the steady state we expect this to always succeed, but during
232 // shutdown it is possible the destination task has already spun down
233 warn!(
234 "gc_and_truncate_background failed to send gc request: {}",
235 e
236 );
237 return None;
238 }
239
240 Some(gc_completed_receiver)
241 }
242
243 pub(crate) async fn gc_and_truncate(
244 machine: &Machine<K, V, T, D>,
245 req: GcReq,
246 ) -> (RoutineMaintenance, GcResults) {
247 let mut step_start = Instant::now();
248 let mut report_step_timing = |counter: &Counter| {
249 let now = Instant::now();
250 counter.inc_by(now.duration_since(step_start).as_secs_f64());
251 step_start = now;
252 };
253 assert_eq!(req.shard_id, machine.shard_id());
254 let remove_finalized = GC_REMOVE_FINALIZED_ROLLUPS.get(&machine.applier.cfg);
255
256 // Double check our GC req: seqno_since will never regress
257 // so we can verify it's not somehow greater than the last-
258 // known seqno_since
259 if req.new_seqno_since > machine.applier.seqno_since() {
260 machine
261 .applier
262 .fetch_and_update_state(Some(req.new_seqno_since))
263 .await;
264 let current_seqno_since = machine.applier.seqno_since();
265 assert!(
266 req.new_seqno_since <= current_seqno_since,
267 "invalid gc req: {:?} vs machine seqno_since {}",
268 req,
269 current_seqno_since
270 );
271 }
272
273 // First, check the latest known state to this process to see
274 // if there's relevant GC work for this seqno_since
275 let gc_rollups =
276 GcRollups::new(machine.applier.rollups_lte_seqno(req.new_seqno_since), &req);
277 let rollups_to_remove_from_state = gc_rollups.rollups_to_remove_from_state();
278 report_step_timing(&machine.applier.metrics.gc.steps.find_removable_rollups);
279
280 let mut gc_results = GcResults::default();
281
282 if rollups_to_remove_from_state.is_empty() {
283 // Either the work has already been done, or there aren't enough rollups
284 // <= seqno_since to have any to delete.
285 return Self::skip_gc(machine, gc_results, remove_finalized).await;
286 }
287
288 debug!(
289 "Finding all rollups <= ({}). Will truncate: {:?}. Will remove rollups from state: {:?}",
290 req.new_seqno_since,
291 gc_rollups.truncate_seqnos().collect::<Vec<_>>(),
292 rollups_to_remove_from_state,
293 );
294
295 let use_active_gc = GC_USE_ACTIVE_GC.get(&machine.applier.cfg);
296 let mut states = if use_active_gc {
297 let diffs = machine
298 .applier
299 .state_versions
300 .fetch_live_diffs_through(&req.shard_id, req.new_seqno_since)
301 .await;
302
303 // An empty result means Consensus holds no diff at or below `new_seqno_since`.
304 // Some other process has already truncated past this request, so the request's
305 // goal is met and there are no diffs left from which to derive blob deletions.
306 // Common on tombstones, whose GC skips the `active_gc` check.
307 let Some(initial_seqno) = diffs.first().map(|x| x.seqno) else {
308 debug!(
309 ?req,
310 "skipping gc - consensus already truncated past seqno_since. concurrent GC?"
311 );
312 return Self::skip_gc(machine, gc_results, remove_finalized).await;
313 };
314
315 let Some(initial_rollup) = gc_rollups.get(initial_seqno) else {
316 // The latest state is always expected to have a reference to a rollup for the
317 // earliest seqno. If our state doesn't, that could mean:
318 // - Our diffs are too old, and some other process has already truncated past this point.
319 // (But currently we fetch diffs _after_ checking state, so that shouldn't happen.)
320 // - Our diffs are too new... someone has added a rollup for this seqno _after_ we fetched
321 // state, then truncated to it.
322 // In either case we're working on outdated data and should stop.
323 debug!(
324 ?initial_seqno,
325 ?gc_rollups,
326 "skipping gc - no rollup at initial seqno. concurrent GC?"
327 );
328 return Self::skip_gc(machine, gc_results, remove_finalized).await;
329 };
330
331 let Some(state) = machine
332 .applier
333 .state_versions
334 .fetch_rollup_at_key::<T>(&req.shard_id, initial_rollup)
335 .await
336 else {
337 debug!(
338 ?initial_seqno,
339 ?gc_rollups,
340 "skipping gc - deleted rollup at initial seqno. concurrent GC?"
341 );
342 return Self::skip_gc(machine, gc_results, remove_finalized).await;
343 };
344
345 UntypedStateVersionsIter::new(
346 req.shard_id,
347 machine.applier.cfg.clone(),
348 Arc::clone(&machine.applier.metrics),
349 state,
350 diffs,
351 )
352 .check_ts_codec()
353 .expect("ts codec has not changed")
354 } else {
355 machine
356 .applier
357 .state_versions
358 .fetch_all_live_states(req.shard_id)
359 .await
360 .expect("state is initialized")
361 .check_ts_codec()
362 .expect("ts codec has not changed")
363 };
364
365 let initial_seqno = states.state().seqno;
366 report_step_timing(&machine.applier.metrics.gc.steps.fetch_seconds);
367
368 machine
369 .applier
370 .shard_metrics
371 .gc_live_diffs
372 .set(u64::cast_from(states.len()));
373
374 debug!(
375 "gc seqno_since: ({}) got {} versions from scan",
376 req.new_seqno_since,
377 states.len()
378 );
379
380 Self::incrementally_delete_and_truncate(
381 &mut states,
382 &gc_rollups,
383 machine,
384 &mut report_step_timing,
385 &mut gc_results,
386 )
387 .await;
388
389 // Now that the blobs are deleted / Consensus is truncated, remove
390 // the rollups from state. Doing this at the end ensures that our
391 // invariant is maintained that the current state contains a rollup
392 // to the earliest state in Consensus, and ensures that if GC crashes
393 // part-way through, we still have a reference to these rollups to
394 // resume their deletion.
395 //
396 // This does mean that if GC crashes part-way through we would
397 // repeat work when it resumes. However the redundant work should
398 // be minimal as Consensus is incrementally truncated, allowing
399 // the next run of GC to skip any work needed for rollups less
400 // than the last truncation.
401 //
402 // In short, while this step is not incremental, it does not need
403 // to be for GC to efficiently resume. And in fact, making it
404 // incremental could be quite expensive (e.g. more CaS operations).
405 let (removed_rollups, maintenance) = machine
406 .remove_rollups(rollups_to_remove_from_state, remove_finalized)
407 .await;
408 report_step_timing(&machine.applier.metrics.gc.steps.remove_rollups_from_state);
409 debug!("CaS removed rollups from state: {:?}", removed_rollups);
410 gc_results.rollups_removed_from_state = removed_rollups;
411
412 // Everything here and below is not strictly needed for GC to complete,
413 // but it's a good opportunity, while we have all live states in hand,
414 // to run some metrics and assertions.
415
416 // Apply all remaining live states to rollup some metrics, like how many
417 // parts are being held (in Blob) that are not part of the latest state.
418 let mut seqno_held_parts = 0;
419 while let Some(_) = states.next(|diff| match diff {
420 InspectDiff::FromInitial(_) => {}
421 InspectDiff::Diff(diff) => {
422 seqno_held_parts += diff.part_deletes().count();
423 }
424 }) {}
425
426 machine
427 .applier
428 .shard_metrics
429 .gc_seqno_held_parts
430 .set(u64::cast_from(seqno_held_parts));
431
432 // verify that the current state contains a rollup to the earliest state
433 // we fetched. this invariant isn't affected by the GC work we just
434 // performed, but it is a property of GC correctness overall / is a
435 // convenient place to run the assertion.
436 //
437 // The check is only meaningful when `states` was built from
438 // `fetch_all_live_states`, where iterating to the end leaves
439 // `states.state()` at the genuine current state. Under active GC we only
440 // fetch diffs through `seqno_since`, so `states.state()` is the
441 // reconstructed state at `seqno_since`, not the current state. A rollup's
442 // entry is inserted into the rollups map by the `add_rollup` transition
443 // at a seqno strictly greater than the seqno it rolls up; when
444 // `seqno_since` precedes that insertion the reconstructed state legitimately
445 // lacks the entry and this check would false-fire. The active-GC path
446 // already validates the same invariant against fresh data when it resolves
447 // the rollup for `initial_seqno` above.
448 if !use_active_gc {
449 let valid_pre_gc_state = states
450 .state()
451 .collections
452 .rollups
453 .contains_key(&initial_seqno);
454
455 // this should never be true in the steady-state, but may be true the
456 // first time GC runs after fixing any correctness bugs related to our
457 // state version invariants. we'll make it an error so we can track
458 // any violations in Sentry, but opt not to panic because the root
459 // cause of the violation cannot be from this GC run (in fact, this
460 // GC run, assuming it's correct, should have fixed the violation!)
461 soft_assert_or_log!(
462 valid_pre_gc_state,
463 "earliest state fetched during GC did not have corresponding rollup: rollups = {:?}, state seqno = {}",
464 states.state().collections.rollups,
465 initial_seqno
466 );
467 }
468
469 report_step_timing(
470 &machine
471 .applier
472 .metrics
473 .gc
474 .steps
475 .post_gc_calculations_seconds,
476 );
477
478 (maintenance, gc_results)
479 }
480
481 /// Finishes a GC pass that turned out to have no work to do, either because
482 /// another process already did it or because there was never any to begin with.
483 ///
484 /// This still calls `remove_rollups` to clear `active_gc` if it was set, so
485 /// the next GC isn't suppressed. A finalized shard leaves it set, which
486 /// `maybe_gc` ignores for tombstones.
487 async fn skip_gc(
488 machine: &Machine<K, V, T, D>,
489 gc_results: GcResults,
490 remove_finalized: bool,
491 ) -> (RoutineMaintenance, GcResults) {
492 let (_removed, maintenance) = machine.remove_rollups(&[], remove_finalized).await;
493 machine.applier.metrics.gc.noop.inc();
494 (maintenance, gc_results)
495 }
496
497 /// Physically deletes all blobs from Blob and live diffs from Consensus that
498 /// are safe to delete, given the `seqno_since`, ensuring that the earliest
499 /// live diff in Consensus has a rollup of seqno `<= seqno_since`.
500 ///
501 /// Internally, performs deletions for each rollup encountered, ensuring that
502 /// incremental progress is made even if the process is interrupted before
503 /// completing all gc work.
504 async fn incrementally_delete_and_truncate<F>(
505 states: &mut StateVersionsIter<T>,
506 gc_rollups: &GcRollups,
507 machine: &Machine<K, V, T, D>,
508 timer: &mut F,
509 gc_results: &mut GcResults,
510 ) where
511 F: FnMut(&Counter),
512 {
513 assert_eq!(states.state().shard_id, machine.shard_id());
514 let shard_id = states.state().shard_id;
515 let mut batch_parts_to_delete = PartDeletes::default();
516 let mut rollups_to_delete: BTreeSet<PartialRollupKey> = BTreeSet::new();
517
518 for truncate_lt in gc_rollups.truncate_seqnos() {
519 assert!(batch_parts_to_delete.is_empty());
520 assert!(rollups_to_delete.is_empty());
521
522 // our state is already past the truncation point. there's no work to do --
523 // some process already truncated this far
524 if states.state().seqno >= truncate_lt {
525 continue;
526 }
527
528 // By our invariant, `states` should always begin on a rollup.
529 assert!(
530 gc_rollups.contains_seqno(&states.state().seqno),
531 "must start with a present rollup before searching for blobs: rollups = {:#?}, state seqno = {}",
532 gc_rollups,
533 states.state().seqno
534 );
535
536 Self::find_removable_blobs(
537 states,
538 truncate_lt,
539 &machine.applier.metrics.gc.steps,
540 timer,
541 &mut batch_parts_to_delete,
542 &mut rollups_to_delete,
543 );
544
545 // After finding removable blobs, our state should be exactly `truncate_lt`,
546 // to ensure we've seen all blob deletions in the diffs needed to reach
547 // this seqno.
548 //
549 // That we can always reach `truncate_lt` given the live diffs we fetched
550 // earlier is a little subtle:
551 // * Our GC request was generated after `seqno_since` was written.
552 // * If our initial seqno on this loop was < `truncate_lt`, then our read
553 // to `fetch_all_live_states` must have seen live diffs through at least
554 // `seqno_since`, because the diffs were not yet truncated.
555 // * `seqno_since` >= `truncate_lt`, therefore we must have enough live
556 // diffs to reach `truncate_lt`.
557 assert_eq!(states.state().seqno, truncate_lt);
558 // `truncate_lt` _is_ the seqno of a rollup, but let's very explicitly
559 // assert that we're about to truncate everything less than a rollup
560 // to maintain our invariant.
561 assert!(
562 gc_rollups.contains_seqno(&states.state().seqno),
563 "must start with a present rollup after searching for blobs: rollups = {:#?}, state seqno = {}",
564 gc_rollups,
565 states.state().seqno
566 );
567
568 // Extra paranoia: verify that none of the blobs we're about to delete
569 // are in our current state (we should only be truncating blobs from
570 // before this state!)
571 states.state().blobs().for_each(|blob| match blob {
572 HollowBlobRef::Batch(batch) => {
573 for live_part in &batch.parts {
574 assert!(!batch_parts_to_delete.contains(live_part));
575 }
576 }
577 HollowBlobRef::Rollup(live_rollup) => {
578 assert_eq!(rollups_to_delete.get(&live_rollup.key), None);
579 // And double check that the rollups we're about to delete are
580 // earlier than our truncation point:
581 match BlobKey::parse_ids(&live_rollup.key.complete(&shard_id)) {
582 Ok((_shard, PartialBlobKey::Rollup(rollup_seqno, _rollup))) => {
583 assert!(rollup_seqno < truncate_lt);
584 }
585 _ => {
586 panic!("invalid rollup during deletion: {:?}", live_rollup);
587 }
588 }
589 }
590 });
591
592 gc_results.truncated_consensus_to.push(truncate_lt);
593 gc_results.batch_parts_deleted_from_blob += batch_parts_to_delete.len();
594 gc_results.rollups_deleted_from_blob += rollups_to_delete.len();
595
596 let deleted = Self::delete_and_truncate(
597 truncate_lt,
598 &mut batch_parts_to_delete,
599 &mut rollups_to_delete,
600 machine,
601 timer,
602 )
603 .await;
604 gc_results.deleted.count += deleted.count;
605 gc_results.deleted.bytes += deleted.bytes;
606 }
607 }
608
609 /// Iterates through `states`, accumulating all deleted blobs (both batch parts
610 /// and rollups) until reaching the seqno `truncate_lt`.
611 ///
612 /// * The initial seqno of `states` MUST be less than `truncate_lt`.
613 /// * The seqno of `states` after this fn will be exactly `truncate_lt`.
614 fn find_removable_blobs<F>(
615 states: &mut StateVersionsIter<T>,
616 truncate_lt: SeqNo,
617 metrics: &GcStepTimings,
618 timer: &mut F,
619 batch_parts_to_delete: &mut PartDeletes<T>,
620 rollups_to_delete: &mut BTreeSet<PartialRollupKey>,
621 ) where
622 F: FnMut(&Counter),
623 {
624 assert!(states.state().seqno < truncate_lt);
625 while let Some(state) = states.next(|diff| match diff {
626 InspectDiff::FromInitial(_) => {}
627 InspectDiff::Diff(diff) => {
628 diff.rollup_deletes().for_each(|rollup| {
629 // we use BTreeSets for fast lookups elsewhere, but we should never
630 // see repeat rollup insertions within a single GC run, otherwise we
631 // have a logic error or our diffs are incorrect (!)
632 assert!(rollups_to_delete.insert(rollup.key.to_owned()));
633 });
634 diff.part_deletes().for_each(|part| {
635 assert!(batch_parts_to_delete.add(part));
636 });
637 }
638 }) {
639 if state.seqno == truncate_lt {
640 break;
641 }
642 }
643 timer(&metrics.find_deletable_blobs_seconds);
644 }
645
646 /// Deletes `batch_parts` and `rollups` from Blob.
647 /// Truncates Consensus to `truncate_lt`.
648 async fn delete_and_truncate<F>(
649 truncate_lt: SeqNo,
650 batch_parts: &mut PartDeletes<T>,
651 rollups: &mut BTreeSet<PartialRollupKey>,
652 machine: &Machine<K, V, T, D>,
653 timer: &mut F,
654 ) -> BlobDeleteStats
655 where
656 F: FnMut(&Counter),
657 {
658 let shard_id = machine.shard_id();
659 let concurrency_limit = GC_BLOB_DELETE_CONCURRENCY_LIMIT.get(&machine.applier.cfg);
660 let delete_semaphore = Semaphore::new(concurrency_limit);
661
662 let batch_parts = std::mem::take(batch_parts);
663 let mut deleted = batch_parts
664 .delete(
665 machine.applier.state_versions.blob.borrow(),
666 shard_id,
667 concurrency_limit,
668 &*machine.applier.metrics,
669 &machine.applier.metrics.retries.external.batch_delete,
670 )
671 .instrument(debug_span!("batch::delete"))
672 .await;
673 timer(&machine.applier.metrics.gc.steps.delete_batch_part_seconds);
674
675 let rollups_deleted = Self::delete_all(
676 machine.applier.state_versions.blob.borrow(),
677 rollups.iter().map(|k| k.complete(&shard_id)),
678 &machine.applier.metrics.retries.external.rollup_delete,
679 debug_span!("rollup::delete"),
680 &delete_semaphore,
681 )
682 .await;
683 deleted.count += rollups_deleted.count;
684 deleted.bytes += rollups_deleted.bytes;
685 rollups.clear();
686 timer(&machine.applier.metrics.gc.steps.delete_rollup_seconds);
687
688 machine
689 .applier
690 .state_versions
691 .truncate_diffs(&shard_id, truncate_lt)
692 .await;
693 timer(&machine.applier.metrics.gc.steps.truncate_diff_seconds);
694 deleted
695 }
696
697 // There's also a bulk delete API in s3 if the performance of this
698 // becomes an issue. Maybe make Blob::delete take a list of keys?
699 //
700 // https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObjects.html
701 async fn delete_all(
702 blob: &dyn Blob,
703 keys: impl Iterator<Item = BlobKey>,
704 metrics: &RetryMetrics,
705 span: Span,
706 semaphore: &Semaphore,
707 ) -> BlobDeleteStats {
708 let futures = FuturesUnordered::new();
709 for key in keys {
710 futures.push(
711 retry_external(metrics, move || {
712 let key = key.clone();
713 async move {
714 let _permit = semaphore
715 .acquire()
716 .await
717 .expect("acquiring permit from open semaphore");
718 blob.delete(&key).await
719 }
720 })
721 .instrument(span.clone()),
722 )
723 }
724
725 let mut deleted = BlobDeleteStats::default();
726 for result in futures.collect::<Vec<_>>().await {
727 deleted.add(result);
728 }
729 deleted
730 }
731}
732
733#[derive(Debug, Default)]
734pub(crate) struct GcResults {
735 pub(crate) batch_parts_deleted_from_blob: usize,
736 pub(crate) rollups_deleted_from_blob: usize,
737 pub(crate) deleted: BlobDeleteStats,
738 pub(crate) truncated_consensus_to: Vec<SeqNo>,
739 pub(crate) rollups_removed_from_state: Vec<SeqNo>,
740}
741
742#[derive(Debug)]
743struct GcRollups {
744 rollups_lte_seqno_since: Vec<(SeqNo, PartialRollupKey)>,
745 rollup_seqnos: HashSet<SeqNo>,
746}
747
748impl GcRollups {
749 fn new(rollups_lte_seqno_since: Vec<(SeqNo, PartialRollupKey)>, gc_req: &GcReq) -> Self {
750 assert!(
751 rollups_lte_seqno_since
752 .iter()
753 .all(|(seqno, _rollup)| *seqno <= gc_req.new_seqno_since)
754 );
755 let rollup_seqnos = rollups_lte_seqno_since.iter().map(|(x, _)| *x).collect();
756 Self {
757 rollups_lte_seqno_since,
758 rollup_seqnos,
759 }
760 }
761
762 /// Return the rollup key for the given seqno, if it exists.
763 fn get(&self, seqno: SeqNo) -> Option<&PartialRollupKey> {
764 let index = self
765 .rollups_lte_seqno_since
766 .binary_search_by_key(&seqno, |(k, _)| *k)
767 .ok()?;
768 Some(&self.rollups_lte_seqno_since[index].1)
769 }
770
771 fn contains_seqno(&self, seqno: &SeqNo) -> bool {
772 self.rollup_seqnos.contains(seqno)
773 }
774
775 /// Returns the seqnos we can safely truncate state to when performing
776 /// incremental GC (all rollups with seqnos <= seqno_since).
777 fn truncate_seqnos(&self) -> impl Iterator<Item = SeqNo> + '_ {
778 self.rollups_lte_seqno_since
779 .iter()
780 .map(|(seqno, _rollup)| *seqno)
781 }
782
783 /// Returns the rollups we can safely remove from state (all rollups
784 /// `<` than the latest rollup `<=` seqno_since).
785 ///
786 /// See the full explanation in [crate::internal::state_versions::StateVersions]
787 /// for how this is derived.
788 fn rollups_to_remove_from_state(&self) -> &[(SeqNo, PartialRollupKey)] {
789 match self.rollups_lte_seqno_since.split_last() {
790 None => &[],
791 Some((_rollup_to_keep, rollups_to_remove_from_state)) => rollups_to_remove_from_state,
792 }
793 }
794}