Skip to main content

gtars_refget/store/
verify.rs

1//! Store integrity verification.
2//!
3//! Streams every stored sequence through the normal decode path
4//! ([`ReadonlyRefgetStore::stream_sequence`]), recomputes its sha512t24u (and
5//! md5, when one is stored) from the decoded bytes, and reports every
6//! sequence whose bytes do not hash to its stored digest.
7//!
8//! This is a generic "bytes vs digest" check: it does not special-case any
9//! alphabet or encoding. A resident `Full` record is checked from its
10//! in-memory bytes; a `Stub` is checked from disk (or, for a remote store,
11//! from the remote source -- which streams every byte over HTTP; this works
12//! but is not the intended primary use case). A freshly opened local store
13//! holds only stubs, so opening a store and calling verify checks the
14//! on-disk bytes, which is what users generally want.
15
16use super::*;
17use super::readonly::ReadonlyRefgetStore;
18
19use std::collections::BTreeMap;
20use std::sync::atomic::{AtomicUsize, Ordering};
21
22use anyhow::{anyhow, Result};
23use serde::Serialize;
24
25use crate::digest::{AlphabetType, SequenceHasher};
26use crate::hashkeyable::{key_to_digest_string, HashKeyable};
27
28/// How often (in verified sequences) to print a progress line, and the
29/// threshold above which a progress line is printed at all.
30const PROGRESS_INTERVAL: usize = 10_000;
31
32/// Read buffer size used while streaming a sequence for verification.
33const VERIFY_READ_BUF_SIZE: usize = 1024 * 1024;
34
35// =========================================================================
36// Options
37// =========================================================================
38
39/// Options controlling [`ReadonlyRefgetStore::verify_sequences`].
40#[derive(Debug, Clone)]
41pub struct VerifyOptions {
42    /// Worker threads. `0` = auto ([`std::thread::available_parallelism`]),
43    /// `1` = serial.
44    pub jobs: usize,
45    /// Also recompute md5 and compare when the stored md5 is non-empty.
46    pub check_md5: bool,
47}
48
49impl Default for VerifyOptions {
50    fn default() -> Self {
51        Self {
52            jobs: 0,
53            check_md5: true,
54        }
55    }
56}
57
58// =========================================================================
59// Report types
60// =========================================================================
61
62/// Why one sequence failed verification.
63///
64/// Precedence when a sequence has several problems (only one failure record
65/// is ever produced per sequence): [`Self::ReadError`] >
66/// [`Self::LengthMismatch`] > [`Self::DigestMismatch`] > [`Self::Md5Mismatch`].
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
68pub enum VerifyFailureKind {
69    /// Decoded bytes hash to a different sha512t24u than the stored key.
70    DigestMismatch,
71    /// sha512t24u matches but the stored md5 does not.
72    Md5Mismatch,
73    /// Stream ended with a different number of bases than metadata.length.
74    LengthMismatch,
75    /// The sequence could not be opened or read (missing/short file, decompress error).
76    ReadError,
77}
78
79impl VerifyFailureKind {
80    /// Stable lowercase-with-underscores name, used by the CLI and language bindings.
81    pub fn as_str(&self) -> &'static str {
82        match self {
83            VerifyFailureKind::DigestMismatch => "digest_mismatch",
84            VerifyFailureKind::Md5Mismatch => "md5_mismatch",
85            VerifyFailureKind::LengthMismatch => "length_mismatch",
86            VerifyFailureKind::ReadError => "read_error",
87        }
88    }
89}
90
91impl std::fmt::Display for VerifyFailureKind {
92    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93        write!(f, "{}", self.as_str())
94    }
95}
96
97/// One sequence that failed verification.
98#[derive(Debug, Clone, Serialize)]
99pub struct VerifyFailure {
100    /// Stored sha512t24u.
101    pub digest: String,
102    /// `metadata.name`.
103    pub name: String,
104    pub alphabet: AlphabetType,
105    /// `metadata.length`.
106    pub length: usize,
107    pub kind: VerifyFailureKind,
108    pub bases_read: u64,
109    /// `None` for [`VerifyFailureKind::ReadError`] when no bytes were hashed.
110    pub computed_sha512t24u: Option<String>,
111    pub stored_md5: String,
112    /// `None` when md5 was not checked, or for a [`VerifyFailureKind::ReadError`].
113    pub computed_md5: Option<String>,
114    /// Set for [`VerifyFailureKind::ReadError`].
115    pub error: Option<String>,
116}
117
118/// Per-alphabet checked/failed counts within a [`VerifyReport`].
119#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
120pub struct AlphabetVerifyCounts {
121    pub checked: usize,
122    pub failed: usize,
123}
124
125/// Result of [`ReadonlyRefgetStore::verify_sequences`] /
126/// [`crate::store::RefgetStore::verify_collection`].
127#[derive(Debug, Clone, Default, Serialize)]
128pub struct VerifyReport {
129    pub n_checked: usize,
130    pub n_ok: usize,
131    pub n_failed: usize,
132    /// Keyed by the alphabet's string form (e.g. "dna2bit", "dnaio", "protein", "ASCII").
133    pub by_alphabet: BTreeMap<String, AlphabetVerifyCounts>,
134    /// Sorted by digest so output does not depend on thread scheduling.
135    pub failures: Vec<VerifyFailure>,
136}
137
138impl VerifyReport {
139    /// True when no sequence failed verification.
140    pub fn is_ok(&self) -> bool {
141        self.n_failed == 0
142    }
143}
144
145// =========================================================================
146// Verification
147// =========================================================================
148
149impl ReadonlyRefgetStore {
150    /// Verify one sequence: stream its decoded bytes, recompute digests, and
151    /// compare against the stored metadata.
152    ///
153    /// Returns `Ok(None)` when the sequence checks out, `Ok(Some(failure))`
154    /// when it does not (including when the sequence could not be read --
155    /// this is reported as a [`VerifyFailureKind::ReadError`], not an `Err`).
156    /// Returns `Err` only when `digest` does not resolve to a known sequence.
157    pub fn verify_sequence(&self, digest: &str, check_md5: bool) -> Result<Option<VerifyFailure>> {
158        // Resolve the digest the same way `stream_sequence` does (accept md5).
159        let meta = self
160            .get_sequence_metadata(digest)
161            .ok_or_else(|| anyhow!("Sequence not found: {}", digest))?;
162
163        let want_md5 = check_md5 && !meta.md5.is_empty();
164
165        let mut reader = match self.stream_sequence(&meta.sha512t24u, None, None) {
166            Ok(r) => r,
167            Err(e) => {
168                return Ok(Some(VerifyFailure {
169                    digest: meta.sha512t24u.clone(),
170                    name: meta.name.clone(),
171                    alphabet: meta.alphabet,
172                    length: meta.length,
173                    kind: VerifyFailureKind::ReadError,
174                    bases_read: 0,
175                    computed_sha512t24u: None,
176                    stored_md5: meta.md5.clone(),
177                    computed_md5: None,
178                    error: Some(e.to_string()),
179                }));
180            }
181        };
182
183        let mut hasher = SequenceHasher::new(want_md5);
184        let mut buf = vec![0u8; VERIFY_READ_BUF_SIZE];
185        let mut bases_read: u64 = 0;
186        loop {
187            match reader.read(&mut buf) {
188                Ok(0) => break,
189                Ok(n) => {
190                    hasher.update(&buf[..n]);
191                    bases_read += n as u64;
192                }
193                Err(e) => {
194                    let (computed_sha512t24u, computed_md5, _) = hasher.finalize();
195                    return Ok(Some(VerifyFailure {
196                        digest: meta.sha512t24u.clone(),
197                        name: meta.name.clone(),
198                        alphabet: meta.alphabet,
199                        length: meta.length,
200                        kind: VerifyFailureKind::ReadError,
201                        bases_read,
202                        computed_sha512t24u: Some(computed_sha512t24u),
203                        stored_md5: meta.md5.clone(),
204                        computed_md5,
205                        error: Some(e.to_string()),
206                    }));
207                }
208            }
209        }
210
211        let (computed_sha512t24u, computed_md5, hashed_len) = hasher.finalize();
212
213        if hashed_len != meta.length as u64 {
214            return Ok(Some(VerifyFailure {
215                digest: meta.sha512t24u.clone(),
216                name: meta.name.clone(),
217                alphabet: meta.alphabet,
218                length: meta.length,
219                kind: VerifyFailureKind::LengthMismatch,
220                bases_read: hashed_len,
221                computed_sha512t24u: Some(computed_sha512t24u),
222                stored_md5: meta.md5.clone(),
223                computed_md5,
224                error: None,
225            }));
226        }
227
228        if computed_sha512t24u != meta.sha512t24u {
229            return Ok(Some(VerifyFailure {
230                digest: meta.sha512t24u.clone(),
231                name: meta.name.clone(),
232                alphabet: meta.alphabet,
233                length: meta.length,
234                kind: VerifyFailureKind::DigestMismatch,
235                bases_read: hashed_len,
236                computed_sha512t24u: Some(computed_sha512t24u),
237                stored_md5: meta.md5.clone(),
238                computed_md5,
239                error: None,
240            }));
241        }
242
243        if want_md5
244            && let Some(cm) = computed_md5.as_ref()
245            && *cm != meta.md5
246        {
247            return Ok(Some(VerifyFailure {
248                digest: meta.sha512t24u.clone(),
249                name: meta.name.clone(),
250                alphabet: meta.alphabet,
251                length: meta.length,
252                kind: VerifyFailureKind::Md5Mismatch,
253                bases_read: hashed_len,
254                computed_sha512t24u: Some(computed_sha512t24u),
255                stored_md5: meta.md5.clone(),
256                computed_md5,
257                error: None,
258            }));
259        }
260
261        Ok(None)
262    }
263
264    /// Verify many sequences (or, with `digests: None`, every sequence in the
265    /// store), in parallel when `opts.jobs != 1`.
266    ///
267    /// `digests` entries must already be resolved sequence identifiers (a
268    /// sha512t24u or md5 digest, with no `SQ.` prefix); an unknown digest
269    /// makes the whole call return `Err` naming every unknown digest, before
270    /// any verification work happens.
271    pub fn verify_sequences(
272        &self,
273        digests: Option<&[String]>,
274        opts: &VerifyOptions,
275    ) -> Result<VerifyReport> {
276        // `stream_sequence` is called from worker threads below, so the store
277        // must be `Sync`. The server use case already needs this; fail loudly
278        // at compile time (not with a confusing runtime error) if it regresses.
279        fn _assert_sync<T: Sync>() {}
280        _assert_sync::<ReadonlyRefgetStore>();
281
282        // 1. Build the (deduped, sorted) work list of canonical sequence keys.
283        let mut work: Vec<DigestKey> = match digests {
284            None => self.sequence_digests().collect(),
285            Some(requested) => {
286                let mut keys = Vec::with_capacity(requested.len());
287                let mut unknown = Vec::new();
288                for d in requested {
289                    if let Some(v) = self.sequence_view(d) {
290                        keys.push(v.sha512t24u().to_key());
291                    } else {
292                        unknown.push(d.clone());
293                    }
294                }
295                if !unknown.is_empty() {
296                    return Err(anyhow!(
297                        "Unknown sequence digest(s): {}",
298                        unknown.join(", ")
299                    ));
300                }
301                keys
302            }
303        };
304        work.sort();
305        work.dedup();
306        let total = work.len();
307
308        // 2. Resolve worker count, same convention as FASTA import.
309        let jobs = match opts.jobs {
310            0 => std::thread::available_parallelism()
311                .map(|n| n.get())
312                .unwrap_or(1),
313            n => n,
314        };
315        let jobs = jobs.min(total.max(1)).max(1);
316
317        let quiet = self.is_quiet();
318        let done = AtomicUsize::new(0);
319        let failed_count = AtomicUsize::new(0);
320
321        let maybe_report_progress = |n: usize| {
322            if !quiet && n.is_multiple_of(PROGRESS_INTERVAL) {
323                eprintln!(
324                    "Verified {} / {} sequences ({} failures so far)",
325                    n,
326                    total,
327                    failed_count.load(Ordering::Relaxed)
328                );
329            }
330        };
331
332        let mut all_failures: Vec<VerifyFailure> = Vec::new();
333        let mut by_alphabet: BTreeMap<String, AlphabetVerifyCounts> = BTreeMap::new();
334
335        let record_one = |key: &DigestKey,
336                           failures: &mut Vec<VerifyFailure>,
337                           counts: &mut BTreeMap<String, AlphabetVerifyCounts>|
338         -> Result<()> {
339            let digest_str = key_to_digest_string(key);
340            let alphabet = self.sequence_view(&digest_str).map(|v| v.alphabet());
341            let outcome = self.verify_sequence(&digest_str, opts.check_md5)?;
342            if let Some(alphabet) = alphabet {
343                let entry = counts.entry(alphabet.to_string()).or_default();
344                entry.checked += 1;
345                if outcome.is_some() {
346                    entry.failed += 1;
347                }
348            }
349            if let Some(failure) = outcome {
350                failed_count.fetch_add(1, Ordering::Relaxed);
351                failures.push(failure);
352            }
353            let n = done.fetch_add(1, Ordering::Relaxed) + 1;
354            maybe_report_progress(n);
355            Ok(())
356        };
357
358        if jobs <= 1 {
359            for key in &work {
360                record_one(key, &mut all_failures, &mut by_alphabet)?;
361            }
362        } else {
363            let index = AtomicUsize::new(0);
364            let work_ref = &work;
365            std::thread::scope(|scope| -> Result<()> {
366                let mut handles = Vec::with_capacity(jobs);
367                for _ in 0..jobs {
368                    let index = &index;
369                    let record_one = &record_one;
370                    handles.push(scope.spawn(move || -> Result<(Vec<VerifyFailure>, BTreeMap<String, AlphabetVerifyCounts>)> {
371                        let mut local_failures = Vec::new();
372                        let mut local_counts: BTreeMap<String, AlphabetVerifyCounts> = BTreeMap::new();
373                        loop {
374                            let i = index.fetch_add(1, Ordering::Relaxed);
375                            if i >= work_ref.len() {
376                                break;
377                            }
378                            record_one(&work_ref[i], &mut local_failures, &mut local_counts)?;
379                        }
380                        Ok((local_failures, local_counts))
381                    }));
382                }
383                for handle in handles {
384                    let (failures, counts) = handle
385                        .join()
386                        .map_err(|_| anyhow!("verify worker thread panicked"))??;
387                    all_failures.extend(failures);
388                    for (alphabet, c) in counts {
389                        let entry = by_alphabet.entry(alphabet).or_default();
390                        entry.checked += c.checked;
391                        entry.failed += c.failed;
392                    }
393                }
394                Ok(())
395            })?;
396        }
397
398        all_failures.sort_by(|a, b| a.digest.cmp(&b.digest));
399        let n_failed = all_failures.len();
400
401        if !quiet {
402            eprintln!(
403                "Verified {} / {} sequences: {} failures",
404                total, total, n_failed
405            );
406        }
407
408        Ok(VerifyReport {
409            n_checked: total,
410            n_ok: total - n_failed,
411            n_failed,
412            by_alphabet,
413            failures: all_failures,
414        })
415    }
416}