Skip to main content

supercov_engine/
coverage_index.rs

1//! Typed coverage columns stored in the immutable query-index container.
2//!
3//! This is not a serialized report. Records contain fixed-width values and
4//! checked references into an interned UTF-8 string table. New query surfaces
5//! add sections without forcing existing readers to parse unrelated data.
6
7use std::collections::{BTreeMap, BTreeSet, HashMap};
8
9use serde::Serialize;
10use supercov_contracts::COVERAGE_MODEL_SCHEMA_VERSION;
11
12use crate::{
13    coverage_analysis::{
14        CoverageCount, CoverageSummary, McdcVector, find_witnesses_for_conditions,
15    },
16    coverage_report::{
17        CoverageModel, CoverageReport, CoverageView, TransportStats, coverage_summary_for_tests,
18    },
19    interned::Id,
20    query_index::{QueryIndex, QueryIndexError, QueryIndexSection},
21};
22
23pub const SECTION_STRING_BYTES: u32 = 1;
24pub const SECTION_STRINGS: u32 = 2;
25pub const SECTION_STRING_RELATIONS: u32 = 3;
26pub const SECTION_VIEW_SUMMARIES: u32 = 10;
27pub const SECTION_FILE_GAPS: u32 = 11;
28pub const SECTION_DECISION_GAPS: u32 = 12;
29pub const SECTION_DIMENSIONS: u32 = 13;
30pub const SECTION_PROJECTIONS: u32 = 14;
31pub const SECTION_SCOPE_ENTRIES: u32 = 15;
32pub const SECTION_CONFIDENCE: u32 = 16;
33pub const SECTION_LINES: u32 = 17;
34pub const SECTION_TEST_SUMMARIES: u32 = 18;
35pub const SECTION_PHASE_SUMMARIES: u32 = 19;
36pub const SECTION_ANCHORS: u32 = 20;
37pub const SECTION_TEST_RETRIES: u32 = 21;
38pub const SECTION_TEST_ATTEMPTS: u32 = 22;
39pub const SECTION_TEST_LINES: u32 = 23;
40pub const SECTION_TEST_HITS: u32 = 24;
41pub const SECTION_TEST_DECISIONS: u32 = 25;
42pub const SECTION_TEST_VECTORS: u32 = 26;
43pub const SECTION_VECTOR_VALUES: u32 = 27;
44pub const SECTION_HIT_METADATA: u32 = 28;
45pub const SECTION_DECISION_METADATA: u32 = 29;
46pub const SECTION_DECISION_DETAILS: u32 = 30;
47pub const SECTION_DECISION_VECTOR_OBSERVATIONS: u32 = 31;
48pub const SECTION_DECISION_CONDITIONS: u32 = 32;
49pub const SECTION_LIMITATIONS: u32 = 33;
50pub const SECTION_COVERAGE_MODEL: u32 = 34;
51
52const STRING_RECORD_SIZE: usize = 16;
53const SUMMARY_RECORD_SIZE: usize = 176;
54const FILE_GAP_RECORD_SIZE: usize = 200;
55const DECISION_GAP_RECORD_SIZE: usize = 96;
56const DIMENSION_RECORD_SIZE: usize = 192;
57const PROJECTION_RECORD_SIZE: usize = 544;
58const SCOPE_ENTRY_RECORD_SIZE: usize = 96;
59const CONFIDENCE_RECORD_SIZE: usize = 96;
60const LINE_RECORD_SIZE: usize = 80;
61const TEST_SUMMARY_RECORD_SIZE: usize = 64;
62const PHASE_SUMMARY_RECORD_SIZE: usize = 64;
63const ANCHOR_RECORD_SIZE: usize = 64;
64const TEST_RETRY_RECORD_SIZE: usize = 16;
65const TEST_ATTEMPT_RECORD_SIZE: usize = 24;
66const TEST_LINE_RECORD_SIZE: usize = 24;
67const TEST_HIT_RECORD_SIZE: usize = 16;
68const TEST_DECISION_RECORD_SIZE: usize = 32;
69const TEST_VECTOR_RECORD_SIZE: usize = 24;
70const HIT_METADATA_RECORD_SIZE: usize = 64;
71const DECISION_METADATA_RECORD_SIZE: usize = 64;
72const DECISION_DETAIL_RECORD_SIZE: usize = 64;
73const DECISION_VECTOR_OBSERVATION_RECORD_SIZE: usize = 64;
74const DECISION_CONDITION_RECORD_SIZE: usize = 64;
75const LIMITATION_RECORD_SIZE: usize = 64;
76const COVERAGE_MODEL_RECORD_SIZE: usize = 48;
77const NO_STRING: u32 = u32::MAX;
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
80#[serde(rename_all = "lowercase")]
81pub enum CoverageViewId {
82    All = 0,
83    Passed = 1,
84    Failed = 2,
85}
86
87impl TryFrom<u8> for CoverageViewId {
88    type Error = CoverageIndexError;
89
90    fn try_from(value: u8) -> Result<Self, Self::Error> {
91        match value {
92            0 => Ok(Self::All),
93            1 => Ok(Self::Passed),
94            2 => Ok(Self::Failed),
95            _ => Err(CoverageIndexError::InvalidRecord("coverage view")),
96        }
97    }
98}
99
100#[derive(Debug)]
101pub enum CoverageIndexError {
102    Container(QueryIndexError),
103    InvalidRecord(&'static str),
104    InvalidUtf8,
105    SizeOverflow,
106}
107
108impl From<QueryIndexError> for CoverageIndexError {
109    fn from(value: QueryIndexError) -> Self {
110        Self::Container(value)
111    }
112}
113
114impl std::fmt::Display for CoverageIndexError {
115    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        match self {
117            Self::Container(error) => write!(formatter, "{error}"),
118            Self::InvalidRecord(reason) => write!(formatter, "invalid coverage index: {reason}"),
119            Self::InvalidUtf8 => write!(formatter, "invalid UTF-8 in coverage index"),
120            Self::SizeOverflow => write!(formatter, "coverage index exceeds format limits"),
121        }
122    }
123}
124
125impl std::error::Error for CoverageIndexError {}
126
127fn put_u32(bytes: &mut [u8], offset: usize, value: u32) {
128    bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
129}
130
131fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
132    bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
133}
134
135/// A field of a record. Every record the reader takes is exactly its kind's
136/// size -- [`CoverageIndex::new`] refuses an index whose sizes differ -- and
137/// every field lies inside it, so a read cannot run past the record.
138fn get_u32(record: &[u8], offset: usize) -> u32 {
139    u32::from_le_bytes(
140        record[offset..offset + 4]
141            .try_into()
142            .expect("a field lies inside its record"),
143    )
144}
145
146fn get_u64(record: &[u8], offset: usize) -> u64 {
147    u64::from_le_bytes(
148        record[offset..offset + 8]
149            .try_into()
150            .expect("a field lies inside its record"),
151    )
152}
153
154fn usize_u64(value: usize) -> Result<u64, CoverageIndexError> {
155    u64::try_from(value).map_err(|_| CoverageIndexError::SizeOverflow)
156}
157
158fn usize_u32(value: usize) -> Result<u32, CoverageIndexError> {
159    u32::try_from(value).map_err(|_| CoverageIndexError::SizeOverflow)
160}
161
162#[derive(Default)]
163struct StringTable {
164    ids: crate::interned::FastMap<String, u32>,
165    strings: Vec<String>,
166    // Keep each allocation alive: its address can then identify repeated Id
167    // references without hashing the same long test name for every line.
168    shared_ids: crate::interned::FastMap<usize, (Id, u32)>,
169}
170
171#[derive(Default)]
172struct StringRelations {
173    values: Vec<u32>,
174    /// Where each distinct run already sits. Readers reach a run only through
175    /// the (offset, count) pair the record stores, so two records naming the
176    /// same run can share one copy of it and nothing downstream can tell.
177    interned: crate::interned::FastMap<Vec<u32>, (u64, u64)>,
178}
179
180impl StringRelations {
181    /// Append a run of interned strings, or point at an identical one already
182    /// stored.
183    ///
184    /// The same run is named over and over: a filtered view repeats the whole
185    /// relation of the view it filters, and one list of tests covers many
186    /// lines of the file they exercise. Appending each time made this the
187    /// largest section in the container -- 61 MB of a 210 MB index, 15.3
188    /// million entries -- for a number of distinct runs far smaller.
189    fn push(
190        &mut self,
191        values: impl IntoIterator<Item = impl AsRef<str>>,
192        strings: &mut StringTable,
193    ) -> Result<(u64, u64), CoverageIndexError> {
194        let mut run = Vec::new();
195        for value in values {
196            run.push(strings.intern(value.as_ref())?);
197        }
198        self.push_run(run)
199    }
200
201    fn push_ids(
202        &mut self,
203        values: &[Id],
204        strings: &mut StringTable,
205    ) -> Result<(u64, u64), CoverageIndexError> {
206        let mut run = Vec::with_capacity(values.len());
207        for value in values {
208            run.push(strings.intern_shared(value)?);
209        }
210        self.push_run(run)
211    }
212
213    fn push_run(&mut self, run: Vec<u32>) -> Result<(u64, u64), CoverageIndexError> {
214        if let Some(found) = self.interned.get(&run) {
215            return Ok(*found);
216        }
217        let offset = usize_u64(self.values.len())?;
218        let count = usize_u64(run.len())?;
219        self.values.extend_from_slice(&run);
220        self.interned.insert(run, (offset, count));
221        Ok((offset, count))
222    }
223
224    fn section(self) -> Result<QueryIndexSection, CoverageIndexError> {
225        let mut bytes = Vec::with_capacity(self.values.len() * 4);
226        for value in self.values {
227            bytes.extend_from_slice(&value.to_le_bytes());
228        }
229        Ok(QueryIndexSection {
230            kind: SECTION_STRING_RELATIONS,
231            record_size: 4,
232            count: usize_u64(bytes.len() / 4)?,
233            bytes,
234        })
235    }
236}
237
238impl StringTable {
239    fn intern_shared(&mut self, value: &Id) -> Result<u32, CoverageIndexError> {
240        let allocation = value.as_str().as_ptr() as usize;
241        if let Some((_, id)) = self.shared_ids.get(&allocation) {
242            return Ok(*id);
243        }
244        // Different allocations of identical text still use the same string
245        // table entry, including IDs built outside the report's interner.
246        let id = self.intern(value.as_str())?;
247        self.shared_ids.insert(allocation, (value.clone(), id));
248        Ok(id)
249    }
250
251    fn intern(&mut self, value: &str) -> Result<u32, CoverageIndexError> {
252        if let Some(id) = self.ids.get(value) {
253            return Ok(*id);
254        }
255        let id = usize_u32(self.strings.len())?;
256        self.ids.insert(value.into(), id);
257        self.strings.push(value.into());
258        Ok(id)
259    }
260
261    fn sections(self) -> Result<[QueryIndexSection; 2], CoverageIndexError> {
262        let mut blob = Vec::new();
263        let mut records = Vec::with_capacity(self.strings.len() * STRING_RECORD_SIZE);
264        for string in self.strings {
265            let offset = usize_u64(blob.len())?;
266            let value = string.as_bytes();
267            let length = usize_u32(value.len())?;
268            blob.extend_from_slice(value);
269            let mut record = [0_u8; STRING_RECORD_SIZE];
270            put_u64(&mut record, 0, offset);
271            put_u32(&mut record, 8, length);
272            records.extend_from_slice(&record);
273        }
274        Ok([
275            QueryIndexSection {
276                kind: SECTION_STRING_BYTES,
277                record_size: 0,
278                count: usize_u64(blob.len())?,
279                bytes: blob,
280            },
281            QueryIndexSection {
282                kind: SECTION_STRINGS,
283                record_size: STRING_RECORD_SIZE as u32,
284                count: usize_u64(records.len() / STRING_RECORD_SIZE)?,
285                bytes: records,
286            },
287        ])
288    }
289}
290
291fn put_count(
292    bytes: &mut [u8],
293    offset: usize,
294    count: &CoverageCount,
295) -> Result<(), CoverageIndexError> {
296    put_u64(bytes, offset, usize_u64(count.covered)?);
297    put_u64(bytes, offset + 8, usize_u64(count.total)?);
298    Ok(())
299}
300
301fn summary_record(
302    id: CoverageViewId,
303    view: &CoverageView,
304    strings: &mut StringTable,
305) -> Result<[u8; SUMMARY_RECORD_SIZE], CoverageIndexError> {
306    let mut record = [0_u8; SUMMARY_RECORD_SIZE];
307    record[0] = id as u8;
308    record[1] = u8::from(view.summary.coverage_complete);
309    record[2] = match view.summary.completeness_blocked {
310        None => 0,
311        Some(false) => 1,
312        Some(true) => 2,
313    };
314    put_u32(&mut record, 4, strings.intern(&view.generated_at)?);
315    put_u32(&mut record, 8, strings.intern(&view.variant)?);
316    let values = [
317        view.summary.decisions,
318        view.summary.executed_decisions,
319        view.summary.covered_decisions,
320        view.summary.conditions,
321        view.summary.covered_conditions,
322    ];
323    for (index, value) in values.into_iter().enumerate() {
324        put_u64(&mut record, 16 + index * 8, usize_u64(value)?);
325    }
326    for (index, count) in [
327        &view.summary.lines,
328        &view.summary.statements,
329        &view.summary.functions,
330        &view.summary.branches,
331        &view.summary.decision_outcomes,
332        &view.summary.condition_outcomes,
333        &view.summary.value_selections,
334    ]
335    .into_iter()
336    .enumerate()
337    {
338        put_count(&mut record, 56 + index * 16, count)?;
339    }
340    Ok(record)
341}
342
343#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
344#[serde(rename_all = "camelCase")]
345pub struct IndexedFileGap {
346    #[serde(skip)]
347    pub view: CoverageViewId,
348    pub file: String,
349    pub uncovered_lines: usize,
350    pub uncovered_statements: usize,
351    pub uncovered_functions: usize,
352    pub missing_branches: usize,
353    pub missing_mcdc_conditions: usize,
354    pub measurement_limitations: usize,
355    pub limitation_kinds: Vec<String>,
356    pub covered_by_other_tests: IndexedGapDimensions,
357    pub uncovered_everywhere: IndexedGapDimensions,
358    /// What the file has to cover, and how much of it the selected tests do.
359    /// The listing gave only what was missing, so no percentage could be
360    /// worked out for a file, or summed for a directory.
361    pub totals: IndexedGapDimensions,
362    pub covered: IndexedGapDimensions,
363    pub score: usize,
364}
365
366#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
367#[serde(rename_all = "camelCase")]
368pub struct IndexedGapDimensions {
369    pub lines: usize,
370    pub statements: usize,
371    pub functions: usize,
372    pub branches: usize,
373    pub mcdc_conditions: usize,
374}
375
376#[derive(Debug, Clone, PartialEq, Serialize)]
377#[serde(rename_all = "camelCase")]
378pub struct IndexedCoverageSnapshot {
379    pub all_summary: CoverageSummary,
380    pub passed_summary: CoverageSummary,
381    pub failed_summary: CoverageSummary,
382    pub all_files: Vec<IndexedFileGap>,
383    pub passed_files: Vec<IndexedFileGap>,
384    pub failed_files: Vec<IndexedFileGap>,
385}
386
387#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
388#[serde(rename_all = "camelCase")]
389pub struct IndexedDecisionGap {
390    #[serde(skip)]
391    pub view: CoverageViewId,
392    #[serde(skip)]
393    pub file: String,
394    pub id: String,
395    pub line: usize,
396    pub column: usize,
397    pub kind: String,
398    pub conditions: usize,
399    pub missing_conditions: usize,
400    pub source: String,
401}
402
403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
404pub enum CoverageDimension {
405    Kind = 0,
406    Runner = 1,
407    /// Every test together: one unnamed entry, what the tests cover between
408    /// them. The run's total less this is what ran outside any test.
409    Tests = 2,
410}
411
412#[derive(Debug, Clone, PartialEq, Serialize)]
413#[serde(rename_all = "camelCase")]
414pub struct IndexedDimensionCoverage {
415    #[serde(skip_serializing_if = "Option::is_none")]
416    pub kind: Option<String>,
417    #[serde(skip_serializing_if = "Option::is_none")]
418    pub runner: Option<String>,
419    pub tests: usize,
420    pub setups: usize,
421    /// How many of `tests` the summary below actually describes. Where this is
422    /// zero and `tests` is not, the dimension ran tests whose coverage nothing
423    /// can narrow, and its summary describes none of them.
424    pub attributed: usize,
425    pub summary: CoverageSummary,
426}
427
428#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
429#[serde(rename_all = "camelCase")]
430pub struct IndexedAttribution {
431    pub browser_explicit: usize,
432    pub browser_fallback: usize,
433    pub server_explicit: usize,
434    pub server_fallback: usize,
435}
436
437#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
438#[serde(rename_all = "camelCase")]
439pub struct IndexedOutcomeCounts {
440    pub passed: usize,
441    pub failed: usize,
442    pub flaky: usize,
443    pub skipped: usize,
444    pub timed_out: usize,
445    pub interrupted: usize,
446    pub unknown: usize,
447    pub unstarted: usize,
448    /// node:test's todo tests, which the runner counts on their own: neither
449    /// passed nor failed, whatever their body did.
450    pub todo: usize,
451}
452
453#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
454#[serde(rename_all = "camelCase")]
455pub struct IndexedMeasurementKinds {
456    #[serde(rename = "dynamic-code")]
457    pub dynamic_code: usize,
458    #[serde(rename = "semantic-safety")]
459    pub semantic_safety: usize,
460    #[serde(rename = "source-scope")]
461    pub source_scope: usize,
462}
463
464#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
465#[serde(rename_all = "camelCase")]
466pub struct IndexedMeasurement {
467    pub complete: bool,
468    pub limitations: usize,
469    pub evidence_corruptions: usize,
470    pub blocking: usize,
471    /// Limitations that declare a boundary of the denominator rather than
472    /// blocking measurement inside it.
473    pub declared: usize,
474    pub files: usize,
475    pub by_kind: IndexedMeasurementKinds,
476}
477
478#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
479#[serde(rename_all = "camelCase")]
480pub struct IndexedConfidenceLines {
481    pub unexecuted: usize,
482    pub executed: usize,
483    pub action: usize,
484    pub asserted: usize,
485}
486
487#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
488#[serde(rename_all = "camelCase")]
489pub struct IndexedSummaryConfidence {
490    pub lines: IndexedConfidenceLines,
491    pub assertion_covered_mcdc_conditions: usize,
492}
493
494#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
495#[serde(rename_all = "camelCase")]
496pub struct IndexedCoverageModel {
497    pub schema_version: u32,
498    pub variant: String,
499    pub name: String,
500    pub completeness_meaning: String,
501    pub measured: Vec<String>,
502    pub not_measured: Vec<String>,
503}
504
505#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
506#[serde(rename_all = "camelCase")]
507pub struct IndexedSourceScope {
508    pub kind: String,
509    pub language: String,
510    pub model: String,
511    #[serde(skip_serializing_if = "Option::is_none")]
512    pub mode: Option<String>,
513    pub roots: Vec<String>,
514    #[serde(skip_serializing_if = "Option::is_none")]
515    pub unit: Option<String>,
516    #[serde(skip_serializing_if = "Option::is_none")]
517    pub measurement_complete: Option<bool>,
518    pub included: usize,
519    pub excluded: usize,
520    pub ambiguous: usize,
521}
522
523#[derive(Debug, Clone, PartialEq)]
524pub struct IndexedProjection {
525    pub view: CoverageViewId,
526    pub kind: Option<String>,
527    pub runner: Option<String>,
528    pub generated_at: String,
529    pub summary: CoverageSummary,
530    pub measurement: IndexedMeasurement,
531    pub attribution: IndexedAttribution,
532    pub transport: Option<TransportStats>,
533    pub empty_evidence_tests: usize,
534    pub first_empty_evidence_test: Option<String>,
535    pub confidence: IndexedSummaryConfidence,
536    pub files_with_gaps: usize,
537    pub files_with_coverage_gaps: usize,
538    pub tests: usize,
539    pub setups: usize,
540    pub test_outcomes: IndexedOutcomeCounts,
541    pub source_scope: Option<IndexedSourceScope>,
542}
543
544#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
545#[serde(rename_all = "camelCase")]
546pub struct IndexedScopeEntry {
547    pub file: String,
548    pub status: String,
549    pub reason: String,
550    #[serde(skip_serializing_if = "Option::is_none")]
551    pub package_root: Option<String>,
552    pub measurement_limitations: usize,
553    pub limitation_kinds: Vec<String>,
554}
555
556#[derive(Debug, Clone, PartialEq)]
557pub struct IndexedLine {
558    pub file: String,
559    pub line: usize,
560    pub covered: bool,
561    /// False when every obligation on the line was declined: the line stays
562    /// addressable and carries its limitation, but it is neither covered nor
563    /// uncovered.
564    pub measured: bool,
565    pub tests: Vec<String>,
566    pub phases: Vec<String>,
567    pub confidence: crate::coverage_report::CoverageConfidence,
568}
569
570#[derive(Debug, Clone, PartialEq)]
571pub struct IndexedTestSummary {
572    pub id: String,
573    pub name: String,
574    pub file: Option<String>,
575    pub title: Option<String>,
576    pub outcome: String,
577    pub role: String,
578    /// `exact`, or `run-wide` when this test ran and nothing can say what it
579    /// reached. Read before any statement about this test's coverage: an
580    /// empty hit set means "reached nothing" only under `exact`.
581    pub attribution: String,
582    pub provenance: crate::coverage_report::TestProvenance,
583}
584
585#[derive(Debug, Clone, PartialEq)]
586pub struct IndexedPhaseSummary {
587    pub id: String,
588    pub kind: String,
589    pub operation: String,
590    pub source: Option<String>,
591    pub test: String,
592    pub status: Option<String>,
593    pub caused_by_phase_id: Option<String>,
594    pub lines: usize,
595    pub decisions: usize,
596}
597
598#[derive(Debug, Clone, PartialEq)]
599pub struct IndexedAnchor {
600    pub kind: String,
601    pub id: String,
602    pub file: String,
603    pub line: usize,
604    pub column: usize,
605    pub covered: bool,
606    pub conditions: Option<usize>,
607    pub covered_conditions: Option<usize>,
608    pub tests: Vec<String>,
609}
610
611#[derive(Debug, Clone, PartialEq)]
612pub struct IndexedTestDetail {
613    pub summary: IndexedTestSummary,
614    pub retries: Vec<usize>,
615    pub attempts: Vec<crate::coverage_report::TestAttempt>,
616    pub hits: Vec<String>,
617    pub decisions: Vec<crate::coverage_report::TestDecisionResult>,
618    pub lines: Vec<crate::coverage_report::SourceLine>,
619}
620
621#[derive(Debug, Clone, PartialEq, Eq)]
622pub struct IndexedHitMetadata {
623    pub id: String,
624    pub obligation: String,
625    pub branch_kind: Option<String>,
626    pub file: String,
627    pub line: usize,
628    pub column: usize,
629    pub label: Option<String>,
630    pub alternative: Option<String>,
631    pub parent_id: Option<String>,
632    pub source: String,
633    pub tests: Vec<String>,
634}
635
636#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
637pub struct IndexedLimitation {
638    pub id: String,
639    pub kind: String,
640    pub file: String,
641    pub line: usize,
642    pub column: usize,
643    pub source: String,
644    pub reason: String,
645    /// Whether this blocks measurement of the denominator, as opposed to
646    /// declaring a boundary of it.
647    pub blocking: bool,
648}
649
650#[derive(Default)]
651struct MutableFileGap {
652    uncovered_lines: usize,
653    uncovered_statements: usize,
654    uncovered_functions: usize,
655    missing_branches: usize,
656    missing_mcdc_conditions: usize,
657    measurement_limitations: usize,
658    limitation_mask: u32,
659    covered_by_other_tests: [usize; 5],
660    uncovered_everywhere: [usize; 5],
661    totals: [usize; 5],
662}
663
664fn limitation_kind(value: &serde_json::Value) -> Option<(&str, &str)> {
665    Some((value.get("file")?.as_str()?, value.get("kind")?.as_str()?))
666}
667
668fn includes_selected<T: AsRef<str>>(
669    tests: &[T],
670    selected: Option<&Selected>,
671    covered: bool,
672) -> bool {
673    selected.map_or(covered, |selected| {
674        tests.iter().any(|test| selected.contains(test.as_ref()))
675    })
676}
677
678fn classify(
679    gap: &mut MutableFileGap,
680    dimension: usize,
681    selected: Option<&Selected>,
682    covered_overall: bool,
683) {
684    if selected.is_some() && covered_overall {
685        gap.covered_by_other_tests[dimension] += 1;
686    } else {
687        gap.uncovered_everywhere[dimension] += 1;
688    }
689}
690
691/// A file's gap, its name copied only the first time the file is met.
692fn gap_for<'m>(
693    files: &'m mut BTreeMap<String, MutableFileGap>,
694    file: &str,
695) -> &'m mut MutableFileGap {
696    if !files.contains_key(file) {
697        files.insert(file.to_owned(), MutableFileGap::default());
698    }
699    files.get_mut(file).expect("gap was inserted")
700}
701
702fn file_gaps(
703    view: &CoverageView,
704    selected: Option<&Selected>,
705) -> Result<Vec<(String, MutableFileGap)>, CoverageIndexError> {
706    let mut files = BTreeMap::<String, MutableFileGap>::new();
707    for line in &view.lines {
708        let gap = gap_for(&mut files, &line.file);
709        gap.totals[0] += usize::from(line.measured);
710        if line.measured && !includes_selected(&line.tests, selected, line.covered) {
711            gap.uncovered_lines += 1;
712            classify(gap, 0, selected, line.covered);
713        }
714    }
715    for point in &view.points {
716        let gap = gap_for(&mut files, &point.meta.file);
717        if point.measured {
718            gap.totals[match point.meta.kind {
719                crate::coverage_analysis::PointKind::Statement => 1,
720                crate::coverage_analysis::PointKind::Function => 2,
721            }] += 1;
722        }
723        if point.measured && !includes_selected(&point.tests, selected, point.covered) {
724            match point.meta.kind {
725                crate::coverage_analysis::PointKind::Statement => {
726                    gap.uncovered_statements += 1;
727                    classify(gap, 1, selected, point.covered);
728                }
729                crate::coverage_analysis::PointKind::Function => {
730                    gap.uncovered_functions += 1;
731                    classify(gap, 2, selected, point.covered);
732                }
733            }
734        }
735    }
736    for branch in &view.branches {
737        let gap = gap_for(&mut files, &branch.meta.file);
738        gap.totals[3] += branch.alternatives.len();
739        for alternative in &branch.alternatives {
740            if !includes_selected(&alternative.tests, selected, alternative.covered) {
741                gap.missing_branches += 1;
742                classify(gap, 3, selected, alternative.covered);
743            }
744        }
745    }
746    for decision in &view.decisions {
747        let gap = gap_for(&mut files, &decision.meta.file);
748        gap.totals[4] += decision.meta.conditions.len();
749        let selected_vectors = decision
750            .vector_observations
751            .iter()
752            .filter(|observation| includes_selected(&observation.tests, selected, true))
753            .map(|observation| observation.vector.clone())
754            .collect::<Vec<_>>();
755        let witnesses =
756            find_witnesses_for_conditions(&selected_vectors, decision.meta.conditions.len())
757                .map_err(|_| CoverageIndexError::InvalidRecord("MC/DC vector width"))?;
758        for (index, witness) in witnesses.into_iter().enumerate() {
759            if witness.is_none() {
760                gap.missing_mcdc_conditions += 1;
761                classify(gap, 4, selected, decision.conditions[index].covered);
762            }
763        }
764    }
765    for limitation in &view.limitations {
766        let Some((file, kind)) = limitation_kind(limitation) else {
767            continue;
768        };
769        let gap = files.entry(file.into()).or_default();
770        gap.measurement_limitations += 1;
771        gap.limitation_mask |= match kind {
772            "dynamic-code" => 1,
773            "semantic-safety" => 2,
774            "source-scope" => 4,
775            _ => 8,
776        };
777    }
778    Ok(files.into_iter().collect())
779}
780
781fn file_gap_record(
782    view_id: CoverageViewId,
783    file: &str,
784    gap: &MutableFileGap,
785    kind: Option<&str>,
786    runner: Option<&str>,
787    strings: &mut StringTable,
788) -> Result<[u8; FILE_GAP_RECORD_SIZE], CoverageIndexError> {
789    let mut record = [0_u8; FILE_GAP_RECORD_SIZE];
790    record[0] = view_id as u8;
791    put_u32(&mut record, 4, strings.intern(file)?);
792    for (index, value) in [
793        gap.uncovered_lines,
794        gap.uncovered_statements,
795        gap.uncovered_functions,
796        gap.missing_branches,
797        gap.missing_mcdc_conditions,
798        gap.measurement_limitations,
799    ]
800    .into_iter()
801    .enumerate()
802    {
803        put_u64(&mut record, 8 + index * 8, usize_u64(value)?);
804    }
805    put_u32(&mut record, 56, gap.limitation_mask);
806    let score = gap.uncovered_lines
807        + gap.uncovered_functions * 2
808        + gap.missing_branches * 2
809        + gap.missing_mcdc_conditions * 3
810        + gap.measurement_limitations * 3;
811    put_u64(&mut record, 64, usize_u64(score)?);
812    put_u32(
813        &mut record,
814        72,
815        kind.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
816    );
817    put_u32(
818        &mut record,
819        76,
820        runner.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
821    );
822    for (index, value) in gap.covered_by_other_tests.into_iter().enumerate() {
823        put_u64(&mut record, 80 + index * 8, usize_u64(value)?);
824    }
825    for (index, value) in gap.uncovered_everywhere.into_iter().enumerate() {
826        put_u64(&mut record, 120 + index * 8, usize_u64(value)?);
827    }
828    for (index, value) in gap.totals.into_iter().enumerate() {
829        put_u64(&mut record, 160 + index * 8, usize_u64(value)?);
830    }
831    Ok(record)
832}
833
834/// The tests a projection selects. Hashed: every line, point, branch and
835/// vector of the view asks whether any of its tests is selected, once per
836/// projection, and a tree of long test names answered each by comparing them.
837type Selected = crate::interned::FastSet<String>;
838
839/// The kind a file's coverage by every test together is filed under.
840pub const ALL_TESTS: &str = "";
841
842fn projections(view: &CoverageView) -> Vec<(Option<String>, Option<String>, Selected)> {
843    let kinds = view
844        .tests
845        .iter()
846        .map(|test| test.provenance.kind.clone())
847        .collect::<BTreeSet<_>>();
848    let runners = view
849        .tests
850        .iter()
851        .map(|test| test.provenance.runner.clone())
852        .collect::<BTreeSet<_>>();
853    let mut selectors = Vec::new();
854    for kind in &kinds {
855        selectors.push((Some(kind.clone()), None));
856    }
857    for runner in &runners {
858        selectors.push((None, Some(runner.clone())));
859    }
860    for kind in &kinds {
861        for runner in &runners {
862            selectors.push((Some(kind.clone()), Some(runner.clone())));
863        }
864    }
865    selectors
866        .into_iter()
867        .filter_map(|(kind, runner)| {
868            let selected = view
869                .tests
870                .iter()
871                .filter(|test| {
872                    kind.as_ref()
873                        .is_none_or(|value| test.provenance.kind == *value)
874                        && runner
875                            .as_ref()
876                            .is_none_or(|value| test.provenance.runner == *value)
877                })
878                .map(|test| test.id.clone())
879                .collect::<Selected>();
880            (!selected.is_empty()).then_some((kind, runner, selected))
881        })
882        .collect()
883}
884
885fn decision_gap_record(
886    view_id: CoverageViewId,
887    decision: &crate::coverage_report::DecisionResult,
888    selected: Option<&Selected>,
889    kind: Option<&str>,
890    runner: Option<&str>,
891    strings: &mut StringTable,
892) -> Result<[u8; DECISION_GAP_RECORD_SIZE], CoverageIndexError> {
893    let vectors = decision
894        .vector_observations
895        .iter()
896        .filter(|observation| includes_selected(&observation.tests, selected, true))
897        .map(|observation| observation.vector.clone())
898        .collect::<Vec<_>>();
899    let witnesses = find_witnesses_for_conditions(&vectors, decision.meta.conditions.len())
900        .map_err(|_| CoverageIndexError::InvalidRecord("MC/DC vector width"))?;
901    let mut record = [0_u8; DECISION_GAP_RECORD_SIZE];
902    record[0] = view_id as u8;
903    put_u32(
904        &mut record,
905        4,
906        kind.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
907    );
908    put_u32(
909        &mut record,
910        8,
911        runner.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
912    );
913    put_u32(&mut record, 12, strings.intern(&decision.meta.id)?);
914    put_u32(&mut record, 16, strings.intern(&decision.meta.file)?);
915    put_u32(&mut record, 20, strings.intern(&decision.meta.kind)?);
916    put_u32(
917        &mut record,
918        24,
919        strings.intern(
920            &decision
921                .meta
922                .source
923                .split_whitespace()
924                .collect::<Vec<_>>()
925                .join(" "),
926        )?,
927    );
928    put_u64(&mut record, 32, usize_u64(decision.meta.line)?);
929    put_u64(&mut record, 40, usize_u64(decision.meta.column)?);
930    put_u64(&mut record, 48, usize_u64(decision.meta.conditions.len())?);
931    put_u64(
932        &mut record,
933        56,
934        usize_u64(witnesses.iter().filter(|witness| witness.is_none()).count())?,
935    );
936    Ok(record)
937}
938
939fn put_summary_payload(
940    record: &mut [u8],
941    flags_offset: usize,
942    base: usize,
943    summary: &CoverageSummary,
944) -> Result<(), CoverageIndexError> {
945    record[flags_offset] = u8::from(summary.coverage_complete);
946    record[flags_offset + 1] = match summary.completeness_blocked {
947        None => 0,
948        Some(false) => 1,
949        Some(true) => 2,
950    };
951    for (index, value) in [
952        summary.decisions,
953        summary.executed_decisions,
954        summary.covered_decisions,
955        summary.conditions,
956        summary.covered_conditions,
957    ]
958    .into_iter()
959    .enumerate()
960    {
961        put_u64(record, base + index * 8, usize_u64(value)?);
962    }
963    for (index, count) in [
964        &summary.lines,
965        &summary.statements,
966        &summary.functions,
967        &summary.branches,
968        &summary.decision_outcomes,
969        &summary.condition_outcomes,
970        &summary.value_selections,
971    ]
972    .into_iter()
973    .enumerate()
974    {
975        put_count(record, base + 40 + index * 16, count)?;
976    }
977    Ok(())
978}
979
980fn dimension_record(
981    view_id: CoverageViewId,
982    dimension: CoverageDimension,
983    value: &crate::coverage_report::DimensionCoverage,
984    strings: &mut StringTable,
985) -> Result<[u8; DIMENSION_RECORD_SIZE], CoverageIndexError> {
986    let mut record = [0_u8; DIMENSION_RECORD_SIZE];
987    record[0] = view_id as u8;
988    record[1] = dimension as u8;
989    let name = match dimension {
990        CoverageDimension::Kind => value.kind.as_deref(),
991        CoverageDimension::Runner => value.runner.as_deref(),
992        CoverageDimension::Tests => Some(""),
993    }
994    .ok_or(CoverageIndexError::InvalidRecord("dimension name"))?;
995    put_u32(&mut record, 4, strings.intern(name)?);
996    put_u64(&mut record, 8, usize_u64(value.tests)?);
997    put_u64(&mut record, 16, usize_u64(value.setups)?);
998    // Bytes 184..192 were reserved from the start and the reader refuses a
999    // record that sets them, so this is an addition rather than a format
1000    // change: the record is the same 192 bytes it always was.
1001    put_u64(&mut record, 184, usize_u64(value.attributed)?);
1002    put_summary_payload(&mut record, 24, 32, &value.summary)?;
1003    Ok(record)
1004}
1005
1006#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1007enum ScopeKind {
1008    SourceDiscovery = 1,
1009    Compiler = 2,
1010}
1011
1012struct ScopeProjection<'a> {
1013    kind: ScopeKind,
1014    language: &'a str,
1015    model: &'a str,
1016    mode: Option<&'a str>,
1017    roots: Vec<String>,
1018    unit: Option<&'a str>,
1019    measurement_complete: Option<bool>,
1020    entries: Option<&'a Vec<serde_json::Value>>,
1021}
1022
1023fn scope_projection<'a>(
1024    scope: Option<&'a serde_json::Value>,
1025    coverage_language: &'a str,
1026    coverage_model: &'a str,
1027) -> Result<Option<ScopeProjection<'a>>, CoverageIndexError> {
1028    let Some(scope) = scope else {
1029        return Ok(None);
1030    };
1031    let object = scope
1032        .as_object()
1033        .ok_or(CoverageIndexError::InvalidRecord("coverage scope"))?;
1034    if let Some(mode) = object.get("mode") {
1035        let mode = mode
1036            .as_str()
1037            .ok_or(CoverageIndexError::InvalidRecord("source-scope mode"))?;
1038        let roots = object
1039            .get("roots")
1040            .and_then(serde_json::Value::as_array)
1041            .ok_or(CoverageIndexError::InvalidRecord("source-scope roots"))?
1042            .iter()
1043            .map(|root| {
1044                root.as_str()
1045                    .map(str::to_owned)
1046                    .ok_or(CoverageIndexError::InvalidRecord("source-scope root"))
1047            })
1048            .collect::<Result<Vec<_>, _>>()?;
1049        let entries = object
1050            .get("entries")
1051            .and_then(serde_json::Value::as_array)
1052            .ok_or(CoverageIndexError::InvalidRecord("source-scope entries"))?;
1053        return Ok(Some(ScopeProjection {
1054            kind: ScopeKind::SourceDiscovery,
1055            language: coverage_language,
1056            model: coverage_model,
1057            mode: Some(mode),
1058            roots,
1059            unit: None,
1060            measurement_complete: None,
1061            entries: Some(entries),
1062        }));
1063    }
1064
1065    let language = object
1066        .get("language")
1067        .and_then(serde_json::Value::as_str)
1068        .ok_or(CoverageIndexError::InvalidRecord("compiler-scope language"))?;
1069    let model = object
1070        .get("model")
1071        .and_then(serde_json::Value::as_str)
1072        .ok_or(CoverageIndexError::InvalidRecord("compiler-scope model"))?;
1073    let unit = object
1074        .get("crate")
1075        .and_then(serde_json::Value::as_str)
1076        .ok_or(CoverageIndexError::InvalidRecord("compiler-scope unit"))?;
1077    let measurement_complete = object
1078        .get("measurementComplete")
1079        .and_then(serde_json::Value::as_bool)
1080        .ok_or(CoverageIndexError::InvalidRecord(
1081            "compiler-scope measurement completeness",
1082        ))?;
1083    Ok(Some(ScopeProjection {
1084        kind: ScopeKind::Compiler,
1085        language,
1086        model,
1087        mode: None,
1088        roots: Vec::new(),
1089        unit: Some(unit),
1090        measurement_complete: Some(measurement_complete),
1091        entries: None,
1092    }))
1093}
1094
1095fn projection_record(
1096    view_id: CoverageViewId,
1097    view: &CoverageView,
1098    selected: Option<&Selected>,
1099    kind: Option<&str>,
1100    runner: Option<&str>,
1101    strings: &mut StringTable,
1102    relations: &mut StringRelations,
1103) -> Result<[u8; PROJECTION_RECORD_SIZE], CoverageIndexError> {
1104    let mut record = [0_u8; PROJECTION_RECORD_SIZE];
1105    record[0] = view_id as u8;
1106    put_u32(
1107        &mut record,
1108        4,
1109        kind.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
1110    );
1111    put_u32(
1112        &mut record,
1113        8,
1114        runner.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
1115    );
1116    put_u32(&mut record, 12, strings.intern(&view.generated_at)?);
1117
1118    let scope = scope_projection(view.scope.as_ref(), &view.model.language, &view.model.name)?;
1119    record[2] = u8::from(scope.is_some());
1120    record[3] = scope.as_ref().map_or(0, |scope| scope.kind as u8);
1121    put_u32(
1122        &mut record,
1123        16,
1124        scope
1125            .as_ref()
1126            .and_then(|scope| scope.mode)
1127            .map_or(Ok(NO_STRING), |value| strings.intern(value))?,
1128    );
1129    let roots = scope
1130        .as_ref()
1131        .map_or_else(Vec::new, |scope| scope.roots.clone());
1132    let (roots_offset, roots_count) = relations.push(roots, strings)?;
1133    put_u64(&mut record, 24, roots_offset);
1134    put_u32(
1135        &mut record,
1136        32,
1137        u32::try_from(roots_count).map_err(|_| CoverageIndexError::SizeOverflow)?,
1138    );
1139
1140    let summary = selected.map_or_else(
1141        || Ok(view.summary.clone()),
1142        |ids| {
1143            coverage_summary_for_tests(view, &ids.iter().cloned().collect())
1144                .map_err(|_| CoverageIndexError::InvalidRecord("projection summary"))
1145        },
1146    )?;
1147    put_summary_payload(&mut record, 36, 40, &summary)?;
1148
1149    let mut limitation_kinds = [0_usize; 3];
1150    let mut limitation_files = BTreeSet::new();
1151    for limitation in &view.limitations {
1152        if let Some((file, kind)) = limitation_kind(limitation) {
1153            limitation_files.insert(file);
1154            match kind {
1155                "dynamic-code" => limitation_kinds[0] += 1,
1156                "semantic-safety" => limitation_kinds[1] += 1,
1157                "source-scope" => limitation_kinds[2] += 1,
1158                _ => {}
1159            }
1160        }
1161    }
1162    let corrupt_records = view
1163        .transport
1164        .as_ref()
1165        .map_or(0, |value| value.corrupt_records);
1166    let corrupt_files = view
1167        .transport
1168        .as_ref()
1169        .map_or(0, |value| value.corrupt_files);
1170    // A limitation that declares a boundary of the denominator does not block
1171    // measurement inside it; corrupt evidence always does.
1172    let declared = view
1173        .limitations
1174        .iter()
1175        .filter(|limitation| !crate::coverage_report::blocking_limitation(limitation))
1176        .count();
1177    for (offset, value) in [
1178        (192, view.limitations.len()),
1179        (200, corrupt_records),
1180        (208, view.limitations.len() - declared + corrupt_records),
1181        (528, declared),
1182        (216, limitation_files.len() + corrupt_files),
1183        (224, limitation_kinds[0]),
1184        (232, limitation_kinds[1]),
1185        (240, limitation_kinds[2]),
1186    ] {
1187        put_u64(&mut record, offset, usize_u64(value)?);
1188    }
1189
1190    let phases = view
1191        .phases
1192        .iter()
1193        .filter(|phase| selected.is_none_or(|selected| selected.contains(phase.test.as_str())));
1194    let mut attribution = [0_usize; 4];
1195    for phase in phases {
1196        attribution[0] += phase.explicit_browser_events;
1197        attribution[1] += phase.inferred_browser_events;
1198        attribution[2] += phase.explicit_server_events;
1199        attribution[3] += phase.inferred_server_events;
1200    }
1201    for (index, value) in attribution.into_iter().enumerate() {
1202        put_u64(&mut record, 248 + index * 8, usize_u64(value)?);
1203    }
1204
1205    let confidence_levels = ["unexecuted", "executed", "action", "asserted"];
1206    for (index, level) in confidence_levels.into_iter().enumerate() {
1207        put_u64(
1208            &mut record,
1209            280 + index * 8,
1210            usize_u64(
1211                view.lines
1212                    .iter()
1213                    .filter(|line| line.confidence.level == level)
1214                    .count(),
1215            )?,
1216        );
1217    }
1218    put_u64(
1219        &mut record,
1220        312,
1221        usize_u64(
1222            view.decisions
1223                .iter()
1224                .flat_map(|decision| &decision.conditions)
1225                .filter(|condition| condition.assertion_covered)
1226                .count(),
1227        )?,
1228    );
1229
1230    let gaps = file_gaps(view, selected)?;
1231    put_u64(
1232        &mut record,
1233        320,
1234        usize_u64(
1235            gaps.iter()
1236                .filter(|(_, gap)| {
1237                    gap.uncovered_lines > 0
1238                        || gap.uncovered_statements > 0
1239                        || gap.uncovered_functions > 0
1240                        || gap.missing_branches > 0
1241                        || gap.missing_mcdc_conditions > 0
1242                        || gap.measurement_limitations > 0
1243                })
1244                .count(),
1245        )?,
1246    );
1247    put_u64(
1248        &mut record,
1249        328,
1250        usize_u64(
1251            gaps.iter()
1252                .filter(|(_, gap)| {
1253                    gap.uncovered_lines > 0
1254                        || gap.uncovered_statements > 0
1255                        || gap.uncovered_functions > 0
1256                        || gap.missing_branches > 0
1257                        || gap.missing_mcdc_conditions > 0
1258                })
1259                .count(),
1260        )?,
1261    );
1262
1263    let selected_tests = view
1264        .tests
1265        .iter()
1266        .filter(|test| selected.is_none_or(|selected| selected.contains(&test.id)))
1267        .collect::<Vec<_>>();
1268    put_u64(
1269        &mut record,
1270        336,
1271        usize_u64(
1272            selected_tests
1273                .iter()
1274                .filter(|test| test.role == "test")
1275                .count(),
1276        )?,
1277    );
1278    put_u64(
1279        &mut record,
1280        344,
1281        usize_u64(
1282            selected_tests
1283                .iter()
1284                .filter(|test| test.role == "setup")
1285                .count(),
1286        )?,
1287    );
1288    for (index, outcome) in [
1289        "passed",
1290        "failed",
1291        "flaky",
1292        "skipped",
1293        "timedOut",
1294        "interrupted",
1295        "unknown",
1296    ]
1297    .into_iter()
1298    .enumerate()
1299    {
1300        put_u64(
1301            &mut record,
1302            352 + index * 8,
1303            usize_u64(
1304                selected_tests
1305                    .iter()
1306                    .filter(|test| test.role == "test" && test.outcome == outcome)
1307                    .count(),
1308            )?,
1309        );
1310    }
1311    put_u64(
1312        &mut record,
1313        520,
1314        usize_u64(
1315            selected_tests
1316                .iter()
1317                .filter(|test| test.role == "test" && test.outcome == "unstarted")
1318                .count(),
1319        )?,
1320    );
1321
1322    if let Some(transport) = &view.transport {
1323        record[1] = 1;
1324        for (index, value) in [
1325            transport.processes,
1326            transport.child_launches,
1327            transport.remote_launches,
1328            transport.workspace_capabilities,
1329            transport.scoped_server_records,
1330            transport.background_server_records,
1331            transport.corrupt_records,
1332            transport.corrupt_files,
1333        ]
1334        .into_iter()
1335        .enumerate()
1336        {
1337            put_u64(&mut record, 408 + index * 8, usize_u64(value)?);
1338        }
1339        put_u64(&mut record, 536, usize_u64(transport.guest_processes)?);
1340    }
1341
1342    let phase_tests = view
1343        .phases
1344        .iter()
1345        .map(|phase| phase.test.as_str())
1346        .collect::<BTreeSet<_>>();
1347    let empty_tests = selected_tests
1348        .iter()
1349        .filter(|test| {
1350            test.role == "test"
1351                && test.lines.is_empty()
1352                && test.hits.is_empty()
1353                && test.decisions.is_empty()
1354                && phase_tests.contains(test.id.as_str())
1355        })
1356        .collect::<Vec<_>>();
1357    put_u64(&mut record, 472, usize_u64(empty_tests.len())?);
1358    put_u32(
1359        &mut record,
1360        20,
1361        empty_tests
1362            .first()
1363            .map_or(Ok(NO_STRING), |test| strings.intern(&test.name))?,
1364    );
1365
1366    let entries = scope.as_ref().and_then(|scope| scope.entries);
1367    for (index, status) in ["included", "excluded", "ambiguous"]
1368        .into_iter()
1369        .enumerate()
1370    {
1371        put_u64(
1372            &mut record,
1373            480 + index * 8,
1374            usize_u64(entries.map_or(0, |entries| {
1375                entries
1376                    .iter()
1377                    .filter(|entry| {
1378                        entry.get("status").and_then(serde_json::Value::as_str) == Some(status)
1379                    })
1380                    .count()
1381            }))?,
1382        );
1383    }
1384    put_u32(
1385        &mut record,
1386        504,
1387        scope
1388            .as_ref()
1389            .map_or(Ok(NO_STRING), |scope| strings.intern(scope.language))?,
1390    );
1391    put_u32(
1392        &mut record,
1393        508,
1394        scope
1395            .as_ref()
1396            .map_or(Ok(NO_STRING), |scope| strings.intern(scope.model))?,
1397    );
1398    put_u32(
1399        &mut record,
1400        512,
1401        scope
1402            .as_ref()
1403            .and_then(|scope| scope.unit)
1404            .map_or(Ok(NO_STRING), |value| strings.intern(value))?,
1405    );
1406    if let Some(measurement_complete) = scope.as_ref().and_then(|scope| scope.measurement_complete)
1407    {
1408        record[516] = 1;
1409        record[517] = u8::from(measurement_complete);
1410    }
1411    Ok(record)
1412}
1413
1414fn scope_entry_records(
1415    view_id: CoverageViewId,
1416    view: &CoverageView,
1417    strings: &mut StringTable,
1418) -> Result<Vec<[u8; SCOPE_ENTRY_RECORD_SIZE]>, CoverageIndexError> {
1419    let Some(scope) = &view.scope else {
1420        return Ok(Vec::new());
1421    };
1422    if scope.get("mode").is_none() {
1423        return Ok(Vec::new());
1424    }
1425    let entries = scope
1426        .get("entries")
1427        .and_then(serde_json::Value::as_array)
1428        .ok_or(CoverageIndexError::InvalidRecord("source-scope entries"))?;
1429    let mut limitations = BTreeMap::<&str, (usize, u32)>::new();
1430    // As the file table reads them: a kind of a language's own -- Go's
1431    // `loop-without-condition`, a file that does not parse -- is one more
1432    // limitation of its file, under a kind this table does not name. Go, Rust
1433    // and JVM runs record a scope now, and refusing such a kind here refused
1434    // the whole run.
1435    for limitation in &view.limitations {
1436        let Some((file, kind)) = limitation_kind(limitation) else {
1437            continue;
1438        };
1439        let value = limitations.entry(file).or_default();
1440        value.0 += 1;
1441        value.1 |= match kind {
1442            "dynamic-code" => 1,
1443            "semantic-safety" => 2,
1444            "source-scope" => 4,
1445            _ => 8,
1446        };
1447    }
1448    entries
1449        .iter()
1450        .map(|entry| {
1451            let file = entry
1452                .get("file")
1453                .and_then(serde_json::Value::as_str)
1454                .ok_or(CoverageIndexError::InvalidRecord("source-scope file"))?;
1455            let status = entry
1456                .get("status")
1457                .and_then(serde_json::Value::as_str)
1458                .ok_or(CoverageIndexError::InvalidRecord("source-scope status"))?;
1459            let reason = entry
1460                .get("reason")
1461                .and_then(serde_json::Value::as_str)
1462                .ok_or(CoverageIndexError::InvalidRecord("source-scope reason"))?;
1463            let package_root = entry
1464                .get("packageRoot")
1465                .map(|value| {
1466                    value.as_str().ok_or(CoverageIndexError::InvalidRecord(
1467                        "source-scope package root",
1468                    ))
1469                })
1470                .transpose()?;
1471            let mut record = [0_u8; SCOPE_ENTRY_RECORD_SIZE];
1472            record[0] = view_id as u8;
1473            record[1] = match status {
1474                "included" => 0,
1475                "excluded" => 1,
1476                "ambiguous" => 2,
1477                _ => return Err(CoverageIndexError::InvalidRecord("source-scope status")),
1478            };
1479            put_u32(&mut record, 4, strings.intern(file)?);
1480            put_u32(&mut record, 8, strings.intern(reason)?);
1481            put_u32(
1482                &mut record,
1483                12,
1484                package_root.map_or(Ok(NO_STRING), |value| strings.intern(value))?,
1485            );
1486            let (count, mask) = limitations.get(file).copied().unwrap_or_default();
1487            put_u64(&mut record, 16, usize_u64(count)?);
1488            put_u32(&mut record, 24, mask);
1489            Ok(record)
1490        })
1491        .collect()
1492}
1493
1494fn optional_string_id(
1495    value: Option<&str>,
1496    strings: &mut StringTable,
1497) -> Result<u32, CoverageIndexError> {
1498    value.map_or(Ok(NO_STRING), |value| strings.intern(value))
1499}
1500
1501fn confidence_record(
1502    confidence: &crate::coverage_report::CoverageConfidence,
1503    strings: &mut StringTable,
1504    relations: &mut StringRelations,
1505) -> Result<[u8; CONFIDENCE_RECORD_SIZE], CoverageIndexError> {
1506    let mut record = [0_u8; CONFIDENCE_RECORD_SIZE];
1507    record[0] = match confidence.level.as_str() {
1508        "unexecuted" => 0,
1509        "executed" => 1,
1510        "action" => 2,
1511        "asserted" => 3,
1512        _ => return Err(CoverageIndexError::InvalidRecord("confidence level")),
1513    };
1514    record[1] = u8::from(confidence.setup_only)
1515        | (u8::from(confidence.background_only) << 1)
1516        | (u8::from(confidence.asserted) << 2)
1517        | (u8::from(confidence.e2e) << 3);
1518    for (index, values) in [&confidence.tests, &confidence.asserted_tests]
1519        .into_iter()
1520        .enumerate()
1521    {
1522        let (offset, count) = relations.push_ids(values, strings)?;
1523        put_u64(&mut record, 8 + index * 16, offset);
1524        put_u64(&mut record, 16 + index * 16, count);
1525    }
1526    for (index, values) in [&confidence.runners, &confidence.kinds]
1527        .into_iter()
1528        .enumerate()
1529    {
1530        let (offset, count) = relations.push(values, strings)?;
1531        put_u64(&mut record, 40 + index * 16, offset);
1532        put_u64(&mut record, 48 + index * 16, count);
1533    }
1534    Ok(record)
1535}
1536
1537fn line_record(
1538    view_id: CoverageViewId,
1539    line: &crate::coverage_report::LineResult,
1540    confidence_index: usize,
1541    strings: &mut StringTable,
1542    relations: &mut StringRelations,
1543) -> Result<[u8; LINE_RECORD_SIZE], CoverageIndexError> {
1544    let mut record = [0_u8; LINE_RECORD_SIZE];
1545    record[0] = view_id as u8;
1546    record[1] = u8::from(line.covered);
1547    // Inverted: a line every frontend declined is the exception, and a zeroed
1548    // byte then still reads as measured.
1549    record[2] = u8::from(!line.measured);
1550    put_u32(&mut record, 4, strings.intern(&line.file)?);
1551    put_u64(&mut record, 8, usize_u64(line.line)?);
1552    let (tests_offset, tests_count) = relations.push_ids(&line.tests, strings)?;
1553    put_u64(&mut record, 16, tests_offset);
1554    put_u64(&mut record, 24, tests_count);
1555    let (phases_offset, phases_count) = relations.push_ids(&line.phases, strings)?;
1556    put_u64(&mut record, 32, phases_offset);
1557    put_u64(&mut record, 40, phases_count);
1558    put_u64(&mut record, 48, usize_u64(confidence_index)?);
1559    Ok(record)
1560}
1561
1562fn test_summary_record(
1563    view_id: CoverageViewId,
1564    test: &crate::coverage_report::TestCoverageResult,
1565    strings: &mut StringTable,
1566    relations: &mut StringRelations,
1567) -> Result<[u8; TEST_SUMMARY_RECORD_SIZE], CoverageIndexError> {
1568    let mut record = [0_u8; TEST_SUMMARY_RECORD_SIZE];
1569    record[0] = view_id as u8;
1570    record[1] = match test.role.as_str() {
1571        "test" => 0,
1572        "setup" => 1,
1573        "background" => 2,
1574        _ => return Err(CoverageIndexError::InvalidRecord("test role")),
1575    };
1576    // Byte 3 was reserved from the start and the reader refuses a record that
1577    // sets it, which is what makes this an addition rather than a format
1578    // change: the record is the same 64 bytes it always was.
1579    record[3] = match test.attribution.as_str() {
1580        crate::coverage_report::ATTRIBUTION_EXACT => 0,
1581        crate::coverage_report::ATTRIBUTION_RUN_WIDE => 1,
1582        crate::coverage_report::ATTRIBUTION_PARTIAL => 2,
1583        crate::coverage_report::ATTRIBUTION_BY_TIME => 3,
1584        _ => return Err(CoverageIndexError::InvalidRecord("test attribution")),
1585    };
1586    record[2] = match test.outcome.as_str() {
1587        "passed" => 0,
1588        "failed" => 1,
1589        "flaky" => 2,
1590        "skipped" => 3,
1591        "timedOut" => 4,
1592        "interrupted" => 5,
1593        "unknown" => 6,
1594        "unstarted" => 7,
1595        "todo" => 8,
1596        _ => return Err(CoverageIndexError::InvalidRecord("test outcome")),
1597    };
1598    put_u32(&mut record, 4, strings.intern(&test.id)?);
1599    put_u32(&mut record, 8, strings.intern(&test.name)?);
1600    put_u32(
1601        &mut record,
1602        12,
1603        optional_string_id(test.file.as_deref(), strings)?,
1604    );
1605    put_u32(
1606        &mut record,
1607        16,
1608        optional_string_id(test.title.as_deref(), strings)?,
1609    );
1610    put_u32(&mut record, 20, strings.intern(&test.provenance.runner)?);
1611    put_u32(&mut record, 24, strings.intern(&test.provenance.kind)?);
1612    put_u32(
1613        &mut record,
1614        28,
1615        optional_string_id(test.provenance.project.as_deref(), strings)?,
1616    );
1617    put_u32(&mut record, 32, strings.intern(&test.provenance.source)?);
1618    // The test's tags, as a run of strings: bytes 40..52 were reserved.
1619    let (tags_offset, tags_count) = relations.push(&test.provenance.tags, strings)?;
1620    put_u64(&mut record, 40, tags_offset);
1621    put_u32(
1622        &mut record,
1623        48,
1624        u32::try_from(tags_count).map_err(|_| CoverageIndexError::SizeOverflow)?,
1625    );
1626    Ok(record)
1627}
1628
1629fn phase_summary_record(
1630    view_id: CoverageViewId,
1631    phase: &crate::coverage_report::PhaseResult,
1632    strings: &mut StringTable,
1633) -> Result<[u8; PHASE_SUMMARY_RECORD_SIZE], CoverageIndexError> {
1634    let mut record = [0_u8; PHASE_SUMMARY_RECORD_SIZE];
1635    record[0] = view_id as u8;
1636    put_u32(&mut record, 4, strings.intern(&phase.phase.id)?);
1637    put_u32(&mut record, 8, strings.intern(&phase.phase.kind)?);
1638    put_u32(&mut record, 12, strings.intern(&phase.phase.operation)?);
1639    put_u32(
1640        &mut record,
1641        16,
1642        optional_string_id(phase.phase.source.as_deref(), strings)?,
1643    );
1644    put_u32(&mut record, 20, strings.intern(&phase.test)?);
1645    put_u32(
1646        &mut record,
1647        24,
1648        optional_string_id(phase.phase.status.as_deref(), strings)?,
1649    );
1650    put_u32(
1651        &mut record,
1652        28,
1653        optional_string_id(phase.phase.caused_by_phase_id.as_deref(), strings)?,
1654    );
1655    put_u64(&mut record, 32, usize_u64(phase.lines.len())?);
1656    put_u64(
1657        &mut record,
1658        40,
1659        usize_u64(
1660            phase
1661                .decisions
1662                .iter()
1663                .map(|decision| decision.vectors.len())
1664                .sum(),
1665        )?,
1666    );
1667    Ok(record)
1668}
1669
1670struct AnchorInput<'a> {
1671    view_id: CoverageViewId,
1672    kind: u8,
1673    id: &'a str,
1674    file: &'a str,
1675    line: usize,
1676    column: usize,
1677    covered: bool,
1678    conditions: Option<(usize, usize)>,
1679    tests: &'a [Id],
1680}
1681
1682fn anchor_record(
1683    input: AnchorInput<'_>,
1684    strings: &mut StringTable,
1685    relations: &mut StringRelations,
1686) -> Result<[u8; ANCHOR_RECORD_SIZE], CoverageIndexError> {
1687    let mut record = [0_u8; ANCHOR_RECORD_SIZE];
1688    record[0] = input.view_id as u8;
1689    record[1] = input.kind;
1690    record[2] = u8::from(input.covered);
1691    put_u32(&mut record, 4, strings.intern(input.id)?);
1692    put_u32(&mut record, 8, strings.intern(input.file)?);
1693    put_u64(&mut record, 16, usize_u64(input.line)?);
1694    put_u64(&mut record, 24, usize_u64(input.column)?);
1695    if let Some((covered, total)) = input.conditions {
1696        put_u64(&mut record, 32, usize_u64(total)?);
1697        put_u64(&mut record, 40, usize_u64(covered)?);
1698    }
1699    let (tests_offset, tests_count) = relations.push_ids(input.tests, strings)?;
1700    put_u64(&mut record, 48, tests_offset);
1701    put_u64(&mut record, 56, tests_count);
1702    Ok(record)
1703}
1704
1705fn test_retry_record(
1706    view_id: CoverageViewId,
1707    test_id: &str,
1708    retry: usize,
1709    strings: &mut StringTable,
1710) -> Result<[u8; TEST_RETRY_RECORD_SIZE], CoverageIndexError> {
1711    let mut record = [0_u8; TEST_RETRY_RECORD_SIZE];
1712    record[0] = view_id as u8;
1713    put_u32(&mut record, 4, strings.intern(test_id)?);
1714    put_u64(&mut record, 8, usize_u64(retry)?);
1715    Ok(record)
1716}
1717
1718fn test_attempt_record(
1719    view_id: CoverageViewId,
1720    test_id: &str,
1721    attempt: &crate::coverage_report::TestAttempt,
1722    strings: &mut StringTable,
1723) -> Result<[u8; TEST_ATTEMPT_RECORD_SIZE], CoverageIndexError> {
1724    let mut record = [0_u8; TEST_ATTEMPT_RECORD_SIZE];
1725    record[0] = view_id as u8;
1726    put_u32(&mut record, 4, strings.intern(test_id)?);
1727    put_u64(&mut record, 8, usize_u64(attempt.retry)?);
1728    put_u32(&mut record, 16, strings.intern(&attempt.status)?);
1729    put_u32(
1730        &mut record,
1731        20,
1732        optional_string_id(attempt.expected_status.as_deref(), strings)?,
1733    );
1734    Ok(record)
1735}
1736
1737fn test_line_record(
1738    view_id: CoverageViewId,
1739    test_id: &str,
1740    line: &crate::coverage_report::SourceLine,
1741    strings: &mut StringTable,
1742) -> Result<[u8; TEST_LINE_RECORD_SIZE], CoverageIndexError> {
1743    let mut record = [0_u8; TEST_LINE_RECORD_SIZE];
1744    record[0] = view_id as u8;
1745    put_u32(&mut record, 4, strings.intern(test_id)?);
1746    put_u32(&mut record, 8, strings.intern(&line.file)?);
1747    put_u64(&mut record, 16, usize_u64(line.line)?);
1748    Ok(record)
1749}
1750
1751fn test_hit_record(
1752    view_id: CoverageViewId,
1753    test_id: &str,
1754    hit: &str,
1755    strings: &mut StringTable,
1756) -> Result<[u8; TEST_HIT_RECORD_SIZE], CoverageIndexError> {
1757    let mut record = [0_u8; TEST_HIT_RECORD_SIZE];
1758    record[0] = view_id as u8;
1759    put_u32(&mut record, 4, strings.intern(test_id)?);
1760    put_u32(&mut record, 8, strings.intern(hit)?);
1761    Ok(record)
1762}
1763
1764fn test_vector_record(
1765    vector: &McdcVector,
1766    values: &mut Vec<u8>,
1767) -> Result<[u8; TEST_VECTOR_RECORD_SIZE], CoverageIndexError> {
1768    let mut record = [0_u8; TEST_VECTOR_RECORD_SIZE];
1769    record[0] = u8::from(vector.outcome);
1770    put_u64(&mut record, 8, usize_u64(values.len())?);
1771    put_u64(&mut record, 16, usize_u64(vector.values.len())?);
1772    values.extend(vector.values.iter().map(|value| match value {
1773        None => 0,
1774        Some(false) => 1,
1775        Some(true) => 2,
1776    }));
1777    Ok(record)
1778}
1779
1780fn test_decision_record(
1781    view_id: CoverageViewId,
1782    test_id: &str,
1783    decision_id: &str,
1784    vectors_offset: usize,
1785    vectors_count: usize,
1786    strings: &mut StringTable,
1787) -> Result<[u8; TEST_DECISION_RECORD_SIZE], CoverageIndexError> {
1788    let mut record = [0_u8; TEST_DECISION_RECORD_SIZE];
1789    record[0] = view_id as u8;
1790    put_u32(&mut record, 4, strings.intern(test_id)?);
1791    put_u32(&mut record, 8, strings.intern(decision_id)?);
1792    put_u64(&mut record, 16, usize_u64(vectors_offset)?);
1793    put_u64(&mut record, 24, usize_u64(vectors_count)?);
1794    Ok(record)
1795}
1796
1797struct HitMetadataInput<'a> {
1798    view_id: CoverageViewId,
1799    kind: u8,
1800    id: &'a str,
1801    file: &'a str,
1802    line: usize,
1803    column: usize,
1804    branch_kind: Option<&'a str>,
1805    label: Option<&'a str>,
1806    alternative: Option<&'a str>,
1807    source: &'a str,
1808    tests: &'a [Id],
1809}
1810
1811fn hit_metadata_record(
1812    input: HitMetadataInput<'_>,
1813    strings: &mut StringTable,
1814    relations: &mut StringRelations,
1815) -> Result<[u8; HIT_METADATA_RECORD_SIZE], CoverageIndexError> {
1816    let mut record = [0_u8; HIT_METADATA_RECORD_SIZE];
1817    record[0] = input.view_id as u8;
1818    record[1] = input.kind;
1819    put_u32(&mut record, 4, strings.intern(input.id)?);
1820    put_u32(&mut record, 8, strings.intern(input.file)?);
1821    put_u64(&mut record, 16, usize_u64(input.line)?);
1822    put_u64(&mut record, 24, usize_u64(input.column)?);
1823    put_u32(
1824        &mut record,
1825        32,
1826        optional_string_id(input.branch_kind, strings)?,
1827    );
1828    put_u32(&mut record, 36, optional_string_id(input.label, strings)?);
1829    put_u32(
1830        &mut record,
1831        40,
1832        optional_string_id(input.alternative, strings)?,
1833    );
1834    put_u32(&mut record, 44, strings.intern(input.source)?);
1835    let (tests_offset, tests_count) = relations.push_ids(input.tests, strings)?;
1836    put_u64(&mut record, 48, tests_offset);
1837    put_u64(&mut record, 56, tests_count);
1838    Ok(record)
1839}
1840
1841fn limitation_record(
1842    view_id: CoverageViewId,
1843    limitation: &serde_json::Value,
1844    strings: &mut StringTable,
1845) -> Result<[u8; LIMITATION_RECORD_SIZE], CoverageIndexError> {
1846    let field = |name| {
1847        limitation
1848            .get(name)
1849            .and_then(serde_json::Value::as_str)
1850            .ok_or(CoverageIndexError::InvalidRecord("coverage limitation"))
1851    };
1852    let number = |name| {
1853        limitation
1854            .get(name)
1855            .and_then(serde_json::Value::as_u64)
1856            .ok_or(CoverageIndexError::InvalidRecord("coverage limitation"))
1857    };
1858    let mut record = [0_u8; LIMITATION_RECORD_SIZE];
1859    record[0] = view_id as u8;
1860    record[1] = u8::from(crate::coverage_report::blocking_limitation(limitation));
1861    put_u32(&mut record, 4, strings.intern(field("id")?)?);
1862    put_u32(&mut record, 8, strings.intern(field("kind")?)?);
1863    put_u32(&mut record, 12, strings.intern(field("file")?)?);
1864    put_u32(&mut record, 16, strings.intern(field("source")?)?);
1865    put_u32(&mut record, 20, strings.intern(field("reason")?)?);
1866    put_u64(&mut record, 24, number("line")?);
1867    put_u64(&mut record, 32, number("column")?);
1868    Ok(record)
1869}
1870
1871fn decision_metadata_record(
1872    view_id: CoverageViewId,
1873    decision: &crate::coverage_report::DecisionResult,
1874    strings: &mut StringTable,
1875    relations: &mut StringRelations,
1876) -> Result<[u8; DECISION_METADATA_RECORD_SIZE], CoverageIndexError> {
1877    let mut record = [0_u8; DECISION_METADATA_RECORD_SIZE];
1878    record[0] = view_id as u8;
1879    put_u32(&mut record, 4, strings.intern(&decision.meta.id)?);
1880    put_u32(&mut record, 8, strings.intern(&decision.meta.file)?);
1881    put_u32(&mut record, 12, strings.intern(&decision.meta.source)?);
1882    put_u32(&mut record, 16, strings.intern(&decision.meta.kind)?);
1883    put_u64(&mut record, 24, usize_u64(decision.meta.line)?);
1884    put_u64(&mut record, 32, usize_u64(decision.meta.column)?);
1885    let (conditions_offset, conditions_count) =
1886        relations.push(decision.meta.conditions.clone(), strings)?;
1887    put_u64(&mut record, 40, conditions_offset);
1888    put_u64(&mut record, 48, conditions_count);
1889    Ok(record)
1890}
1891
1892fn decision_vector_observation_record(
1893    observation: &crate::coverage_report::VectorObservation,
1894    confidence_index: usize,
1895    vector_index: usize,
1896    strings: &mut StringTable,
1897    relations: &mut StringRelations,
1898) -> Result<[u8; DECISION_VECTOR_OBSERVATION_RECORD_SIZE], CoverageIndexError> {
1899    let mut record = [0_u8; DECISION_VECTOR_OBSERVATION_RECORD_SIZE];
1900    put_u64(&mut record, 0, usize_u64(confidence_index)?);
1901    put_u64(&mut record, 8, usize_u64(vector_index)?);
1902    for (offset, values) in [
1903        (16, &observation.tests),
1904        (32, &observation.phases),
1905        (48, &observation.explicit_phases),
1906    ] {
1907        let (relation_offset, relation_count) = relations.push_ids(values, strings)?;
1908        put_u64(&mut record, offset, relation_offset);
1909        put_u64(&mut record, offset + 8, relation_count);
1910    }
1911    Ok(record)
1912}
1913
1914fn decision_condition_record(
1915    condition: &crate::coverage_report::ConditionResult,
1916    witness_vectors: Option<(usize, usize)>,
1917    strings: &mut StringTable,
1918    relations: &mut StringRelations,
1919) -> Result<[u8; DECISION_CONDITION_RECORD_SIZE], CoverageIndexError> {
1920    let mut record = [0_u8; DECISION_CONDITION_RECORD_SIZE];
1921    record[0] = u8::from(condition.covered)
1922        | (u8::from(condition.assertion_covered) << 1)
1923        | (u8::from(condition.witness.is_some()) << 2);
1924    put_u32(&mut record, 4, strings.intern(&condition.source)?);
1925    put_u64(&mut record, 8, usize_u64(condition.index)?);
1926    if let Some((first, second)) = witness_vectors {
1927        put_u64(&mut record, 16, usize_u64(first)?);
1928        put_u64(&mut record, 24, usize_u64(second)?);
1929    }
1930    let empty = [Vec::new(), Vec::new()];
1931    let witness_tests = condition.witness_tests.as_ref().unwrap_or(&empty);
1932    for (offset, values) in [(32, &witness_tests[0]), (48, &witness_tests[1])] {
1933        let (relation_offset, relation_count) = relations.push_ids(values, strings)?;
1934        put_u64(&mut record, offset, relation_offset);
1935        put_u64(&mut record, offset + 8, relation_count);
1936    }
1937    Ok(record)
1938}
1939
1940struct DecisionDetailInput<'a> {
1941    view_id: CoverageViewId,
1942    decision: &'a crate::coverage_report::DecisionResult,
1943    confidence_index: usize,
1944    observations: (usize, usize),
1945    conditions: (usize, usize),
1946}
1947
1948fn decision_detail_record(
1949    input: DecisionDetailInput<'_>,
1950    strings: &mut StringTable,
1951    relations: &mut StringRelations,
1952) -> Result<[u8; DECISION_DETAIL_RECORD_SIZE], CoverageIndexError> {
1953    let mut record = [0_u8; DECISION_DETAIL_RECORD_SIZE];
1954    record[0] = input.view_id as u8;
1955    record[1] = u8::from(input.decision.executed) | (u8::from(input.decision.covered) << 1);
1956    put_u32(&mut record, 4, strings.intern(&input.decision.meta.id)?);
1957    put_u64(&mut record, 8, usize_u64(input.confidence_index)?);
1958    let (tests_offset, tests_count) = relations.push_ids(&input.decision.tests, strings)?;
1959    put_u64(&mut record, 16, tests_offset);
1960    put_u64(&mut record, 24, tests_count);
1961    put_u64(&mut record, 32, usize_u64(input.observations.0)?);
1962    put_u64(&mut record, 40, usize_u64(input.observations.1)?);
1963    put_u64(&mut record, 48, usize_u64(input.conditions.0)?);
1964    put_u64(&mut record, 56, usize_u64(input.conditions.1)?);
1965    Ok(record)
1966}
1967
1968fn coverage_model_record(
1969    variant: &str,
1970    model: &CoverageModel,
1971    strings: &mut StringTable,
1972    relations: &mut StringRelations,
1973) -> Result<[u8; COVERAGE_MODEL_RECORD_SIZE], CoverageIndexError> {
1974    let mut record = [0_u8; COVERAGE_MODEL_RECORD_SIZE];
1975    put_u32(&mut record, 0, strings.intern(variant)?);
1976    put_u32(&mut record, 4, strings.intern(&model.name)?);
1977    put_u32(&mut record, 8, strings.intern(&model.completeness_meaning)?);
1978    let (measured_offset, measured_count) = relations.push(model.measured.clone(), strings)?;
1979    put_u64(&mut record, 16, measured_offset);
1980    put_u64(&mut record, 24, measured_count);
1981    let (not_measured_offset, not_measured_count) =
1982        relations.push(model.not_measured.clone(), strings)?;
1983    put_u64(&mut record, 32, not_measured_offset);
1984    put_u64(&mut record, 40, not_measured_count);
1985    Ok(record)
1986}
1987
1988pub fn coverage_index_sections(
1989    report: &CoverageReport,
1990) -> Result<Vec<QueryIndexSection>, CoverageIndexError> {
1991    let views = [
1992        (CoverageViewId::All, &report.view),
1993        (CoverageViewId::Passed, &report.filters.passed),
1994        (CoverageViewId::Failed, &report.filters.failed),
1995    ];
1996    let mut strings = StringTable::default();
1997    let mut relations = StringRelations::default();
1998    let mut summaries = Vec::with_capacity(views.len() * SUMMARY_RECORD_SIZE);
1999    let mut gaps = Vec::new();
2000    let mut decision_gaps = Vec::new();
2001    let mut dimensions = Vec::new();
2002    let mut projection_records = Vec::new();
2003    let mut scope_entries = Vec::new();
2004    let mut confidence_records = Vec::new();
2005    let mut line_records = Vec::new();
2006    let mut test_summaries = Vec::new();
2007    let mut phase_summaries = Vec::new();
2008    let mut anchors = Vec::new();
2009    let mut test_retries = Vec::new();
2010    let mut test_attempts = Vec::new();
2011    let mut test_lines = Vec::new();
2012    let mut test_hits = Vec::new();
2013    let mut test_decisions = Vec::new();
2014    let mut test_vectors = Vec::new();
2015    let mut vector_values = Vec::new();
2016    let mut hit_metadata = Vec::new();
2017    let mut decision_metadata = Vec::new();
2018    let mut decision_details = Vec::new();
2019    let mut decision_vector_observations = Vec::new();
2020    let mut decision_conditions = Vec::new();
2021    let mut limitations = Vec::new();
2022    for (id, view) in views {
2023        summaries.extend_from_slice(&summary_record(id, view, &mut strings)?);
2024        projection_records.extend_from_slice(&projection_record(
2025            id,
2026            view,
2027            None,
2028            None,
2029            None,
2030            &mut strings,
2031            &mut relations,
2032        )?);
2033        for entry in scope_entry_records(id, view, &mut strings)? {
2034            scope_entries.extend_from_slice(&entry);
2035        }
2036        for limitation in &view.limitations {
2037            limitations.extend_from_slice(&limitation_record(id, limitation, &mut strings)?);
2038        }
2039        for line in &view.lines {
2040            let confidence_index = confidence_records.len() / CONFIDENCE_RECORD_SIZE;
2041            confidence_records.extend_from_slice(&confidence_record(
2042                &line.confidence,
2043                &mut strings,
2044                &mut relations,
2045            )?);
2046            line_records.extend_from_slice(&line_record(
2047                id,
2048                line,
2049                confidence_index,
2050                &mut strings,
2051                &mut relations,
2052            )?);
2053        }
2054        for test in &view.tests {
2055            test_summaries.extend_from_slice(&test_summary_record(
2056                id,
2057                test,
2058                &mut strings,
2059                &mut relations,
2060            )?);
2061            for retry in &test.retries {
2062                test_retries.extend_from_slice(&test_retry_record(
2063                    id,
2064                    &test.id,
2065                    *retry,
2066                    &mut strings,
2067                )?);
2068            }
2069            for attempt in &test.attempts {
2070                test_attempts.extend_from_slice(&test_attempt_record(
2071                    id,
2072                    &test.id,
2073                    attempt,
2074                    &mut strings,
2075                )?);
2076            }
2077            for line in &test.lines {
2078                test_lines.extend_from_slice(&test_line_record(id, &test.id, line, &mut strings)?);
2079            }
2080            for hit in &test.hits {
2081                test_hits.extend_from_slice(&test_hit_record(id, &test.id, hit, &mut strings)?);
2082            }
2083            for decision in &test.decisions {
2084                let vectors_offset = test_vectors.len() / TEST_VECTOR_RECORD_SIZE;
2085                for vector in &decision.vectors {
2086                    test_vectors
2087                        .extend_from_slice(&test_vector_record(vector, &mut vector_values)?);
2088                }
2089                test_decisions.extend_from_slice(&test_decision_record(
2090                    id,
2091                    &test.id,
2092                    &decision.id,
2093                    vectors_offset,
2094                    decision.vectors.len(),
2095                    &mut strings,
2096                )?);
2097            }
2098        }
2099        for phase in &view.phases {
2100            phase_summaries.extend_from_slice(&phase_summary_record(id, phase, &mut strings)?);
2101        }
2102        for decision in &view.decisions {
2103            let confidence_index = confidence_records.len() / CONFIDENCE_RECORD_SIZE;
2104            confidence_records.extend_from_slice(&confidence_record(
2105                &decision.confidence,
2106                &mut strings,
2107                &mut relations,
2108            )?);
2109            let observations_offset =
2110                decision_vector_observations.len() / DECISION_VECTOR_OBSERVATION_RECORD_SIZE;
2111            for observation in &decision.vector_observations {
2112                let observation_confidence = confidence_records.len() / CONFIDENCE_RECORD_SIZE;
2113                confidence_records.extend_from_slice(&confidence_record(
2114                    &observation.confidence,
2115                    &mut strings,
2116                    &mut relations,
2117                )?);
2118                let vector_index = test_vectors.len() / TEST_VECTOR_RECORD_SIZE;
2119                test_vectors.extend_from_slice(&test_vector_record(
2120                    &observation.vector,
2121                    &mut vector_values,
2122                )?);
2123                decision_vector_observations.extend_from_slice(
2124                    &decision_vector_observation_record(
2125                        observation,
2126                        observation_confidence,
2127                        vector_index,
2128                        &mut strings,
2129                        &mut relations,
2130                    )?,
2131                );
2132            }
2133            let conditions_offset = decision_conditions.len() / DECISION_CONDITION_RECORD_SIZE;
2134            for condition in &decision.conditions {
2135                let witness_vectors = if let Some(witness) = &condition.witness {
2136                    let first = test_vectors.len() / TEST_VECTOR_RECORD_SIZE;
2137                    test_vectors
2138                        .extend_from_slice(&test_vector_record(&witness[0], &mut vector_values)?);
2139                    let second = test_vectors.len() / TEST_VECTOR_RECORD_SIZE;
2140                    test_vectors
2141                        .extend_from_slice(&test_vector_record(&witness[1], &mut vector_values)?);
2142                    Some((first, second))
2143                } else {
2144                    None
2145                };
2146                decision_conditions.extend_from_slice(&decision_condition_record(
2147                    condition,
2148                    witness_vectors,
2149                    &mut strings,
2150                    &mut relations,
2151                )?);
2152            }
2153            decision_details.extend_from_slice(&decision_detail_record(
2154                DecisionDetailInput {
2155                    view_id: id,
2156                    decision,
2157                    confidence_index,
2158                    observations: (observations_offset, decision.vector_observations.len()),
2159                    conditions: (conditions_offset, decision.conditions.len()),
2160                },
2161                &mut strings,
2162                &mut relations,
2163            )?);
2164            decision_metadata.extend_from_slice(&decision_metadata_record(
2165                id,
2166                decision,
2167                &mut strings,
2168                &mut relations,
2169            )?);
2170            anchors.extend_from_slice(&anchor_record(
2171                AnchorInput {
2172                    view_id: id,
2173                    kind: 0,
2174                    id: &decision.meta.id,
2175                    file: &decision.meta.file,
2176                    line: decision.meta.line,
2177                    column: decision.meta.column,
2178                    covered: decision.covered,
2179                    conditions: Some((
2180                        decision
2181                            .conditions
2182                            .iter()
2183                            .filter(|condition| condition.covered)
2184                            .count(),
2185                        decision.conditions.len(),
2186                    )),
2187                    tests: &decision.tests,
2188                },
2189                &mut strings,
2190                &mut relations,
2191            )?);
2192        }
2193        for branch in &view.branches {
2194            anchors.extend_from_slice(&anchor_record(
2195                AnchorInput {
2196                    view_id: id,
2197                    kind: 1,
2198                    id: &branch.meta.id,
2199                    file: &branch.meta.file,
2200                    line: branch.meta.line,
2201                    column: branch.meta.column,
2202                    covered: branch.covered,
2203                    conditions: None,
2204                    tests: &[],
2205                },
2206                &mut strings,
2207                &mut relations,
2208            )?);
2209            for alternative in &branch.alternatives {
2210                hit_metadata.extend_from_slice(&hit_metadata_record(
2211                    HitMetadataInput {
2212                        view_id: id,
2213                        kind: 2,
2214                        id: &alternative.id,
2215                        file: &branch.meta.file,
2216                        line: branch.meta.line,
2217                        column: branch.meta.column,
2218                        branch_kind: Some(&branch.meta.kind),
2219                        label: Some(&branch.meta.id),
2220                        alternative: Some(&alternative.label),
2221                        source: &branch.meta.source,
2222                        tests: &alternative.tests,
2223                    },
2224                    &mut strings,
2225                    &mut relations,
2226                )?);
2227            }
2228        }
2229        for point in &view.points {
2230            anchors.extend_from_slice(&anchor_record(
2231                AnchorInput {
2232                    view_id: id,
2233                    kind: match point.meta.kind {
2234                        crate::coverage_analysis::PointKind::Statement => 2,
2235                        crate::coverage_analysis::PointKind::Function => 3,
2236                    },
2237                    id: &point.meta.id,
2238                    file: &point.meta.file,
2239                    line: point.meta.line,
2240                    column: point.meta.column,
2241                    covered: point.covered,
2242                    conditions: None,
2243                    tests: &point.tests,
2244                },
2245                &mut strings,
2246                &mut relations,
2247            )?);
2248            hit_metadata.extend_from_slice(&hit_metadata_record(
2249                HitMetadataInput {
2250                    view_id: id,
2251                    kind: match point.meta.kind {
2252                        crate::coverage_analysis::PointKind::Statement => 0,
2253                        crate::coverage_analysis::PointKind::Function => 1,
2254                    },
2255                    id: &point.meta.id,
2256                    file: &point.meta.file,
2257                    line: point.meta.line,
2258                    column: point.meta.column,
2259                    branch_kind: None,
2260                    label: point.meta.label.as_deref(),
2261                    alternative: None,
2262                    source: &point.meta.source,
2263                    tests: &point.tests,
2264                },
2265                &mut strings,
2266                &mut relations,
2267            )?);
2268        }
2269        for value in &view.coverage_by_kind {
2270            dimensions.extend_from_slice(&dimension_record(
2271                id,
2272                CoverageDimension::Kind,
2273                value,
2274                &mut strings,
2275            )?);
2276        }
2277        for value in &view.coverage_by_runner {
2278            dimensions.extend_from_slice(&dimension_record(
2279                id,
2280                CoverageDimension::Runner,
2281                value,
2282                &mut strings,
2283            )?);
2284        }
2285        let role = |role: &str| view.tests.iter().filter(|test| test.role == role).count();
2286        dimensions.extend_from_slice(&dimension_record(
2287            id,
2288            CoverageDimension::Tests,
2289            &crate::coverage_report::DimensionCoverage {
2290                kind: None,
2291                runner: None,
2292                tests: role("test"),
2293                setups: role("setup"),
2294                attributed: view
2295                    .tests
2296                    .iter()
2297                    .filter(|test| {
2298                        test.role == "test"
2299                            && crate::coverage_report::coverage_is_its_own(&test.attribution)
2300                    })
2301                    .count(),
2302                summary: crate::coverage_report::summary_for_tests(view)
2303                    .map_err(|_| CoverageIndexError::InvalidRecord("coverage of the tests"))?,
2304            },
2305            &mut strings,
2306        )?);
2307        for decision in &view.decisions {
2308            decision_gaps.extend_from_slice(&decision_gap_record(
2309                id,
2310                decision,
2311                None,
2312                None,
2313                None,
2314                &mut strings,
2315            )?);
2316        }
2317        for (file, gap) in file_gaps(view, None)? {
2318            gaps.extend_from_slice(&file_gap_record(id, &file, &gap, None, None, &mut strings)?);
2319        }
2320        for (kind, runner, selected) in projections(view) {
2321            projection_records.extend_from_slice(&projection_record(
2322                id,
2323                view,
2324                Some(&selected),
2325                kind.as_deref(),
2326                runner.as_deref(),
2327                &mut strings,
2328                &mut relations,
2329            )?);
2330            for decision in &view.decisions {
2331                decision_gaps.extend_from_slice(&decision_gap_record(
2332                    id,
2333                    decision,
2334                    Some(&selected),
2335                    kind.as_deref(),
2336                    runner.as_deref(),
2337                    &mut strings,
2338                )?);
2339            }
2340            for (file, gap) in file_gaps(view, Some(&selected))? {
2341                gaps.extend_from_slice(&file_gap_record(
2342                    id,
2343                    &file,
2344                    &gap,
2345                    kind.as_deref(),
2346                    runner.as_deref(),
2347                    &mut strings,
2348                )?);
2349            }
2350        }
2351        // What the tests cover of each file, all kinds together: a directory
2352        // read e2e 18.18%, every other kind 0.00% and 100.00% in all, and
2353        // nothing said that the rest ran while no test was running. Filed
2354        // under the name the tests' own dimension has, which no kind can be.
2355        let tested = crate::coverage_report::entries_in_kind_rows(view)
2356            .into_iter()
2357            .collect::<Selected>();
2358        if !tested.is_empty() {
2359            for (file, gap) in file_gaps(view, Some(&tested))? {
2360                gaps.extend_from_slice(&file_gap_record(
2361                    id,
2362                    &file,
2363                    &gap,
2364                    Some(ALL_TESTS),
2365                    None,
2366                    &mut strings,
2367                )?);
2368            }
2369        }
2370    }
2371    let model = coverage_model_record(
2372        &report.view.variant,
2373        &report.view.model,
2374        &mut strings,
2375        &mut relations,
2376    )?;
2377    let [blob, string_records] = strings.sections()?;
2378    let string_relations = relations.section()?;
2379    Ok(vec![
2380        blob,
2381        string_records,
2382        string_relations,
2383        QueryIndexSection {
2384            kind: SECTION_VIEW_SUMMARIES,
2385            record_size: SUMMARY_RECORD_SIZE as u32,
2386            count: usize_u64(summaries.len() / SUMMARY_RECORD_SIZE)?,
2387            bytes: summaries,
2388        },
2389        QueryIndexSection {
2390            kind: SECTION_FILE_GAPS,
2391            record_size: FILE_GAP_RECORD_SIZE as u32,
2392            count: usize_u64(gaps.len() / FILE_GAP_RECORD_SIZE)?,
2393            bytes: gaps,
2394        },
2395        QueryIndexSection {
2396            kind: SECTION_DECISION_GAPS,
2397            record_size: DECISION_GAP_RECORD_SIZE as u32,
2398            count: usize_u64(decision_gaps.len() / DECISION_GAP_RECORD_SIZE)?,
2399            bytes: decision_gaps,
2400        },
2401        QueryIndexSection {
2402            kind: SECTION_DIMENSIONS,
2403            record_size: DIMENSION_RECORD_SIZE as u32,
2404            count: usize_u64(dimensions.len() / DIMENSION_RECORD_SIZE)?,
2405            bytes: dimensions,
2406        },
2407        QueryIndexSection {
2408            kind: SECTION_PROJECTIONS,
2409            record_size: PROJECTION_RECORD_SIZE as u32,
2410            count: usize_u64(projection_records.len() / PROJECTION_RECORD_SIZE)?,
2411            bytes: projection_records,
2412        },
2413        QueryIndexSection {
2414            kind: SECTION_SCOPE_ENTRIES,
2415            record_size: SCOPE_ENTRY_RECORD_SIZE as u32,
2416            count: usize_u64(scope_entries.len() / SCOPE_ENTRY_RECORD_SIZE)?,
2417            bytes: scope_entries,
2418        },
2419        QueryIndexSection {
2420            kind: SECTION_CONFIDENCE,
2421            record_size: CONFIDENCE_RECORD_SIZE as u32,
2422            count: usize_u64(confidence_records.len() / CONFIDENCE_RECORD_SIZE)?,
2423            bytes: confidence_records,
2424        },
2425        QueryIndexSection {
2426            kind: SECTION_LINES,
2427            record_size: LINE_RECORD_SIZE as u32,
2428            count: usize_u64(line_records.len() / LINE_RECORD_SIZE)?,
2429            bytes: line_records,
2430        },
2431        QueryIndexSection {
2432            kind: SECTION_TEST_SUMMARIES,
2433            record_size: TEST_SUMMARY_RECORD_SIZE as u32,
2434            count: usize_u64(test_summaries.len() / TEST_SUMMARY_RECORD_SIZE)?,
2435            bytes: test_summaries,
2436        },
2437        QueryIndexSection {
2438            kind: SECTION_PHASE_SUMMARIES,
2439            record_size: PHASE_SUMMARY_RECORD_SIZE as u32,
2440            count: usize_u64(phase_summaries.len() / PHASE_SUMMARY_RECORD_SIZE)?,
2441            bytes: phase_summaries,
2442        },
2443        QueryIndexSection {
2444            kind: SECTION_ANCHORS,
2445            record_size: ANCHOR_RECORD_SIZE as u32,
2446            count: usize_u64(anchors.len() / ANCHOR_RECORD_SIZE)?,
2447            bytes: anchors,
2448        },
2449        QueryIndexSection {
2450            kind: SECTION_TEST_RETRIES,
2451            record_size: TEST_RETRY_RECORD_SIZE as u32,
2452            count: usize_u64(test_retries.len() / TEST_RETRY_RECORD_SIZE)?,
2453            bytes: test_retries,
2454        },
2455        QueryIndexSection {
2456            kind: SECTION_TEST_ATTEMPTS,
2457            record_size: TEST_ATTEMPT_RECORD_SIZE as u32,
2458            count: usize_u64(test_attempts.len() / TEST_ATTEMPT_RECORD_SIZE)?,
2459            bytes: test_attempts,
2460        },
2461        QueryIndexSection {
2462            kind: SECTION_TEST_LINES,
2463            record_size: TEST_LINE_RECORD_SIZE as u32,
2464            count: usize_u64(test_lines.len() / TEST_LINE_RECORD_SIZE)?,
2465            bytes: test_lines,
2466        },
2467        QueryIndexSection {
2468            kind: SECTION_TEST_HITS,
2469            record_size: TEST_HIT_RECORD_SIZE as u32,
2470            count: usize_u64(test_hits.len() / TEST_HIT_RECORD_SIZE)?,
2471            bytes: test_hits,
2472        },
2473        QueryIndexSection {
2474            kind: SECTION_TEST_DECISIONS,
2475            record_size: TEST_DECISION_RECORD_SIZE as u32,
2476            count: usize_u64(test_decisions.len() / TEST_DECISION_RECORD_SIZE)?,
2477            bytes: test_decisions,
2478        },
2479        QueryIndexSection {
2480            kind: SECTION_TEST_VECTORS,
2481            record_size: TEST_VECTOR_RECORD_SIZE as u32,
2482            count: usize_u64(test_vectors.len() / TEST_VECTOR_RECORD_SIZE)?,
2483            bytes: test_vectors,
2484        },
2485        QueryIndexSection {
2486            kind: SECTION_VECTOR_VALUES,
2487            record_size: 1,
2488            count: usize_u64(vector_values.len())?,
2489            bytes: vector_values,
2490        },
2491        QueryIndexSection {
2492            kind: SECTION_HIT_METADATA,
2493            record_size: HIT_METADATA_RECORD_SIZE as u32,
2494            count: usize_u64(hit_metadata.len() / HIT_METADATA_RECORD_SIZE)?,
2495            bytes: hit_metadata,
2496        },
2497        QueryIndexSection {
2498            kind: SECTION_DECISION_METADATA,
2499            record_size: DECISION_METADATA_RECORD_SIZE as u32,
2500            count: usize_u64(decision_metadata.len() / DECISION_METADATA_RECORD_SIZE)?,
2501            bytes: decision_metadata,
2502        },
2503        QueryIndexSection {
2504            kind: SECTION_DECISION_DETAILS,
2505            record_size: DECISION_DETAIL_RECORD_SIZE as u32,
2506            count: usize_u64(decision_details.len() / DECISION_DETAIL_RECORD_SIZE)?,
2507            bytes: decision_details,
2508        },
2509        QueryIndexSection {
2510            kind: SECTION_DECISION_VECTOR_OBSERVATIONS,
2511            record_size: DECISION_VECTOR_OBSERVATION_RECORD_SIZE as u32,
2512            count: usize_u64(
2513                decision_vector_observations.len() / DECISION_VECTOR_OBSERVATION_RECORD_SIZE,
2514            )?,
2515            bytes: decision_vector_observations,
2516        },
2517        QueryIndexSection {
2518            kind: SECTION_DECISION_CONDITIONS,
2519            record_size: DECISION_CONDITION_RECORD_SIZE as u32,
2520            count: usize_u64(decision_conditions.len() / DECISION_CONDITION_RECORD_SIZE)?,
2521            bytes: decision_conditions,
2522        },
2523        QueryIndexSection {
2524            kind: SECTION_LIMITATIONS,
2525            record_size: LIMITATION_RECORD_SIZE as u32,
2526            count: usize_u64(limitations.len() / LIMITATION_RECORD_SIZE)?,
2527            bytes: limitations,
2528        },
2529        QueryIndexSection {
2530            kind: SECTION_COVERAGE_MODEL,
2531            record_size: COVERAGE_MODEL_RECORD_SIZE as u32,
2532            count: 1,
2533            bytes: model.to_vec(),
2534        },
2535    ])
2536}
2537
2538pub struct CoverageIndex<'a> {
2539    index: &'a QueryIndex,
2540}
2541
2542impl<'a> CoverageIndex<'a> {
2543    pub fn new(index: &'a QueryIndex) -> Result<Self, CoverageIndexError> {
2544        for (kind, size) in [
2545            (SECTION_STRINGS, STRING_RECORD_SIZE),
2546            (SECTION_VIEW_SUMMARIES, SUMMARY_RECORD_SIZE),
2547            (SECTION_FILE_GAPS, FILE_GAP_RECORD_SIZE),
2548            (SECTION_DECISION_GAPS, DECISION_GAP_RECORD_SIZE),
2549            (SECTION_DIMENSIONS, DIMENSION_RECORD_SIZE),
2550            (SECTION_PROJECTIONS, PROJECTION_RECORD_SIZE),
2551            (SECTION_SCOPE_ENTRIES, SCOPE_ENTRY_RECORD_SIZE),
2552            (SECTION_CONFIDENCE, CONFIDENCE_RECORD_SIZE),
2553            (SECTION_LINES, LINE_RECORD_SIZE),
2554            (SECTION_TEST_SUMMARIES, TEST_SUMMARY_RECORD_SIZE),
2555            (SECTION_PHASE_SUMMARIES, PHASE_SUMMARY_RECORD_SIZE),
2556            (SECTION_ANCHORS, ANCHOR_RECORD_SIZE),
2557            (SECTION_TEST_RETRIES, TEST_RETRY_RECORD_SIZE),
2558            (SECTION_TEST_ATTEMPTS, TEST_ATTEMPT_RECORD_SIZE),
2559            (SECTION_TEST_LINES, TEST_LINE_RECORD_SIZE),
2560            (SECTION_TEST_HITS, TEST_HIT_RECORD_SIZE),
2561            (SECTION_TEST_DECISIONS, TEST_DECISION_RECORD_SIZE),
2562            (SECTION_TEST_VECTORS, TEST_VECTOR_RECORD_SIZE),
2563            (SECTION_VECTOR_VALUES, 1),
2564            (SECTION_HIT_METADATA, HIT_METADATA_RECORD_SIZE),
2565            (SECTION_DECISION_METADATA, DECISION_METADATA_RECORD_SIZE),
2566            (SECTION_DECISION_DETAILS, DECISION_DETAIL_RECORD_SIZE),
2567            (
2568                SECTION_DECISION_VECTOR_OBSERVATIONS,
2569                DECISION_VECTOR_OBSERVATION_RECORD_SIZE,
2570            ),
2571            (SECTION_DECISION_CONDITIONS, DECISION_CONDITION_RECORD_SIZE),
2572            (SECTION_LIMITATIONS, LIMITATION_RECORD_SIZE),
2573            (SECTION_COVERAGE_MODEL, COVERAGE_MODEL_RECORD_SIZE),
2574        ] {
2575            if index.descriptor(kind)?.record_size as usize != size {
2576                return Err(CoverageIndexError::InvalidRecord("record size"));
2577            }
2578        }
2579        index.descriptor(SECTION_STRING_BYTES)?;
2580        if index.descriptor(SECTION_STRING_RELATIONS)?.record_size != 4 {
2581            return Err(CoverageIndexError::InvalidRecord(
2582                "string-relation record size",
2583            ));
2584        }
2585        Ok(Self { index })
2586    }
2587
2588    pub fn model(&self) -> Result<IndexedCoverageModel, CoverageIndexError> {
2589        let descriptor = self.index.descriptor(SECTION_COVERAGE_MODEL)?;
2590        if descriptor.count != 1 {
2591            return Err(CoverageIndexError::InvalidRecord(
2592                "coverage model record count",
2593            ));
2594        }
2595        let record = self.index.record(SECTION_COVERAGE_MODEL, 0)?;
2596        if record[12..16].iter().any(|byte| *byte != 0) {
2597            return Err(CoverageIndexError::InvalidRecord(
2598                "coverage model reserved bytes",
2599            ));
2600        }
2601        Ok(IndexedCoverageModel {
2602            schema_version: COVERAGE_MODEL_SCHEMA_VERSION,
2603            variant: self.string(get_u32(record, 0))?,
2604            name: self.string(get_u32(record, 4))?,
2605            completeness_meaning: self.string(get_u32(record, 8))?,
2606            measured: self.relation_strings(get_u64(record, 16), get_u64(record, 24))?,
2607            not_measured: self.relation_strings(get_u64(record, 32), get_u64(record, 40))?,
2608        })
2609    }
2610
2611    /// Whether a string is `expected`, compared in place: a filter asks this
2612    /// of every record, and copying each one out to compare it was most of
2613    /// a one-file query's time.
2614    fn string_equals(&self, id: u32, expected: &str) -> Result<bool, CoverageIndexError> {
2615        let record = self.index.record(SECTION_STRINGS, u64::from(id))?;
2616        let length = u64::from(get_u32(record, 8));
2617        if length != expected.len() as u64 {
2618            return Ok(false);
2619        }
2620        let value = self
2621            .index
2622            .bytes(SECTION_STRING_BYTES, get_u64(record, 0), length)?;
2623        Ok(value == expected.as_bytes())
2624    }
2625
2626    fn string(&self, id: u32) -> Result<String, CoverageIndexError> {
2627        let record = self.index.record(SECTION_STRINGS, u64::from(id))?;
2628        if record[12..].iter().any(|byte| *byte != 0) {
2629            return Err(CoverageIndexError::InvalidRecord("string reserved bytes"));
2630        }
2631        let offset = get_u64(record, 0);
2632        let length = u64::from(get_u32(record, 8));
2633        let value = self.index.bytes(SECTION_STRING_BYTES, offset, length)?;
2634        std::str::from_utf8(value)
2635            .map(str::to_owned)
2636            .map_err(|_| CoverageIndexError::InvalidUtf8)
2637    }
2638
2639    pub fn summary(&self, view: CoverageViewId) -> Result<CoverageSummary, CoverageIndexError> {
2640        let descriptor = self.index.descriptor(SECTION_VIEW_SUMMARIES)?;
2641        if descriptor.count != 3 {
2642            return Err(CoverageIndexError::InvalidRecord("summary view count"));
2643        }
2644        let mut found = None;
2645        for index in 0..descriptor.count {
2646            let record = self.index.record(SECTION_VIEW_SUMMARIES, index)?;
2647            if CoverageViewId::try_from(record[0])? != view {
2648                continue;
2649            }
2650            if record[3] != 0 || record[12..16].iter().any(|byte| *byte != 0) {
2651                return Err(CoverageIndexError::InvalidRecord("summary reserved bytes"));
2652            }
2653            self.string(get_u32(record, 4))?;
2654            self.string(get_u32(record, 8))?;
2655            let count = |offset: usize| -> Result<CoverageCount, CoverageIndexError> {
2656                let covered = usize::try_from(get_u64(record, offset))
2657                    .map_err(|_| CoverageIndexError::SizeOverflow)?;
2658                let total = usize::try_from(get_u64(record, offset + 8))
2659                    .map_err(|_| CoverageIndexError::SizeOverflow)?;
2660                if covered > total {
2661                    return Err(CoverageIndexError::InvalidRecord("covered exceeds total"));
2662                }
2663                Ok(CoverageCount {
2664                    covered,
2665                    total,
2666                    percentage: percentage(covered, total),
2667                })
2668            };
2669            let value = |offset: usize| -> Result<usize, CoverageIndexError> {
2670                usize::try_from(get_u64(record, offset))
2671                    .map_err(|_| CoverageIndexError::SizeOverflow)
2672            };
2673            let conditions = value(40)?;
2674            let covered_conditions = value(48)?;
2675            if covered_conditions > conditions {
2676                return Err(CoverageIndexError::InvalidRecord(
2677                    "covered conditions exceed total",
2678                ));
2679            }
2680            let decisions = value(16)?;
2681            let executed_decisions = value(24)?;
2682            let covered_decisions = value(32)?;
2683            if covered_decisions > executed_decisions || executed_decisions > decisions {
2684                return Err(CoverageIndexError::InvalidRecord("decision count ordering"));
2685            }
2686            let summary = CoverageSummary {
2687                unmeasured_obligations: None,
2688                exact_fraction_pct: None,
2689                decisions,
2690                executed_decisions,
2691                covered_decisions,
2692                conditions,
2693                covered_conditions,
2694                condition_coverage_pct: percentage(covered_conditions, conditions),
2695                lines: count(56)?,
2696                statements: count(72)?,
2697                functions: count(88)?,
2698                branches: count(104)?,
2699                decision_outcomes: count(120)?,
2700                condition_outcomes: count(136)?,
2701                value_selections: count(152)?,
2702                coverage_complete: bool_field(record[1])?,
2703                completeness_blocked: match record[2] {
2704                    0 => None,
2705                    1 => Some(false),
2706                    2 => Some(true),
2707                    _ => return Err(CoverageIndexError::InvalidRecord("optional boolean")),
2708                },
2709            };
2710            if found.replace(summary).is_some() {
2711                return Err(CoverageIndexError::InvalidRecord("duplicate coverage view"));
2712            }
2713        }
2714        found.ok_or(CoverageIndexError::InvalidRecord("missing coverage view"))
2715    }
2716
2717    pub fn file_gaps(
2718        &self,
2719        view: CoverageViewId,
2720        kind: Option<&str>,
2721        runner: Option<&str>,
2722    ) -> Result<Vec<IndexedFileGap>, CoverageIndexError> {
2723        let descriptor = self.index.descriptor(SECTION_FILE_GAPS)?;
2724        let mut gaps = Vec::new();
2725        for index in 0..descriptor.count {
2726            let record = self.index.record(SECTION_FILE_GAPS, index)?;
2727            if CoverageViewId::try_from(record[0])? != view {
2728                continue;
2729            }
2730            if record[1..4].iter().any(|byte| *byte != 0)
2731                || record[60..64].iter().any(|byte| *byte != 0)
2732            {
2733                return Err(CoverageIndexError::InvalidRecord("file-gap reserved bytes"));
2734            }
2735            let number = |offset: usize| -> Result<usize, CoverageIndexError> {
2736                usize::try_from(get_u64(record, offset))
2737                    .map_err(|_| CoverageIndexError::SizeOverflow)
2738            };
2739            let mask = get_u32(record, 56);
2740            if mask & !15 != 0 {
2741                return Err(CoverageIndexError::InvalidRecord("limitation mask"));
2742            }
2743            let measurement_limitations = number(48)?;
2744            if (measurement_limitations == 0) != (mask == 0) {
2745                return Err(CoverageIndexError::InvalidRecord(
2746                    "limitation count and kinds disagree",
2747                ));
2748            }
2749            let uncovered_lines = number(8)?;
2750            let uncovered_statements = number(16)?;
2751            let uncovered_functions = number(24)?;
2752            let missing_branches = number(32)?;
2753            let missing_mcdc_conditions = number(40)?;
2754            let score = number(64)?;
2755            let expected_score = uncovered_lines
2756                + uncovered_functions * 2
2757                + missing_branches * 2
2758                + missing_mcdc_conditions * 3
2759                + measurement_limitations * 3;
2760            if score != expected_score {
2761                return Err(CoverageIndexError::InvalidRecord("file-gap score"));
2762            }
2763            let record_kind = self.optional_string(get_u32(record, 72))?;
2764            let record_runner = self.optional_string(get_u32(record, 76))?;
2765            if record_kind.as_deref() != kind || record_runner.as_deref() != runner {
2766                continue;
2767            }
2768            let mut limitation_kinds = Vec::new();
2769            for (bit, kind) in [
2770                (1, "dynamic-code"),
2771                (2, "semantic-safety"),
2772                (4, "source-scope"),
2773                (8, "unknown"),
2774            ] {
2775                if mask & bit != 0 {
2776                    limitation_kinds.push(kind.into());
2777                }
2778            }
2779            let totals = IndexedGapDimensions {
2780                lines: number(160)?,
2781                statements: number(168)?,
2782                functions: number(176)?,
2783                branches: number(184)?,
2784                mcdc_conditions: number(192)?,
2785            };
2786            let covered = |total: usize, missing: usize| {
2787                total
2788                    .checked_sub(missing)
2789                    .ok_or(CoverageIndexError::InvalidRecord("file-gap totals"))
2790            };
2791            gaps.push(IndexedFileGap {
2792                view,
2793                file: self.string(get_u32(record, 4))?,
2794                uncovered_lines,
2795                uncovered_statements,
2796                uncovered_functions,
2797                missing_branches,
2798                missing_mcdc_conditions,
2799                measurement_limitations,
2800                limitation_kinds,
2801                covered_by_other_tests: IndexedGapDimensions {
2802                    lines: number(80)?,
2803                    statements: number(88)?,
2804                    functions: number(96)?,
2805                    branches: number(104)?,
2806                    mcdc_conditions: number(112)?,
2807                },
2808                uncovered_everywhere: IndexedGapDimensions {
2809                    lines: number(120)?,
2810                    statements: number(128)?,
2811                    functions: number(136)?,
2812                    branches: number(144)?,
2813                    mcdc_conditions: number(152)?,
2814                },
2815                totals: totals.clone(),
2816                covered: IndexedGapDimensions {
2817                    lines: covered(totals.lines, uncovered_lines)?,
2818                    statements: covered(totals.statements, uncovered_statements)?,
2819                    functions: covered(totals.functions, uncovered_functions)?,
2820                    branches: covered(totals.branches, missing_branches)?,
2821                    mcdc_conditions: covered(totals.mcdc_conditions, missing_mcdc_conditions)?,
2822                },
2823                score,
2824            });
2825        }
2826        gaps.sort_by(|left, right| {
2827            right
2828                .score
2829                .cmp(&left.score)
2830                .then_with(|| left.file.cmp(&right.file))
2831        });
2832        Ok(gaps)
2833    }
2834
2835    fn optional_string(&self, id: u32) -> Result<Option<String>, CoverageIndexError> {
2836        if id == NO_STRING {
2837            Ok(None)
2838        } else {
2839            self.string(id).map(Some)
2840        }
2841    }
2842
2843    fn relation_ids(&self, offset: u64, count: u64) -> Result<Vec<Id>, CoverageIndexError> {
2844        Ok(self
2845            .relation_strings(offset, count)?
2846            .into_iter()
2847            .map(Id::from)
2848            .collect())
2849    }
2850
2851    fn relation_strings(&self, offset: u64, count: u64) -> Result<Vec<String>, CoverageIndexError> {
2852        let end = offset
2853            .checked_add(count)
2854            .ok_or(CoverageIndexError::SizeOverflow)?;
2855        let descriptor = self.index.descriptor(SECTION_STRING_RELATIONS)?;
2856        if end > descriptor.count {
2857            return Err(CoverageIndexError::InvalidRecord("string relation range"));
2858        }
2859        (offset..end)
2860            .map(|index| {
2861                let record = self.index.record(SECTION_STRING_RELATIONS, index)?;
2862                self.string(get_u32(record, 0))
2863            })
2864            .collect()
2865    }
2866
2867    pub fn projection(
2868        &self,
2869        view: CoverageViewId,
2870        kind: Option<&str>,
2871        runner: Option<&str>,
2872    ) -> Result<IndexedProjection, CoverageIndexError> {
2873        let descriptor = self.index.descriptor(SECTION_PROJECTIONS)?;
2874        let mut found = None;
2875        for index in 0..descriptor.count {
2876            let record = self.index.record(SECTION_PROJECTIONS, index)?;
2877            if CoverageViewId::try_from(record[0])? != view {
2878                continue;
2879            }
2880            if record[38..40].iter().any(|byte| *byte != 0)
2881                || record[518..520].iter().any(|byte| *byte != 0)
2882            {
2883                return Err(CoverageIndexError::InvalidRecord(
2884                    "projection reserved bytes",
2885                ));
2886            }
2887            let record_kind = self.optional_string(get_u32(record, 4))?;
2888            let record_runner = self.optional_string(get_u32(record, 8))?;
2889            if record_kind.as_deref() != kind || record_runner.as_deref() != runner {
2890                continue;
2891            }
2892            if found.is_some() {
2893                return Err(CoverageIndexError::InvalidRecord(
2894                    "duplicate coverage projection",
2895                ));
2896            }
2897            let number = |offset: usize| -> Result<usize, CoverageIndexError> {
2898                usize::try_from(get_u64(record, offset))
2899                    .map_err(|_| CoverageIndexError::SizeOverflow)
2900            };
2901            let limitations = number(192)?;
2902            let evidence_corruptions = number(200)?;
2903            let blocking = number(208)?;
2904            let declared = number(528)?;
2905            if blocking + declared != limitations + evidence_corruptions {
2906                return Err(CoverageIndexError::InvalidRecord(
2907                    "measurement blocking count",
2908                ));
2909            }
2910            let mut transport_values = (0..8)
2911                .map(|index| number(408 + index * 8))
2912                .collect::<Result<Vec<_>, _>>()?;
2913            transport_values.push(number(536)?);
2914            let transport = if bool_field(record[1])? {
2915                Some(TransportStats {
2916                    processes: transport_values[0],
2917                    child_launches: transport_values[1],
2918                    remote_launches: transport_values[2],
2919                    workspace_capabilities: transport_values[3],
2920                    guest_processes: transport_values[8],
2921                    scoped_server_records: transport_values[4],
2922                    background_server_records: transport_values[5],
2923                    corrupt_records: transport_values[6],
2924                    corrupt_files: transport_values[7],
2925                })
2926            } else {
2927                if transport_values.iter().any(|value| *value != 0) {
2928                    return Err(CoverageIndexError::InvalidRecord("transport presence flag"));
2929                }
2930                None
2931            };
2932            let has_scope = bool_field(record[2])?;
2933            let scope_kind = match record[3] {
2934                0 => None,
2935                1 => Some((ScopeKind::SourceDiscovery, "source-discovery")),
2936                2 => Some((ScopeKind::Compiler, "compiler")),
2937                _ => return Err(CoverageIndexError::InvalidRecord("coverage scope kind")),
2938            };
2939            let scope_mode = self.optional_string(get_u32(record, 16))?;
2940            let scope_language = self.optional_string(get_u32(record, 504))?;
2941            let scope_model = self.optional_string(get_u32(record, 508))?;
2942            let scope_unit = self.optional_string(get_u32(record, 512))?;
2943            let has_measurement_complete = bool_field(record[516])?;
2944            let measurement_complete = bool_field(record[517])?;
2945            if !has_measurement_complete && measurement_complete {
2946                return Err(CoverageIndexError::InvalidRecord(
2947                    "scope measurement completeness flag",
2948                ));
2949            }
2950            if has_scope
2951                != (scope_kind.is_some() && scope_language.is_some() && scope_model.is_some())
2952            {
2953                return Err(CoverageIndexError::InvalidRecord("scope presence flag"));
2954            }
2955            let source_scope = if let Some((kind, kind_name)) = scope_kind {
2956                match kind {
2957                    ScopeKind::SourceDiscovery => {
2958                        if scope_mode.is_none() || scope_unit.is_some() || has_measurement_complete
2959                        {
2960                            return Err(CoverageIndexError::InvalidRecord(
2961                                "source-discovery scope shape",
2962                            ));
2963                        }
2964                    }
2965                    ScopeKind::Compiler => {
2966                        if scope_mode.is_some()
2967                            || scope_unit.is_none()
2968                            || !has_measurement_complete
2969                            || get_u32(record, 32) != 0
2970                            || number(480)? != 0
2971                            || number(488)? != 0
2972                            || number(496)? != 0
2973                        {
2974                            return Err(CoverageIndexError::InvalidRecord("compiler scope shape"));
2975                        }
2976                    }
2977                }
2978                Some(IndexedSourceScope {
2979                    kind: kind_name.into(),
2980                    language: scope_language.expect("validated scope language"),
2981                    model: scope_model.expect("validated scope model"),
2982                    mode: scope_mode,
2983                    roots: self
2984                        .relation_strings(get_u64(record, 24), u64::from(get_u32(record, 32)))?,
2985                    unit: scope_unit,
2986                    measurement_complete: has_measurement_complete.then_some(measurement_complete),
2987                    included: number(480)?,
2988                    excluded: number(488)?,
2989                    ambiguous: number(496)?,
2990                })
2991            } else {
2992                if get_u32(record, 32) != 0
2993                    || scope_mode.is_some()
2994                    || scope_language.is_some()
2995                    || scope_model.is_some()
2996                    || scope_unit.is_some()
2997                    || has_measurement_complete
2998                    || number(480)? != 0
2999                    || number(488)? != 0
3000                    || number(496)? != 0
3001                {
3002                    return Err(CoverageIndexError::InvalidRecord("absent scope data"));
3003                }
3004                None
3005            };
3006            let empty_evidence_tests = number(472)?;
3007            let first_empty_evidence_test = self.optional_string(get_u32(record, 20))?;
3008            if (empty_evidence_tests == 0) != first_empty_evidence_test.is_none() {
3009                return Err(CoverageIndexError::InvalidRecord(
3010                    "empty-evidence diagnostic identity",
3011                ));
3012            }
3013            found = Some(IndexedProjection {
3014                view,
3015                kind: record_kind,
3016                runner: record_runner,
3017                generated_at: self.string(get_u32(record, 12))?,
3018                summary: decode_summary(record, 36, 40)?,
3019                measurement: IndexedMeasurement {
3020                    complete: blocking == 0,
3021                    limitations,
3022                    evidence_corruptions,
3023                    blocking,
3024                    declared,
3025                    files: number(216)?,
3026                    by_kind: IndexedMeasurementKinds {
3027                        dynamic_code: number(224)?,
3028                        semantic_safety: number(232)?,
3029                        source_scope: number(240)?,
3030                    },
3031                },
3032                attribution: IndexedAttribution {
3033                    browser_explicit: number(248)?,
3034                    browser_fallback: number(256)?,
3035                    server_explicit: number(264)?,
3036                    server_fallback: number(272)?,
3037                },
3038                transport,
3039                empty_evidence_tests,
3040                first_empty_evidence_test,
3041                confidence: IndexedSummaryConfidence {
3042                    lines: IndexedConfidenceLines {
3043                        unexecuted: number(280)?,
3044                        executed: number(288)?,
3045                        action: number(296)?,
3046                        asserted: number(304)?,
3047                    },
3048                    assertion_covered_mcdc_conditions: number(312)?,
3049                },
3050                files_with_gaps: number(320)?,
3051                files_with_coverage_gaps: number(328)?,
3052                tests: number(336)?,
3053                setups: number(344)?,
3054                test_outcomes: {
3055                    let mut outcomes = IndexedOutcomeCounts {
3056                        passed: number(352)?,
3057                        failed: number(360)?,
3058                        flaky: number(368)?,
3059                        skipped: number(376)?,
3060                        timed_out: number(384)?,
3061                        interrupted: number(392)?,
3062                        unknown: number(400)?,
3063                        unstarted: number(520)?,
3064                        todo: 0,
3065                    };
3066                    // The projection record has no slot left, so todo is the
3067                    // tests no other outcome counts; zero in older indexes.
3068                    outcomes.todo = number(336)?.saturating_sub(
3069                        outcomes.passed
3070                            + outcomes.failed
3071                            + outcomes.flaky
3072                            + outcomes.skipped
3073                            + outcomes.timed_out
3074                            + outcomes.interrupted
3075                            + outcomes.unknown
3076                            + outcomes.unstarted,
3077                    );
3078                    outcomes
3079                },
3080                source_scope,
3081            });
3082        }
3083        found.ok_or(CoverageIndexError::InvalidRecord(
3084            "missing coverage projection",
3085        ))
3086    }
3087
3088    pub fn decision_gaps(
3089        &self,
3090        view: CoverageViewId,
3091        kind: Option<&str>,
3092        runner: Option<&str>,
3093        file: &str,
3094    ) -> Result<Vec<IndexedDecisionGap>, CoverageIndexError> {
3095        let descriptor = self.index.descriptor(SECTION_DECISION_GAPS)?;
3096        let mut decisions = Vec::new();
3097        for index in 0..descriptor.count {
3098            let record = self.index.record(SECTION_DECISION_GAPS, index)?;
3099            if CoverageViewId::try_from(record[0])? != view {
3100                continue;
3101            }
3102            if record[1..4].iter().any(|byte| *byte != 0)
3103                || record[28..32].iter().any(|byte| *byte != 0)
3104                || record[64..].iter().any(|byte| *byte != 0)
3105            {
3106                return Err(CoverageIndexError::InvalidRecord(
3107                    "decision-gap reserved bytes",
3108                ));
3109            }
3110            let record_kind = self.optional_string(get_u32(record, 4))?;
3111            let record_runner = self.optional_string(get_u32(record, 8))?;
3112            if record_kind.as_deref() != kind || record_runner.as_deref() != runner {
3113                continue;
3114            }
3115            let record_file = self.string(get_u32(record, 16))?;
3116            if record_file != file {
3117                continue;
3118            }
3119            let number = |offset: usize| -> Result<usize, CoverageIndexError> {
3120                usize::try_from(get_u64(record, offset))
3121                    .map_err(|_| CoverageIndexError::SizeOverflow)
3122            };
3123            let conditions = number(48)?;
3124            let missing_conditions = number(56)?;
3125            if conditions == 0 || missing_conditions > conditions {
3126                return Err(CoverageIndexError::InvalidRecord(
3127                    "decision condition counts",
3128                ));
3129            }
3130            decisions.push(IndexedDecisionGap {
3131                view,
3132                file: record_file,
3133                id: self.string(get_u32(record, 12))?,
3134                line: number(32)?,
3135                column: number(40)?,
3136                kind: self.string(get_u32(record, 20))?,
3137                conditions,
3138                missing_conditions,
3139                source: self.string(get_u32(record, 24))?,
3140            });
3141        }
3142        Ok(decisions)
3143    }
3144
3145    pub fn dimensions(
3146        &self,
3147        view: CoverageViewId,
3148        dimension: CoverageDimension,
3149    ) -> Result<Vec<IndexedDimensionCoverage>, CoverageIndexError> {
3150        let descriptor = self.index.descriptor(SECTION_DIMENSIONS)?;
3151        let mut values = Vec::new();
3152        for index in 0..descriptor.count {
3153            let record = self.index.record(SECTION_DIMENSIONS, index)?;
3154            if CoverageViewId::try_from(record[0])? != view {
3155                continue;
3156            }
3157            let record_dimension = match record[1] {
3158                0 => CoverageDimension::Kind,
3159                1 => CoverageDimension::Runner,
3160                2 => CoverageDimension::Tests,
3161                _ => return Err(CoverageIndexError::InvalidRecord("dimension type")),
3162            };
3163            if record_dimension != dimension {
3164                continue;
3165            }
3166            if record[26..32].iter().any(|byte| *byte != 0) {
3167                return Err(CoverageIndexError::InvalidRecord(
3168                    "dimension reserved bytes",
3169                ));
3170            }
3171            let name = self.string(get_u32(record, 4))?;
3172            values.push(IndexedDimensionCoverage {
3173                kind: (dimension == CoverageDimension::Kind).then(|| name.clone()),
3174                runner: (dimension == CoverageDimension::Runner).then_some(name),
3175                tests: usize::try_from(get_u64(record, 8))
3176                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3177                setups: usize::try_from(get_u64(record, 16))
3178                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3179                attributed: usize::try_from(get_u64(record, 184))
3180                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3181                summary: decode_summary(record, 24, 32)?,
3182            });
3183        }
3184        Ok(values)
3185    }
3186
3187    pub fn scope_entries(
3188        &self,
3189        view: CoverageViewId,
3190    ) -> Result<Vec<IndexedScopeEntry>, CoverageIndexError> {
3191        let descriptor = self.index.descriptor(SECTION_SCOPE_ENTRIES)?;
3192        let mut entries = Vec::new();
3193        for index in 0..descriptor.count {
3194            let record = self.index.record(SECTION_SCOPE_ENTRIES, index)?;
3195            if CoverageViewId::try_from(record[0])? != view {
3196                continue;
3197            }
3198            if record[2..4].iter().any(|byte| *byte != 0)
3199                || record[28..].iter().any(|byte| *byte != 0)
3200            {
3201                return Err(CoverageIndexError::InvalidRecord(
3202                    "source-scope reserved bytes",
3203                ));
3204            }
3205            let status = match record[1] {
3206                0 => "included",
3207                1 => "excluded",
3208                2 => "ambiguous",
3209                _ => return Err(CoverageIndexError::InvalidRecord("source-scope status")),
3210            };
3211            let measurement_limitations = usize::try_from(get_u64(record, 16))
3212                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3213            let mask = get_u32(record, 24);
3214            if mask & !15 != 0 || (measurement_limitations == 0) != (mask == 0) {
3215                return Err(CoverageIndexError::InvalidRecord(
3216                    "source-scope limitation annotation",
3217                ));
3218            }
3219            let mut limitation_kinds = Vec::new();
3220            for (bit, kind) in [
3221                (1, "dynamic-code"),
3222                (2, "semantic-safety"),
3223                (4, "source-scope"),
3224                (8, "unknown"),
3225            ] {
3226                if mask & bit != 0 {
3227                    limitation_kinds.push(kind.into());
3228                }
3229            }
3230            entries.push(IndexedScopeEntry {
3231                file: self.string(get_u32(record, 4))?,
3232                status: status.into(),
3233                reason: self.string(get_u32(record, 8))?,
3234                package_root: self.optional_string(get_u32(record, 12))?,
3235                measurement_limitations,
3236                limitation_kinds,
3237            });
3238        }
3239        Ok(entries)
3240    }
3241
3242    fn confidence(
3243        &self,
3244        index: u64,
3245    ) -> Result<crate::coverage_report::CoverageConfidence, CoverageIndexError> {
3246        let record = self.index.record(SECTION_CONFIDENCE, index)?;
3247        if record[2..8].iter().any(|byte| *byte != 0)
3248            || record[72..].iter().any(|byte| *byte != 0)
3249            || record[1] & !15 != 0
3250        {
3251            return Err(CoverageIndexError::InvalidRecord("confidence record"));
3252        }
3253        let values = (0..4)
3254            .map(|index| {
3255                self.relation_strings(
3256                    get_u64(record, 8 + index * 16),
3257                    get_u64(record, 16 + index * 16),
3258                )
3259            })
3260            .collect::<Result<Vec<_>, _>>()?;
3261        Ok(crate::coverage_report::CoverageConfidence {
3262            level: match record[0] {
3263                0 => "unexecuted",
3264                1 => "executed",
3265                2 => "action",
3266                3 => "asserted",
3267                _ => return Err(CoverageIndexError::InvalidRecord("confidence level")),
3268            }
3269            .into(),
3270            setup_only: record[1] & 1 != 0,
3271            background_only: record[1] & 2 != 0,
3272            asserted: record[1] & 4 != 0,
3273            e2e: record[1] & 8 != 0,
3274            tests: values[0].iter().map(Id::from).collect(),
3275            asserted_tests: values[1].iter().map(Id::from).collect(),
3276            runners: values[2].clone(),
3277            kinds: values[3].clone(),
3278        })
3279    }
3280
3281    pub fn line(
3282        &self,
3283        view: CoverageViewId,
3284        file: &str,
3285        line: usize,
3286    ) -> Result<Option<IndexedLine>, CoverageIndexError> {
3287        let descriptor = self.index.descriptor(SECTION_LINES)?;
3288        let mut found = None;
3289        for index in 0..descriptor.count {
3290            let record = self.index.record(SECTION_LINES, index)?;
3291            if CoverageViewId::try_from(record[0])? != view {
3292                continue;
3293            }
3294            if record[3] != 0 || record[56..].iter().any(|byte| *byte != 0) {
3295                return Err(CoverageIndexError::InvalidRecord("line record"));
3296            }
3297            let record_file = self.string(get_u32(record, 4))?;
3298            let record_line = usize::try_from(get_u64(record, 8))
3299                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3300            if record_file != file || record_line != line {
3301                continue;
3302            }
3303            if found.is_some() {
3304                return Err(CoverageIndexError::InvalidRecord("duplicate line"));
3305            }
3306            found = Some(IndexedLine {
3307                file: record_file,
3308                line: record_line,
3309                covered: bool_field(record[1])?,
3310                measured: !bool_field(record[2])?,
3311                tests: self.relation_strings(get_u64(record, 16), get_u64(record, 24))?,
3312                phases: self.relation_strings(get_u64(record, 32), get_u64(record, 40))?,
3313                confidence: self.confidence(get_u64(record, 48))?,
3314            });
3315        }
3316        Ok(found)
3317    }
3318
3319    pub fn lines(&self, view: CoverageViewId) -> Result<Vec<IndexedLine>, CoverageIndexError> {
3320        self.lines_where(view, None)
3321    }
3322
3323    /// `lines`, of one file only: records of other files are skipped before anything in them is decoded.
3324    pub fn lines_in_file(
3325        &self,
3326        view: CoverageViewId,
3327        file: &str,
3328    ) -> Result<Vec<IndexedLine>, CoverageIndexError> {
3329        self.lines_where(view, Some(file))
3330    }
3331
3332    fn lines_where(
3333        &self,
3334        view: CoverageViewId,
3335        file: Option<&str>,
3336    ) -> Result<Vec<IndexedLine>, CoverageIndexError> {
3337        let descriptor = self.index.descriptor(SECTION_LINES)?;
3338        let mut lines = Vec::new();
3339        for index in 0..descriptor.count {
3340            let record = self.index.record(SECTION_LINES, index)?;
3341            if CoverageViewId::try_from(record[0])? != view {
3342                continue;
3343            }
3344            if let Some(file) = file
3345                && !self.string_equals(get_u32(record, 4), file)?
3346            {
3347                continue;
3348            }
3349            if record[3] != 0 || record[56..].iter().any(|byte| *byte != 0) {
3350                return Err(CoverageIndexError::InvalidRecord("line record"));
3351            }
3352            lines.push(IndexedLine {
3353                file: self.string(get_u32(record, 4))?,
3354                line: usize::try_from(get_u64(record, 8))
3355                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3356                covered: bool_field(record[1])?,
3357                measured: !bool_field(record[2])?,
3358                tests: self.relation_strings(get_u64(record, 16), get_u64(record, 24))?,
3359                phases: self.relation_strings(get_u64(record, 32), get_u64(record, 40))?,
3360                confidence: self.confidence(get_u64(record, 48))?,
3361            });
3362        }
3363        Ok(lines)
3364    }
3365
3366    pub fn test_summaries(
3367        &self,
3368        view: CoverageViewId,
3369    ) -> Result<Vec<IndexedTestSummary>, CoverageIndexError> {
3370        let descriptor = self.index.descriptor(SECTION_TEST_SUMMARIES)?;
3371        let mut tests = Vec::new();
3372        for index in 0..descriptor.count {
3373            let record = self.index.record(SECTION_TEST_SUMMARIES, index)?;
3374            if CoverageViewId::try_from(record[0])? != view {
3375                continue;
3376            }
3377            if record[36..40]
3378                .iter()
3379                .chain(&record[52..])
3380                .any(|byte| *byte != 0)
3381            {
3382                return Err(CoverageIndexError::InvalidRecord("test summary record"));
3383            }
3384            tests.push(IndexedTestSummary {
3385                id: self.string(get_u32(record, 4))?,
3386                name: self.string(get_u32(record, 8))?,
3387                file: self.optional_string(get_u32(record, 12))?,
3388                title: self.optional_string(get_u32(record, 16))?,
3389                role: match record[1] {
3390                    0 => "test",
3391                    1 => "setup",
3392                    2 => "background",
3393                    _ => return Err(CoverageIndexError::InvalidRecord("test role")),
3394                }
3395                .into(),
3396                attribution: match record[3] {
3397                    0 => crate::coverage_report::ATTRIBUTION_EXACT,
3398                    1 => crate::coverage_report::ATTRIBUTION_RUN_WIDE,
3399                    2 => crate::coverage_report::ATTRIBUTION_PARTIAL,
3400                    3 => crate::coverage_report::ATTRIBUTION_BY_TIME,
3401                    _ => return Err(CoverageIndexError::InvalidRecord("test attribution")),
3402                }
3403                .into(),
3404                outcome: match record[2] {
3405                    0 => "passed",
3406                    1 => "failed",
3407                    2 => "flaky",
3408                    3 => "skipped",
3409                    4 => "timedOut",
3410                    5 => "interrupted",
3411                    6 => "unknown",
3412                    7 => "unstarted",
3413                    8 => "todo",
3414                    _ => return Err(CoverageIndexError::InvalidRecord("test outcome")),
3415                }
3416                .into(),
3417                provenance: crate::coverage_report::TestProvenance {
3418                    runner: self.string(get_u32(record, 20))?,
3419                    kind: self.string(get_u32(record, 24))?,
3420                    project: self.optional_string(get_u32(record, 28))?,
3421                    source: self.string(get_u32(record, 32))?,
3422                    tags: self
3423                        .relation_strings(get_u64(record, 40), u64::from(get_u32(record, 48)))?,
3424                },
3425            });
3426        }
3427        Ok(tests)
3428    }
3429
3430    fn test_vector(&self, index: u64) -> Result<McdcVector, CoverageIndexError> {
3431        let record = self.index.record(SECTION_TEST_VECTORS, index)?;
3432        if record[1..8].iter().any(|byte| *byte != 0) {
3433            return Err(CoverageIndexError::InvalidRecord("test vector record"));
3434        }
3435        let offset = get_u64(record, 8);
3436        let count = get_u64(record, 16);
3437        let descriptor = self.index.descriptor(SECTION_VECTOR_VALUES)?;
3438        let end = offset
3439            .checked_add(count)
3440            .ok_or(CoverageIndexError::InvalidRecord("vector value range"))?;
3441        if end > descriptor.count {
3442            return Err(CoverageIndexError::InvalidRecord("vector value range"));
3443        }
3444        let mut values = Vec::with_capacity(
3445            usize::try_from(count).map_err(|_| CoverageIndexError::SizeOverflow)?,
3446        );
3447        for index in offset..end {
3448            values.push(match self.index.record(SECTION_VECTOR_VALUES, index)?[0] {
3449                0 => None,
3450                1 => Some(false),
3451                2 => Some(true),
3452                _ => return Err(CoverageIndexError::InvalidRecord("vector value")),
3453            });
3454        }
3455        Ok(McdcVector {
3456            values,
3457            outcome: bool_field(record[0])?,
3458        })
3459    }
3460
3461    pub fn test_details(
3462        &self,
3463        view: CoverageViewId,
3464    ) -> Result<Vec<IndexedTestDetail>, CoverageIndexError> {
3465        let summaries = self.test_summaries(view)?;
3466        let positions = summaries
3467            .iter()
3468            .enumerate()
3469            .map(|(index, test)| (test.id.clone(), index))
3470            .collect::<HashMap<_, _>>();
3471        if positions.len() != summaries.len() {
3472            return Err(CoverageIndexError::InvalidRecord("duplicate test summary"));
3473        }
3474        let mut details = summaries
3475            .into_iter()
3476            .map(|summary| IndexedTestDetail {
3477                summary,
3478                retries: Vec::new(),
3479                attempts: Vec::new(),
3480                hits: Vec::new(),
3481                decisions: Vec::new(),
3482                lines: Vec::new(),
3483            })
3484            .collect::<Vec<_>>();
3485        let position = |record: &[u8]| -> Result<Option<usize>, CoverageIndexError> {
3486            if CoverageViewId::try_from(record[0])? != view {
3487                return Ok(None);
3488            }
3489            let id = self.string(get_u32(record, 4))?;
3490            positions
3491                .get(&id)
3492                .copied()
3493                .map(Some)
3494                .ok_or(CoverageIndexError::InvalidRecord("unknown test relation"))
3495        };
3496        let descriptor = self.index.descriptor(SECTION_TEST_RETRIES)?;
3497        for index in 0..descriptor.count {
3498            let record = self.index.record(SECTION_TEST_RETRIES, index)?;
3499            if record[1..4].iter().any(|byte| *byte != 0) {
3500                return Err(CoverageIndexError::InvalidRecord("test retry record"));
3501            }
3502            if let Some(position) = position(record)? {
3503                details[position].retries.push(
3504                    usize::try_from(get_u64(record, 8))
3505                        .map_err(|_| CoverageIndexError::SizeOverflow)?,
3506                );
3507            }
3508        }
3509        let descriptor = self.index.descriptor(SECTION_TEST_ATTEMPTS)?;
3510        for index in 0..descriptor.count {
3511            let record = self.index.record(SECTION_TEST_ATTEMPTS, index)?;
3512            if record[1..4].iter().any(|byte| *byte != 0) {
3513                return Err(CoverageIndexError::InvalidRecord("test attempt record"));
3514            }
3515            if let Some(position) = position(record)? {
3516                details[position]
3517                    .attempts
3518                    .push(crate::coverage_report::TestAttempt {
3519                        retry: usize::try_from(get_u64(record, 8))
3520                            .map_err(|_| CoverageIndexError::SizeOverflow)?,
3521                        status: self.string(get_u32(record, 16))?,
3522                        expected_status: self.optional_string(get_u32(record, 20))?,
3523                    });
3524            }
3525        }
3526        let descriptor = self.index.descriptor(SECTION_TEST_LINES)?;
3527        for index in 0..descriptor.count {
3528            let record = self.index.record(SECTION_TEST_LINES, index)?;
3529            if record[1..4].iter().any(|byte| *byte != 0)
3530                || record[12..16].iter().any(|byte| *byte != 0)
3531            {
3532                return Err(CoverageIndexError::InvalidRecord("test line record"));
3533            }
3534            if let Some(position) = position(record)? {
3535                details[position]
3536                    .lines
3537                    .push(crate::coverage_report::SourceLine {
3538                        file: self.string(get_u32(record, 8))?.into(),
3539                        line: usize::try_from(get_u64(record, 16))
3540                            .map_err(|_| CoverageIndexError::SizeOverflow)?,
3541                    });
3542            }
3543        }
3544        let descriptor = self.index.descriptor(SECTION_TEST_HITS)?;
3545        for index in 0..descriptor.count {
3546            let record = self.index.record(SECTION_TEST_HITS, index)?;
3547            if record[1..4].iter().any(|byte| *byte != 0)
3548                || record[12..].iter().any(|byte| *byte != 0)
3549            {
3550                return Err(CoverageIndexError::InvalidRecord("test hit record"));
3551            }
3552            if let Some(position) = position(record)? {
3553                details[position]
3554                    .hits
3555                    .push(self.string(get_u32(record, 8))?);
3556            }
3557        }
3558        let descriptor = self.index.descriptor(SECTION_TEST_DECISIONS)?;
3559        let vectors = self.index.descriptor(SECTION_TEST_VECTORS)?.count;
3560        for index in 0..descriptor.count {
3561            let record = self.index.record(SECTION_TEST_DECISIONS, index)?;
3562            if record[1..4].iter().any(|byte| *byte != 0)
3563                || record[12..16].iter().any(|byte| *byte != 0)
3564            {
3565                return Err(CoverageIndexError::InvalidRecord("test decision record"));
3566            }
3567            if let Some(position) = position(record)? {
3568                let offset = get_u64(record, 16);
3569                let count = get_u64(record, 24);
3570                let end = offset
3571                    .checked_add(count)
3572                    .ok_or(CoverageIndexError::InvalidRecord("test vector range"))?;
3573                if end > vectors {
3574                    return Err(CoverageIndexError::InvalidRecord("test vector range"));
3575                }
3576                let mut observed = Vec::with_capacity(
3577                    usize::try_from(count).map_err(|_| CoverageIndexError::SizeOverflow)?,
3578                );
3579                for vector in offset..end {
3580                    observed.push(self.test_vector(vector)?);
3581                }
3582                details[position]
3583                    .decisions
3584                    .push(crate::coverage_report::TestDecisionResult {
3585                        id: self.string(get_u32(record, 8))?,
3586                        vectors: observed,
3587                    });
3588            }
3589        }
3590        Ok(details)
3591    }
3592
3593    pub fn hit_metadata(
3594        &self,
3595        view: CoverageViewId,
3596    ) -> Result<Vec<IndexedHitMetadata>, CoverageIndexError> {
3597        self.hit_metadata_where(view, None)
3598    }
3599
3600    /// `hit_metadata`, of one file only: records of other files are skipped before anything in them is decoded.
3601    pub fn hit_metadata_in_file(
3602        &self,
3603        view: CoverageViewId,
3604        file: &str,
3605    ) -> Result<Vec<IndexedHitMetadata>, CoverageIndexError> {
3606        self.hit_metadata_where(view, Some(file))
3607    }
3608
3609    fn hit_metadata_where(
3610        &self,
3611        view: CoverageViewId,
3612        file: Option<&str>,
3613    ) -> Result<Vec<IndexedHitMetadata>, CoverageIndexError> {
3614        let descriptor = self.index.descriptor(SECTION_HIT_METADATA)?;
3615        let mut metadata = Vec::new();
3616        for index in 0..descriptor.count {
3617            let record = self.index.record(SECTION_HIT_METADATA, index)?;
3618            if CoverageViewId::try_from(record[0])? != view {
3619                continue;
3620            }
3621            if let Some(file) = file
3622                && !self.string_equals(get_u32(record, 8), file)?
3623            {
3624                continue;
3625            }
3626            if record[2..4].iter().any(|byte| *byte != 0)
3627                || record[12..16].iter().any(|byte| *byte != 0)
3628            {
3629                return Err(CoverageIndexError::InvalidRecord("hit metadata record"));
3630            }
3631            let obligation = match record[1] {
3632                0 => "statement",
3633                1 => "function",
3634                2 => "branch",
3635                _ => return Err(CoverageIndexError::InvalidRecord("hit obligation")),
3636            };
3637            let metadata_label = self.optional_string(get_u32(record, 36))?;
3638            metadata.push(IndexedHitMetadata {
3639                id: self.string(get_u32(record, 4))?,
3640                obligation: obligation.into(),
3641                file: self.string(get_u32(record, 8))?,
3642                line: usize::try_from(get_u64(record, 16))
3643                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3644                column: usize::try_from(get_u64(record, 24))
3645                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3646                branch_kind: self.optional_string(get_u32(record, 32))?,
3647                label: (obligation != "branch")
3648                    .then_some(metadata_label.clone())
3649                    .flatten(),
3650                alternative: self.optional_string(get_u32(record, 40))?,
3651                parent_id: (obligation == "branch").then_some(metadata_label).flatten(),
3652                source: self.string(get_u32(record, 44))?,
3653                tests: self.relation_strings(get_u64(record, 48), get_u64(record, 56))?,
3654            });
3655        }
3656        Ok(metadata)
3657    }
3658
3659    pub fn limitations(
3660        &self,
3661        view: CoverageViewId,
3662    ) -> Result<Vec<IndexedLimitation>, CoverageIndexError> {
3663        self.limitations_where(view, None)
3664    }
3665
3666    /// `limitations`, of one file only: records of other files are skipped before anything in them is decoded.
3667    pub fn limitations_in_file(
3668        &self,
3669        view: CoverageViewId,
3670        file: &str,
3671    ) -> Result<Vec<IndexedLimitation>, CoverageIndexError> {
3672        self.limitations_where(view, Some(file))
3673    }
3674
3675    fn limitations_where(
3676        &self,
3677        view: CoverageViewId,
3678        file: Option<&str>,
3679    ) -> Result<Vec<IndexedLimitation>, CoverageIndexError> {
3680        let descriptor = self.index.descriptor(SECTION_LIMITATIONS)?;
3681        let mut limitations = Vec::new();
3682        for index in 0..descriptor.count {
3683            let record = self.index.record(SECTION_LIMITATIONS, index)?;
3684            if CoverageViewId::try_from(record[0])? != view {
3685                continue;
3686            }
3687            if let Some(file) = file
3688                && !self.string_equals(get_u32(record, 12), file)?
3689            {
3690                continue;
3691            }
3692            if record[2..4].iter().any(|byte| *byte != 0)
3693                || record[40..].iter().any(|byte| *byte != 0)
3694            {
3695                return Err(CoverageIndexError::InvalidRecord("limitation record"));
3696            }
3697            limitations.push(IndexedLimitation {
3698                id: self.string(get_u32(record, 4))?,
3699                kind: self.string(get_u32(record, 8))?,
3700                file: self.string(get_u32(record, 12))?,
3701                source: self.string(get_u32(record, 16))?,
3702                reason: self.string(get_u32(record, 20))?,
3703                line: usize::try_from(get_u64(record, 24))
3704                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3705                column: usize::try_from(get_u64(record, 32))
3706                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3707                blocking: bool_field(record[1])?,
3708            });
3709        }
3710        Ok(limitations)
3711    }
3712
3713    pub fn decision_metadata(
3714        &self,
3715        view: CoverageViewId,
3716    ) -> Result<Vec<crate::coverage_report::DecisionMeta>, CoverageIndexError> {
3717        let descriptor = self.index.descriptor(SECTION_DECISION_METADATA)?;
3718        let mut metadata = Vec::new();
3719        for index in 0..descriptor.count {
3720            let record = self.index.record(SECTION_DECISION_METADATA, index)?;
3721            if CoverageViewId::try_from(record[0])? != view {
3722                continue;
3723            }
3724            if record[1..4].iter().any(|byte| *byte != 0)
3725                || record[20..24].iter().any(|byte| *byte != 0)
3726                || record[56..].iter().any(|byte| *byte != 0)
3727            {
3728                return Err(CoverageIndexError::InvalidRecord(
3729                    "decision metadata record",
3730                ));
3731            }
3732            metadata.push(crate::coverage_report::DecisionMeta {
3733                id: self.string(get_u32(record, 4))?,
3734                file: self.string(get_u32(record, 8))?,
3735                source: self.string(get_u32(record, 12))?,
3736                kind: self.string(get_u32(record, 16))?,
3737                line: usize::try_from(get_u64(record, 24))
3738                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3739                column: usize::try_from(get_u64(record, 32))
3740                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3741                conditions: self.relation_strings(get_u64(record, 40), get_u64(record, 48))?,
3742            });
3743        }
3744        Ok(metadata)
3745    }
3746
3747    fn decision_vector_observation(
3748        &self,
3749        index: u64,
3750    ) -> Result<crate::coverage_report::VectorObservation, CoverageIndexError> {
3751        let record = self
3752            .index
3753            .record(SECTION_DECISION_VECTOR_OBSERVATIONS, index)?;
3754        Ok(crate::coverage_report::VectorObservation {
3755            confidence: self.confidence(get_u64(record, 0))?,
3756            vector: self.test_vector(get_u64(record, 8))?,
3757            tests: self.relation_ids(get_u64(record, 16), get_u64(record, 24))?,
3758            phases: self.relation_ids(get_u64(record, 32), get_u64(record, 40))?,
3759            explicit_phases: self.relation_ids(get_u64(record, 48), get_u64(record, 56))?,
3760        })
3761    }
3762
3763    fn decision_condition(
3764        &self,
3765        index: u64,
3766    ) -> Result<crate::coverage_report::ConditionResult, CoverageIndexError> {
3767        let record = self.index.record(SECTION_DECISION_CONDITIONS, index)?;
3768        if record[0] & !7 != 0 || record[1..4].iter().any(|byte| *byte != 0) {
3769            return Err(CoverageIndexError::InvalidRecord(
3770                "decision condition record",
3771            ));
3772        }
3773        let has_witness = record[0] & 4 != 0;
3774        let witness = if has_witness {
3775            Some([
3776                self.test_vector(get_u64(record, 16))?,
3777                self.test_vector(get_u64(record, 24))?,
3778            ])
3779        } else {
3780            None
3781        };
3782        let first_tests = self.relation_strings(get_u64(record, 32), get_u64(record, 40))?;
3783        let second_tests = self.relation_strings(get_u64(record, 48), get_u64(record, 56))?;
3784        if !has_witness && (!first_tests.is_empty() || !second_tests.is_empty()) {
3785            return Err(CoverageIndexError::InvalidRecord(
3786                "condition witness tests without witness",
3787            ));
3788        }
3789        Ok(crate::coverage_report::ConditionResult {
3790            index: usize::try_from(get_u64(record, 8))
3791                .map_err(|_| CoverageIndexError::SizeOverflow)?,
3792            source: self.string(get_u32(record, 4))?,
3793            covered: record[0] & 1 != 0,
3794            assertion_covered: record[0] & 2 != 0,
3795            witness,
3796            witness_tests: has_witness.then_some([
3797                first_tests.into_iter().map(Id::from).collect(),
3798                second_tests.into_iter().map(Id::from).collect(),
3799            ]),
3800        })
3801    }
3802
3803    pub fn decision_details(
3804        &self,
3805        view: CoverageViewId,
3806    ) -> Result<Vec<crate::coverage_report::DecisionResult>, CoverageIndexError> {
3807        self.decision_details_where(view, None)
3808    }
3809
3810    /// `decision_details`, of one file only: a decision of another file is
3811    /// skipped before its vectors and conditions are decoded.
3812    pub fn decision_details_in_file(
3813        &self,
3814        view: CoverageViewId,
3815        file: &str,
3816    ) -> Result<Vec<crate::coverage_report::DecisionResult>, CoverageIndexError> {
3817        self.decision_details_where(view, Some(file))
3818    }
3819
3820    fn decision_details_where(
3821        &self,
3822        view: CoverageViewId,
3823        file: Option<&str>,
3824    ) -> Result<Vec<crate::coverage_report::DecisionResult>, CoverageIndexError> {
3825        let metadata = self
3826            .decision_metadata(view)?
3827            .into_iter()
3828            .map(|meta| (meta.id.clone(), meta))
3829            .collect::<HashMap<_, _>>();
3830        let descriptor = self.index.descriptor(SECTION_DECISION_DETAILS)?;
3831        let observation_count = self
3832            .index
3833            .descriptor(SECTION_DECISION_VECTOR_OBSERVATIONS)?
3834            .count;
3835        let condition_count = self.index.descriptor(SECTION_DECISION_CONDITIONS)?.count;
3836        let mut decisions = Vec::new();
3837        for index in 0..descriptor.count {
3838            let record = self.index.record(SECTION_DECISION_DETAILS, index)?;
3839            if CoverageViewId::try_from(record[0])? != view {
3840                continue;
3841            }
3842            if record[1] & !3 != 0 || record[2..4].iter().any(|byte| *byte != 0) {
3843                return Err(CoverageIndexError::InvalidRecord("decision detail record"));
3844            }
3845            let executed = record[1] & 1 != 0;
3846            let covered = record[1] & 2 != 0;
3847            if covered && !executed {
3848                return Err(CoverageIndexError::InvalidRecord(
3849                    "covered unexecuted decision",
3850                ));
3851            }
3852            let range = |offset: usize,
3853                         available: u64,
3854                         label: &'static str|
3855             -> Result<std::ops::Range<u64>, CoverageIndexError> {
3856                let start = get_u64(record, offset);
3857                let count = get_u64(record, offset + 8);
3858                let end = start
3859                    .checked_add(count)
3860                    .ok_or(CoverageIndexError::InvalidRecord(label))?;
3861                if end > available {
3862                    return Err(CoverageIndexError::InvalidRecord(label));
3863                }
3864                Ok(start..end)
3865            };
3866            if let Some(file) = file
3867                && metadata
3868                    .get(&self.string(get_u32(record, 4))?)
3869                    .is_some_and(|meta| meta.file != file)
3870            {
3871                continue;
3872            }
3873            let observations = range(32, observation_count, "decision observation range")?
3874                .map(|index| self.decision_vector_observation(index))
3875                .collect::<Result<Vec<_>, _>>()?;
3876            let conditions = range(48, condition_count, "decision condition range")?
3877                .map(|index| self.decision_condition(index))
3878                .collect::<Result<Vec<_>, _>>()?;
3879            let id = self.string(get_u32(record, 4))?;
3880            let meta = metadata
3881                .get(&id)
3882                .cloned()
3883                .ok_or(CoverageIndexError::InvalidRecord(
3884                    "missing decision metadata",
3885                ))?;
3886            if conditions.len() != meta.conditions.len()
3887                || conditions.iter().enumerate().any(|(index, condition)| {
3888                    condition.index != index || condition.source != meta.conditions[index]
3889                })
3890            {
3891                return Err(CoverageIndexError::InvalidRecord(
3892                    "decision condition denominator",
3893                ));
3894            }
3895            decisions.push(crate::coverage_report::DecisionResult {
3896                meta,
3897                executed,
3898                covered,
3899                vectors: observations
3900                    .iter()
3901                    .map(|observation| observation.vector.clone())
3902                    .collect(),
3903                vector_observations: observations,
3904                conditions,
3905                tests: self.relation_ids(get_u64(record, 16), get_u64(record, 24))?,
3906                confidence: self.confidence(get_u64(record, 8))?,
3907            });
3908        }
3909        Ok(decisions)
3910    }
3911
3912    pub fn phase_summaries(
3913        &self,
3914        view: CoverageViewId,
3915    ) -> Result<Vec<IndexedPhaseSummary>, CoverageIndexError> {
3916        let descriptor = self.index.descriptor(SECTION_PHASE_SUMMARIES)?;
3917        let mut phases = Vec::new();
3918        for index in 0..descriptor.count {
3919            let record = self.index.record(SECTION_PHASE_SUMMARIES, index)?;
3920            if CoverageViewId::try_from(record[0])? != view {
3921                continue;
3922            }
3923            if record[1..4].iter().any(|byte| *byte != 0)
3924                || record[48..].iter().any(|byte| *byte != 0)
3925            {
3926                return Err(CoverageIndexError::InvalidRecord("phase summary record"));
3927            }
3928            phases.push(IndexedPhaseSummary {
3929                id: self.string(get_u32(record, 4))?,
3930                kind: self.string(get_u32(record, 8))?,
3931                operation: self.string(get_u32(record, 12))?,
3932                source: self.optional_string(get_u32(record, 16))?,
3933                test: self.string(get_u32(record, 20))?,
3934                status: self.optional_string(get_u32(record, 24))?,
3935                caused_by_phase_id: self.optional_string(get_u32(record, 28))?,
3936                lines: usize::try_from(get_u64(record, 32))
3937                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3938                decisions: usize::try_from(get_u64(record, 40))
3939                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3940            });
3941        }
3942        Ok(phases)
3943    }
3944
3945    pub fn anchors(
3946        &self,
3947        view: CoverageViewId,
3948        file: &str,
3949        line: usize,
3950    ) -> Result<Vec<IndexedAnchor>, CoverageIndexError> {
3951        let descriptor = self.index.descriptor(SECTION_ANCHORS)?;
3952        let mut anchors = Vec::new();
3953        for index in 0..descriptor.count {
3954            let record = self.index.record(SECTION_ANCHORS, index)?;
3955            if CoverageViewId::try_from(record[0])? != view {
3956                continue;
3957            }
3958            if record[3] != 0 || record[12..16].iter().any(|byte| *byte != 0) {
3959                return Err(CoverageIndexError::InvalidRecord("anchor record"));
3960            }
3961            let record_file = self.string(get_u32(record, 8))?;
3962            let record_line = usize::try_from(get_u64(record, 16))
3963                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3964            if record_file != file || record_line != line {
3965                continue;
3966            }
3967            let total = usize::try_from(get_u64(record, 32))
3968                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3969            let covered_conditions = usize::try_from(get_u64(record, 40))
3970                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3971            let (kind, conditions, covered_conditions) = match record[1] {
3972                0 => {
3973                    if total == 0 || covered_conditions > total {
3974                        return Err(CoverageIndexError::InvalidRecord(
3975                            "decision anchor conditions",
3976                        ));
3977                    }
3978                    ("decision", Some(total), Some(covered_conditions))
3979                }
3980                1 => ("branch", None, None),
3981                2 => ("statement", None, None),
3982                3 => ("function", None, None),
3983                _ => return Err(CoverageIndexError::InvalidRecord("anchor kind")),
3984            };
3985            if kind != "decision" && (total != 0 || covered_conditions.is_some()) {
3986                return Err(CoverageIndexError::InvalidRecord("anchor conditions"));
3987            }
3988            anchors.push(IndexedAnchor {
3989                kind: kind.into(),
3990                id: self.string(get_u32(record, 4))?,
3991                file: record_file,
3992                line: record_line,
3993                column: usize::try_from(get_u64(record, 24))
3994                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3995                covered: bool_field(record[2])?,
3996                conditions,
3997                covered_conditions,
3998                tests: self.relation_strings(get_u64(record, 48), get_u64(record, 56))?,
3999            });
4000        }
4001        anchors.sort_by_key(|anchor| anchor.column);
4002        Ok(anchors)
4003    }
4004
4005    pub fn snapshot(&self) -> Result<IndexedCoverageSnapshot, CoverageIndexError> {
4006        Ok(IndexedCoverageSnapshot {
4007            all_summary: self.summary(CoverageViewId::All)?,
4008            passed_summary: self.summary(CoverageViewId::Passed)?,
4009            failed_summary: self.summary(CoverageViewId::Failed)?,
4010            all_files: self.file_gaps(CoverageViewId::All, None, None)?,
4011            passed_files: self.file_gaps(CoverageViewId::Passed, None, None)?,
4012            failed_files: self.file_gaps(CoverageViewId::Failed, None, None)?,
4013        })
4014    }
4015}
4016
4017fn bool_field(value: u8) -> Result<bool, CoverageIndexError> {
4018    match value {
4019        0 => Ok(false),
4020        1 => Ok(true),
4021        _ => Err(CoverageIndexError::InvalidRecord("boolean")),
4022    }
4023}
4024
4025fn decode_summary(
4026    record: &[u8],
4027    flags_offset: usize,
4028    base: usize,
4029) -> Result<CoverageSummary, CoverageIndexError> {
4030    let number = |offset: usize| -> Result<usize, CoverageIndexError> {
4031        usize::try_from(get_u64(record, offset)).map_err(|_| CoverageIndexError::SizeOverflow)
4032    };
4033    let count = |offset: usize| -> Result<CoverageCount, CoverageIndexError> {
4034        let covered = number(offset)?;
4035        let total = number(offset + 8)?;
4036        if covered > total {
4037            return Err(CoverageIndexError::InvalidRecord("covered exceeds total"));
4038        }
4039        Ok(CoverageCount {
4040            covered,
4041            total,
4042            percentage: percentage(covered, total),
4043        })
4044    };
4045    let decisions = number(base)?;
4046    let executed_decisions = number(base + 8)?;
4047    let covered_decisions = number(base + 16)?;
4048    let conditions = number(base + 24)?;
4049    let covered_conditions = number(base + 32)?;
4050    if covered_decisions > executed_decisions
4051        || executed_decisions > decisions
4052        || covered_conditions > conditions
4053    {
4054        return Err(CoverageIndexError::InvalidRecord("summary count ordering"));
4055    }
4056    Ok(CoverageSummary {
4057        unmeasured_obligations: None,
4058        exact_fraction_pct: None,
4059        decisions,
4060        executed_decisions,
4061        covered_decisions,
4062        conditions,
4063        covered_conditions,
4064        condition_coverage_pct: percentage(covered_conditions, conditions),
4065        lines: count(base + 40)?,
4066        statements: count(base + 56)?,
4067        functions: count(base + 72)?,
4068        branches: count(base + 88)?,
4069        decision_outcomes: count(base + 104)?,
4070        condition_outcomes: count(base + 120)?,
4071        value_selections: count(base + 136)?,
4072        coverage_complete: bool_field(record[flags_offset])?,
4073        completeness_blocked: match record[flags_offset + 1] {
4074            0 => None,
4075            1 => Some(false),
4076            2 => Some(true),
4077            _ => return Err(CoverageIndexError::InvalidRecord("optional boolean")),
4078        },
4079    })
4080}
4081
4082fn percentage(covered: usize, total: usize) -> f64 {
4083    if total == 0 {
4084        100.0
4085    } else {
4086        ((covered as f64 / total as f64) * 10_000.0).round() / 100.0
4087    }
4088}
4089
4090#[cfg(test)]
4091mod tests {
4092    use std::{
4093        fs,
4094        sync::atomic::{AtomicU64, Ordering},
4095        time::{SystemTime, UNIX_EPOCH},
4096    };
4097
4098    use crate::{
4099        coverage_analysis::{McdcVector, PointKind},
4100        coverage_report::{
4101            CoverageManifest, CoverageReportRequest, DecisionMeta, ExitCodeInput, PointMeta,
4102            RawTestResult, RuntimeSnapshot, TestProvenance, analyze_coverage_results,
4103        },
4104        query_index::{QueryIndexIdentity, write_query_index},
4105    };
4106
4107    use super::*;
4108
4109    static ROOT_SEQUENCE: AtomicU64 = AtomicU64::new(0);
4110
4111    fn root() -> crate::test_directory::TestDirectory {
4112        let nonce = SystemTime::now()
4113            .duration_since(UNIX_EPOCH)
4114            .unwrap()
4115            .as_nanos();
4116        let root = std::env::temp_dir().join(format!(
4117            "supercov-coverage-index-{}-{nonce}-{}",
4118            std::process::id(),
4119            ROOT_SEQUENCE.fetch_add(1, Ordering::Relaxed),
4120        ));
4121        fs::create_dir(&root).unwrap();
4122        crate::test_directory::TestDirectory::adopt(root)
4123    }
4124
4125    fn identity() -> QueryIndexIdentity {
4126        QueryIndexIdentity {
4127            evidence_sha256: [1; 32],
4128            evidence_bytes: 100,
4129            analysis_sha256: [2; 32],
4130            producer_sha256: [3; 32],
4131            archive_schema_version: 2,
4132        }
4133    }
4134
4135    fn report() -> CoverageReport {
4136        let decision = DecisionMeta {
4137            id: "d".into(),
4138            file: "src/a.js".into(),
4139            line: 1,
4140            column: 1,
4141            source: "a && b".into(),
4142            conditions: vec!["a".into(), "b".into()],
4143            kind: "if".into(),
4144        };
4145        analyze_coverage_results(&CoverageReportRequest {
4146            run_id: "run".into(),
4147            manifest: CoverageManifest {
4148                unmeasured: Vec::new(),
4149                decisions: vec![decision.clone()],
4150                points: vec![PointMeta {
4151                    id: "point".into(),
4152                    kind: PointKind::Statement,
4153                    file: "src/a.js".into(),
4154                    line: 2,
4155                    column: 3,
4156                    source: "work();".into(),
4157                    label: None,
4158                }],
4159                branches: Vec::new(),
4160                limitations: vec![serde_json::json!({
4161                    "id": "dynamic",
4162                    "kind": "dynamic-code",
4163                    "file": "src/a.js",
4164                    "line": 3,
4165                    "column": 1,
4166                    "source": "eval(code)",
4167                    "reason": "dynamic source"
4168                })],
4169                scope: None,
4170                assertion_sites: Vec::new(),
4171            },
4172            raw_results: vec![RawTestResult {
4173                test_id: Some("test".into()),
4174                scope: None,
4175                test: "test".into(),
4176                test_file: Some("tests/a.js".into()),
4177                title: None,
4178                retry: Some(0),
4179                status: Some("passed".into()),
4180                expected_status: None,
4181                flaky: false,
4182                provenance: TestProvenance {
4183                    runner: "node:test".into(),
4184                    kind: "unit".into(),
4185                    project: None,
4186                    source: "runner-default".into(),
4187                    tags: Vec::new(),
4188                },
4189                role: "test".into(),
4190                attribution: crate::coverage_report::ATTRIBUTION_EXACT.into(),
4191                phases: Vec::new(),
4192                runtime: vec![RuntimeSnapshot {
4193                    decisions: vec![crate::coverage_report::DecisionSnapshot {
4194                        meta: decision,
4195                        vectors: vec![McdcVector {
4196                            values: vec![Some(false), None],
4197                            outcome: false,
4198                        }],
4199                    }],
4200                    hits: vec!["point".into()],
4201                    events: Vec::new(),
4202                    logicals: Vec::new(),
4203                    phase_id: None,
4204                }],
4205                browser: Vec::new(),
4206                server: Vec::new(),
4207            }],
4208            generated_at: "time".into(),
4209            coverage_model: None,
4210            integrity: None,
4211            test_exit_code: ExitCodeInput::Present(Some(0)),
4212        })
4213        .unwrap()
4214    }
4215
4216    fn report_attributed(attribution: &str) -> CoverageReport {
4217        let mut report = report();
4218        for view in [
4219            &mut report.view,
4220            &mut report.filters.passed,
4221            &mut report.filters.failed,
4222        ] {
4223            for test in &mut view.tests {
4224                test.attribution = attribution.to_owned();
4225            }
4226        }
4227        report
4228    }
4229
4230    #[test]
4231    fn declined_lines_and_points_are_not_reported_as_coverage_gaps() {
4232        let mut report = report();
4233        for line in &mut report.view.lines {
4234            line.measured = false;
4235            line.covered = false;
4236            line.tests.clear();
4237        }
4238        for point in &mut report.view.points {
4239            point.measured = false;
4240            point.covered = false;
4241            point.tests.clear();
4242        }
4243        let selected = Selected::default();
4244        for filter in [None, Some(&selected)] {
4245            let gaps = file_gaps(&report.view, filter).unwrap();
4246            let (_, gap) = &gaps[0];
4247            assert_eq!(gap.uncovered_lines, 0);
4248            assert_eq!(gap.uncovered_statements, 0);
4249            assert_eq!(gap.uncovered_functions, 0);
4250            assert_eq!(gap.uncovered_everywhere[0..3], [0, 0, 0]);
4251            assert_eq!(gap.measurement_limitations, 1);
4252        }
4253        // Actual missed obligations must still appear.
4254        report.view.lines[0].measured = true;
4255        report.view.points[0].measured = true;
4256        let gaps = file_gaps(&report.view, None).unwrap();
4257        assert_eq!(gaps[0].1.uncovered_lines, 1);
4258        assert_eq!(gaps[0].1.uncovered_statements, 1);
4259    }
4260
4261    #[test]
4262    fn a_test_keeps_the_attribution_it_was_written_with() {
4263        // Attribution rides in a byte the reader used to refuse outright, so a
4264        // value that does not survive the trip is not a wrong number on a
4265        // report -- it is a run that will not open. Only `exact` was ever
4266        // written by a test, which left the other two arms of both the encoder
4267        // and the decoder standing on the claim that they matched.
4268        let root = root();
4269        for attribution in [
4270            crate::coverage_report::ATTRIBUTION_EXACT,
4271            crate::coverage_report::ATTRIBUTION_RUN_WIDE,
4272            crate::coverage_report::ATTRIBUTION_PARTIAL,
4273        ] {
4274            let report = report_attributed(attribution);
4275            let path = root.join(format!("query-index-{attribution}.v1.bin"));
4276            write_query_index(
4277                &coverage_index_sections(&report).unwrap(),
4278                &identity(),
4279                &path,
4280            )
4281            .unwrap();
4282            let container = QueryIndex::open(&path, &identity()).unwrap();
4283            let index = CoverageIndex::new(&container).unwrap();
4284            let tests = index.test_summaries(CoverageViewId::All).unwrap();
4285            assert_eq!(tests.len(), 1);
4286            assert_eq!(
4287                tests[0].attribution, attribution,
4288                "written as `{attribution}` and read back as `{}`",
4289                tests[0].attribution
4290            );
4291        }
4292    }
4293
4294    #[test]
4295    fn an_attribution_the_byte_has_no_room_for_is_refused_at_the_write() {
4296        // Refusing here is what keeps the reserved byte honest: a value nobody
4297        // taught the encoder must not be written as some neighbouring one and
4298        // read back as a measurement.
4299        let error = coverage_index_sections(&report_attributed("probably-exact")).unwrap_err();
4300        assert!(
4301            matches!(error, CoverageIndexError::InvalidRecord("test attribution")),
4302            "{error:?}"
4303        );
4304    }
4305
4306    // The same run is named over and over -- a filtered view repeats the
4307    // relation of the view it filters, and one list of tests covers many lines
4308    // of the file they exercise. Storing each naming separately made this the
4309    // largest section in the container: 61 MB of a 210 MB index.
4310    #[test]
4311    fn a_relation_named_twice_is_stored_once() {
4312        let mut strings = StringTable::default();
4313        let mut relations = StringRelations::default();
4314        let run = || ["alpha".to_string(), "beta".to_string(), "gamma".to_string()];
4315
4316        let first = relations.push(run(), &mut strings).unwrap();
4317        let second = relations.push(run(), &mut strings).unwrap();
4318        assert_eq!(first, second, "the second naming points at the first run");
4319        assert_eq!(relations.values.len(), 3, "and nothing was appended for it");
4320
4321        // A different run still gets its own storage, after the one already
4322        // there -- readers reach a run only by (offset, count), so the
4323        // existing pair must keep meaning what it meant.
4324        let other = relations
4325            .push(["alpha".to_string(), "delta".to_string()], &mut strings)
4326            .unwrap();
4327        assert_eq!(other, (3, 2));
4328        assert_eq!(relations.values.len(), 5);
4329
4330        // A prefix of a stored run is a different run, and is stored as one
4331        // rather than aliasing into the middle of another.
4332        let prefix = relations.push(["alpha".to_string()], &mut strings).unwrap();
4333        assert_eq!(prefix, (5, 1));
4334
4335        // What each pair resolves to is what was pushed.
4336        let read = |(offset, count): (u64, u64)| {
4337            relations.values[offset as usize..(offset + count) as usize].to_vec()
4338        };
4339        assert_eq!(read(first), read(second));
4340        assert_eq!(read(first).len(), 3);
4341        assert_ne!(read(first), read(other));
4342    }
4343
4344    #[test]
4345    fn shared_id_relations_match_text_relations_across_allocations() {
4346        let mut shared_strings = StringTable::default();
4347        let mut text_strings = StringTable::default();
4348        let mut shared_relations = StringRelations::default();
4349        let mut text_relations = StringRelations::default();
4350        let original: Vec<Id> = ["", "test::a[1]", "test::a[10]", "unicodé ✓"]
4351            .into_iter()
4352            .map(Id::from)
4353            .collect();
4354        let copies = original.clone();
4355        let separate: Vec<Id> = original.iter().map(|id| Id::from(id.as_str())).collect();
4356        for values in [&original[..], &copies, &separate, &separate[1..], &[]] {
4357            assert_eq!(
4358                shared_relations
4359                    .push_ids(values, &mut shared_strings)
4360                    .unwrap(),
4361                text_relations.push(values, &mut text_strings).unwrap(),
4362            );
4363        }
4364        // The table owns references to cached allocations even after callers
4365        // drop theirs, so a later ID cannot reuse an earlier cache address.
4366        drop(original);
4367        drop(copies);
4368        drop(separate);
4369        for value in ["new", "test::a[1]", ""] {
4370            let id = Id::from(value);
4371            assert_eq!(
4372                shared_strings.intern_shared(&id).unwrap(),
4373                text_strings.intern(value).unwrap(),
4374            );
4375        }
4376        assert_eq!(shared_relations.values, text_relations.values);
4377        assert_eq!(shared_strings.strings, text_strings.strings);
4378    }
4379
4380    #[test]
4381    fn typed_columns_round_trip_all_outcome_views_without_json() {
4382        let report = report();
4383        let root = root();
4384        let path = root.join("query-index.v1.bin");
4385        write_query_index(
4386            &coverage_index_sections(&report).unwrap(),
4387            &identity(),
4388            &path,
4389        )
4390        .unwrap();
4391        let container = QueryIndex::open(&path, &identity()).unwrap();
4392        let index = CoverageIndex::new(&container).unwrap();
4393        assert_eq!(
4394            index.model().unwrap(),
4395            IndexedCoverageModel {
4396                schema_version: COVERAGE_MODEL_SCHEMA_VERSION,
4397                variant: report.view.variant.clone(),
4398                name: report.view.model.name.clone(),
4399                completeness_meaning: report.view.model.completeness_meaning.clone(),
4400                measured: report.view.model.measured.clone(),
4401                not_measured: report.view.model.not_measured.clone(),
4402            }
4403        );
4404        for (id, view) in [
4405            (CoverageViewId::All, &report.view),
4406            (CoverageViewId::Passed, &report.filters.passed),
4407            (CoverageViewId::Failed, &report.filters.failed),
4408        ] {
4409            assert_eq!(index.summary(id).unwrap(), view.summary);
4410        }
4411        let gaps = index.file_gaps(CoverageViewId::All, None, None).unwrap();
4412        assert_eq!(gaps.len(), 1);
4413        assert_eq!(gaps[0].file, "src/a.js");
4414        assert_eq!(gaps[0].missing_mcdc_conditions, 2);
4415        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
4416        assert_eq!(projection.summary, report.view.summary);
4417        assert_eq!(projection.tests, 1);
4418        assert_eq!(projection.setups, 0);
4419        assert_eq!(projection.test_outcomes.passed, 1);
4420        assert!(projection.source_scope.is_none());
4421        let line = index
4422            .line(CoverageViewId::All, "src/a.js", 2)
4423            .unwrap()
4424            .unwrap();
4425        assert!(line.covered);
4426        assert_eq!(line.tests, ["test"]);
4427        assert_eq!(line.confidence.level, "executed");
4428        let tests = index.test_summaries(CoverageViewId::All).unwrap();
4429        assert_eq!(tests.len(), 1);
4430        assert_eq!(tests[0].provenance.runner, "node:test");
4431        // The decision, and its two outcomes as a branch.
4432        let anchors = index.anchors(CoverageViewId::All, "src/a.js", 1).unwrap();
4433        assert_eq!(anchors.len(), 2);
4434        let decision = anchors
4435            .iter()
4436            .filter(|anchor| anchor.kind == "decision")
4437            .collect::<Vec<_>>();
4438        assert_eq!(decision.len(), 1);
4439        assert_eq!(decision[0].conditions, Some(2));
4440        assert_eq!(decision[0].tests, ["test"]);
4441        assert!(anchors.iter().any(|anchor| anchor.kind == "branch"));
4442        let point = index.anchors(CoverageViewId::All, "src/a.js", 2).unwrap();
4443        assert_eq!(point.len(), 1);
4444        assert_eq!(point[0].kind, "statement");
4445        assert_eq!(point[0].tests, ["test"]);
4446        let details = index.test_details(CoverageViewId::All).unwrap();
4447        assert_eq!(details.len(), 1);
4448        assert_eq!(details[0].retries, [0]);
4449        assert_eq!(details[0].attempts.len(), 1);
4450        assert_eq!(details[0].hits, ["point"]);
4451        assert_eq!(details[0].lines.len(), 1);
4452        assert_eq!(details[0].lines[0].line, 2);
4453        assert_eq!(details[0].decisions.len(), 1);
4454        assert_eq!(details[0].decisions[0].vectors.len(), 1);
4455        assert_eq!(
4456            details[0].decisions[0].vectors[0].values,
4457            [Some(false), None]
4458        );
4459        let hits = index.hit_metadata(CoverageViewId::All).unwrap();
4460        // The point, and the decision's two outcomes.
4461        assert_eq!(hits.len(), 3);
4462        let hits = hits
4463            .into_iter()
4464            .filter(|hit| hit.obligation != "branch")
4465            .collect::<Vec<_>>();
4466        assert_eq!(hits.len(), 1);
4467        assert_eq!(hits[0].id, "point");
4468        assert_eq!(hits[0].source, "work();");
4469        assert_eq!(hits[0].tests, ["test"]);
4470        let decisions = index.decision_metadata(CoverageViewId::All).unwrap();
4471        assert_eq!(decisions.len(), 1);
4472        assert_eq!(decisions[0].conditions, ["a", "b"]);
4473        assert_eq!(
4474            index.decision_details(CoverageViewId::All).unwrap(),
4475            report.view.decisions
4476        );
4477        let limitations = index.limitations(CoverageViewId::All).unwrap();
4478        assert_eq!(limitations.len(), 1);
4479        assert_eq!(limitations[0].kind, "dynamic-code");
4480        assert_eq!(limitations[0].line, 3);
4481        fs::remove_dir_all(root).unwrap();
4482    }
4483
4484    #[test]
4485    fn index_preserves_catalogued_unstarted_tests_without_attempts() {
4486        let report = analyze_coverage_results(&CoverageReportRequest {
4487            run_id: "run".into(),
4488            manifest: CoverageManifest {
4489                unmeasured: Vec::new(),
4490                decisions: Vec::new(),
4491                points: Vec::new(),
4492                branches: Vec::new(),
4493                limitations: Vec::new(),
4494                scope: None,
4495                assertion_sites: Vec::new(),
4496            },
4497            raw_results: vec![RawTestResult {
4498                test_id: Some("unstarted".into()),
4499                scope: None,
4500                test: "unstarted".into(),
4501                test_file: Some("tests/a.rs".into()),
4502                title: None,
4503                retry: None,
4504                status: Some("unstarted".into()),
4505                expected_status: Some("passed".into()),
4506                flaky: false,
4507                provenance: TestProvenance {
4508                    runner: "rust-nextest".into(),
4509                    kind: "unit".into(),
4510                    project: None,
4511                    source: "selected-but-not-started".into(),
4512                    tags: Vec::new(),
4513                },
4514                role: "test".into(),
4515                attribution: crate::coverage_report::ATTRIBUTION_EXACT.into(),
4516                phases: Vec::new(),
4517                runtime: Vec::new(),
4518                browser: Vec::new(),
4519                server: Vec::new(),
4520            }],
4521            generated_at: "time".into(),
4522            coverage_model: None,
4523            integrity: None,
4524            test_exit_code: ExitCodeInput::Present(Some(100)),
4525        })
4526        .unwrap();
4527        let root = root();
4528        let path = root.join("query-index.v1.bin");
4529        write_query_index(
4530            &coverage_index_sections(&report).unwrap(),
4531            &identity(),
4532            &path,
4533        )
4534        .unwrap();
4535        let container = QueryIndex::open(&path, &identity()).unwrap();
4536        let index = CoverageIndex::new(&container).unwrap();
4537        let summaries = index.test_summaries(CoverageViewId::All).unwrap();
4538        assert_eq!(summaries.len(), 1);
4539        assert_eq!(summaries[0].outcome, "unstarted");
4540        let details = index.test_details(CoverageViewId::All).unwrap();
4541        assert!(details[0].retries.is_empty());
4542        assert!(details[0].attempts.is_empty());
4543        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
4544        assert_eq!(projection.tests, 1);
4545        assert_eq!(projection.test_outcomes.unstarted, 1);
4546        fs::remove_dir_all(root).unwrap();
4547    }
4548
4549    #[test]
4550    fn source_discovery_scope_preserves_python_language() {
4551        let mut report = report();
4552        let scope = serde_json::json!({
4553            "version": 1,
4554            "mode": "automatic",
4555            "roots": ["."],
4556            "entries": [{
4557                "file": "src/a.py",
4558                "status": "included",
4559                "reason": "python source",
4560                "packageRoot": "."
4561            }]
4562        });
4563        for view in [
4564            &mut report.view,
4565            &mut report.filters.passed,
4566            &mut report.filters.failed,
4567        ] {
4568            view.scope = Some(scope.clone());
4569            view.model.language = "python".into();
4570            view.model.name = "python-probes-v1".into();
4571        }
4572        let root = root();
4573        let path = root.join("query-index.python.bin");
4574        write_query_index(
4575            &coverage_index_sections(&report).unwrap(),
4576            &identity(),
4577            &path,
4578        )
4579        .unwrap();
4580        let container = QueryIndex::open(&path, &identity()).unwrap();
4581        let index = CoverageIndex::new(&container).unwrap();
4582        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
4583        let source_scope = projection.source_scope.unwrap();
4584        assert_eq!(source_scope.language, "python");
4585        assert_eq!(source_scope.model, "python-probes-v1");
4586        assert_eq!(source_scope.kind, "source-discovery");
4587        assert_eq!(source_scope.included, 1);
4588        assert_eq!(index.scope_entries(CoverageViewId::All).unwrap().len(), 1);
4589        fs::remove_dir_all(root).unwrap();
4590    }
4591
4592    #[test]
4593    fn a_scope_entry_carries_a_limitation_of_its_language_s_own_kind() {
4594        // Go records `loop-without-condition`; with a scope recorded for a Go
4595        // run, a kind this table did not name refused the whole index:
4596        // "invalid coverage index: coverage limitation kind".
4597        let mut report = report();
4598        let scope = serde_json::json!({
4599            "version": 1,
4600            "mode": "automatic",
4601            "roots": ["."],
4602            "entries": [{ "file": "mux.go", "status": "included", "reason": "Go application source" }]
4603        });
4604        for view in [
4605            &mut report.view,
4606            &mut report.filters.passed,
4607            &mut report.filters.failed,
4608        ] {
4609            view.scope = Some(scope.clone());
4610            view.model.language = "go".into();
4611            view.limitations = vec![serde_json::json!({
4612                "id": "go-loop-1",
4613                "kind": "loop-without-condition",
4614                "file": "mux.go",
4615                "line": 4,
4616                "column": 1,
4617                "source": "for {",
4618                "reason": "a loop with no condition has no decision to measure"
4619            })];
4620        }
4621        let root = root();
4622        let path = root.join("query-index.go.bin");
4623        write_query_index(
4624            &coverage_index_sections(&report).unwrap(),
4625            &identity(),
4626            &path,
4627        )
4628        .unwrap();
4629        let container = QueryIndex::open(&path, &identity()).unwrap();
4630        let index = CoverageIndex::new(&container).unwrap();
4631        let entries = index.scope_entries(CoverageViewId::All).unwrap();
4632        assert_eq!(entries.len(), 1);
4633        assert_eq!(entries[0].measurement_limitations, 1);
4634        assert_eq!(entries[0].limitation_kinds, ["unknown"]);
4635        fs::remove_dir_all(root).unwrap();
4636    }
4637
4638    #[test]
4639    fn compiler_owned_scope_round_trips_without_javascript_scope_fields() {
4640        let mut report = report();
4641        let scope = serde_json::json!({
4642            "language": "rust",
4643            "model": "rust-source-v1",
4644            "crate": "fixture",
4645            "measurementComplete": false
4646        });
4647        report.view.scope = Some(scope.clone());
4648        report.filters.passed.scope = Some(scope.clone());
4649        report.filters.failed.scope = Some(scope);
4650        let root = root();
4651        let path = root.join("query-index.v2.bin");
4652        write_query_index(
4653            &coverage_index_sections(&report).unwrap(),
4654            &identity(),
4655            &path,
4656        )
4657        .unwrap();
4658        let container = QueryIndex::open(&path, &identity()).unwrap();
4659        let index = CoverageIndex::new(&container).unwrap();
4660        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
4661        assert_eq!(
4662            projection.source_scope,
4663            Some(IndexedSourceScope {
4664                kind: "compiler".into(),
4665                language: "rust".into(),
4666                model: "rust-source-v1".into(),
4667                mode: None,
4668                roots: Vec::new(),
4669                unit: Some("fixture".into()),
4670                measurement_complete: Some(false),
4671                included: 0,
4672                excluded: 0,
4673                ambiguous: 0,
4674            })
4675        );
4676        assert!(index.scope_entries(CoverageViewId::All).unwrap().is_empty());
4677        fs::remove_dir_all(root).unwrap();
4678    }
4679}