Skip to main content

mz_persist_client/cli/
inspect.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
10//! CLI introspection tools for persist
11
12use std::collections::btree_map::Entry;
13use std::collections::{BTreeMap, BTreeSet};
14use std::pin::pin;
15use std::str::FromStr;
16use std::sync::{Arc, Mutex};
17
18use anyhow::anyhow;
19use bytes::{BufMut, Bytes};
20use differential_dataflow::lattice::Lattice;
21use differential_dataflow::trace::Description;
22use futures_util::{StreamExt, TryStreamExt};
23use mz_ore::cast::CastFrom;
24use mz_ore::metrics::MetricsRegistry;
25use mz_ore::now::SYSTEM_TIME;
26use mz_ore::url::SensitiveUrl;
27use mz_persist::indexed::encoding::BlobTraceBatchPart;
28use mz_persist::location::VersionedData;
29use mz_persist_types::codec_impls::TodoSchema;
30use mz_persist_types::{Codec, Codec64};
31use mz_proto::RustType;
32use prost::Message;
33use serde_json::json;
34
35use crate::async_runtime::IsolatedRuntime;
36use crate::cache::StateCache;
37use crate::cli::args::{NO_COMMIT, READ_ALL_BUILD_INFO, StateArgs, make_blob, make_consensus};
38use crate::error::CodecConcreteType;
39use crate::fetch::{EncodedPart, FetchConfig};
40use crate::internal::encoding::{Rollup, UntypedState};
41use crate::internal::paths::{
42    BlobKey, BlobKeyPrefix, PartialBatchKey, PartialBlobKey, PartialRollupKey, WriterKey,
43};
44use crate::internal::state::{
45    BatchPart, HollowBlobRef, HollowRunRef, ProtoRollup, ProtoStateDiff, RunPart, State,
46};
47use crate::internal::state_diff::StateDiff;
48use crate::internal::state_versions::{StateVersions, UntypedStateVersionsIter};
49use crate::rpc::NoopPubSubSender;
50use crate::usage::{HumanBytes, StorageUsageClient};
51use crate::{Metrics, PersistClient, PersistConfig, ShardId};
52
53/// Commands for read-only inspection of persist state
54#[derive(Debug, clap::Args)]
55pub struct InspectArgs {
56    #[clap(subcommand)]
57    command: Command,
58}
59
60/// Individual subcommands of inspect
61#[derive(Debug, clap::Subcommand)]
62pub(crate) enum Command {
63    /// Prints latest consensus state as JSON
64    State(StateArgs),
65
66    /// Prints latest consensus rollup state as JSON
67    StateRollup(StateRollupArgs),
68
69    /// Prints consensus rollup state of all known rollups as JSON
70    StateRollups(StateArgs),
71
72    /// Prints the count and size of blobs in an environment
73    BlobCount(BlobArgs),
74
75    /// Prints blob batch part contents
76    BlobBatchPart(BlobBatchPartArgs),
77
78    /// Prints consolidated and unconsolidated size, in bytes and update count
79    ConsolidatedSize(StateArgs),
80
81    /// Prints the unreferenced blobs across all shards
82    UnreferencedBlobs(StateArgs),
83
84    /// Prints various statistics about the latest rollups for all the shards in an environment
85    ShardStats(BlobArgs),
86
87    /// Prints information about blob usage for a shard
88    BlobUsage(StateArgs),
89
90    /// Checks that every blob referenced by a live state version exists, as JSON
91    AuditBlobs(StateArgs),
92
93    /// Reports the controller since, upper and size in updates from one shard state
94    AuditFrontiers(StateArgs),
95
96    /// Prints each consensus state change as JSON. Output includes the full consensus state
97    /// before and after each state transitions:
98    ///
99    /// ```text
100    /// {
101    ///     "previous": previous_consensus_state,
102    ///     "new": new_consensus_state,
103    /// }
104    /// ```
105    ///
106    /// This is most helpfully consumed using a JSON diff tool like `jd`. A useful incantation
107    /// to show only the changed fields between state transitions:
108    ///
109    /// ```text
110    /// persistcli inspect state-diff --shard-id <shard> --consensus-uri <consensus_uri> |
111    ///     while read diff; do
112    ///         echo $diff | jq '.new' > temp_new
113    ///         echo $diff | jq '.previous' > temp_previous
114    ///         echo $diff | jq '.new.seqno'
115    ///         jd -color -set temp_previous temp_new
116    ///     done
117    /// ```
118    ///
119    #[clap(verbatim_doc_comment)]
120    StateDiff(StateArgs),
121}
122
123/// Runs the given read-only inspect command.
124pub async fn run(command: InspectArgs) -> Result<(), anyhow::Error> {
125    match command.command {
126        Command::State(args) => {
127            let state = fetch_latest_state(&args).await?;
128            println!(
129                "{}",
130                serde_json::to_string_pretty(&state).expect("unserializable state")
131            );
132        }
133        Command::StateRollup(args) => {
134            let state_rollup = fetch_state_rollup(&args).await?;
135            println!(
136                "{}",
137                serde_json::to_string_pretty(&state_rollup).expect("unserializable state")
138            );
139        }
140        Command::StateRollups(args) => {
141            let state_rollups = fetch_state_rollups(&args).await?;
142            println!(
143                "{}",
144                serde_json::to_string_pretty(&state_rollups).expect("unserializable state")
145            );
146        }
147        Command::StateDiff(args) => {
148            let states = fetch_state_diffs(&args).await?;
149            for window in states.windows(2) {
150                println!(
151                    "{}",
152                    json!({
153                        "previous": window[0],
154                        "new": window[1]
155                    })
156                );
157            }
158        }
159        Command::BlobCount(args) => {
160            let blob_counts = blob_counts(&args.blob_uri).await?;
161            println!("{}", json!(blob_counts));
162        }
163        Command::BlobBatchPart(args) => {
164            let shard_id = ShardId::from_str(&args.shard_id).expect("invalid shard id");
165            let updates = blob_batch_part(&args.blob_uri, shard_id, args.key, args.limit).await?;
166            println!("{}", json!(updates));
167        }
168        Command::ConsolidatedSize(args) => {
169            let () = consolidated_size(&args).await?;
170        }
171        Command::UnreferencedBlobs(args) => {
172            let unreferenced_blobs = unreferenced_blobs(&args).await?;
173            println!("{}", json!(unreferenced_blobs));
174        }
175        Command::BlobUsage(args) => {
176            let () = blob_usage(&args).await?;
177        }
178        Command::ShardStats(args) => {
179            shard_stats(&args.blob_uri).await?;
180        }
181        Command::AuditBlobs(args) => {
182            let versions = args.open().await?;
183            let report = audit_blobs(&versions, args.shard_id()).await?;
184            println!("{}", json!(report));
185        }
186        Command::AuditFrontiers(args) => {
187            let versions = args.open().await?;
188            let report = audit_frontiers(&versions, args.shard_id()).await?;
189            println!("{}", json!(report));
190        }
191    }
192
193    Ok(())
194}
195
196/// Arguments for viewing the state rollup of a shard
197#[derive(Debug, Clone, clap::Parser)]
198pub struct StateRollupArgs {
199    #[clap(flatten)]
200    pub(crate) state: StateArgs,
201
202    /// Inspect the state rollup with the given ID, if available.
203    #[clap(long)]
204    pub(crate) rollup_key: Option<String>,
205}
206
207/// Fetches the current state of a given shard
208pub async fn fetch_latest_state(args: &StateArgs) -> Result<impl serde::Serialize, anyhow::Error> {
209    let shard_id = args.shard_id();
210    let state_versions = args.open().await?;
211    let versions = state_versions
212        .fetch_recent_live_diffs::<u64>(&shard_id)
213        .await;
214    let state = state_versions
215        .fetch_current_state::<u64>(&shard_id, versions.0.clone())
216        .await;
217    Ok(Rollup::from_untyped_state_without_diffs(state).into_proto())
218}
219
220/// Fetches a state rollup of a given shard. If the seqno is not provided, choose the latest;
221/// if the rollup id is not provided, discover it by inspecting state.
222pub async fn fetch_state_rollup(
223    args: &StateRollupArgs,
224) -> Result<impl serde::Serialize, anyhow::Error> {
225    let shard_id = args.state.shard_id();
226    let state_versions = args.state.open().await?;
227
228    let rollup_key = if let Some(rollup_key) = &args.rollup_key {
229        PartialRollupKey(rollup_key.to_owned())
230    } else {
231        let latest_state = state_versions.consensus.head(&shard_id.to_string()).await?;
232        let diff_buf = latest_state.ok_or_else(|| anyhow!("unknown shard"))?;
233        let diff = ProtoStateDiff::decode(diff_buf.data).expect("invalid encoded diff");
234        PartialRollupKey(diff.latest_rollup_key)
235    };
236    let rollup_buf = state_versions
237        .blob
238        .get(&rollup_key.complete(&shard_id))
239        .await?
240        .expect("fetching the specified state rollup");
241    let proto = ProtoRollup::decode(rollup_buf).expect("invalid encoded state");
242    Ok(proto)
243}
244
245/// Fetches the state from all known rollups of a given shard
246pub async fn fetch_state_rollups(args: &StateArgs) -> Result<impl serde::Serialize, anyhow::Error> {
247    let shard_id = args.shard_id();
248    let state_versions = args.open().await?;
249
250    let mut rollup_keys = BTreeSet::new();
251    let mut state_iter = state_versions
252        .fetch_all_live_states::<u64>(shard_id)
253        .await
254        .expect("requested shard should exist")
255        .check_ts_codec()?;
256    while let Some(v) = state_iter.next(|_| {}) {
257        for rollup in v.collections.rollups.values() {
258            rollup_keys.insert(rollup.key.clone());
259        }
260    }
261
262    if rollup_keys.is_empty() {
263        return Err(anyhow!("unknown shard"));
264    }
265
266    let mut rollup_states = BTreeMap::new();
267    for key in rollup_keys {
268        let rollup_buf = state_versions
269            .blob
270            .get(&key.complete(&shard_id))
271            .await
272            .unwrap();
273        if let Some(rollup_buf) = rollup_buf {
274            let proto = ProtoRollup::decode(rollup_buf).expect("invalid encoded state");
275            rollup_states.insert(key.to_string(), proto);
276        }
277    }
278
279    Ok(rollup_states)
280}
281
282/// Fetches each state in a shard
283pub async fn fetch_state_diffs(
284    args: &StateArgs,
285) -> Result<Vec<impl serde::Serialize>, anyhow::Error> {
286    let shard_id = args.shard_id();
287    let state_versions = args.open().await?;
288
289    let mut live_states = vec![];
290    let mut state_iter = state_versions
291        .fetch_all_live_states::<u64>(shard_id)
292        .await
293        .expect("requested shard should exist")
294        .check_ts_codec()?;
295    while let Some(_) = state_iter.next(|_| {}) {
296        live_states.push(state_iter.into_rollup_proto_without_diffs());
297    }
298
299    Ok(live_states)
300}
301
302/// Arguments for viewing contents of a batch part
303#[derive(Debug, Clone, clap::Parser)]
304pub struct BlobBatchPartArgs {
305    /// Shard to view
306    #[clap(long)]
307    shard_id: String,
308
309    /// Blob key (without shard)
310    #[clap(long)]
311    key: String,
312
313    /// Blob to use
314    ///
315    /// When connecting to a deployed environment's blob, the necessary connection glue must be in
316    /// place. e.g. for S3, sign into SSO, set AWS_PROFILE and AWS_REGION appropriately, with a blob
317    /// URI scoped to the environment's bucket prefix.
318    #[clap(long)]
319    blob_uri: SensitiveUrl,
320
321    /// Number of updates to output. Default is unbounded.
322    #[clap(long, default_value = "18446744073709551615")]
323    limit: usize,
324}
325
326#[derive(Debug, serde::Serialize)]
327struct BatchPartOutput {
328    desc: Description<u64>,
329    updates: Vec<BatchPartUpdate>,
330}
331
332#[derive(Debug, serde::Serialize)]
333struct BatchPartUpdate {
334    k: String,
335    v: String,
336    t: u64,
337    d: i64,
338}
339
340/// Fetches the updates in a blob batch part
341pub async fn blob_batch_part(
342    blob_uri: &SensitiveUrl,
343    shard_id: ShardId,
344    partial_key: String,
345    limit: usize,
346) -> Result<impl serde::Serialize, anyhow::Error> {
347    let cfg = PersistConfig::new_default_configs(&READ_ALL_BUILD_INFO, SYSTEM_TIME.clone());
348    let metrics = Arc::new(Metrics::new(&cfg, &MetricsRegistry::new()));
349    let blob = make_blob(&cfg, blob_uri, NO_COMMIT, Arc::clone(&metrics)).await?;
350
351    let key = PartialBatchKey(partial_key);
352    let buf = blob
353        .get(&*key.complete(&shard_id))
354        .await
355        .expect("blob exists")
356        .expect("part exists");
357    let parsed = BlobTraceBatchPart::<u64>::decode(&buf, &metrics.columnar).expect("decodable");
358    let desc = parsed.desc.clone();
359
360    let encoded_part = EncodedPart::new(
361        &FetchConfig::from_persist_config(&cfg),
362        metrics.read.snapshot.clone(),
363        parsed.desc.clone(),
364        &key.0,
365        None,
366        parsed,
367    );
368    let mut out = BatchPartOutput {
369        desc,
370        updates: Vec::new(),
371    };
372    let records = encoded_part
373        .updates()
374        .as_part()
375        .ok_or_else(|| anyhow!("expected structured data"))?
376        .as_ord();
377    for (k, v, t, d) in records.iter() {
378        if out.updates.len() > limit {
379            break;
380        }
381        out.updates.push(BatchPartUpdate {
382            k: k.to_string(),
383            v: v.to_string(),
384            t: u64::from_le_bytes(t),
385            d: i64::from_le_bytes(d),
386        });
387    }
388
389    Ok(out)
390}
391
392async fn consolidated_size(args: &StateArgs) -> Result<(), anyhow::Error> {
393    let shard_id = args.shard_id();
394    let state_versions = args.open().await?;
395    let cfg = &state_versions.cfg;
396    let versions = state_versions
397        .fetch_recent_live_diffs::<u64>(&shard_id)
398        .await;
399    let state = state_versions
400        .fetch_current_state::<u64>(&shard_id, versions.0.clone())
401        .await;
402    let state = state.check_ts_codec(&shard_id)?;
403    let shard_metrics = state_versions.metrics.shards.shard(&shard_id, "unknown");
404    // This is odd, but advance by the upper to get maximal consolidation.
405    let as_of = state.upper().borrow();
406
407    let mut parts = Vec::new();
408    for batch in state.collections.trace.batches() {
409        let mut part_stream =
410            pin!(batch.part_stream(shard_id, &*state_versions.blob, &*state_versions.metrics));
411        while let Some(part) = part_stream.try_next().await? {
412            tracing::info!("fetching {}", part.printable_name());
413            let encoded_part = EncodedPart::fetch(
414                &FetchConfig::from_persist_config(cfg),
415                &shard_id,
416                &*state_versions.blob,
417                &state_versions.metrics,
418                &shard_metrics,
419                &state_versions.metrics.read.snapshot,
420                &batch.desc,
421                &part,
422            )
423            .await
424            .expect("part exists");
425            let part = encoded_part.updates();
426            let part = part
427                .as_part()
428                .ok_or_else(|| anyhow!("expected structured data"))?
429                .as_ord();
430            parts.push(part);
431        }
432    }
433
434    let mut updates = vec![];
435    for part in &parts {
436        for (k, v, t, d) in part.iter() {
437            let mut t = <u64 as Codec64>::decode(t);
438            t.advance_by(as_of);
439            let d = <i64 as Codec64>::decode(d);
440            updates.push(((k, v), t, d));
441        }
442    }
443
444    let bytes: usize = updates
445        .iter()
446        .map(|((k, v), _, _)| k.goodbytes() + v.goodbytes())
447        .sum();
448    println!("before: {} updates {} bytes", updates.len(), bytes);
449    differential_dataflow::consolidation::consolidate_updates(&mut updates);
450    let bytes: usize = updates
451        .iter()
452        .map(|((k, v), _, _)| k.goodbytes() + v.goodbytes())
453        .sum();
454    println!("after : {} updates {} bytes", updates.len(), bytes);
455
456    Ok(())
457}
458
459/// Arguments for commands that run only against the blob store.
460#[derive(Debug, Clone, clap::Parser)]
461pub struct BlobArgs {
462    /// Blob to use
463    ///
464    /// When connecting to a deployed environment's blob, the necessary connection glue must be in
465    /// place. e.g. for S3, sign into SSO, set AWS_PROFILE and AWS_REGION appropriately, with a blob
466    /// URI scoped to the environment's bucket prefix.
467    #[clap(long)]
468    blob_uri: SensitiveUrl,
469}
470
471#[derive(Debug, Default, serde::Serialize)]
472struct BlobCounts {
473    batch_part_count: usize,
474    batch_part_bytes: usize,
475    rollup_count: usize,
476    rollup_bytes: usize,
477}
478
479/// Fetches the blob count for given path
480pub async fn blob_counts(blob_uri: &SensitiveUrl) -> Result<impl serde::Serialize, anyhow::Error> {
481    let cfg = PersistConfig::new_default_configs(&READ_ALL_BUILD_INFO, SYSTEM_TIME.clone());
482    let metrics = Arc::new(Metrics::new(&cfg, &MetricsRegistry::new()));
483    let blob = make_blob(&cfg, blob_uri, NO_COMMIT, metrics).await?;
484
485    let mut blob_counts = BTreeMap::new();
486    let () = blob
487        .list_keys_and_metadata(&BlobKeyPrefix::All.to_string(), &mut |metadata| {
488            match BlobKey::parse_ids(metadata.key) {
489                Ok((shard, PartialBlobKey::Batch(_, _))) => {
490                    let blob_count = blob_counts.entry(shard).or_insert_with(BlobCounts::default);
491                    blob_count.batch_part_count += 1;
492                    blob_count.batch_part_bytes += usize::cast_from(metadata.size_in_bytes);
493                }
494                Ok((shard, PartialBlobKey::Rollup(_, _))) => {
495                    let blob_count = blob_counts.entry(shard).or_insert_with(BlobCounts::default);
496                    blob_count.rollup_count += 1;
497                    blob_count.rollup_bytes += usize::cast_from(metadata.size_in_bytes);
498                }
499                Err(err) => {
500                    eprintln!("error parsing blob: {}", err);
501                }
502            }
503        })
504        .await?;
505
506    Ok(blob_counts)
507}
508
509/// Rummages through S3 to find the latest rollup for each shard, then calculates summary stats.
510pub async fn shard_stats(blob_uri: &SensitiveUrl) -> anyhow::Result<()> {
511    let cfg = PersistConfig::new_default_configs(&READ_ALL_BUILD_INFO, SYSTEM_TIME.clone());
512    let metrics = Arc::new(Metrics::new(&cfg, &MetricsRegistry::new()));
513    let blob = make_blob(&cfg, blob_uri, NO_COMMIT, metrics).await?;
514
515    // Collect the latest rollup for every shard with the given blob_uri
516    let mut rollup_keys = BTreeMap::new();
517    blob.list_keys_and_metadata(&BlobKeyPrefix::All.to_string(), &mut |metadata| {
518        if let Ok((shard, PartialBlobKey::Rollup(seqno, rollup_id))) =
519            BlobKey::parse_ids(metadata.key)
520        {
521            let key = (seqno, rollup_id);
522            match rollup_keys.entry(shard) {
523                Entry::Vacant(v) => {
524                    v.insert(key);
525                }
526                Entry::Occupied(o) => {
527                    if key.0 > o.get().0 {
528                        *o.into_mut() = key;
529                    }
530                }
531            };
532        }
533    })
534    .await?;
535
536    println!(
537        "shard,bytes,parts,runs,batches,empty_batches,longest_run,byte_width,leased_readers,critical_readers,writers"
538    );
539    for (shard, (seqno, rollup)) in rollup_keys {
540        let rollup_key = PartialRollupKey::new(seqno, &rollup).complete(&shard);
541        // Basic stats about the trace.
542        let mut bytes = 0;
543        let mut parts = 0;
544        let mut runs = 0;
545        let mut batches = 0;
546        let mut empty_batches = 0;
547        let mut longest_run = 0;
548        // The sum of the largest part in every run, measured in bytes.
549        // A rough proxy for the worst-case amount of data we'd need to fetch to consolidate
550        // down a single key-value pair.
551        let mut byte_width = 0;
552
553        let Some(rollup) = blob.get(&rollup_key).await? else {
554            // Deleted between listing and now?
555            continue;
556        };
557
558        let state: State<u64> =
559            UntypedState::decode(&cfg.build_version, rollup).check_ts_codec(&shard)?;
560
561        let leased_readers = state.collections.leased_readers.len();
562        let critical_readers = state.collections.critical_readers.len();
563        let writers = state.collections.writers.len();
564
565        state.collections.trace.map_batches(|b| {
566            bytes += b.encoded_size_bytes();
567            parts += b.part_count();
568            batches += 1;
569            if b.is_empty() {
570                empty_batches += 1;
571            }
572            for (_meta, run) in b.runs() {
573                let largest_part = run.iter().map(|p| p.max_part_bytes()).max().unwrap_or(0);
574                runs += 1;
575                longest_run = longest_run.max(run.len());
576                byte_width += largest_part;
577            }
578        });
579        println!(
580            "{shard},{bytes},{parts},{runs},{batches},{empty_batches},{longest_run},{byte_width},{leased_readers},{critical_readers},{writers}"
581        );
582    }
583
584    Ok(())
585}
586
587#[derive(Debug, Default, serde::Serialize)]
588struct UnreferencedBlobs {
589    batch_parts: BTreeSet<PartialBatchKey>,
590    rollups: BTreeSet<PartialRollupKey>,
591}
592
593/// Fetches the unreferenced blobs for given environment
594pub async fn unreferenced_blobs(args: &StateArgs) -> Result<impl serde::Serialize, anyhow::Error> {
595    let shard_id = args.shard_id();
596    let state_versions = args.open().await?;
597
598    let mut all_parts = vec![];
599    let mut all_rollups = vec![];
600    let () = state_versions
601        .blob
602        .list_keys_and_metadata(
603            &BlobKeyPrefix::Shard(&shard_id).to_string(),
604            &mut |metadata| match BlobKey::parse_ids(metadata.key) {
605                Ok((_, PartialBlobKey::Batch(writer, part))) => {
606                    all_parts.push((PartialBatchKey::new(&writer, &part), writer.clone()));
607                }
608                Ok((_, PartialBlobKey::Rollup(seqno, rollup))) => {
609                    all_rollups.push(PartialRollupKey::new(seqno, &rollup));
610                }
611                Err(_) => {}
612            },
613        )
614        .await?;
615
616    let mut state_iter = state_versions
617        .fetch_all_live_states::<u64>(shard_id)
618        .await
619        .expect("requested shard should exist")
620        .check_ts_codec()?;
621
622    let mut known_parts = BTreeSet::new();
623    let mut known_rollups = BTreeSet::new();
624    while let Some(v) = state_iter.next(|_| {}) {
625        for batch in v.collections.trace.batches() {
626            // TODO: this may end up refetching externally-stored runs once per batch...
627            // but if we have enough parts for this to be a problem, we may need to track a more
628            // efficient state representation.
629            let mut parts =
630                pin!(batch.part_stream(shard_id, &*state_versions.blob, &*state_versions.metrics));
631            while let Some(batch_part) = parts.next().await {
632                match &*batch_part? {
633                    BatchPart::Hollow(x) => known_parts.insert(x.key.clone()),
634                    BatchPart::Inline { .. } => continue,
635                };
636            }
637        }
638        for rollup in v.collections.rollups.values() {
639            known_rollups.insert(rollup.key.clone());
640        }
641    }
642
643    let mut unreferenced_blobs = UnreferencedBlobs::default();
644    // In the future, this is likely to include a "grace period" so recent but non-current
645    // versions are also considered live
646    let minimum_version = WriterKey::for_version(&state_versions.cfg.build_version);
647    for (part, writer) in all_parts {
648        let is_unreferenced = writer < minimum_version;
649        if is_unreferenced && !known_parts.contains(&part) {
650            unreferenced_blobs.batch_parts.insert(part);
651        }
652    }
653    for rollup in all_rollups {
654        if !known_rollups.contains(&rollup) {
655            unreferenced_blobs.rollups.insert(rollup);
656        }
657    }
658
659    Ok(unreferenced_blobs)
660}
661
662/// Returns information about blob usage for a shard
663pub async fn blob_usage(args: &StateArgs) -> Result<(), anyhow::Error> {
664    let shard_id = if args.shard_id.is_empty() {
665        None
666    } else {
667        Some(args.shard_id())
668    };
669    let cfg = PersistConfig::new_default_configs(&READ_ALL_BUILD_INFO, SYSTEM_TIME.clone());
670    let metrics_registry = MetricsRegistry::new();
671    let metrics = Arc::new(Metrics::new(&cfg, &metrics_registry));
672    let consensus =
673        make_consensus(&cfg, &args.consensus_uri, NO_COMMIT, Arc::clone(&metrics)).await?;
674    let blob = make_blob(&cfg, &args.blob_uri, NO_COMMIT, Arc::clone(&metrics)).await?;
675    let isolated_runtime = Arc::new(IsolatedRuntime::new(&metrics_registry, None));
676    let state_cache = Arc::new(StateCache::new(
677        &cfg,
678        Arc::clone(&metrics),
679        Arc::new(NoopPubSubSender),
680    ));
681    let usage = StorageUsageClient::open(PersistClient::new(
682        cfg,
683        blob,
684        consensus,
685        metrics,
686        isolated_runtime,
687        state_cache,
688        Arc::new(NoopPubSubSender),
689    )?);
690
691    if let Some(shard_id) = shard_id {
692        let usage = usage.shard_usage_audit(shard_id).await;
693        println!("{}\n{}", shard_id, usage);
694    } else {
695        let usage = usage.shards_usage_audit().await;
696        let mut by_shard = usage.by_shard.iter().collect::<Vec<_>>();
697        by_shard.sort_by_key(|(_, x)| x.total_bytes());
698        by_shard.reverse();
699        for (shard_id, usage) in by_shard {
700            println!("{}\n{}\n", shard_id, usage);
701        }
702        println!("unattributable: {}", HumanBytes(usage.unattributable_bytes));
703    }
704
705    Ok(())
706}
707
708struct LiveShard {
709    diffs: Vec<VersionedData>,
710    earliest: UntypedState<u64>,
711    current: State<u64>,
712}
713
714/// What a load of shard state found. The loads of [StateVersions] retry a
715/// missing rollup indefinitely, which would hide data loss.
716enum Loaded<T> {
717    Uninitialized,
718    Live(T),
719    /// A rollup referenced by the head of consensus is absent from blob.
720    MissingRollup(PartialRollupKey),
721}
722
723/// Reconstructs the endpoints of a single consensus scan.
724async fn load_live_shard(
725    versions: &StateVersions,
726    shard_id: ShardId,
727) -> Result<Loaded<LiveShard>, anyhow::Error> {
728    let diffs = versions.fetch_all_live_diffs(&shard_id).await;
729    let (Some(first), Some(last)) = (diffs.first(), diffs.last()) else {
730        return Ok(Loaded::Uninitialized);
731    };
732    let earliest_seqno = first.seqno;
733    let latest_rollup_key =
734        StateDiff::<u64>::decode(&versions.cfg.build_version, last.data.clone()).latest_rollup_key;
735    let Some(mut current) = versions
736        .fetch_rollup_at_key::<u64>(&shard_id, &latest_rollup_key)
737        .await
738    else {
739        return Ok(Loaded::MissingRollup(latest_rollup_key));
740    };
741    current.apply_encoded_diffs(&versions.cfg, &versions.metrics, &diffs);
742    // GC removes a rollup from state only after truncating consensus past it,
743    // so a consistent scan always finds the earliest live diff's rollup here.
744    let earliest_rollup_key = current
745        .rollups()
746        .get(&earliest_seqno)
747        .map(|rollup| rollup.key.clone())
748        .ok_or_else(|| {
749            anyhow!("head of {shard_id} has no rollup for the earliest live diff {earliest_seqno}")
750        })?;
751    let Some(earliest) = versions
752        .fetch_rollup_at_key::<u64>(&shard_id, &earliest_rollup_key)
753        .await
754    else {
755        return Ok(Loaded::MissingRollup(earliest_rollup_key));
756    };
757    Ok(Loaded::Live(LiveShard {
758        diffs,
759        earliest,
760        current: current.check_ts_codec(&shard_id)?,
761    }))
762}
763
764/// Reconstructs the head of consensus from the diffs since its latest rollup.
765async fn load_head(
766    versions: &StateVersions,
767    shard_id: ShardId,
768) -> Result<Loaded<State<u64>>, anyhow::Error> {
769    let diffs = versions.fetch_recent_live_diffs::<u64>(&shard_id).await.0;
770    let Some(last) = diffs.last() else {
771        return Ok(Loaded::Uninitialized);
772    };
773    let key =
774        StateDiff::<u64>::decode(&versions.cfg.build_version, last.data.clone()).latest_rollup_key;
775    let Some(mut head) = versions.fetch_rollup_at_key::<u64>(&shard_id, &key).await else {
776        return Ok(Loaded::MissingRollup(key));
777    };
778    head.apply_encoded_diffs(&versions.cfg, &versions.metrics, &diffs);
779    Ok(Loaded::Live(head.check_ts_codec(&shard_id)?))
780}
781
782/// Rollup keys are never re-added. A key still referenced and missing on a
783/// second load could not have been deleted by a concurrent GC.
784async fn confirmed<T, F, Fut>(shard_id: ShardId, mut load: F) -> Result<Loaded<T>, anyhow::Error>
785where
786    F: FnMut() -> Fut,
787    Fut: Future<Output = Result<Loaded<T>, anyhow::Error>>,
788{
789    let mut previous_missing = None;
790    for _ in 0..5 {
791        match load().await? {
792            Loaded::MissingRollup(key) => {
793                if previous_missing.as_ref() == Some(&key) {
794                    return Ok(Loaded::MissingRollup(key));
795                }
796                previous_missing = Some(key);
797                tokio::time::sleep(std::time::Duration::from_secs(1)).await;
798            }
799            loaded => return Ok(loaded),
800        }
801    }
802    Err(anyhow!(
803        "rollups referenced by the head of {shard_id} disappeared on repeated loads"
804    ))
805}
806
807#[derive(Debug, Default, serde::Serialize)]
808struct BlobAuditReport {
809    since: Option<Vec<u64>>,
810    missing: Vec<String>,
811}
812
813fn add_part(
814    shard_id: ShardId,
815    part: &RunPart<u64>,
816    keys: &mut BTreeSet<String>,
817    runs: &mut Vec<HollowRunRef<u64>>,
818) {
819    match part {
820        RunPart::Single(BatchPart::Hollow(part)) => {
821            keys.insert(part.key.complete(&shard_id).to_string());
822        }
823        RunPart::Single(BatchPart::Inline { .. }) => {}
824        RunPart::Many(run) => {
825            if keys.insert(run.key.complete(&shard_id).to_string()) {
826                runs.push(run.clone());
827            }
828        }
829    }
830}
831
832/// The key of every blob that a state version at or above seqno_since
833/// references, including the parts of hollow runs.
834async fn referenced_blobs(
835    versions: &StateVersions,
836    shard_id: ShardId,
837    live: LiveShard,
838) -> Result<BTreeSet<String>, anyhow::Error> {
839    let seqno_since = live.current.seqno_since();
840    let mut keys = BTreeSet::new();
841    let mut runs = Vec::new();
842    let mut add = |blob: HollowBlobRef<'_, u64>| match blob {
843        HollowBlobRef::Batch(batch) => {
844            for part in &batch.parts {
845                add_part(shard_id, part, &mut keys, &mut runs);
846            }
847        }
848        HollowBlobRef::Rollup(rollup) => {
849            keys.insert(rollup.key.complete(&shard_id).to_string());
850        }
851    };
852    let mut states = UntypedStateVersionsIter::new(
853        shard_id,
854        versions.cfg.clone(),
855        Arc::clone(&versions.metrics),
856        live.earliest,
857        live.diffs,
858    )
859    .check_ts_codec()?;
860    // NOTE: Visiting every part of every version would multiply the work by
861    // the number of versions that a long read hold retains. Like GC, this
862    // takes the first version in full and then only what each diff adds.
863    let mut seeded = false;
864    while let Some(state) = states.next(|diff| {
865        if seeded {
866            diff.referenced_blobs().for_each(&mut add);
867        }
868    }) {
869        if !seeded && state.seqno >= seqno_since {
870            state.blobs().for_each(&mut add);
871            seeded = true;
872        }
873    }
874    // A missing run is reported by its own key.
875    while let Some(run) = runs.pop() {
876        if let Some(run) = run.get(shard_id, &*versions.blob, &versions.metrics).await {
877            for part in &run.parts {
878                add_part(shard_id, part, &mut keys, &mut runs);
879            }
880        }
881    }
882    Ok(keys)
883}
884
885/// Checks every batch part, hollow run and rollup referenced at or above
886/// seqno_since without taking a read hold that would prevent GC.
887async fn audit_blobs(
888    versions: &StateVersions,
889    shard_id: ShardId,
890) -> Result<BlobAuditReport, anyhow::Error> {
891    let mut report = BlobAuditReport::default();
892    let live = match confirmed(shard_id, || load_live_shard(versions, shard_id)).await? {
893        Loaded::Uninitialized => return Ok(report),
894        Loaded::MissingRollup(key) => {
895            report.missing.push(key.complete(&shard_id).to_string());
896            return Ok(report);
897        }
898        Loaded::Live(live) => live,
899    };
900    report.since = Some(live.current.collections.trace.since().elements().to_vec());
901    let mut unlisted = referenced_blobs(versions, shard_id, live).await?;
902    // Listing avoids fetching the contents of every referenced part.
903    versions
904        .blob
905        .list_keys_and_metadata(&BlobKeyPrefix::Shard(&shard_id).to_string(), &mut |m| {
906            unlisted.remove(m.key);
907        })
908        .await?;
909    let mut absent = Vec::new();
910    for key in unlisted {
911        if versions.blob.get(&key).await?.is_none() {
912            absent.push(key);
913        }
914    }
915    if absent.is_empty() {
916        return Ok(report);
917    }
918    // GC may have released every version that referenced a key between the
919    // scan and the GETs. Keys are never referenced again once released, so a
920    // key that a fresh scan still references is lost.
921    let referenced = match confirmed(shard_id, || load_live_shard(versions, shard_id)).await? {
922        Loaded::Live(fresh) => referenced_blobs(versions, shard_id, fresh).await?,
923        Loaded::MissingRollup(key) => {
924            report.missing.push(key.complete(&shard_id).to_string());
925            return Ok(report);
926        }
927        Loaded::Uninitialized => {
928            return Err(anyhow!(
929                "{shard_id} lost all of its live diffs during the audit"
930            ));
931        }
932    };
933    report.missing = absent
934        .into_iter()
935        .filter(|key| referenced.contains(key))
936        .collect();
937    Ok(report)
938}
939
940#[derive(Debug, serde::Serialize)]
941struct FrontierAuditReport {
942    since: Vec<u64>,
943    upper: Vec<u64>,
944    updates: usize,
945}
946
947/// Reads the controller's critical since (or the shard since if unregistered)
948/// and the export bootstrap state without taking a read hold.
949async fn audit_frontiers(
950    versions: &StateVersions,
951    shard_id: ShardId,
952) -> anyhow::Result<Option<FrontierAuditReport>> {
953    let state = match confirmed(shard_id, || load_head(versions, shard_id)).await? {
954        Loaded::Uninitialized => return Ok(None),
955        Loaded::MissingRollup(key) => {
956            return Err(anyhow!("{shard_id} references missing rollup {key}"));
957        }
958        Loaded::Live(state) => state,
959    };
960    let trace = &state.collections.trace;
961    if state.collections.is_tombstone() {
962        return Ok(None);
963    }
964    let since = state
965        .collections
966        .critical_readers
967        .get(&PersistClient::CONTROLLER_CRITICAL_SINCE)
968        .map_or_else(|| trace.since(), |reader| &reader.since);
969    Ok(Some(FrontierAuditReport {
970        since: since.elements().to_vec(),
971        upper: trace.upper().elements().to_vec(),
972        updates: trace.batches().map(|b| b.len).sum(),
973    }))
974}
975
976/// The following is a very terrible hack that no one should draw inspiration from. Currently State
977/// is generic over <K, V, T, D>, with KVD being represented as phantom data for type safety and to
978/// detect persisted codec mismatches. However, reading persisted States does not require actually
979/// decoding KVD, so we only need their codec _names_ to match, not the full types. For the purposes
980/// of `persistcli inspect`, which only wants to read the persistent data, we create new types that
981/// return static Codec names, and rebind the names if/when we get a CodecMismatch, so we can convince
982/// the type system and our safety checks that we really can read the data.
983
984#[derive(Default, Debug, PartialEq, Eq)]
985pub(crate) struct K;
986#[derive(Default, Debug, PartialEq, Eq)]
987pub(crate) struct V;
988
989pub(crate) static KVTD_CODECS: Mutex<(String, String, String, String, Option<CodecConcreteType>)> =
990    Mutex::new((
991        String::new(),
992        String::new(),
993        String::new(),
994        String::new(),
995        None,
996    ));
997
998impl Codec for K {
999    type Storage = ();
1000    type Schema = TodoSchema<K>;
1001
1002    fn codec_name() -> String {
1003        KVTD_CODECS.lock().expect("lockable").0.clone()
1004    }
1005
1006    fn encode<B>(&self, _buf: &mut B)
1007    where
1008        B: BufMut,
1009    {
1010    }
1011
1012    fn decode(_buf: &[u8], _schema: &TodoSchema<K>) -> Result<Self, String> {
1013        Ok(Self)
1014    }
1015
1016    fn encode_schema(_schema: &Self::Schema) -> Bytes {
1017        Bytes::new()
1018    }
1019
1020    fn decode_schema(buf: &Bytes) -> Self::Schema {
1021        assert_eq!(*buf, Bytes::new());
1022        TodoSchema::default()
1023    }
1024}
1025
1026impl Codec for V {
1027    type Storage = ();
1028    type Schema = TodoSchema<V>;
1029
1030    fn codec_name() -> String {
1031        KVTD_CODECS.lock().expect("lockable").1.clone()
1032    }
1033
1034    fn encode<B>(&self, _buf: &mut B)
1035    where
1036        B: BufMut,
1037    {
1038    }
1039
1040    fn decode(_buf: &[u8], _schema: &TodoSchema<V>) -> Result<Self, String> {
1041        Ok(Self)
1042    }
1043
1044    fn encode_schema(_schema: &Self::Schema) -> Bytes {
1045        Bytes::new()
1046    }
1047
1048    fn decode_schema(buf: &Bytes) -> Self::Schema {
1049        assert_eq!(*buf, Bytes::new());
1050        TodoSchema::default()
1051    }
1052}
1053
1054pub(crate) static FAKE_OPAQUE_CODEC: Mutex<String> = Mutex::new(String::new());
1055
1056#[derive(Debug, Clone, PartialEq, Default)]
1057pub(crate) struct O([u8; 8]);
1058
1059impl Codec64 for O {
1060    fn codec_name() -> String {
1061        FAKE_OPAQUE_CODEC.lock().expect("lockable").clone()
1062    }
1063
1064    fn encode(&self) -> [u8; 8] {
1065        self.0
1066    }
1067
1068    fn decode(buf: [u8; 8]) -> Self {
1069        Self(buf)
1070    }
1071}
1072
1073#[cfg(test)]
1074mod tests {
1075    use mz_dyncfg::ConfigUpdates;
1076    use timely::progress::Antichain;
1077
1078    use crate::Diagnostics;
1079    use crate::batch::{INLINE_WRITES_SINGLE_MAX_BYTES, INLINE_WRITES_TOTAL_MAX_BYTES};
1080    use crate::critical::Opaque;
1081    use crate::tests::new_test_client;
1082
1083    use super::*;
1084
1085    async fn shard_with_parts(config: &ConfigUpdates) -> (PersistClient, ShardId) {
1086        let client = new_test_client(config).await;
1087        client.cfg.set_config(&INLINE_WRITES_SINGLE_MAX_BYTES, 0);
1088        client.cfg.set_config(&INLINE_WRITES_TOTAL_MAX_BYTES, 0);
1089        let shard_id = ShardId::new();
1090        let (mut write, _read) = client
1091            .expect_open::<String, String, u64, i64>(shard_id)
1092            .await;
1093        write
1094            .expect_compare_and_append(&[(("a".into(), "1".into()), 0, 1)], 0, 1)
1095            .await;
1096        (client, shard_id)
1097    }
1098
1099    fn state_versions(client: &PersistClient) -> StateVersions {
1100        StateVersions::new(
1101            client.cfg.clone(),
1102            Arc::clone(&client.consensus),
1103            Arc::clone(&client.blob),
1104            Arc::clone(&client.metrics),
1105        )
1106    }
1107
1108    async fn shard_keys(
1109        client: &PersistClient,
1110        shard_id: ShardId,
1111    ) -> Vec<(String, PartialBlobKey)> {
1112        let mut keys = Vec::new();
1113        client
1114            .blob
1115            .list_keys_and_metadata(&BlobKeyPrefix::Shard(&shard_id).to_string(), &mut |m| {
1116                let (_, partial) = BlobKey::parse_ids(m.key).expect("valid key");
1117                keys.push((m.key.to_owned(), partial));
1118            })
1119            .await
1120            .expect("listable");
1121        keys
1122    }
1123
1124    #[mz_persist_proc::test(tokio::test)]
1125    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1126    async fn audit_blobs_reports_deleted_blobs(dyncfgs: ConfigUpdates) {
1127        let (client, shard_id) = shard_with_parts(&dyncfgs).await;
1128        let versions = state_versions(&client);
1129
1130        let report = audit_blobs(&versions, shard_id)
1131            .await
1132            .expect("audit succeeds");
1133        assert!(report.since.is_some());
1134        assert!(report.missing.is_empty(), "{report:?}");
1135
1136        let mut deleted = BTreeSet::new();
1137        for (key, partial) in shard_keys(&client, shard_id).await {
1138            if let PartialBlobKey::Batch(..) = partial {
1139                client.blob.delete(&key).await.expect("deletable");
1140                deleted.insert(key);
1141            }
1142        }
1143        let report = audit_blobs(&versions, shard_id)
1144            .await
1145            .expect("audit succeeds");
1146        assert!(!report.missing.is_empty(), "{report:?}");
1147        for missing in &report.missing {
1148            assert!(deleted.contains(missing), "{missing:?}");
1149        }
1150    }
1151
1152    #[mz_persist_proc::test(tokio::test)]
1153    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1154    async fn audits_report_deleted_head_rollup(dyncfgs: ConfigUpdates) {
1155        let (client, shard_id) = shard_with_parts(&dyncfgs).await;
1156        let mut deleted = BTreeSet::new();
1157        for (key, partial) in shard_keys(&client, shard_id).await {
1158            if let PartialBlobKey::Rollup(..) = partial {
1159                client.blob.delete(&key).await.expect("deletable");
1160                deleted.insert(key);
1161            }
1162        }
1163
1164        let report = audit_blobs(&state_versions(&client), shard_id)
1165            .await
1166            .expect("audit succeeds");
1167        assert_eq!(report.missing.len(), 1, "{report:?}");
1168        assert!(deleted.contains(&report.missing[0]));
1169        assert!(
1170            audit_frontiers(&state_versions(&client), shard_id)
1171                .await
1172                .is_err()
1173        );
1174    }
1175
1176    #[mz_persist_proc::test(tokio::test)]
1177    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1178    async fn audit_frontiers_reports_reader_sinces(dyncfgs: ConfigUpdates) {
1179        let client = new_test_client(&dyncfgs).await;
1180        let shard_id = ShardId::new();
1181        let (mut write, read) = client
1182            .expect_open::<String, String, u64, i64>(shard_id)
1183            .await;
1184        write
1185            .expect_compare_and_append(&[(("a".into(), "1".into()), 0, 1)], 0, 3)
1186            .await;
1187        let mut critical = client
1188            .open_critical_since::<String, String, u64, i64>(
1189                shard_id,
1190                PersistClient::CONTROLLER_CRITICAL_SINCE,
1191                Opaque::encode(&0i64),
1192                Diagnostics::for_tests(),
1193            )
1194            .await
1195            .expect("codec match");
1196        critical
1197            .compare_and_downgrade_since(
1198                &Opaque::encode(&0i64),
1199                (&Opaque::encode(&0i64), &Antichain::from_elem(2)),
1200            )
1201            .await
1202            .expect("opaque matches");
1203
1204        let report = audit_frontiers(&state_versions(&client), shard_id)
1205            .await
1206            .expect("audit succeeds");
1207        let report = report.expect("initialized shard");
1208        assert_eq!(report.upper, vec![3]);
1209        assert_eq!(report.updates, 1);
1210        // The leased reader still holds the shard since at zero.
1211        assert_eq!(report.since, vec![2]);
1212        drop(read);
1213    }
1214
1215    #[mz_persist_proc::test(tokio::test)]
1216    #[cfg_attr(miri, ignore)] // unsupported operation: returning ready events from epoll_wait is not yet implemented
1217    async fn audits_report_uninitialized_shard(dyncfgs: ConfigUpdates) {
1218        let client = new_test_client(&dyncfgs).await;
1219        let versions = state_versions(&client);
1220        let shard_id = ShardId::new();
1221        assert!(
1222            audit_blobs(&versions, shard_id)
1223                .await
1224                .unwrap()
1225                .since
1226                .is_none()
1227        );
1228        assert!(
1229            audit_frontiers(&versions, shard_id)
1230                .await
1231                .unwrap()
1232                .is_none()
1233        );
1234    }
1235}