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) -> Result<[u8; TEST_SUMMARY_RECORD_SIZE], CoverageIndexError> {
1567    let mut record = [0_u8; TEST_SUMMARY_RECORD_SIZE];
1568    record[0] = view_id as u8;
1569    record[1] = match test.role.as_str() {
1570        "test" => 0,
1571        "setup" => 1,
1572        "background" => 2,
1573        _ => return Err(CoverageIndexError::InvalidRecord("test role")),
1574    };
1575    // Byte 3 was reserved from the start and the reader refuses a record that
1576    // sets it, which is what makes this an addition rather than a format
1577    // change: the record is the same 64 bytes it always was.
1578    record[3] = match test.attribution.as_str() {
1579        crate::coverage_report::ATTRIBUTION_EXACT => 0,
1580        crate::coverage_report::ATTRIBUTION_RUN_WIDE => 1,
1581        crate::coverage_report::ATTRIBUTION_PARTIAL => 2,
1582        crate::coverage_report::ATTRIBUTION_BY_TIME => 3,
1583        _ => return Err(CoverageIndexError::InvalidRecord("test attribution")),
1584    };
1585    record[2] = match test.outcome.as_str() {
1586        "passed" => 0,
1587        "failed" => 1,
1588        "flaky" => 2,
1589        "skipped" => 3,
1590        "timedOut" => 4,
1591        "interrupted" => 5,
1592        "unknown" => 6,
1593        "unstarted" => 7,
1594        "todo" => 8,
1595        _ => return Err(CoverageIndexError::InvalidRecord("test outcome")),
1596    };
1597    put_u32(&mut record, 4, strings.intern(&test.id)?);
1598    put_u32(&mut record, 8, strings.intern(&test.name)?);
1599    put_u32(
1600        &mut record,
1601        12,
1602        optional_string_id(test.file.as_deref(), strings)?,
1603    );
1604    put_u32(
1605        &mut record,
1606        16,
1607        optional_string_id(test.title.as_deref(), strings)?,
1608    );
1609    put_u32(&mut record, 20, strings.intern(&test.provenance.runner)?);
1610    put_u32(&mut record, 24, strings.intern(&test.provenance.kind)?);
1611    put_u32(
1612        &mut record,
1613        28,
1614        optional_string_id(test.provenance.project.as_deref(), strings)?,
1615    );
1616    put_u32(&mut record, 32, strings.intern(&test.provenance.source)?);
1617    Ok(record)
1618}
1619
1620fn phase_summary_record(
1621    view_id: CoverageViewId,
1622    phase: &crate::coverage_report::PhaseResult,
1623    strings: &mut StringTable,
1624) -> Result<[u8; PHASE_SUMMARY_RECORD_SIZE], CoverageIndexError> {
1625    let mut record = [0_u8; PHASE_SUMMARY_RECORD_SIZE];
1626    record[0] = view_id as u8;
1627    put_u32(&mut record, 4, strings.intern(&phase.phase.id)?);
1628    put_u32(&mut record, 8, strings.intern(&phase.phase.kind)?);
1629    put_u32(&mut record, 12, strings.intern(&phase.phase.operation)?);
1630    put_u32(
1631        &mut record,
1632        16,
1633        optional_string_id(phase.phase.source.as_deref(), strings)?,
1634    );
1635    put_u32(&mut record, 20, strings.intern(&phase.test)?);
1636    put_u32(
1637        &mut record,
1638        24,
1639        optional_string_id(phase.phase.status.as_deref(), strings)?,
1640    );
1641    put_u32(
1642        &mut record,
1643        28,
1644        optional_string_id(phase.phase.caused_by_phase_id.as_deref(), strings)?,
1645    );
1646    put_u64(&mut record, 32, usize_u64(phase.lines.len())?);
1647    put_u64(
1648        &mut record,
1649        40,
1650        usize_u64(
1651            phase
1652                .decisions
1653                .iter()
1654                .map(|decision| decision.vectors.len())
1655                .sum(),
1656        )?,
1657    );
1658    Ok(record)
1659}
1660
1661struct AnchorInput<'a> {
1662    view_id: CoverageViewId,
1663    kind: u8,
1664    id: &'a str,
1665    file: &'a str,
1666    line: usize,
1667    column: usize,
1668    covered: bool,
1669    conditions: Option<(usize, usize)>,
1670    tests: &'a [Id],
1671}
1672
1673fn anchor_record(
1674    input: AnchorInput<'_>,
1675    strings: &mut StringTable,
1676    relations: &mut StringRelations,
1677) -> Result<[u8; ANCHOR_RECORD_SIZE], CoverageIndexError> {
1678    let mut record = [0_u8; ANCHOR_RECORD_SIZE];
1679    record[0] = input.view_id as u8;
1680    record[1] = input.kind;
1681    record[2] = u8::from(input.covered);
1682    put_u32(&mut record, 4, strings.intern(input.id)?);
1683    put_u32(&mut record, 8, strings.intern(input.file)?);
1684    put_u64(&mut record, 16, usize_u64(input.line)?);
1685    put_u64(&mut record, 24, usize_u64(input.column)?);
1686    if let Some((covered, total)) = input.conditions {
1687        put_u64(&mut record, 32, usize_u64(total)?);
1688        put_u64(&mut record, 40, usize_u64(covered)?);
1689    }
1690    let (tests_offset, tests_count) = relations.push_ids(input.tests, strings)?;
1691    put_u64(&mut record, 48, tests_offset);
1692    put_u64(&mut record, 56, tests_count);
1693    Ok(record)
1694}
1695
1696fn test_retry_record(
1697    view_id: CoverageViewId,
1698    test_id: &str,
1699    retry: usize,
1700    strings: &mut StringTable,
1701) -> Result<[u8; TEST_RETRY_RECORD_SIZE], CoverageIndexError> {
1702    let mut record = [0_u8; TEST_RETRY_RECORD_SIZE];
1703    record[0] = view_id as u8;
1704    put_u32(&mut record, 4, strings.intern(test_id)?);
1705    put_u64(&mut record, 8, usize_u64(retry)?);
1706    Ok(record)
1707}
1708
1709fn test_attempt_record(
1710    view_id: CoverageViewId,
1711    test_id: &str,
1712    attempt: &crate::coverage_report::TestAttempt,
1713    strings: &mut StringTable,
1714) -> Result<[u8; TEST_ATTEMPT_RECORD_SIZE], CoverageIndexError> {
1715    let mut record = [0_u8; TEST_ATTEMPT_RECORD_SIZE];
1716    record[0] = view_id as u8;
1717    put_u32(&mut record, 4, strings.intern(test_id)?);
1718    put_u64(&mut record, 8, usize_u64(attempt.retry)?);
1719    put_u32(&mut record, 16, strings.intern(&attempt.status)?);
1720    put_u32(
1721        &mut record,
1722        20,
1723        optional_string_id(attempt.expected_status.as_deref(), strings)?,
1724    );
1725    Ok(record)
1726}
1727
1728fn test_line_record(
1729    view_id: CoverageViewId,
1730    test_id: &str,
1731    line: &crate::coverage_report::SourceLine,
1732    strings: &mut StringTable,
1733) -> Result<[u8; TEST_LINE_RECORD_SIZE], CoverageIndexError> {
1734    let mut record = [0_u8; TEST_LINE_RECORD_SIZE];
1735    record[0] = view_id as u8;
1736    put_u32(&mut record, 4, strings.intern(test_id)?);
1737    put_u32(&mut record, 8, strings.intern(&line.file)?);
1738    put_u64(&mut record, 16, usize_u64(line.line)?);
1739    Ok(record)
1740}
1741
1742fn test_hit_record(
1743    view_id: CoverageViewId,
1744    test_id: &str,
1745    hit: &str,
1746    strings: &mut StringTable,
1747) -> Result<[u8; TEST_HIT_RECORD_SIZE], CoverageIndexError> {
1748    let mut record = [0_u8; TEST_HIT_RECORD_SIZE];
1749    record[0] = view_id as u8;
1750    put_u32(&mut record, 4, strings.intern(test_id)?);
1751    put_u32(&mut record, 8, strings.intern(hit)?);
1752    Ok(record)
1753}
1754
1755fn test_vector_record(
1756    vector: &McdcVector,
1757    values: &mut Vec<u8>,
1758) -> Result<[u8; TEST_VECTOR_RECORD_SIZE], CoverageIndexError> {
1759    let mut record = [0_u8; TEST_VECTOR_RECORD_SIZE];
1760    record[0] = u8::from(vector.outcome);
1761    put_u64(&mut record, 8, usize_u64(values.len())?);
1762    put_u64(&mut record, 16, usize_u64(vector.values.len())?);
1763    values.extend(vector.values.iter().map(|value| match value {
1764        None => 0,
1765        Some(false) => 1,
1766        Some(true) => 2,
1767    }));
1768    Ok(record)
1769}
1770
1771fn test_decision_record(
1772    view_id: CoverageViewId,
1773    test_id: &str,
1774    decision_id: &str,
1775    vectors_offset: usize,
1776    vectors_count: usize,
1777    strings: &mut StringTable,
1778) -> Result<[u8; TEST_DECISION_RECORD_SIZE], CoverageIndexError> {
1779    let mut record = [0_u8; TEST_DECISION_RECORD_SIZE];
1780    record[0] = view_id as u8;
1781    put_u32(&mut record, 4, strings.intern(test_id)?);
1782    put_u32(&mut record, 8, strings.intern(decision_id)?);
1783    put_u64(&mut record, 16, usize_u64(vectors_offset)?);
1784    put_u64(&mut record, 24, usize_u64(vectors_count)?);
1785    Ok(record)
1786}
1787
1788struct HitMetadataInput<'a> {
1789    view_id: CoverageViewId,
1790    kind: u8,
1791    id: &'a str,
1792    file: &'a str,
1793    line: usize,
1794    column: usize,
1795    branch_kind: Option<&'a str>,
1796    label: Option<&'a str>,
1797    alternative: Option<&'a str>,
1798    source: &'a str,
1799    tests: &'a [Id],
1800}
1801
1802fn hit_metadata_record(
1803    input: HitMetadataInput<'_>,
1804    strings: &mut StringTable,
1805    relations: &mut StringRelations,
1806) -> Result<[u8; HIT_METADATA_RECORD_SIZE], CoverageIndexError> {
1807    let mut record = [0_u8; HIT_METADATA_RECORD_SIZE];
1808    record[0] = input.view_id as u8;
1809    record[1] = input.kind;
1810    put_u32(&mut record, 4, strings.intern(input.id)?);
1811    put_u32(&mut record, 8, strings.intern(input.file)?);
1812    put_u64(&mut record, 16, usize_u64(input.line)?);
1813    put_u64(&mut record, 24, usize_u64(input.column)?);
1814    put_u32(
1815        &mut record,
1816        32,
1817        optional_string_id(input.branch_kind, strings)?,
1818    );
1819    put_u32(&mut record, 36, optional_string_id(input.label, strings)?);
1820    put_u32(
1821        &mut record,
1822        40,
1823        optional_string_id(input.alternative, strings)?,
1824    );
1825    put_u32(&mut record, 44, strings.intern(input.source)?);
1826    let (tests_offset, tests_count) = relations.push_ids(input.tests, strings)?;
1827    put_u64(&mut record, 48, tests_offset);
1828    put_u64(&mut record, 56, tests_count);
1829    Ok(record)
1830}
1831
1832fn limitation_record(
1833    view_id: CoverageViewId,
1834    limitation: &serde_json::Value,
1835    strings: &mut StringTable,
1836) -> Result<[u8; LIMITATION_RECORD_SIZE], CoverageIndexError> {
1837    let field = |name| {
1838        limitation
1839            .get(name)
1840            .and_then(serde_json::Value::as_str)
1841            .ok_or(CoverageIndexError::InvalidRecord("coverage limitation"))
1842    };
1843    let number = |name| {
1844        limitation
1845            .get(name)
1846            .and_then(serde_json::Value::as_u64)
1847            .ok_or(CoverageIndexError::InvalidRecord("coverage limitation"))
1848    };
1849    let mut record = [0_u8; LIMITATION_RECORD_SIZE];
1850    record[0] = view_id as u8;
1851    record[1] = u8::from(crate::coverage_report::blocking_limitation(limitation));
1852    put_u32(&mut record, 4, strings.intern(field("id")?)?);
1853    put_u32(&mut record, 8, strings.intern(field("kind")?)?);
1854    put_u32(&mut record, 12, strings.intern(field("file")?)?);
1855    put_u32(&mut record, 16, strings.intern(field("source")?)?);
1856    put_u32(&mut record, 20, strings.intern(field("reason")?)?);
1857    put_u64(&mut record, 24, number("line")?);
1858    put_u64(&mut record, 32, number("column")?);
1859    Ok(record)
1860}
1861
1862fn decision_metadata_record(
1863    view_id: CoverageViewId,
1864    decision: &crate::coverage_report::DecisionResult,
1865    strings: &mut StringTable,
1866    relations: &mut StringRelations,
1867) -> Result<[u8; DECISION_METADATA_RECORD_SIZE], CoverageIndexError> {
1868    let mut record = [0_u8; DECISION_METADATA_RECORD_SIZE];
1869    record[0] = view_id as u8;
1870    put_u32(&mut record, 4, strings.intern(&decision.meta.id)?);
1871    put_u32(&mut record, 8, strings.intern(&decision.meta.file)?);
1872    put_u32(&mut record, 12, strings.intern(&decision.meta.source)?);
1873    put_u32(&mut record, 16, strings.intern(&decision.meta.kind)?);
1874    put_u64(&mut record, 24, usize_u64(decision.meta.line)?);
1875    put_u64(&mut record, 32, usize_u64(decision.meta.column)?);
1876    let (conditions_offset, conditions_count) =
1877        relations.push(decision.meta.conditions.clone(), strings)?;
1878    put_u64(&mut record, 40, conditions_offset);
1879    put_u64(&mut record, 48, conditions_count);
1880    Ok(record)
1881}
1882
1883fn decision_vector_observation_record(
1884    observation: &crate::coverage_report::VectorObservation,
1885    confidence_index: usize,
1886    vector_index: usize,
1887    strings: &mut StringTable,
1888    relations: &mut StringRelations,
1889) -> Result<[u8; DECISION_VECTOR_OBSERVATION_RECORD_SIZE], CoverageIndexError> {
1890    let mut record = [0_u8; DECISION_VECTOR_OBSERVATION_RECORD_SIZE];
1891    put_u64(&mut record, 0, usize_u64(confidence_index)?);
1892    put_u64(&mut record, 8, usize_u64(vector_index)?);
1893    for (offset, values) in [
1894        (16, &observation.tests),
1895        (32, &observation.phases),
1896        (48, &observation.explicit_phases),
1897    ] {
1898        let (relation_offset, relation_count) = relations.push_ids(values, strings)?;
1899        put_u64(&mut record, offset, relation_offset);
1900        put_u64(&mut record, offset + 8, relation_count);
1901    }
1902    Ok(record)
1903}
1904
1905fn decision_condition_record(
1906    condition: &crate::coverage_report::ConditionResult,
1907    witness_vectors: Option<(usize, usize)>,
1908    strings: &mut StringTable,
1909    relations: &mut StringRelations,
1910) -> Result<[u8; DECISION_CONDITION_RECORD_SIZE], CoverageIndexError> {
1911    let mut record = [0_u8; DECISION_CONDITION_RECORD_SIZE];
1912    record[0] = u8::from(condition.covered)
1913        | (u8::from(condition.assertion_covered) << 1)
1914        | (u8::from(condition.witness.is_some()) << 2);
1915    put_u32(&mut record, 4, strings.intern(&condition.source)?);
1916    put_u64(&mut record, 8, usize_u64(condition.index)?);
1917    if let Some((first, second)) = witness_vectors {
1918        put_u64(&mut record, 16, usize_u64(first)?);
1919        put_u64(&mut record, 24, usize_u64(second)?);
1920    }
1921    let empty = [Vec::new(), Vec::new()];
1922    let witness_tests = condition.witness_tests.as_ref().unwrap_or(&empty);
1923    for (offset, values) in [(32, &witness_tests[0]), (48, &witness_tests[1])] {
1924        let (relation_offset, relation_count) = relations.push_ids(values, strings)?;
1925        put_u64(&mut record, offset, relation_offset);
1926        put_u64(&mut record, offset + 8, relation_count);
1927    }
1928    Ok(record)
1929}
1930
1931struct DecisionDetailInput<'a> {
1932    view_id: CoverageViewId,
1933    decision: &'a crate::coverage_report::DecisionResult,
1934    confidence_index: usize,
1935    observations: (usize, usize),
1936    conditions: (usize, usize),
1937}
1938
1939fn decision_detail_record(
1940    input: DecisionDetailInput<'_>,
1941    strings: &mut StringTable,
1942    relations: &mut StringRelations,
1943) -> Result<[u8; DECISION_DETAIL_RECORD_SIZE], CoverageIndexError> {
1944    let mut record = [0_u8; DECISION_DETAIL_RECORD_SIZE];
1945    record[0] = input.view_id as u8;
1946    record[1] = u8::from(input.decision.executed) | (u8::from(input.decision.covered) << 1);
1947    put_u32(&mut record, 4, strings.intern(&input.decision.meta.id)?);
1948    put_u64(&mut record, 8, usize_u64(input.confidence_index)?);
1949    let (tests_offset, tests_count) = relations.push_ids(&input.decision.tests, strings)?;
1950    put_u64(&mut record, 16, tests_offset);
1951    put_u64(&mut record, 24, tests_count);
1952    put_u64(&mut record, 32, usize_u64(input.observations.0)?);
1953    put_u64(&mut record, 40, usize_u64(input.observations.1)?);
1954    put_u64(&mut record, 48, usize_u64(input.conditions.0)?);
1955    put_u64(&mut record, 56, usize_u64(input.conditions.1)?);
1956    Ok(record)
1957}
1958
1959fn coverage_model_record(
1960    variant: &str,
1961    model: &CoverageModel,
1962    strings: &mut StringTable,
1963    relations: &mut StringRelations,
1964) -> Result<[u8; COVERAGE_MODEL_RECORD_SIZE], CoverageIndexError> {
1965    let mut record = [0_u8; COVERAGE_MODEL_RECORD_SIZE];
1966    put_u32(&mut record, 0, strings.intern(variant)?);
1967    put_u32(&mut record, 4, strings.intern(&model.name)?);
1968    put_u32(&mut record, 8, strings.intern(&model.completeness_meaning)?);
1969    let (measured_offset, measured_count) = relations.push(model.measured.clone(), strings)?;
1970    put_u64(&mut record, 16, measured_offset);
1971    put_u64(&mut record, 24, measured_count);
1972    let (not_measured_offset, not_measured_count) =
1973        relations.push(model.not_measured.clone(), strings)?;
1974    put_u64(&mut record, 32, not_measured_offset);
1975    put_u64(&mut record, 40, not_measured_count);
1976    Ok(record)
1977}
1978
1979pub fn coverage_index_sections(
1980    report: &CoverageReport,
1981) -> Result<Vec<QueryIndexSection>, CoverageIndexError> {
1982    let views = [
1983        (CoverageViewId::All, &report.view),
1984        (CoverageViewId::Passed, &report.filters.passed),
1985        (CoverageViewId::Failed, &report.filters.failed),
1986    ];
1987    let mut strings = StringTable::default();
1988    let mut relations = StringRelations::default();
1989    let mut summaries = Vec::with_capacity(views.len() * SUMMARY_RECORD_SIZE);
1990    let mut gaps = Vec::new();
1991    let mut decision_gaps = Vec::new();
1992    let mut dimensions = Vec::new();
1993    let mut projection_records = Vec::new();
1994    let mut scope_entries = Vec::new();
1995    let mut confidence_records = Vec::new();
1996    let mut line_records = Vec::new();
1997    let mut test_summaries = Vec::new();
1998    let mut phase_summaries = Vec::new();
1999    let mut anchors = Vec::new();
2000    let mut test_retries = Vec::new();
2001    let mut test_attempts = Vec::new();
2002    let mut test_lines = Vec::new();
2003    let mut test_hits = Vec::new();
2004    let mut test_decisions = Vec::new();
2005    let mut test_vectors = Vec::new();
2006    let mut vector_values = Vec::new();
2007    let mut hit_metadata = Vec::new();
2008    let mut decision_metadata = Vec::new();
2009    let mut decision_details = Vec::new();
2010    let mut decision_vector_observations = Vec::new();
2011    let mut decision_conditions = Vec::new();
2012    let mut limitations = Vec::new();
2013    for (id, view) in views {
2014        summaries.extend_from_slice(&summary_record(id, view, &mut strings)?);
2015        projection_records.extend_from_slice(&projection_record(
2016            id,
2017            view,
2018            None,
2019            None,
2020            None,
2021            &mut strings,
2022            &mut relations,
2023        )?);
2024        for entry in scope_entry_records(id, view, &mut strings)? {
2025            scope_entries.extend_from_slice(&entry);
2026        }
2027        for limitation in &view.limitations {
2028            limitations.extend_from_slice(&limitation_record(id, limitation, &mut strings)?);
2029        }
2030        for line in &view.lines {
2031            let confidence_index = confidence_records.len() / CONFIDENCE_RECORD_SIZE;
2032            confidence_records.extend_from_slice(&confidence_record(
2033                &line.confidence,
2034                &mut strings,
2035                &mut relations,
2036            )?);
2037            line_records.extend_from_slice(&line_record(
2038                id,
2039                line,
2040                confidence_index,
2041                &mut strings,
2042                &mut relations,
2043            )?);
2044        }
2045        for test in &view.tests {
2046            test_summaries.extend_from_slice(&test_summary_record(id, test, &mut strings)?);
2047            for retry in &test.retries {
2048                test_retries.extend_from_slice(&test_retry_record(
2049                    id,
2050                    &test.id,
2051                    *retry,
2052                    &mut strings,
2053                )?);
2054            }
2055            for attempt in &test.attempts {
2056                test_attempts.extend_from_slice(&test_attempt_record(
2057                    id,
2058                    &test.id,
2059                    attempt,
2060                    &mut strings,
2061                )?);
2062            }
2063            for line in &test.lines {
2064                test_lines.extend_from_slice(&test_line_record(id, &test.id, line, &mut strings)?);
2065            }
2066            for hit in &test.hits {
2067                test_hits.extend_from_slice(&test_hit_record(id, &test.id, hit, &mut strings)?);
2068            }
2069            for decision in &test.decisions {
2070                let vectors_offset = test_vectors.len() / TEST_VECTOR_RECORD_SIZE;
2071                for vector in &decision.vectors {
2072                    test_vectors
2073                        .extend_from_slice(&test_vector_record(vector, &mut vector_values)?);
2074                }
2075                test_decisions.extend_from_slice(&test_decision_record(
2076                    id,
2077                    &test.id,
2078                    &decision.id,
2079                    vectors_offset,
2080                    decision.vectors.len(),
2081                    &mut strings,
2082                )?);
2083            }
2084        }
2085        for phase in &view.phases {
2086            phase_summaries.extend_from_slice(&phase_summary_record(id, phase, &mut strings)?);
2087        }
2088        for decision in &view.decisions {
2089            let confidence_index = confidence_records.len() / CONFIDENCE_RECORD_SIZE;
2090            confidence_records.extend_from_slice(&confidence_record(
2091                &decision.confidence,
2092                &mut strings,
2093                &mut relations,
2094            )?);
2095            let observations_offset =
2096                decision_vector_observations.len() / DECISION_VECTOR_OBSERVATION_RECORD_SIZE;
2097            for observation in &decision.vector_observations {
2098                let observation_confidence = confidence_records.len() / CONFIDENCE_RECORD_SIZE;
2099                confidence_records.extend_from_slice(&confidence_record(
2100                    &observation.confidence,
2101                    &mut strings,
2102                    &mut relations,
2103                )?);
2104                let vector_index = test_vectors.len() / TEST_VECTOR_RECORD_SIZE;
2105                test_vectors.extend_from_slice(&test_vector_record(
2106                    &observation.vector,
2107                    &mut vector_values,
2108                )?);
2109                decision_vector_observations.extend_from_slice(
2110                    &decision_vector_observation_record(
2111                        observation,
2112                        observation_confidence,
2113                        vector_index,
2114                        &mut strings,
2115                        &mut relations,
2116                    )?,
2117                );
2118            }
2119            let conditions_offset = decision_conditions.len() / DECISION_CONDITION_RECORD_SIZE;
2120            for condition in &decision.conditions {
2121                let witness_vectors = if let Some(witness) = &condition.witness {
2122                    let first = test_vectors.len() / TEST_VECTOR_RECORD_SIZE;
2123                    test_vectors
2124                        .extend_from_slice(&test_vector_record(&witness[0], &mut vector_values)?);
2125                    let second = test_vectors.len() / TEST_VECTOR_RECORD_SIZE;
2126                    test_vectors
2127                        .extend_from_slice(&test_vector_record(&witness[1], &mut vector_values)?);
2128                    Some((first, second))
2129                } else {
2130                    None
2131                };
2132                decision_conditions.extend_from_slice(&decision_condition_record(
2133                    condition,
2134                    witness_vectors,
2135                    &mut strings,
2136                    &mut relations,
2137                )?);
2138            }
2139            decision_details.extend_from_slice(&decision_detail_record(
2140                DecisionDetailInput {
2141                    view_id: id,
2142                    decision,
2143                    confidence_index,
2144                    observations: (observations_offset, decision.vector_observations.len()),
2145                    conditions: (conditions_offset, decision.conditions.len()),
2146                },
2147                &mut strings,
2148                &mut relations,
2149            )?);
2150            decision_metadata.extend_from_slice(&decision_metadata_record(
2151                id,
2152                decision,
2153                &mut strings,
2154                &mut relations,
2155            )?);
2156            anchors.extend_from_slice(&anchor_record(
2157                AnchorInput {
2158                    view_id: id,
2159                    kind: 0,
2160                    id: &decision.meta.id,
2161                    file: &decision.meta.file,
2162                    line: decision.meta.line,
2163                    column: decision.meta.column,
2164                    covered: decision.covered,
2165                    conditions: Some((
2166                        decision
2167                            .conditions
2168                            .iter()
2169                            .filter(|condition| condition.covered)
2170                            .count(),
2171                        decision.conditions.len(),
2172                    )),
2173                    tests: &decision.tests,
2174                },
2175                &mut strings,
2176                &mut relations,
2177            )?);
2178        }
2179        for branch in &view.branches {
2180            anchors.extend_from_slice(&anchor_record(
2181                AnchorInput {
2182                    view_id: id,
2183                    kind: 1,
2184                    id: &branch.meta.id,
2185                    file: &branch.meta.file,
2186                    line: branch.meta.line,
2187                    column: branch.meta.column,
2188                    covered: branch.covered,
2189                    conditions: None,
2190                    tests: &[],
2191                },
2192                &mut strings,
2193                &mut relations,
2194            )?);
2195            for alternative in &branch.alternatives {
2196                hit_metadata.extend_from_slice(&hit_metadata_record(
2197                    HitMetadataInput {
2198                        view_id: id,
2199                        kind: 2,
2200                        id: &alternative.id,
2201                        file: &branch.meta.file,
2202                        line: branch.meta.line,
2203                        column: branch.meta.column,
2204                        branch_kind: Some(&branch.meta.kind),
2205                        label: Some(&branch.meta.id),
2206                        alternative: Some(&alternative.label),
2207                        source: &branch.meta.source,
2208                        tests: &alternative.tests,
2209                    },
2210                    &mut strings,
2211                    &mut relations,
2212                )?);
2213            }
2214        }
2215        for point in &view.points {
2216            anchors.extend_from_slice(&anchor_record(
2217                AnchorInput {
2218                    view_id: id,
2219                    kind: match point.meta.kind {
2220                        crate::coverage_analysis::PointKind::Statement => 2,
2221                        crate::coverage_analysis::PointKind::Function => 3,
2222                    },
2223                    id: &point.meta.id,
2224                    file: &point.meta.file,
2225                    line: point.meta.line,
2226                    column: point.meta.column,
2227                    covered: point.covered,
2228                    conditions: None,
2229                    tests: &point.tests,
2230                },
2231                &mut strings,
2232                &mut relations,
2233            )?);
2234            hit_metadata.extend_from_slice(&hit_metadata_record(
2235                HitMetadataInput {
2236                    view_id: id,
2237                    kind: match point.meta.kind {
2238                        crate::coverage_analysis::PointKind::Statement => 0,
2239                        crate::coverage_analysis::PointKind::Function => 1,
2240                    },
2241                    id: &point.meta.id,
2242                    file: &point.meta.file,
2243                    line: point.meta.line,
2244                    column: point.meta.column,
2245                    branch_kind: None,
2246                    label: point.meta.label.as_deref(),
2247                    alternative: None,
2248                    source: &point.meta.source,
2249                    tests: &point.tests,
2250                },
2251                &mut strings,
2252                &mut relations,
2253            )?);
2254        }
2255        for value in &view.coverage_by_kind {
2256            dimensions.extend_from_slice(&dimension_record(
2257                id,
2258                CoverageDimension::Kind,
2259                value,
2260                &mut strings,
2261            )?);
2262        }
2263        for value in &view.coverage_by_runner {
2264            dimensions.extend_from_slice(&dimension_record(
2265                id,
2266                CoverageDimension::Runner,
2267                value,
2268                &mut strings,
2269            )?);
2270        }
2271        let role = |role: &str| view.tests.iter().filter(|test| test.role == role).count();
2272        dimensions.extend_from_slice(&dimension_record(
2273            id,
2274            CoverageDimension::Tests,
2275            &crate::coverage_report::DimensionCoverage {
2276                kind: None,
2277                runner: None,
2278                tests: role("test"),
2279                setups: role("setup"),
2280                attributed: view
2281                    .tests
2282                    .iter()
2283                    .filter(|test| {
2284                        test.role == "test"
2285                            && crate::coverage_report::coverage_is_its_own(&test.attribution)
2286                    })
2287                    .count(),
2288                summary: crate::coverage_report::summary_for_tests(view)
2289                    .map_err(|_| CoverageIndexError::InvalidRecord("coverage of the tests"))?,
2290            },
2291            &mut strings,
2292        )?);
2293        for decision in &view.decisions {
2294            decision_gaps.extend_from_slice(&decision_gap_record(
2295                id,
2296                decision,
2297                None,
2298                None,
2299                None,
2300                &mut strings,
2301            )?);
2302        }
2303        for (file, gap) in file_gaps(view, None)? {
2304            gaps.extend_from_slice(&file_gap_record(id, &file, &gap, None, None, &mut strings)?);
2305        }
2306        for (kind, runner, selected) in projections(view) {
2307            projection_records.extend_from_slice(&projection_record(
2308                id,
2309                view,
2310                Some(&selected),
2311                kind.as_deref(),
2312                runner.as_deref(),
2313                &mut strings,
2314                &mut relations,
2315            )?);
2316            for decision in &view.decisions {
2317                decision_gaps.extend_from_slice(&decision_gap_record(
2318                    id,
2319                    decision,
2320                    Some(&selected),
2321                    kind.as_deref(),
2322                    runner.as_deref(),
2323                    &mut strings,
2324                )?);
2325            }
2326            for (file, gap) in file_gaps(view, Some(&selected))? {
2327                gaps.extend_from_slice(&file_gap_record(
2328                    id,
2329                    &file,
2330                    &gap,
2331                    kind.as_deref(),
2332                    runner.as_deref(),
2333                    &mut strings,
2334                )?);
2335            }
2336        }
2337        // What the tests cover of each file, all kinds together: a directory
2338        // read e2e 18.18%, every other kind 0.00% and 100.00% in all, and
2339        // nothing said that the rest ran while no test was running. Filed
2340        // under the name the tests' own dimension has, which no kind can be.
2341        let tested = crate::coverage_report::entries_in_kind_rows(view)
2342            .into_iter()
2343            .collect::<Selected>();
2344        if !tested.is_empty() {
2345            for (file, gap) in file_gaps(view, Some(&tested))? {
2346                gaps.extend_from_slice(&file_gap_record(
2347                    id,
2348                    &file,
2349                    &gap,
2350                    Some(ALL_TESTS),
2351                    None,
2352                    &mut strings,
2353                )?);
2354            }
2355        }
2356    }
2357    let model = coverage_model_record(
2358        &report.view.variant,
2359        &report.view.model,
2360        &mut strings,
2361        &mut relations,
2362    )?;
2363    let [blob, string_records] = strings.sections()?;
2364    let string_relations = relations.section()?;
2365    Ok(vec![
2366        blob,
2367        string_records,
2368        string_relations,
2369        QueryIndexSection {
2370            kind: SECTION_VIEW_SUMMARIES,
2371            record_size: SUMMARY_RECORD_SIZE as u32,
2372            count: usize_u64(summaries.len() / SUMMARY_RECORD_SIZE)?,
2373            bytes: summaries,
2374        },
2375        QueryIndexSection {
2376            kind: SECTION_FILE_GAPS,
2377            record_size: FILE_GAP_RECORD_SIZE as u32,
2378            count: usize_u64(gaps.len() / FILE_GAP_RECORD_SIZE)?,
2379            bytes: gaps,
2380        },
2381        QueryIndexSection {
2382            kind: SECTION_DECISION_GAPS,
2383            record_size: DECISION_GAP_RECORD_SIZE as u32,
2384            count: usize_u64(decision_gaps.len() / DECISION_GAP_RECORD_SIZE)?,
2385            bytes: decision_gaps,
2386        },
2387        QueryIndexSection {
2388            kind: SECTION_DIMENSIONS,
2389            record_size: DIMENSION_RECORD_SIZE as u32,
2390            count: usize_u64(dimensions.len() / DIMENSION_RECORD_SIZE)?,
2391            bytes: dimensions,
2392        },
2393        QueryIndexSection {
2394            kind: SECTION_PROJECTIONS,
2395            record_size: PROJECTION_RECORD_SIZE as u32,
2396            count: usize_u64(projection_records.len() / PROJECTION_RECORD_SIZE)?,
2397            bytes: projection_records,
2398        },
2399        QueryIndexSection {
2400            kind: SECTION_SCOPE_ENTRIES,
2401            record_size: SCOPE_ENTRY_RECORD_SIZE as u32,
2402            count: usize_u64(scope_entries.len() / SCOPE_ENTRY_RECORD_SIZE)?,
2403            bytes: scope_entries,
2404        },
2405        QueryIndexSection {
2406            kind: SECTION_CONFIDENCE,
2407            record_size: CONFIDENCE_RECORD_SIZE as u32,
2408            count: usize_u64(confidence_records.len() / CONFIDENCE_RECORD_SIZE)?,
2409            bytes: confidence_records,
2410        },
2411        QueryIndexSection {
2412            kind: SECTION_LINES,
2413            record_size: LINE_RECORD_SIZE as u32,
2414            count: usize_u64(line_records.len() / LINE_RECORD_SIZE)?,
2415            bytes: line_records,
2416        },
2417        QueryIndexSection {
2418            kind: SECTION_TEST_SUMMARIES,
2419            record_size: TEST_SUMMARY_RECORD_SIZE as u32,
2420            count: usize_u64(test_summaries.len() / TEST_SUMMARY_RECORD_SIZE)?,
2421            bytes: test_summaries,
2422        },
2423        QueryIndexSection {
2424            kind: SECTION_PHASE_SUMMARIES,
2425            record_size: PHASE_SUMMARY_RECORD_SIZE as u32,
2426            count: usize_u64(phase_summaries.len() / PHASE_SUMMARY_RECORD_SIZE)?,
2427            bytes: phase_summaries,
2428        },
2429        QueryIndexSection {
2430            kind: SECTION_ANCHORS,
2431            record_size: ANCHOR_RECORD_SIZE as u32,
2432            count: usize_u64(anchors.len() / ANCHOR_RECORD_SIZE)?,
2433            bytes: anchors,
2434        },
2435        QueryIndexSection {
2436            kind: SECTION_TEST_RETRIES,
2437            record_size: TEST_RETRY_RECORD_SIZE as u32,
2438            count: usize_u64(test_retries.len() / TEST_RETRY_RECORD_SIZE)?,
2439            bytes: test_retries,
2440        },
2441        QueryIndexSection {
2442            kind: SECTION_TEST_ATTEMPTS,
2443            record_size: TEST_ATTEMPT_RECORD_SIZE as u32,
2444            count: usize_u64(test_attempts.len() / TEST_ATTEMPT_RECORD_SIZE)?,
2445            bytes: test_attempts,
2446        },
2447        QueryIndexSection {
2448            kind: SECTION_TEST_LINES,
2449            record_size: TEST_LINE_RECORD_SIZE as u32,
2450            count: usize_u64(test_lines.len() / TEST_LINE_RECORD_SIZE)?,
2451            bytes: test_lines,
2452        },
2453        QueryIndexSection {
2454            kind: SECTION_TEST_HITS,
2455            record_size: TEST_HIT_RECORD_SIZE as u32,
2456            count: usize_u64(test_hits.len() / TEST_HIT_RECORD_SIZE)?,
2457            bytes: test_hits,
2458        },
2459        QueryIndexSection {
2460            kind: SECTION_TEST_DECISIONS,
2461            record_size: TEST_DECISION_RECORD_SIZE as u32,
2462            count: usize_u64(test_decisions.len() / TEST_DECISION_RECORD_SIZE)?,
2463            bytes: test_decisions,
2464        },
2465        QueryIndexSection {
2466            kind: SECTION_TEST_VECTORS,
2467            record_size: TEST_VECTOR_RECORD_SIZE as u32,
2468            count: usize_u64(test_vectors.len() / TEST_VECTOR_RECORD_SIZE)?,
2469            bytes: test_vectors,
2470        },
2471        QueryIndexSection {
2472            kind: SECTION_VECTOR_VALUES,
2473            record_size: 1,
2474            count: usize_u64(vector_values.len())?,
2475            bytes: vector_values,
2476        },
2477        QueryIndexSection {
2478            kind: SECTION_HIT_METADATA,
2479            record_size: HIT_METADATA_RECORD_SIZE as u32,
2480            count: usize_u64(hit_metadata.len() / HIT_METADATA_RECORD_SIZE)?,
2481            bytes: hit_metadata,
2482        },
2483        QueryIndexSection {
2484            kind: SECTION_DECISION_METADATA,
2485            record_size: DECISION_METADATA_RECORD_SIZE as u32,
2486            count: usize_u64(decision_metadata.len() / DECISION_METADATA_RECORD_SIZE)?,
2487            bytes: decision_metadata,
2488        },
2489        QueryIndexSection {
2490            kind: SECTION_DECISION_DETAILS,
2491            record_size: DECISION_DETAIL_RECORD_SIZE as u32,
2492            count: usize_u64(decision_details.len() / DECISION_DETAIL_RECORD_SIZE)?,
2493            bytes: decision_details,
2494        },
2495        QueryIndexSection {
2496            kind: SECTION_DECISION_VECTOR_OBSERVATIONS,
2497            record_size: DECISION_VECTOR_OBSERVATION_RECORD_SIZE as u32,
2498            count: usize_u64(
2499                decision_vector_observations.len() / DECISION_VECTOR_OBSERVATION_RECORD_SIZE,
2500            )?,
2501            bytes: decision_vector_observations,
2502        },
2503        QueryIndexSection {
2504            kind: SECTION_DECISION_CONDITIONS,
2505            record_size: DECISION_CONDITION_RECORD_SIZE as u32,
2506            count: usize_u64(decision_conditions.len() / DECISION_CONDITION_RECORD_SIZE)?,
2507            bytes: decision_conditions,
2508        },
2509        QueryIndexSection {
2510            kind: SECTION_LIMITATIONS,
2511            record_size: LIMITATION_RECORD_SIZE as u32,
2512            count: usize_u64(limitations.len() / LIMITATION_RECORD_SIZE)?,
2513            bytes: limitations,
2514        },
2515        QueryIndexSection {
2516            kind: SECTION_COVERAGE_MODEL,
2517            record_size: COVERAGE_MODEL_RECORD_SIZE as u32,
2518            count: 1,
2519            bytes: model.to_vec(),
2520        },
2521    ])
2522}
2523
2524pub struct CoverageIndex<'a> {
2525    index: &'a QueryIndex,
2526}
2527
2528impl<'a> CoverageIndex<'a> {
2529    pub fn new(index: &'a QueryIndex) -> Result<Self, CoverageIndexError> {
2530        for (kind, size) in [
2531            (SECTION_STRINGS, STRING_RECORD_SIZE),
2532            (SECTION_VIEW_SUMMARIES, SUMMARY_RECORD_SIZE),
2533            (SECTION_FILE_GAPS, FILE_GAP_RECORD_SIZE),
2534            (SECTION_DECISION_GAPS, DECISION_GAP_RECORD_SIZE),
2535            (SECTION_DIMENSIONS, DIMENSION_RECORD_SIZE),
2536            (SECTION_PROJECTIONS, PROJECTION_RECORD_SIZE),
2537            (SECTION_SCOPE_ENTRIES, SCOPE_ENTRY_RECORD_SIZE),
2538            (SECTION_CONFIDENCE, CONFIDENCE_RECORD_SIZE),
2539            (SECTION_LINES, LINE_RECORD_SIZE),
2540            (SECTION_TEST_SUMMARIES, TEST_SUMMARY_RECORD_SIZE),
2541            (SECTION_PHASE_SUMMARIES, PHASE_SUMMARY_RECORD_SIZE),
2542            (SECTION_ANCHORS, ANCHOR_RECORD_SIZE),
2543            (SECTION_TEST_RETRIES, TEST_RETRY_RECORD_SIZE),
2544            (SECTION_TEST_ATTEMPTS, TEST_ATTEMPT_RECORD_SIZE),
2545            (SECTION_TEST_LINES, TEST_LINE_RECORD_SIZE),
2546            (SECTION_TEST_HITS, TEST_HIT_RECORD_SIZE),
2547            (SECTION_TEST_DECISIONS, TEST_DECISION_RECORD_SIZE),
2548            (SECTION_TEST_VECTORS, TEST_VECTOR_RECORD_SIZE),
2549            (SECTION_VECTOR_VALUES, 1),
2550            (SECTION_HIT_METADATA, HIT_METADATA_RECORD_SIZE),
2551            (SECTION_DECISION_METADATA, DECISION_METADATA_RECORD_SIZE),
2552            (SECTION_DECISION_DETAILS, DECISION_DETAIL_RECORD_SIZE),
2553            (
2554                SECTION_DECISION_VECTOR_OBSERVATIONS,
2555                DECISION_VECTOR_OBSERVATION_RECORD_SIZE,
2556            ),
2557            (SECTION_DECISION_CONDITIONS, DECISION_CONDITION_RECORD_SIZE),
2558            (SECTION_LIMITATIONS, LIMITATION_RECORD_SIZE),
2559            (SECTION_COVERAGE_MODEL, COVERAGE_MODEL_RECORD_SIZE),
2560        ] {
2561            if index.descriptor(kind)?.record_size as usize != size {
2562                return Err(CoverageIndexError::InvalidRecord("record size"));
2563            }
2564        }
2565        index.descriptor(SECTION_STRING_BYTES)?;
2566        if index.descriptor(SECTION_STRING_RELATIONS)?.record_size != 4 {
2567            return Err(CoverageIndexError::InvalidRecord(
2568                "string-relation record size",
2569            ));
2570        }
2571        Ok(Self { index })
2572    }
2573
2574    pub fn model(&self) -> Result<IndexedCoverageModel, CoverageIndexError> {
2575        let descriptor = self.index.descriptor(SECTION_COVERAGE_MODEL)?;
2576        if descriptor.count != 1 {
2577            return Err(CoverageIndexError::InvalidRecord(
2578                "coverage model record count",
2579            ));
2580        }
2581        let record = self.index.record(SECTION_COVERAGE_MODEL, 0)?;
2582        if record[12..16].iter().any(|byte| *byte != 0) {
2583            return Err(CoverageIndexError::InvalidRecord(
2584                "coverage model reserved bytes",
2585            ));
2586        }
2587        Ok(IndexedCoverageModel {
2588            schema_version: COVERAGE_MODEL_SCHEMA_VERSION,
2589            variant: self.string(get_u32(record, 0))?,
2590            name: self.string(get_u32(record, 4))?,
2591            completeness_meaning: self.string(get_u32(record, 8))?,
2592            measured: self.relation_strings(get_u64(record, 16), get_u64(record, 24))?,
2593            not_measured: self.relation_strings(get_u64(record, 32), get_u64(record, 40))?,
2594        })
2595    }
2596
2597    /// Whether a string is `expected`, compared in place: a filter asks this
2598    /// of every record, and copying each one out to compare it was most of
2599    /// a one-file query's time.
2600    fn string_equals(&self, id: u32, expected: &str) -> Result<bool, CoverageIndexError> {
2601        let record = self.index.record(SECTION_STRINGS, u64::from(id))?;
2602        let length = u64::from(get_u32(record, 8));
2603        if length != expected.len() as u64 {
2604            return Ok(false);
2605        }
2606        let value = self
2607            .index
2608            .bytes(SECTION_STRING_BYTES, get_u64(record, 0), length)?;
2609        Ok(value == expected.as_bytes())
2610    }
2611
2612    fn string(&self, id: u32) -> Result<String, CoverageIndexError> {
2613        let record = self.index.record(SECTION_STRINGS, u64::from(id))?;
2614        if record[12..].iter().any(|byte| *byte != 0) {
2615            return Err(CoverageIndexError::InvalidRecord("string reserved bytes"));
2616        }
2617        let offset = get_u64(record, 0);
2618        let length = u64::from(get_u32(record, 8));
2619        let value = self.index.bytes(SECTION_STRING_BYTES, offset, length)?;
2620        std::str::from_utf8(value)
2621            .map(str::to_owned)
2622            .map_err(|_| CoverageIndexError::InvalidUtf8)
2623    }
2624
2625    pub fn summary(&self, view: CoverageViewId) -> Result<CoverageSummary, CoverageIndexError> {
2626        let descriptor = self.index.descriptor(SECTION_VIEW_SUMMARIES)?;
2627        if descriptor.count != 3 {
2628            return Err(CoverageIndexError::InvalidRecord("summary view count"));
2629        }
2630        let mut found = None;
2631        for index in 0..descriptor.count {
2632            let record = self.index.record(SECTION_VIEW_SUMMARIES, index)?;
2633            if CoverageViewId::try_from(record[0])? != view {
2634                continue;
2635            }
2636            if record[3] != 0 || record[12..16].iter().any(|byte| *byte != 0) {
2637                return Err(CoverageIndexError::InvalidRecord("summary reserved bytes"));
2638            }
2639            self.string(get_u32(record, 4))?;
2640            self.string(get_u32(record, 8))?;
2641            let count = |offset: usize| -> Result<CoverageCount, CoverageIndexError> {
2642                let covered = usize::try_from(get_u64(record, offset))
2643                    .map_err(|_| CoverageIndexError::SizeOverflow)?;
2644                let total = usize::try_from(get_u64(record, offset + 8))
2645                    .map_err(|_| CoverageIndexError::SizeOverflow)?;
2646                if covered > total {
2647                    return Err(CoverageIndexError::InvalidRecord("covered exceeds total"));
2648                }
2649                Ok(CoverageCount {
2650                    covered,
2651                    total,
2652                    percentage: percentage(covered, total),
2653                })
2654            };
2655            let value = |offset: usize| -> Result<usize, CoverageIndexError> {
2656                usize::try_from(get_u64(record, offset))
2657                    .map_err(|_| CoverageIndexError::SizeOverflow)
2658            };
2659            let conditions = value(40)?;
2660            let covered_conditions = value(48)?;
2661            if covered_conditions > conditions {
2662                return Err(CoverageIndexError::InvalidRecord(
2663                    "covered conditions exceed total",
2664                ));
2665            }
2666            let decisions = value(16)?;
2667            let executed_decisions = value(24)?;
2668            let covered_decisions = value(32)?;
2669            if covered_decisions > executed_decisions || executed_decisions > decisions {
2670                return Err(CoverageIndexError::InvalidRecord("decision count ordering"));
2671            }
2672            let summary = CoverageSummary {
2673                unmeasured_obligations: None,
2674                exact_fraction_pct: None,
2675                decisions,
2676                executed_decisions,
2677                covered_decisions,
2678                conditions,
2679                covered_conditions,
2680                condition_coverage_pct: percentage(covered_conditions, conditions),
2681                lines: count(56)?,
2682                statements: count(72)?,
2683                functions: count(88)?,
2684                branches: count(104)?,
2685                decision_outcomes: count(120)?,
2686                condition_outcomes: count(136)?,
2687                value_selections: count(152)?,
2688                coverage_complete: bool_field(record[1])?,
2689                completeness_blocked: match record[2] {
2690                    0 => None,
2691                    1 => Some(false),
2692                    2 => Some(true),
2693                    _ => return Err(CoverageIndexError::InvalidRecord("optional boolean")),
2694                },
2695            };
2696            if found.replace(summary).is_some() {
2697                return Err(CoverageIndexError::InvalidRecord("duplicate coverage view"));
2698            }
2699        }
2700        found.ok_or(CoverageIndexError::InvalidRecord("missing coverage view"))
2701    }
2702
2703    pub fn file_gaps(
2704        &self,
2705        view: CoverageViewId,
2706        kind: Option<&str>,
2707        runner: Option<&str>,
2708    ) -> Result<Vec<IndexedFileGap>, CoverageIndexError> {
2709        let descriptor = self.index.descriptor(SECTION_FILE_GAPS)?;
2710        let mut gaps = Vec::new();
2711        for index in 0..descriptor.count {
2712            let record = self.index.record(SECTION_FILE_GAPS, index)?;
2713            if CoverageViewId::try_from(record[0])? != view {
2714                continue;
2715            }
2716            if record[1..4].iter().any(|byte| *byte != 0)
2717                || record[60..64].iter().any(|byte| *byte != 0)
2718            {
2719                return Err(CoverageIndexError::InvalidRecord("file-gap reserved bytes"));
2720            }
2721            let number = |offset: usize| -> Result<usize, CoverageIndexError> {
2722                usize::try_from(get_u64(record, offset))
2723                    .map_err(|_| CoverageIndexError::SizeOverflow)
2724            };
2725            let mask = get_u32(record, 56);
2726            if mask & !15 != 0 {
2727                return Err(CoverageIndexError::InvalidRecord("limitation mask"));
2728            }
2729            let measurement_limitations = number(48)?;
2730            if (measurement_limitations == 0) != (mask == 0) {
2731                return Err(CoverageIndexError::InvalidRecord(
2732                    "limitation count and kinds disagree",
2733                ));
2734            }
2735            let uncovered_lines = number(8)?;
2736            let uncovered_statements = number(16)?;
2737            let uncovered_functions = number(24)?;
2738            let missing_branches = number(32)?;
2739            let missing_mcdc_conditions = number(40)?;
2740            let score = number(64)?;
2741            let expected_score = uncovered_lines
2742                + uncovered_functions * 2
2743                + missing_branches * 2
2744                + missing_mcdc_conditions * 3
2745                + measurement_limitations * 3;
2746            if score != expected_score {
2747                return Err(CoverageIndexError::InvalidRecord("file-gap score"));
2748            }
2749            let record_kind = self.optional_string(get_u32(record, 72))?;
2750            let record_runner = self.optional_string(get_u32(record, 76))?;
2751            if record_kind.as_deref() != kind || record_runner.as_deref() != runner {
2752                continue;
2753            }
2754            let mut limitation_kinds = Vec::new();
2755            for (bit, kind) in [
2756                (1, "dynamic-code"),
2757                (2, "semantic-safety"),
2758                (4, "source-scope"),
2759                (8, "unknown"),
2760            ] {
2761                if mask & bit != 0 {
2762                    limitation_kinds.push(kind.into());
2763                }
2764            }
2765            let totals = IndexedGapDimensions {
2766                lines: number(160)?,
2767                statements: number(168)?,
2768                functions: number(176)?,
2769                branches: number(184)?,
2770                mcdc_conditions: number(192)?,
2771            };
2772            let covered = |total: usize, missing: usize| {
2773                total
2774                    .checked_sub(missing)
2775                    .ok_or(CoverageIndexError::InvalidRecord("file-gap totals"))
2776            };
2777            gaps.push(IndexedFileGap {
2778                view,
2779                file: self.string(get_u32(record, 4))?,
2780                uncovered_lines,
2781                uncovered_statements,
2782                uncovered_functions,
2783                missing_branches,
2784                missing_mcdc_conditions,
2785                measurement_limitations,
2786                limitation_kinds,
2787                covered_by_other_tests: IndexedGapDimensions {
2788                    lines: number(80)?,
2789                    statements: number(88)?,
2790                    functions: number(96)?,
2791                    branches: number(104)?,
2792                    mcdc_conditions: number(112)?,
2793                },
2794                uncovered_everywhere: IndexedGapDimensions {
2795                    lines: number(120)?,
2796                    statements: number(128)?,
2797                    functions: number(136)?,
2798                    branches: number(144)?,
2799                    mcdc_conditions: number(152)?,
2800                },
2801                totals: totals.clone(),
2802                covered: IndexedGapDimensions {
2803                    lines: covered(totals.lines, uncovered_lines)?,
2804                    statements: covered(totals.statements, uncovered_statements)?,
2805                    functions: covered(totals.functions, uncovered_functions)?,
2806                    branches: covered(totals.branches, missing_branches)?,
2807                    mcdc_conditions: covered(totals.mcdc_conditions, missing_mcdc_conditions)?,
2808                },
2809                score,
2810            });
2811        }
2812        gaps.sort_by(|left, right| {
2813            right
2814                .score
2815                .cmp(&left.score)
2816                .then_with(|| left.file.cmp(&right.file))
2817        });
2818        Ok(gaps)
2819    }
2820
2821    fn optional_string(&self, id: u32) -> Result<Option<String>, CoverageIndexError> {
2822        if id == NO_STRING {
2823            Ok(None)
2824        } else {
2825            self.string(id).map(Some)
2826        }
2827    }
2828
2829    fn relation_ids(&self, offset: u64, count: u64) -> Result<Vec<Id>, CoverageIndexError> {
2830        Ok(self
2831            .relation_strings(offset, count)?
2832            .into_iter()
2833            .map(Id::from)
2834            .collect())
2835    }
2836
2837    fn relation_strings(&self, offset: u64, count: u64) -> Result<Vec<String>, CoverageIndexError> {
2838        let end = offset
2839            .checked_add(count)
2840            .ok_or(CoverageIndexError::SizeOverflow)?;
2841        let descriptor = self.index.descriptor(SECTION_STRING_RELATIONS)?;
2842        if end > descriptor.count {
2843            return Err(CoverageIndexError::InvalidRecord("string relation range"));
2844        }
2845        (offset..end)
2846            .map(|index| {
2847                let record = self.index.record(SECTION_STRING_RELATIONS, index)?;
2848                self.string(get_u32(record, 0))
2849            })
2850            .collect()
2851    }
2852
2853    pub fn projection(
2854        &self,
2855        view: CoverageViewId,
2856        kind: Option<&str>,
2857        runner: Option<&str>,
2858    ) -> Result<IndexedProjection, CoverageIndexError> {
2859        let descriptor = self.index.descriptor(SECTION_PROJECTIONS)?;
2860        let mut found = None;
2861        for index in 0..descriptor.count {
2862            let record = self.index.record(SECTION_PROJECTIONS, index)?;
2863            if CoverageViewId::try_from(record[0])? != view {
2864                continue;
2865            }
2866            if record[38..40].iter().any(|byte| *byte != 0)
2867                || record[518..520].iter().any(|byte| *byte != 0)
2868            {
2869                return Err(CoverageIndexError::InvalidRecord(
2870                    "projection reserved bytes",
2871                ));
2872            }
2873            let record_kind = self.optional_string(get_u32(record, 4))?;
2874            let record_runner = self.optional_string(get_u32(record, 8))?;
2875            if record_kind.as_deref() != kind || record_runner.as_deref() != runner {
2876                continue;
2877            }
2878            if found.is_some() {
2879                return Err(CoverageIndexError::InvalidRecord(
2880                    "duplicate coverage projection",
2881                ));
2882            }
2883            let number = |offset: usize| -> Result<usize, CoverageIndexError> {
2884                usize::try_from(get_u64(record, offset))
2885                    .map_err(|_| CoverageIndexError::SizeOverflow)
2886            };
2887            let limitations = number(192)?;
2888            let evidence_corruptions = number(200)?;
2889            let blocking = number(208)?;
2890            let declared = number(528)?;
2891            if blocking + declared != limitations + evidence_corruptions {
2892                return Err(CoverageIndexError::InvalidRecord(
2893                    "measurement blocking count",
2894                ));
2895            }
2896            let mut transport_values = (0..8)
2897                .map(|index| number(408 + index * 8))
2898                .collect::<Result<Vec<_>, _>>()?;
2899            transport_values.push(number(536)?);
2900            let transport = if bool_field(record[1])? {
2901                Some(TransportStats {
2902                    processes: transport_values[0],
2903                    child_launches: transport_values[1],
2904                    remote_launches: transport_values[2],
2905                    workspace_capabilities: transport_values[3],
2906                    guest_processes: transport_values[8],
2907                    scoped_server_records: transport_values[4],
2908                    background_server_records: transport_values[5],
2909                    corrupt_records: transport_values[6],
2910                    corrupt_files: transport_values[7],
2911                })
2912            } else {
2913                if transport_values.iter().any(|value| *value != 0) {
2914                    return Err(CoverageIndexError::InvalidRecord("transport presence flag"));
2915                }
2916                None
2917            };
2918            let has_scope = bool_field(record[2])?;
2919            let scope_kind = match record[3] {
2920                0 => None,
2921                1 => Some((ScopeKind::SourceDiscovery, "source-discovery")),
2922                2 => Some((ScopeKind::Compiler, "compiler")),
2923                _ => return Err(CoverageIndexError::InvalidRecord("coverage scope kind")),
2924            };
2925            let scope_mode = self.optional_string(get_u32(record, 16))?;
2926            let scope_language = self.optional_string(get_u32(record, 504))?;
2927            let scope_model = self.optional_string(get_u32(record, 508))?;
2928            let scope_unit = self.optional_string(get_u32(record, 512))?;
2929            let has_measurement_complete = bool_field(record[516])?;
2930            let measurement_complete = bool_field(record[517])?;
2931            if !has_measurement_complete && measurement_complete {
2932                return Err(CoverageIndexError::InvalidRecord(
2933                    "scope measurement completeness flag",
2934                ));
2935            }
2936            if has_scope
2937                != (scope_kind.is_some() && scope_language.is_some() && scope_model.is_some())
2938            {
2939                return Err(CoverageIndexError::InvalidRecord("scope presence flag"));
2940            }
2941            let source_scope = if let Some((kind, kind_name)) = scope_kind {
2942                match kind {
2943                    ScopeKind::SourceDiscovery => {
2944                        if scope_mode.is_none() || scope_unit.is_some() || has_measurement_complete
2945                        {
2946                            return Err(CoverageIndexError::InvalidRecord(
2947                                "source-discovery scope shape",
2948                            ));
2949                        }
2950                    }
2951                    ScopeKind::Compiler => {
2952                        if scope_mode.is_some()
2953                            || scope_unit.is_none()
2954                            || !has_measurement_complete
2955                            || get_u32(record, 32) != 0
2956                            || number(480)? != 0
2957                            || number(488)? != 0
2958                            || number(496)? != 0
2959                        {
2960                            return Err(CoverageIndexError::InvalidRecord("compiler scope shape"));
2961                        }
2962                    }
2963                }
2964                Some(IndexedSourceScope {
2965                    kind: kind_name.into(),
2966                    language: scope_language.expect("validated scope language"),
2967                    model: scope_model.expect("validated scope model"),
2968                    mode: scope_mode,
2969                    roots: self
2970                        .relation_strings(get_u64(record, 24), u64::from(get_u32(record, 32)))?,
2971                    unit: scope_unit,
2972                    measurement_complete: has_measurement_complete.then_some(measurement_complete),
2973                    included: number(480)?,
2974                    excluded: number(488)?,
2975                    ambiguous: number(496)?,
2976                })
2977            } else {
2978                if get_u32(record, 32) != 0
2979                    || scope_mode.is_some()
2980                    || scope_language.is_some()
2981                    || scope_model.is_some()
2982                    || scope_unit.is_some()
2983                    || has_measurement_complete
2984                    || number(480)? != 0
2985                    || number(488)? != 0
2986                    || number(496)? != 0
2987                {
2988                    return Err(CoverageIndexError::InvalidRecord("absent scope data"));
2989                }
2990                None
2991            };
2992            let empty_evidence_tests = number(472)?;
2993            let first_empty_evidence_test = self.optional_string(get_u32(record, 20))?;
2994            if (empty_evidence_tests == 0) != first_empty_evidence_test.is_none() {
2995                return Err(CoverageIndexError::InvalidRecord(
2996                    "empty-evidence diagnostic identity",
2997                ));
2998            }
2999            found = Some(IndexedProjection {
3000                view,
3001                kind: record_kind,
3002                runner: record_runner,
3003                generated_at: self.string(get_u32(record, 12))?,
3004                summary: decode_summary(record, 36, 40)?,
3005                measurement: IndexedMeasurement {
3006                    complete: blocking == 0,
3007                    limitations,
3008                    evidence_corruptions,
3009                    blocking,
3010                    declared,
3011                    files: number(216)?,
3012                    by_kind: IndexedMeasurementKinds {
3013                        dynamic_code: number(224)?,
3014                        semantic_safety: number(232)?,
3015                        source_scope: number(240)?,
3016                    },
3017                },
3018                attribution: IndexedAttribution {
3019                    browser_explicit: number(248)?,
3020                    browser_fallback: number(256)?,
3021                    server_explicit: number(264)?,
3022                    server_fallback: number(272)?,
3023                },
3024                transport,
3025                empty_evidence_tests,
3026                first_empty_evidence_test,
3027                confidence: IndexedSummaryConfidence {
3028                    lines: IndexedConfidenceLines {
3029                        unexecuted: number(280)?,
3030                        executed: number(288)?,
3031                        action: number(296)?,
3032                        asserted: number(304)?,
3033                    },
3034                    assertion_covered_mcdc_conditions: number(312)?,
3035                },
3036                files_with_gaps: number(320)?,
3037                files_with_coverage_gaps: number(328)?,
3038                tests: number(336)?,
3039                setups: number(344)?,
3040                test_outcomes: {
3041                    let mut outcomes = IndexedOutcomeCounts {
3042                        passed: number(352)?,
3043                        failed: number(360)?,
3044                        flaky: number(368)?,
3045                        skipped: number(376)?,
3046                        timed_out: number(384)?,
3047                        interrupted: number(392)?,
3048                        unknown: number(400)?,
3049                        unstarted: number(520)?,
3050                        todo: 0,
3051                    };
3052                    // The projection record has no slot left, so todo is the
3053                    // tests no other outcome counts; zero in older indexes.
3054                    outcomes.todo = number(336)?.saturating_sub(
3055                        outcomes.passed
3056                            + outcomes.failed
3057                            + outcomes.flaky
3058                            + outcomes.skipped
3059                            + outcomes.timed_out
3060                            + outcomes.interrupted
3061                            + outcomes.unknown
3062                            + outcomes.unstarted,
3063                    );
3064                    outcomes
3065                },
3066                source_scope,
3067            });
3068        }
3069        found.ok_or(CoverageIndexError::InvalidRecord(
3070            "missing coverage projection",
3071        ))
3072    }
3073
3074    pub fn decision_gaps(
3075        &self,
3076        view: CoverageViewId,
3077        kind: Option<&str>,
3078        runner: Option<&str>,
3079        file: &str,
3080    ) -> Result<Vec<IndexedDecisionGap>, CoverageIndexError> {
3081        let descriptor = self.index.descriptor(SECTION_DECISION_GAPS)?;
3082        let mut decisions = Vec::new();
3083        for index in 0..descriptor.count {
3084            let record = self.index.record(SECTION_DECISION_GAPS, index)?;
3085            if CoverageViewId::try_from(record[0])? != view {
3086                continue;
3087            }
3088            if record[1..4].iter().any(|byte| *byte != 0)
3089                || record[28..32].iter().any(|byte| *byte != 0)
3090                || record[64..].iter().any(|byte| *byte != 0)
3091            {
3092                return Err(CoverageIndexError::InvalidRecord(
3093                    "decision-gap reserved bytes",
3094                ));
3095            }
3096            let record_kind = self.optional_string(get_u32(record, 4))?;
3097            let record_runner = self.optional_string(get_u32(record, 8))?;
3098            if record_kind.as_deref() != kind || record_runner.as_deref() != runner {
3099                continue;
3100            }
3101            let record_file = self.string(get_u32(record, 16))?;
3102            if record_file != file {
3103                continue;
3104            }
3105            let number = |offset: usize| -> Result<usize, CoverageIndexError> {
3106                usize::try_from(get_u64(record, offset))
3107                    .map_err(|_| CoverageIndexError::SizeOverflow)
3108            };
3109            let conditions = number(48)?;
3110            let missing_conditions = number(56)?;
3111            if conditions == 0 || missing_conditions > conditions {
3112                return Err(CoverageIndexError::InvalidRecord(
3113                    "decision condition counts",
3114                ));
3115            }
3116            decisions.push(IndexedDecisionGap {
3117                view,
3118                file: record_file,
3119                id: self.string(get_u32(record, 12))?,
3120                line: number(32)?,
3121                column: number(40)?,
3122                kind: self.string(get_u32(record, 20))?,
3123                conditions,
3124                missing_conditions,
3125                source: self.string(get_u32(record, 24))?,
3126            });
3127        }
3128        Ok(decisions)
3129    }
3130
3131    pub fn dimensions(
3132        &self,
3133        view: CoverageViewId,
3134        dimension: CoverageDimension,
3135    ) -> Result<Vec<IndexedDimensionCoverage>, CoverageIndexError> {
3136        let descriptor = self.index.descriptor(SECTION_DIMENSIONS)?;
3137        let mut values = Vec::new();
3138        for index in 0..descriptor.count {
3139            let record = self.index.record(SECTION_DIMENSIONS, index)?;
3140            if CoverageViewId::try_from(record[0])? != view {
3141                continue;
3142            }
3143            let record_dimension = match record[1] {
3144                0 => CoverageDimension::Kind,
3145                1 => CoverageDimension::Runner,
3146                2 => CoverageDimension::Tests,
3147                _ => return Err(CoverageIndexError::InvalidRecord("dimension type")),
3148            };
3149            if record_dimension != dimension {
3150                continue;
3151            }
3152            if record[26..32].iter().any(|byte| *byte != 0) {
3153                return Err(CoverageIndexError::InvalidRecord(
3154                    "dimension reserved bytes",
3155                ));
3156            }
3157            let name = self.string(get_u32(record, 4))?;
3158            values.push(IndexedDimensionCoverage {
3159                kind: (dimension == CoverageDimension::Kind).then(|| name.clone()),
3160                runner: (dimension == CoverageDimension::Runner).then_some(name),
3161                tests: usize::try_from(get_u64(record, 8))
3162                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3163                setups: usize::try_from(get_u64(record, 16))
3164                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3165                attributed: usize::try_from(get_u64(record, 184))
3166                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3167                summary: decode_summary(record, 24, 32)?,
3168            });
3169        }
3170        Ok(values)
3171    }
3172
3173    pub fn scope_entries(
3174        &self,
3175        view: CoverageViewId,
3176    ) -> Result<Vec<IndexedScopeEntry>, CoverageIndexError> {
3177        let descriptor = self.index.descriptor(SECTION_SCOPE_ENTRIES)?;
3178        let mut entries = Vec::new();
3179        for index in 0..descriptor.count {
3180            let record = self.index.record(SECTION_SCOPE_ENTRIES, index)?;
3181            if CoverageViewId::try_from(record[0])? != view {
3182                continue;
3183            }
3184            if record[2..4].iter().any(|byte| *byte != 0)
3185                || record[28..].iter().any(|byte| *byte != 0)
3186            {
3187                return Err(CoverageIndexError::InvalidRecord(
3188                    "source-scope reserved bytes",
3189                ));
3190            }
3191            let status = match record[1] {
3192                0 => "included",
3193                1 => "excluded",
3194                2 => "ambiguous",
3195                _ => return Err(CoverageIndexError::InvalidRecord("source-scope status")),
3196            };
3197            let measurement_limitations = usize::try_from(get_u64(record, 16))
3198                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3199            let mask = get_u32(record, 24);
3200            if mask & !15 != 0 || (measurement_limitations == 0) != (mask == 0) {
3201                return Err(CoverageIndexError::InvalidRecord(
3202                    "source-scope limitation annotation",
3203                ));
3204            }
3205            let mut limitation_kinds = Vec::new();
3206            for (bit, kind) in [
3207                (1, "dynamic-code"),
3208                (2, "semantic-safety"),
3209                (4, "source-scope"),
3210                (8, "unknown"),
3211            ] {
3212                if mask & bit != 0 {
3213                    limitation_kinds.push(kind.into());
3214                }
3215            }
3216            entries.push(IndexedScopeEntry {
3217                file: self.string(get_u32(record, 4))?,
3218                status: status.into(),
3219                reason: self.string(get_u32(record, 8))?,
3220                package_root: self.optional_string(get_u32(record, 12))?,
3221                measurement_limitations,
3222                limitation_kinds,
3223            });
3224        }
3225        Ok(entries)
3226    }
3227
3228    fn confidence(
3229        &self,
3230        index: u64,
3231    ) -> Result<crate::coverage_report::CoverageConfidence, CoverageIndexError> {
3232        let record = self.index.record(SECTION_CONFIDENCE, index)?;
3233        if record[2..8].iter().any(|byte| *byte != 0)
3234            || record[72..].iter().any(|byte| *byte != 0)
3235            || record[1] & !15 != 0
3236        {
3237            return Err(CoverageIndexError::InvalidRecord("confidence record"));
3238        }
3239        let values = (0..4)
3240            .map(|index| {
3241                self.relation_strings(
3242                    get_u64(record, 8 + index * 16),
3243                    get_u64(record, 16 + index * 16),
3244                )
3245            })
3246            .collect::<Result<Vec<_>, _>>()?;
3247        Ok(crate::coverage_report::CoverageConfidence {
3248            level: match record[0] {
3249                0 => "unexecuted",
3250                1 => "executed",
3251                2 => "action",
3252                3 => "asserted",
3253                _ => return Err(CoverageIndexError::InvalidRecord("confidence level")),
3254            }
3255            .into(),
3256            setup_only: record[1] & 1 != 0,
3257            background_only: record[1] & 2 != 0,
3258            asserted: record[1] & 4 != 0,
3259            e2e: record[1] & 8 != 0,
3260            tests: values[0].iter().map(Id::from).collect(),
3261            asserted_tests: values[1].iter().map(Id::from).collect(),
3262            runners: values[2].clone(),
3263            kinds: values[3].clone(),
3264        })
3265    }
3266
3267    pub fn line(
3268        &self,
3269        view: CoverageViewId,
3270        file: &str,
3271        line: usize,
3272    ) -> Result<Option<IndexedLine>, CoverageIndexError> {
3273        let descriptor = self.index.descriptor(SECTION_LINES)?;
3274        let mut found = None;
3275        for index in 0..descriptor.count {
3276            let record = self.index.record(SECTION_LINES, index)?;
3277            if CoverageViewId::try_from(record[0])? != view {
3278                continue;
3279            }
3280            if record[3] != 0 || record[56..].iter().any(|byte| *byte != 0) {
3281                return Err(CoverageIndexError::InvalidRecord("line record"));
3282            }
3283            let record_file = self.string(get_u32(record, 4))?;
3284            let record_line = usize::try_from(get_u64(record, 8))
3285                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3286            if record_file != file || record_line != line {
3287                continue;
3288            }
3289            if found.is_some() {
3290                return Err(CoverageIndexError::InvalidRecord("duplicate line"));
3291            }
3292            found = Some(IndexedLine {
3293                file: record_file,
3294                line: record_line,
3295                covered: bool_field(record[1])?,
3296                measured: !bool_field(record[2])?,
3297                tests: self.relation_strings(get_u64(record, 16), get_u64(record, 24))?,
3298                phases: self.relation_strings(get_u64(record, 32), get_u64(record, 40))?,
3299                confidence: self.confidence(get_u64(record, 48))?,
3300            });
3301        }
3302        Ok(found)
3303    }
3304
3305    pub fn lines(&self, view: CoverageViewId) -> Result<Vec<IndexedLine>, CoverageIndexError> {
3306        self.lines_where(view, None)
3307    }
3308
3309    /// `lines`, of one file only: records of other files are skipped before anything in them is decoded.
3310    pub fn lines_in_file(
3311        &self,
3312        view: CoverageViewId,
3313        file: &str,
3314    ) -> Result<Vec<IndexedLine>, CoverageIndexError> {
3315        self.lines_where(view, Some(file))
3316    }
3317
3318    fn lines_where(
3319        &self,
3320        view: CoverageViewId,
3321        file: Option<&str>,
3322    ) -> Result<Vec<IndexedLine>, CoverageIndexError> {
3323        let descriptor = self.index.descriptor(SECTION_LINES)?;
3324        let mut lines = Vec::new();
3325        for index in 0..descriptor.count {
3326            let record = self.index.record(SECTION_LINES, index)?;
3327            if CoverageViewId::try_from(record[0])? != view {
3328                continue;
3329            }
3330            if let Some(file) = file
3331                && !self.string_equals(get_u32(record, 4), file)?
3332            {
3333                continue;
3334            }
3335            if record[3] != 0 || record[56..].iter().any(|byte| *byte != 0) {
3336                return Err(CoverageIndexError::InvalidRecord("line record"));
3337            }
3338            lines.push(IndexedLine {
3339                file: self.string(get_u32(record, 4))?,
3340                line: usize::try_from(get_u64(record, 8))
3341                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3342                covered: bool_field(record[1])?,
3343                measured: !bool_field(record[2])?,
3344                tests: self.relation_strings(get_u64(record, 16), get_u64(record, 24))?,
3345                phases: self.relation_strings(get_u64(record, 32), get_u64(record, 40))?,
3346                confidence: self.confidence(get_u64(record, 48))?,
3347            });
3348        }
3349        Ok(lines)
3350    }
3351
3352    pub fn test_summaries(
3353        &self,
3354        view: CoverageViewId,
3355    ) -> Result<Vec<IndexedTestSummary>, CoverageIndexError> {
3356        let descriptor = self.index.descriptor(SECTION_TEST_SUMMARIES)?;
3357        let mut tests = Vec::new();
3358        for index in 0..descriptor.count {
3359            let record = self.index.record(SECTION_TEST_SUMMARIES, index)?;
3360            if CoverageViewId::try_from(record[0])? != view {
3361                continue;
3362            }
3363            if record[36..].iter().any(|byte| *byte != 0) {
3364                return Err(CoverageIndexError::InvalidRecord("test summary record"));
3365            }
3366            tests.push(IndexedTestSummary {
3367                id: self.string(get_u32(record, 4))?,
3368                name: self.string(get_u32(record, 8))?,
3369                file: self.optional_string(get_u32(record, 12))?,
3370                title: self.optional_string(get_u32(record, 16))?,
3371                role: match record[1] {
3372                    0 => "test",
3373                    1 => "setup",
3374                    2 => "background",
3375                    _ => return Err(CoverageIndexError::InvalidRecord("test role")),
3376                }
3377                .into(),
3378                attribution: match record[3] {
3379                    0 => crate::coverage_report::ATTRIBUTION_EXACT,
3380                    1 => crate::coverage_report::ATTRIBUTION_RUN_WIDE,
3381                    2 => crate::coverage_report::ATTRIBUTION_PARTIAL,
3382                    3 => crate::coverage_report::ATTRIBUTION_BY_TIME,
3383                    _ => return Err(CoverageIndexError::InvalidRecord("test attribution")),
3384                }
3385                .into(),
3386                outcome: match record[2] {
3387                    0 => "passed",
3388                    1 => "failed",
3389                    2 => "flaky",
3390                    3 => "skipped",
3391                    4 => "timedOut",
3392                    5 => "interrupted",
3393                    6 => "unknown",
3394                    7 => "unstarted",
3395                    8 => "todo",
3396                    _ => return Err(CoverageIndexError::InvalidRecord("test outcome")),
3397                }
3398                .into(),
3399                provenance: crate::coverage_report::TestProvenance {
3400                    runner: self.string(get_u32(record, 20))?,
3401                    kind: self.string(get_u32(record, 24))?,
3402                    project: self.optional_string(get_u32(record, 28))?,
3403                    source: self.string(get_u32(record, 32))?,
3404                },
3405            });
3406        }
3407        Ok(tests)
3408    }
3409
3410    fn test_vector(&self, index: u64) -> Result<McdcVector, CoverageIndexError> {
3411        let record = self.index.record(SECTION_TEST_VECTORS, index)?;
3412        if record[1..8].iter().any(|byte| *byte != 0) {
3413            return Err(CoverageIndexError::InvalidRecord("test vector record"));
3414        }
3415        let offset = get_u64(record, 8);
3416        let count = get_u64(record, 16);
3417        let descriptor = self.index.descriptor(SECTION_VECTOR_VALUES)?;
3418        let end = offset
3419            .checked_add(count)
3420            .ok_or(CoverageIndexError::InvalidRecord("vector value range"))?;
3421        if end > descriptor.count {
3422            return Err(CoverageIndexError::InvalidRecord("vector value range"));
3423        }
3424        let mut values = Vec::with_capacity(
3425            usize::try_from(count).map_err(|_| CoverageIndexError::SizeOverflow)?,
3426        );
3427        for index in offset..end {
3428            values.push(match self.index.record(SECTION_VECTOR_VALUES, index)?[0] {
3429                0 => None,
3430                1 => Some(false),
3431                2 => Some(true),
3432                _ => return Err(CoverageIndexError::InvalidRecord("vector value")),
3433            });
3434        }
3435        Ok(McdcVector {
3436            values,
3437            outcome: bool_field(record[0])?,
3438        })
3439    }
3440
3441    pub fn test_details(
3442        &self,
3443        view: CoverageViewId,
3444    ) -> Result<Vec<IndexedTestDetail>, CoverageIndexError> {
3445        let summaries = self.test_summaries(view)?;
3446        let positions = summaries
3447            .iter()
3448            .enumerate()
3449            .map(|(index, test)| (test.id.clone(), index))
3450            .collect::<HashMap<_, _>>();
3451        if positions.len() != summaries.len() {
3452            return Err(CoverageIndexError::InvalidRecord("duplicate test summary"));
3453        }
3454        let mut details = summaries
3455            .into_iter()
3456            .map(|summary| IndexedTestDetail {
3457                summary,
3458                retries: Vec::new(),
3459                attempts: Vec::new(),
3460                hits: Vec::new(),
3461                decisions: Vec::new(),
3462                lines: Vec::new(),
3463            })
3464            .collect::<Vec<_>>();
3465        let position = |record: &[u8]| -> Result<Option<usize>, CoverageIndexError> {
3466            if CoverageViewId::try_from(record[0])? != view {
3467                return Ok(None);
3468            }
3469            let id = self.string(get_u32(record, 4))?;
3470            positions
3471                .get(&id)
3472                .copied()
3473                .map(Some)
3474                .ok_or(CoverageIndexError::InvalidRecord("unknown test relation"))
3475        };
3476        let descriptor = self.index.descriptor(SECTION_TEST_RETRIES)?;
3477        for index in 0..descriptor.count {
3478            let record = self.index.record(SECTION_TEST_RETRIES, index)?;
3479            if record[1..4].iter().any(|byte| *byte != 0) {
3480                return Err(CoverageIndexError::InvalidRecord("test retry record"));
3481            }
3482            if let Some(position) = position(record)? {
3483                details[position].retries.push(
3484                    usize::try_from(get_u64(record, 8))
3485                        .map_err(|_| CoverageIndexError::SizeOverflow)?,
3486                );
3487            }
3488        }
3489        let descriptor = self.index.descriptor(SECTION_TEST_ATTEMPTS)?;
3490        for index in 0..descriptor.count {
3491            let record = self.index.record(SECTION_TEST_ATTEMPTS, index)?;
3492            if record[1..4].iter().any(|byte| *byte != 0) {
3493                return Err(CoverageIndexError::InvalidRecord("test attempt record"));
3494            }
3495            if let Some(position) = position(record)? {
3496                details[position]
3497                    .attempts
3498                    .push(crate::coverage_report::TestAttempt {
3499                        retry: usize::try_from(get_u64(record, 8))
3500                            .map_err(|_| CoverageIndexError::SizeOverflow)?,
3501                        status: self.string(get_u32(record, 16))?,
3502                        expected_status: self.optional_string(get_u32(record, 20))?,
3503                    });
3504            }
3505        }
3506        let descriptor = self.index.descriptor(SECTION_TEST_LINES)?;
3507        for index in 0..descriptor.count {
3508            let record = self.index.record(SECTION_TEST_LINES, index)?;
3509            if record[1..4].iter().any(|byte| *byte != 0)
3510                || record[12..16].iter().any(|byte| *byte != 0)
3511            {
3512                return Err(CoverageIndexError::InvalidRecord("test line record"));
3513            }
3514            if let Some(position) = position(record)? {
3515                details[position]
3516                    .lines
3517                    .push(crate::coverage_report::SourceLine {
3518                        file: self.string(get_u32(record, 8))?.into(),
3519                        line: usize::try_from(get_u64(record, 16))
3520                            .map_err(|_| CoverageIndexError::SizeOverflow)?,
3521                    });
3522            }
3523        }
3524        let descriptor = self.index.descriptor(SECTION_TEST_HITS)?;
3525        for index in 0..descriptor.count {
3526            let record = self.index.record(SECTION_TEST_HITS, index)?;
3527            if record[1..4].iter().any(|byte| *byte != 0)
3528                || record[12..].iter().any(|byte| *byte != 0)
3529            {
3530                return Err(CoverageIndexError::InvalidRecord("test hit record"));
3531            }
3532            if let Some(position) = position(record)? {
3533                details[position]
3534                    .hits
3535                    .push(self.string(get_u32(record, 8))?);
3536            }
3537        }
3538        let descriptor = self.index.descriptor(SECTION_TEST_DECISIONS)?;
3539        let vectors = self.index.descriptor(SECTION_TEST_VECTORS)?.count;
3540        for index in 0..descriptor.count {
3541            let record = self.index.record(SECTION_TEST_DECISIONS, index)?;
3542            if record[1..4].iter().any(|byte| *byte != 0)
3543                || record[12..16].iter().any(|byte| *byte != 0)
3544            {
3545                return Err(CoverageIndexError::InvalidRecord("test decision record"));
3546            }
3547            if let Some(position) = position(record)? {
3548                let offset = get_u64(record, 16);
3549                let count = get_u64(record, 24);
3550                let end = offset
3551                    .checked_add(count)
3552                    .ok_or(CoverageIndexError::InvalidRecord("test vector range"))?;
3553                if end > vectors {
3554                    return Err(CoverageIndexError::InvalidRecord("test vector range"));
3555                }
3556                let mut observed = Vec::with_capacity(
3557                    usize::try_from(count).map_err(|_| CoverageIndexError::SizeOverflow)?,
3558                );
3559                for vector in offset..end {
3560                    observed.push(self.test_vector(vector)?);
3561                }
3562                details[position]
3563                    .decisions
3564                    .push(crate::coverage_report::TestDecisionResult {
3565                        id: self.string(get_u32(record, 8))?,
3566                        vectors: observed,
3567                    });
3568            }
3569        }
3570        Ok(details)
3571    }
3572
3573    pub fn hit_metadata(
3574        &self,
3575        view: CoverageViewId,
3576    ) -> Result<Vec<IndexedHitMetadata>, CoverageIndexError> {
3577        self.hit_metadata_where(view, None)
3578    }
3579
3580    /// `hit_metadata`, of one file only: records of other files are skipped before anything in them is decoded.
3581    pub fn hit_metadata_in_file(
3582        &self,
3583        view: CoverageViewId,
3584        file: &str,
3585    ) -> Result<Vec<IndexedHitMetadata>, CoverageIndexError> {
3586        self.hit_metadata_where(view, Some(file))
3587    }
3588
3589    fn hit_metadata_where(
3590        &self,
3591        view: CoverageViewId,
3592        file: Option<&str>,
3593    ) -> Result<Vec<IndexedHitMetadata>, CoverageIndexError> {
3594        let descriptor = self.index.descriptor(SECTION_HIT_METADATA)?;
3595        let mut metadata = Vec::new();
3596        for index in 0..descriptor.count {
3597            let record = self.index.record(SECTION_HIT_METADATA, index)?;
3598            if CoverageViewId::try_from(record[0])? != view {
3599                continue;
3600            }
3601            if let Some(file) = file
3602                && !self.string_equals(get_u32(record, 8), file)?
3603            {
3604                continue;
3605            }
3606            if record[2..4].iter().any(|byte| *byte != 0)
3607                || record[12..16].iter().any(|byte| *byte != 0)
3608            {
3609                return Err(CoverageIndexError::InvalidRecord("hit metadata record"));
3610            }
3611            let obligation = match record[1] {
3612                0 => "statement",
3613                1 => "function",
3614                2 => "branch",
3615                _ => return Err(CoverageIndexError::InvalidRecord("hit obligation")),
3616            };
3617            let metadata_label = self.optional_string(get_u32(record, 36))?;
3618            metadata.push(IndexedHitMetadata {
3619                id: self.string(get_u32(record, 4))?,
3620                obligation: obligation.into(),
3621                file: self.string(get_u32(record, 8))?,
3622                line: usize::try_from(get_u64(record, 16))
3623                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3624                column: usize::try_from(get_u64(record, 24))
3625                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3626                branch_kind: self.optional_string(get_u32(record, 32))?,
3627                label: (obligation != "branch")
3628                    .then_some(metadata_label.clone())
3629                    .flatten(),
3630                alternative: self.optional_string(get_u32(record, 40))?,
3631                parent_id: (obligation == "branch").then_some(metadata_label).flatten(),
3632                source: self.string(get_u32(record, 44))?,
3633                tests: self.relation_strings(get_u64(record, 48), get_u64(record, 56))?,
3634            });
3635        }
3636        Ok(metadata)
3637    }
3638
3639    pub fn limitations(
3640        &self,
3641        view: CoverageViewId,
3642    ) -> Result<Vec<IndexedLimitation>, CoverageIndexError> {
3643        self.limitations_where(view, None)
3644    }
3645
3646    /// `limitations`, of one file only: records of other files are skipped before anything in them is decoded.
3647    pub fn limitations_in_file(
3648        &self,
3649        view: CoverageViewId,
3650        file: &str,
3651    ) -> Result<Vec<IndexedLimitation>, CoverageIndexError> {
3652        self.limitations_where(view, Some(file))
3653    }
3654
3655    fn limitations_where(
3656        &self,
3657        view: CoverageViewId,
3658        file: Option<&str>,
3659    ) -> Result<Vec<IndexedLimitation>, CoverageIndexError> {
3660        let descriptor = self.index.descriptor(SECTION_LIMITATIONS)?;
3661        let mut limitations = Vec::new();
3662        for index in 0..descriptor.count {
3663            let record = self.index.record(SECTION_LIMITATIONS, index)?;
3664            if CoverageViewId::try_from(record[0])? != view {
3665                continue;
3666            }
3667            if let Some(file) = file
3668                && !self.string_equals(get_u32(record, 12), file)?
3669            {
3670                continue;
3671            }
3672            if record[2..4].iter().any(|byte| *byte != 0)
3673                || record[40..].iter().any(|byte| *byte != 0)
3674            {
3675                return Err(CoverageIndexError::InvalidRecord("limitation record"));
3676            }
3677            limitations.push(IndexedLimitation {
3678                id: self.string(get_u32(record, 4))?,
3679                kind: self.string(get_u32(record, 8))?,
3680                file: self.string(get_u32(record, 12))?,
3681                source: self.string(get_u32(record, 16))?,
3682                reason: self.string(get_u32(record, 20))?,
3683                line: usize::try_from(get_u64(record, 24))
3684                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3685                column: usize::try_from(get_u64(record, 32))
3686                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3687                blocking: bool_field(record[1])?,
3688            });
3689        }
3690        Ok(limitations)
3691    }
3692
3693    pub fn decision_metadata(
3694        &self,
3695        view: CoverageViewId,
3696    ) -> Result<Vec<crate::coverage_report::DecisionMeta>, CoverageIndexError> {
3697        let descriptor = self.index.descriptor(SECTION_DECISION_METADATA)?;
3698        let mut metadata = Vec::new();
3699        for index in 0..descriptor.count {
3700            let record = self.index.record(SECTION_DECISION_METADATA, index)?;
3701            if CoverageViewId::try_from(record[0])? != view {
3702                continue;
3703            }
3704            if record[1..4].iter().any(|byte| *byte != 0)
3705                || record[20..24].iter().any(|byte| *byte != 0)
3706                || record[56..].iter().any(|byte| *byte != 0)
3707            {
3708                return Err(CoverageIndexError::InvalidRecord(
3709                    "decision metadata record",
3710                ));
3711            }
3712            metadata.push(crate::coverage_report::DecisionMeta {
3713                id: self.string(get_u32(record, 4))?,
3714                file: self.string(get_u32(record, 8))?,
3715                source: self.string(get_u32(record, 12))?,
3716                kind: self.string(get_u32(record, 16))?,
3717                line: usize::try_from(get_u64(record, 24))
3718                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3719                column: usize::try_from(get_u64(record, 32))
3720                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3721                conditions: self.relation_strings(get_u64(record, 40), get_u64(record, 48))?,
3722            });
3723        }
3724        Ok(metadata)
3725    }
3726
3727    fn decision_vector_observation(
3728        &self,
3729        index: u64,
3730    ) -> Result<crate::coverage_report::VectorObservation, CoverageIndexError> {
3731        let record = self
3732            .index
3733            .record(SECTION_DECISION_VECTOR_OBSERVATIONS, index)?;
3734        Ok(crate::coverage_report::VectorObservation {
3735            confidence: self.confidence(get_u64(record, 0))?,
3736            vector: self.test_vector(get_u64(record, 8))?,
3737            tests: self.relation_ids(get_u64(record, 16), get_u64(record, 24))?,
3738            phases: self.relation_ids(get_u64(record, 32), get_u64(record, 40))?,
3739            explicit_phases: self.relation_ids(get_u64(record, 48), get_u64(record, 56))?,
3740        })
3741    }
3742
3743    fn decision_condition(
3744        &self,
3745        index: u64,
3746    ) -> Result<crate::coverage_report::ConditionResult, CoverageIndexError> {
3747        let record = self.index.record(SECTION_DECISION_CONDITIONS, index)?;
3748        if record[0] & !7 != 0 || record[1..4].iter().any(|byte| *byte != 0) {
3749            return Err(CoverageIndexError::InvalidRecord(
3750                "decision condition record",
3751            ));
3752        }
3753        let has_witness = record[0] & 4 != 0;
3754        let witness = if has_witness {
3755            Some([
3756                self.test_vector(get_u64(record, 16))?,
3757                self.test_vector(get_u64(record, 24))?,
3758            ])
3759        } else {
3760            None
3761        };
3762        let first_tests = self.relation_strings(get_u64(record, 32), get_u64(record, 40))?;
3763        let second_tests = self.relation_strings(get_u64(record, 48), get_u64(record, 56))?;
3764        if !has_witness && (!first_tests.is_empty() || !second_tests.is_empty()) {
3765            return Err(CoverageIndexError::InvalidRecord(
3766                "condition witness tests without witness",
3767            ));
3768        }
3769        Ok(crate::coverage_report::ConditionResult {
3770            index: usize::try_from(get_u64(record, 8))
3771                .map_err(|_| CoverageIndexError::SizeOverflow)?,
3772            source: self.string(get_u32(record, 4))?,
3773            covered: record[0] & 1 != 0,
3774            assertion_covered: record[0] & 2 != 0,
3775            witness,
3776            witness_tests: has_witness.then_some([
3777                first_tests.into_iter().map(Id::from).collect(),
3778                second_tests.into_iter().map(Id::from).collect(),
3779            ]),
3780        })
3781    }
3782
3783    pub fn decision_details(
3784        &self,
3785        view: CoverageViewId,
3786    ) -> Result<Vec<crate::coverage_report::DecisionResult>, CoverageIndexError> {
3787        self.decision_details_where(view, None)
3788    }
3789
3790    /// `decision_details`, of one file only: a decision of another file is
3791    /// skipped before its vectors and conditions are decoded.
3792    pub fn decision_details_in_file(
3793        &self,
3794        view: CoverageViewId,
3795        file: &str,
3796    ) -> Result<Vec<crate::coverage_report::DecisionResult>, CoverageIndexError> {
3797        self.decision_details_where(view, Some(file))
3798    }
3799
3800    fn decision_details_where(
3801        &self,
3802        view: CoverageViewId,
3803        file: Option<&str>,
3804    ) -> Result<Vec<crate::coverage_report::DecisionResult>, CoverageIndexError> {
3805        let metadata = self
3806            .decision_metadata(view)?
3807            .into_iter()
3808            .map(|meta| (meta.id.clone(), meta))
3809            .collect::<HashMap<_, _>>();
3810        let descriptor = self.index.descriptor(SECTION_DECISION_DETAILS)?;
3811        let observation_count = self
3812            .index
3813            .descriptor(SECTION_DECISION_VECTOR_OBSERVATIONS)?
3814            .count;
3815        let condition_count = self.index.descriptor(SECTION_DECISION_CONDITIONS)?.count;
3816        let mut decisions = Vec::new();
3817        for index in 0..descriptor.count {
3818            let record = self.index.record(SECTION_DECISION_DETAILS, index)?;
3819            if CoverageViewId::try_from(record[0])? != view {
3820                continue;
3821            }
3822            if record[1] & !3 != 0 || record[2..4].iter().any(|byte| *byte != 0) {
3823                return Err(CoverageIndexError::InvalidRecord("decision detail record"));
3824            }
3825            let executed = record[1] & 1 != 0;
3826            let covered = record[1] & 2 != 0;
3827            if covered && !executed {
3828                return Err(CoverageIndexError::InvalidRecord(
3829                    "covered unexecuted decision",
3830                ));
3831            }
3832            let range = |offset: usize,
3833                         available: u64,
3834                         label: &'static str|
3835             -> Result<std::ops::Range<u64>, CoverageIndexError> {
3836                let start = get_u64(record, offset);
3837                let count = get_u64(record, offset + 8);
3838                let end = start
3839                    .checked_add(count)
3840                    .ok_or(CoverageIndexError::InvalidRecord(label))?;
3841                if end > available {
3842                    return Err(CoverageIndexError::InvalidRecord(label));
3843                }
3844                Ok(start..end)
3845            };
3846            if let Some(file) = file
3847                && metadata
3848                    .get(&self.string(get_u32(record, 4))?)
3849                    .is_some_and(|meta| meta.file != file)
3850            {
3851                continue;
3852            }
3853            let observations = range(32, observation_count, "decision observation range")?
3854                .map(|index| self.decision_vector_observation(index))
3855                .collect::<Result<Vec<_>, _>>()?;
3856            let conditions = range(48, condition_count, "decision condition range")?
3857                .map(|index| self.decision_condition(index))
3858                .collect::<Result<Vec<_>, _>>()?;
3859            let id = self.string(get_u32(record, 4))?;
3860            let meta = metadata
3861                .get(&id)
3862                .cloned()
3863                .ok_or(CoverageIndexError::InvalidRecord(
3864                    "missing decision metadata",
3865                ))?;
3866            if conditions.len() != meta.conditions.len()
3867                || conditions.iter().enumerate().any(|(index, condition)| {
3868                    condition.index != index || condition.source != meta.conditions[index]
3869                })
3870            {
3871                return Err(CoverageIndexError::InvalidRecord(
3872                    "decision condition denominator",
3873                ));
3874            }
3875            decisions.push(crate::coverage_report::DecisionResult {
3876                meta,
3877                executed,
3878                covered,
3879                vectors: observations
3880                    .iter()
3881                    .map(|observation| observation.vector.clone())
3882                    .collect(),
3883                vector_observations: observations,
3884                conditions,
3885                tests: self.relation_ids(get_u64(record, 16), get_u64(record, 24))?,
3886                confidence: self.confidence(get_u64(record, 8))?,
3887            });
3888        }
3889        Ok(decisions)
3890    }
3891
3892    pub fn phase_summaries(
3893        &self,
3894        view: CoverageViewId,
3895    ) -> Result<Vec<IndexedPhaseSummary>, CoverageIndexError> {
3896        let descriptor = self.index.descriptor(SECTION_PHASE_SUMMARIES)?;
3897        let mut phases = Vec::new();
3898        for index in 0..descriptor.count {
3899            let record = self.index.record(SECTION_PHASE_SUMMARIES, index)?;
3900            if CoverageViewId::try_from(record[0])? != view {
3901                continue;
3902            }
3903            if record[1..4].iter().any(|byte| *byte != 0)
3904                || record[48..].iter().any(|byte| *byte != 0)
3905            {
3906                return Err(CoverageIndexError::InvalidRecord("phase summary record"));
3907            }
3908            phases.push(IndexedPhaseSummary {
3909                id: self.string(get_u32(record, 4))?,
3910                kind: self.string(get_u32(record, 8))?,
3911                operation: self.string(get_u32(record, 12))?,
3912                source: self.optional_string(get_u32(record, 16))?,
3913                test: self.string(get_u32(record, 20))?,
3914                status: self.optional_string(get_u32(record, 24))?,
3915                caused_by_phase_id: self.optional_string(get_u32(record, 28))?,
3916                lines: usize::try_from(get_u64(record, 32))
3917                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3918                decisions: usize::try_from(get_u64(record, 40))
3919                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3920            });
3921        }
3922        Ok(phases)
3923    }
3924
3925    pub fn anchors(
3926        &self,
3927        view: CoverageViewId,
3928        file: &str,
3929        line: usize,
3930    ) -> Result<Vec<IndexedAnchor>, CoverageIndexError> {
3931        let descriptor = self.index.descriptor(SECTION_ANCHORS)?;
3932        let mut anchors = Vec::new();
3933        for index in 0..descriptor.count {
3934            let record = self.index.record(SECTION_ANCHORS, index)?;
3935            if CoverageViewId::try_from(record[0])? != view {
3936                continue;
3937            }
3938            if record[3] != 0 || record[12..16].iter().any(|byte| *byte != 0) {
3939                return Err(CoverageIndexError::InvalidRecord("anchor record"));
3940            }
3941            let record_file = self.string(get_u32(record, 8))?;
3942            let record_line = usize::try_from(get_u64(record, 16))
3943                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3944            if record_file != file || record_line != line {
3945                continue;
3946            }
3947            let total = usize::try_from(get_u64(record, 32))
3948                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3949            let covered_conditions = usize::try_from(get_u64(record, 40))
3950                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3951            let (kind, conditions, covered_conditions) = match record[1] {
3952                0 => {
3953                    if total == 0 || covered_conditions > total {
3954                        return Err(CoverageIndexError::InvalidRecord(
3955                            "decision anchor conditions",
3956                        ));
3957                    }
3958                    ("decision", Some(total), Some(covered_conditions))
3959                }
3960                1 => ("branch", None, None),
3961                2 => ("statement", None, None),
3962                3 => ("function", None, None),
3963                _ => return Err(CoverageIndexError::InvalidRecord("anchor kind")),
3964            };
3965            if kind != "decision" && (total != 0 || covered_conditions.is_some()) {
3966                return Err(CoverageIndexError::InvalidRecord("anchor conditions"));
3967            }
3968            anchors.push(IndexedAnchor {
3969                kind: kind.into(),
3970                id: self.string(get_u32(record, 4))?,
3971                file: record_file,
3972                line: record_line,
3973                column: usize::try_from(get_u64(record, 24))
3974                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3975                covered: bool_field(record[2])?,
3976                conditions,
3977                covered_conditions,
3978                tests: self.relation_strings(get_u64(record, 48), get_u64(record, 56))?,
3979            });
3980        }
3981        anchors.sort_by_key(|anchor| anchor.column);
3982        Ok(anchors)
3983    }
3984
3985    pub fn snapshot(&self) -> Result<IndexedCoverageSnapshot, CoverageIndexError> {
3986        Ok(IndexedCoverageSnapshot {
3987            all_summary: self.summary(CoverageViewId::All)?,
3988            passed_summary: self.summary(CoverageViewId::Passed)?,
3989            failed_summary: self.summary(CoverageViewId::Failed)?,
3990            all_files: self.file_gaps(CoverageViewId::All, None, None)?,
3991            passed_files: self.file_gaps(CoverageViewId::Passed, None, None)?,
3992            failed_files: self.file_gaps(CoverageViewId::Failed, None, None)?,
3993        })
3994    }
3995}
3996
3997fn bool_field(value: u8) -> Result<bool, CoverageIndexError> {
3998    match value {
3999        0 => Ok(false),
4000        1 => Ok(true),
4001        _ => Err(CoverageIndexError::InvalidRecord("boolean")),
4002    }
4003}
4004
4005fn decode_summary(
4006    record: &[u8],
4007    flags_offset: usize,
4008    base: usize,
4009) -> Result<CoverageSummary, CoverageIndexError> {
4010    let number = |offset: usize| -> Result<usize, CoverageIndexError> {
4011        usize::try_from(get_u64(record, offset)).map_err(|_| CoverageIndexError::SizeOverflow)
4012    };
4013    let count = |offset: usize| -> Result<CoverageCount, CoverageIndexError> {
4014        let covered = number(offset)?;
4015        let total = number(offset + 8)?;
4016        if covered > total {
4017            return Err(CoverageIndexError::InvalidRecord("covered exceeds total"));
4018        }
4019        Ok(CoverageCount {
4020            covered,
4021            total,
4022            percentage: percentage(covered, total),
4023        })
4024    };
4025    let decisions = number(base)?;
4026    let executed_decisions = number(base + 8)?;
4027    let covered_decisions = number(base + 16)?;
4028    let conditions = number(base + 24)?;
4029    let covered_conditions = number(base + 32)?;
4030    if covered_decisions > executed_decisions
4031        || executed_decisions > decisions
4032        || covered_conditions > conditions
4033    {
4034        return Err(CoverageIndexError::InvalidRecord("summary count ordering"));
4035    }
4036    Ok(CoverageSummary {
4037        unmeasured_obligations: None,
4038        exact_fraction_pct: None,
4039        decisions,
4040        executed_decisions,
4041        covered_decisions,
4042        conditions,
4043        covered_conditions,
4044        condition_coverage_pct: percentage(covered_conditions, conditions),
4045        lines: count(base + 40)?,
4046        statements: count(base + 56)?,
4047        functions: count(base + 72)?,
4048        branches: count(base + 88)?,
4049        decision_outcomes: count(base + 104)?,
4050        condition_outcomes: count(base + 120)?,
4051        value_selections: count(base + 136)?,
4052        coverage_complete: bool_field(record[flags_offset])?,
4053        completeness_blocked: match record[flags_offset + 1] {
4054            0 => None,
4055            1 => Some(false),
4056            2 => Some(true),
4057            _ => return Err(CoverageIndexError::InvalidRecord("optional boolean")),
4058        },
4059    })
4060}
4061
4062fn percentage(covered: usize, total: usize) -> f64 {
4063    if total == 0 {
4064        100.0
4065    } else {
4066        ((covered as f64 / total as f64) * 10_000.0).round() / 100.0
4067    }
4068}
4069
4070#[cfg(test)]
4071mod tests {
4072    use std::{
4073        fs,
4074        sync::atomic::{AtomicU64, Ordering},
4075        time::{SystemTime, UNIX_EPOCH},
4076    };
4077
4078    use crate::{
4079        coverage_analysis::{McdcVector, PointKind},
4080        coverage_report::{
4081            CoverageManifest, CoverageReportRequest, DecisionMeta, ExitCodeInput, PointMeta,
4082            RawTestResult, RuntimeSnapshot, TestProvenance, analyze_coverage_results,
4083        },
4084        query_index::{QueryIndexIdentity, write_query_index},
4085    };
4086
4087    use super::*;
4088
4089    static ROOT_SEQUENCE: AtomicU64 = AtomicU64::new(0);
4090
4091    fn root() -> crate::test_directory::TestDirectory {
4092        let nonce = SystemTime::now()
4093            .duration_since(UNIX_EPOCH)
4094            .unwrap()
4095            .as_nanos();
4096        let root = std::env::temp_dir().join(format!(
4097            "supercov-coverage-index-{}-{nonce}-{}",
4098            std::process::id(),
4099            ROOT_SEQUENCE.fetch_add(1, Ordering::Relaxed),
4100        ));
4101        fs::create_dir(&root).unwrap();
4102        crate::test_directory::TestDirectory::adopt(root)
4103    }
4104
4105    fn identity() -> QueryIndexIdentity {
4106        QueryIndexIdentity {
4107            evidence_sha256: [1; 32],
4108            evidence_bytes: 100,
4109            analysis_sha256: [2; 32],
4110            producer_sha256: [3; 32],
4111            archive_schema_version: 2,
4112        }
4113    }
4114
4115    fn report() -> CoverageReport {
4116        let decision = DecisionMeta {
4117            id: "d".into(),
4118            file: "src/a.js".into(),
4119            line: 1,
4120            column: 1,
4121            source: "a && b".into(),
4122            conditions: vec!["a".into(), "b".into()],
4123            kind: "if".into(),
4124        };
4125        analyze_coverage_results(&CoverageReportRequest {
4126            run_id: "run".into(),
4127            manifest: CoverageManifest {
4128                unmeasured: Vec::new(),
4129                decisions: vec![decision.clone()],
4130                points: vec![PointMeta {
4131                    id: "point".into(),
4132                    kind: PointKind::Statement,
4133                    file: "src/a.js".into(),
4134                    line: 2,
4135                    column: 3,
4136                    source: "work();".into(),
4137                    label: None,
4138                }],
4139                branches: Vec::new(),
4140                limitations: vec![serde_json::json!({
4141                    "id": "dynamic",
4142                    "kind": "dynamic-code",
4143                    "file": "src/a.js",
4144                    "line": 3,
4145                    "column": 1,
4146                    "source": "eval(code)",
4147                    "reason": "dynamic source"
4148                })],
4149                scope: None,
4150                assertion_sites: Vec::new(),
4151            },
4152            raw_results: vec![RawTestResult {
4153                test_id: Some("test".into()),
4154                scope: None,
4155                test: "test".into(),
4156                test_file: Some("tests/a.js".into()),
4157                title: None,
4158                retry: Some(0),
4159                status: Some("passed".into()),
4160                expected_status: None,
4161                flaky: false,
4162                provenance: TestProvenance {
4163                    runner: "node:test".into(),
4164                    kind: "unit".into(),
4165                    project: None,
4166                    source: "runner-default".into(),
4167                },
4168                role: "test".into(),
4169                attribution: crate::coverage_report::ATTRIBUTION_EXACT.into(),
4170                phases: Vec::new(),
4171                runtime: vec![RuntimeSnapshot {
4172                    decisions: vec![crate::coverage_report::DecisionSnapshot {
4173                        meta: decision,
4174                        vectors: vec![McdcVector {
4175                            values: vec![Some(false), None],
4176                            outcome: false,
4177                        }],
4178                    }],
4179                    hits: vec!["point".into()],
4180                    events: Vec::new(),
4181                    logicals: Vec::new(),
4182                    phase_id: None,
4183                }],
4184                browser: Vec::new(),
4185                server: Vec::new(),
4186            }],
4187            generated_at: "time".into(),
4188            coverage_model: None,
4189            integrity: None,
4190            test_exit_code: ExitCodeInput::Present(Some(0)),
4191        })
4192        .unwrap()
4193    }
4194
4195    fn report_attributed(attribution: &str) -> CoverageReport {
4196        let mut report = report();
4197        for view in [
4198            &mut report.view,
4199            &mut report.filters.passed,
4200            &mut report.filters.failed,
4201        ] {
4202            for test in &mut view.tests {
4203                test.attribution = attribution.to_owned();
4204            }
4205        }
4206        report
4207    }
4208
4209    #[test]
4210    fn declined_lines_and_points_are_not_reported_as_coverage_gaps() {
4211        let mut report = report();
4212        for line in &mut report.view.lines {
4213            line.measured = false;
4214            line.covered = false;
4215            line.tests.clear();
4216        }
4217        for point in &mut report.view.points {
4218            point.measured = false;
4219            point.covered = false;
4220            point.tests.clear();
4221        }
4222        let selected = Selected::default();
4223        for filter in [None, Some(&selected)] {
4224            let gaps = file_gaps(&report.view, filter).unwrap();
4225            let (_, gap) = &gaps[0];
4226            assert_eq!(gap.uncovered_lines, 0);
4227            assert_eq!(gap.uncovered_statements, 0);
4228            assert_eq!(gap.uncovered_functions, 0);
4229            assert_eq!(gap.uncovered_everywhere[0..3], [0, 0, 0]);
4230            assert_eq!(gap.measurement_limitations, 1);
4231        }
4232        // Actual missed obligations must still appear.
4233        report.view.lines[0].measured = true;
4234        report.view.points[0].measured = true;
4235        let gaps = file_gaps(&report.view, None).unwrap();
4236        assert_eq!(gaps[0].1.uncovered_lines, 1);
4237        assert_eq!(gaps[0].1.uncovered_statements, 1);
4238    }
4239
4240    #[test]
4241    fn a_test_keeps_the_attribution_it_was_written_with() {
4242        // Attribution rides in a byte the reader used to refuse outright, so a
4243        // value that does not survive the trip is not a wrong number on a
4244        // report -- it is a run that will not open. Only `exact` was ever
4245        // written by a test, which left the other two arms of both the encoder
4246        // and the decoder standing on the claim that they matched.
4247        let root = root();
4248        for attribution in [
4249            crate::coverage_report::ATTRIBUTION_EXACT,
4250            crate::coverage_report::ATTRIBUTION_RUN_WIDE,
4251            crate::coverage_report::ATTRIBUTION_PARTIAL,
4252        ] {
4253            let report = report_attributed(attribution);
4254            let path = root.join(format!("query-index-{attribution}.v1.bin"));
4255            write_query_index(
4256                &coverage_index_sections(&report).unwrap(),
4257                &identity(),
4258                &path,
4259            )
4260            .unwrap();
4261            let container = QueryIndex::open(&path, &identity()).unwrap();
4262            let index = CoverageIndex::new(&container).unwrap();
4263            let tests = index.test_summaries(CoverageViewId::All).unwrap();
4264            assert_eq!(tests.len(), 1);
4265            assert_eq!(
4266                tests[0].attribution, attribution,
4267                "written as `{attribution}` and read back as `{}`",
4268                tests[0].attribution
4269            );
4270        }
4271    }
4272
4273    #[test]
4274    fn an_attribution_the_byte_has_no_room_for_is_refused_at_the_write() {
4275        // Refusing here is what keeps the reserved byte honest: a value nobody
4276        // taught the encoder must not be written as some neighbouring one and
4277        // read back as a measurement.
4278        let error = coverage_index_sections(&report_attributed("probably-exact")).unwrap_err();
4279        assert!(
4280            matches!(error, CoverageIndexError::InvalidRecord("test attribution")),
4281            "{error:?}"
4282        );
4283    }
4284
4285    // The same run is named over and over -- a filtered view repeats the
4286    // relation of the view it filters, and one list of tests covers many lines
4287    // of the file they exercise. Storing each naming separately made this the
4288    // largest section in the container: 61 MB of a 210 MB index.
4289    #[test]
4290    fn a_relation_named_twice_is_stored_once() {
4291        let mut strings = StringTable::default();
4292        let mut relations = StringRelations::default();
4293        let run = || ["alpha".to_string(), "beta".to_string(), "gamma".to_string()];
4294
4295        let first = relations.push(run(), &mut strings).unwrap();
4296        let second = relations.push(run(), &mut strings).unwrap();
4297        assert_eq!(first, second, "the second naming points at the first run");
4298        assert_eq!(relations.values.len(), 3, "and nothing was appended for it");
4299
4300        // A different run still gets its own storage, after the one already
4301        // there -- readers reach a run only by (offset, count), so the
4302        // existing pair must keep meaning what it meant.
4303        let other = relations
4304            .push(["alpha".to_string(), "delta".to_string()], &mut strings)
4305            .unwrap();
4306        assert_eq!(other, (3, 2));
4307        assert_eq!(relations.values.len(), 5);
4308
4309        // A prefix of a stored run is a different run, and is stored as one
4310        // rather than aliasing into the middle of another.
4311        let prefix = relations.push(["alpha".to_string()], &mut strings).unwrap();
4312        assert_eq!(prefix, (5, 1));
4313
4314        // What each pair resolves to is what was pushed.
4315        let read = |(offset, count): (u64, u64)| {
4316            relations.values[offset as usize..(offset + count) as usize].to_vec()
4317        };
4318        assert_eq!(read(first), read(second));
4319        assert_eq!(read(first).len(), 3);
4320        assert_ne!(read(first), read(other));
4321    }
4322
4323    #[test]
4324    fn shared_id_relations_match_text_relations_across_allocations() {
4325        let mut shared_strings = StringTable::default();
4326        let mut text_strings = StringTable::default();
4327        let mut shared_relations = StringRelations::default();
4328        let mut text_relations = StringRelations::default();
4329        let original: Vec<Id> = ["", "test::a[1]", "test::a[10]", "unicodé ✓"]
4330            .into_iter()
4331            .map(Id::from)
4332            .collect();
4333        let copies = original.clone();
4334        let separate: Vec<Id> = original.iter().map(|id| Id::from(id.as_str())).collect();
4335        for values in [&original[..], &copies, &separate, &separate[1..], &[]] {
4336            assert_eq!(
4337                shared_relations
4338                    .push_ids(values, &mut shared_strings)
4339                    .unwrap(),
4340                text_relations.push(values, &mut text_strings).unwrap(),
4341            );
4342        }
4343        // The table owns references to cached allocations even after callers
4344        // drop theirs, so a later ID cannot reuse an earlier cache address.
4345        drop(original);
4346        drop(copies);
4347        drop(separate);
4348        for value in ["new", "test::a[1]", ""] {
4349            let id = Id::from(value);
4350            assert_eq!(
4351                shared_strings.intern_shared(&id).unwrap(),
4352                text_strings.intern(value).unwrap(),
4353            );
4354        }
4355        assert_eq!(shared_relations.values, text_relations.values);
4356        assert_eq!(shared_strings.strings, text_strings.strings);
4357    }
4358
4359    #[test]
4360    fn typed_columns_round_trip_all_outcome_views_without_json() {
4361        let report = report();
4362        let root = root();
4363        let path = root.join("query-index.v1.bin");
4364        write_query_index(
4365            &coverage_index_sections(&report).unwrap(),
4366            &identity(),
4367            &path,
4368        )
4369        .unwrap();
4370        let container = QueryIndex::open(&path, &identity()).unwrap();
4371        let index = CoverageIndex::new(&container).unwrap();
4372        assert_eq!(
4373            index.model().unwrap(),
4374            IndexedCoverageModel {
4375                schema_version: COVERAGE_MODEL_SCHEMA_VERSION,
4376                variant: report.view.variant.clone(),
4377                name: report.view.model.name.clone(),
4378                completeness_meaning: report.view.model.completeness_meaning.clone(),
4379                measured: report.view.model.measured.clone(),
4380                not_measured: report.view.model.not_measured.clone(),
4381            }
4382        );
4383        for (id, view) in [
4384            (CoverageViewId::All, &report.view),
4385            (CoverageViewId::Passed, &report.filters.passed),
4386            (CoverageViewId::Failed, &report.filters.failed),
4387        ] {
4388            assert_eq!(index.summary(id).unwrap(), view.summary);
4389        }
4390        let gaps = index.file_gaps(CoverageViewId::All, None, None).unwrap();
4391        assert_eq!(gaps.len(), 1);
4392        assert_eq!(gaps[0].file, "src/a.js");
4393        assert_eq!(gaps[0].missing_mcdc_conditions, 2);
4394        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
4395        assert_eq!(projection.summary, report.view.summary);
4396        assert_eq!(projection.tests, 1);
4397        assert_eq!(projection.setups, 0);
4398        assert_eq!(projection.test_outcomes.passed, 1);
4399        assert!(projection.source_scope.is_none());
4400        let line = index
4401            .line(CoverageViewId::All, "src/a.js", 2)
4402            .unwrap()
4403            .unwrap();
4404        assert!(line.covered);
4405        assert_eq!(line.tests, ["test"]);
4406        assert_eq!(line.confidence.level, "executed");
4407        let tests = index.test_summaries(CoverageViewId::All).unwrap();
4408        assert_eq!(tests.len(), 1);
4409        assert_eq!(tests[0].provenance.runner, "node:test");
4410        // The decision, and its two outcomes as a branch.
4411        let anchors = index.anchors(CoverageViewId::All, "src/a.js", 1).unwrap();
4412        assert_eq!(anchors.len(), 2);
4413        let decision = anchors
4414            .iter()
4415            .filter(|anchor| anchor.kind == "decision")
4416            .collect::<Vec<_>>();
4417        assert_eq!(decision.len(), 1);
4418        assert_eq!(decision[0].conditions, Some(2));
4419        assert_eq!(decision[0].tests, ["test"]);
4420        assert!(anchors.iter().any(|anchor| anchor.kind == "branch"));
4421        let point = index.anchors(CoverageViewId::All, "src/a.js", 2).unwrap();
4422        assert_eq!(point.len(), 1);
4423        assert_eq!(point[0].kind, "statement");
4424        assert_eq!(point[0].tests, ["test"]);
4425        let details = index.test_details(CoverageViewId::All).unwrap();
4426        assert_eq!(details.len(), 1);
4427        assert_eq!(details[0].retries, [0]);
4428        assert_eq!(details[0].attempts.len(), 1);
4429        assert_eq!(details[0].hits, ["point"]);
4430        assert_eq!(details[0].lines.len(), 1);
4431        assert_eq!(details[0].lines[0].line, 2);
4432        assert_eq!(details[0].decisions.len(), 1);
4433        assert_eq!(details[0].decisions[0].vectors.len(), 1);
4434        assert_eq!(
4435            details[0].decisions[0].vectors[0].values,
4436            [Some(false), None]
4437        );
4438        let hits = index.hit_metadata(CoverageViewId::All).unwrap();
4439        // The point, and the decision's two outcomes.
4440        assert_eq!(hits.len(), 3);
4441        let hits = hits
4442            .into_iter()
4443            .filter(|hit| hit.obligation != "branch")
4444            .collect::<Vec<_>>();
4445        assert_eq!(hits.len(), 1);
4446        assert_eq!(hits[0].id, "point");
4447        assert_eq!(hits[0].source, "work();");
4448        assert_eq!(hits[0].tests, ["test"]);
4449        let decisions = index.decision_metadata(CoverageViewId::All).unwrap();
4450        assert_eq!(decisions.len(), 1);
4451        assert_eq!(decisions[0].conditions, ["a", "b"]);
4452        assert_eq!(
4453            index.decision_details(CoverageViewId::All).unwrap(),
4454            report.view.decisions
4455        );
4456        let limitations = index.limitations(CoverageViewId::All).unwrap();
4457        assert_eq!(limitations.len(), 1);
4458        assert_eq!(limitations[0].kind, "dynamic-code");
4459        assert_eq!(limitations[0].line, 3);
4460        fs::remove_dir_all(root).unwrap();
4461    }
4462
4463    #[test]
4464    fn index_preserves_catalogued_unstarted_tests_without_attempts() {
4465        let report = analyze_coverage_results(&CoverageReportRequest {
4466            run_id: "run".into(),
4467            manifest: CoverageManifest {
4468                unmeasured: Vec::new(),
4469                decisions: Vec::new(),
4470                points: Vec::new(),
4471                branches: Vec::new(),
4472                limitations: Vec::new(),
4473                scope: None,
4474                assertion_sites: Vec::new(),
4475            },
4476            raw_results: vec![RawTestResult {
4477                test_id: Some("unstarted".into()),
4478                scope: None,
4479                test: "unstarted".into(),
4480                test_file: Some("tests/a.rs".into()),
4481                title: None,
4482                retry: None,
4483                status: Some("unstarted".into()),
4484                expected_status: Some("passed".into()),
4485                flaky: false,
4486                provenance: TestProvenance {
4487                    runner: "rust-nextest".into(),
4488                    kind: "unit".into(),
4489                    project: None,
4490                    source: "selected-but-not-started".into(),
4491                },
4492                role: "test".into(),
4493                attribution: crate::coverage_report::ATTRIBUTION_EXACT.into(),
4494                phases: Vec::new(),
4495                runtime: Vec::new(),
4496                browser: Vec::new(),
4497                server: Vec::new(),
4498            }],
4499            generated_at: "time".into(),
4500            coverage_model: None,
4501            integrity: None,
4502            test_exit_code: ExitCodeInput::Present(Some(100)),
4503        })
4504        .unwrap();
4505        let root = root();
4506        let path = root.join("query-index.v1.bin");
4507        write_query_index(
4508            &coverage_index_sections(&report).unwrap(),
4509            &identity(),
4510            &path,
4511        )
4512        .unwrap();
4513        let container = QueryIndex::open(&path, &identity()).unwrap();
4514        let index = CoverageIndex::new(&container).unwrap();
4515        let summaries = index.test_summaries(CoverageViewId::All).unwrap();
4516        assert_eq!(summaries.len(), 1);
4517        assert_eq!(summaries[0].outcome, "unstarted");
4518        let details = index.test_details(CoverageViewId::All).unwrap();
4519        assert!(details[0].retries.is_empty());
4520        assert!(details[0].attempts.is_empty());
4521        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
4522        assert_eq!(projection.tests, 1);
4523        assert_eq!(projection.test_outcomes.unstarted, 1);
4524        fs::remove_dir_all(root).unwrap();
4525    }
4526
4527    #[test]
4528    fn source_discovery_scope_preserves_python_language() {
4529        let mut report = report();
4530        let scope = serde_json::json!({
4531            "version": 1,
4532            "mode": "automatic",
4533            "roots": ["."],
4534            "entries": [{
4535                "file": "src/a.py",
4536                "status": "included",
4537                "reason": "python source",
4538                "packageRoot": "."
4539            }]
4540        });
4541        for view in [
4542            &mut report.view,
4543            &mut report.filters.passed,
4544            &mut report.filters.failed,
4545        ] {
4546            view.scope = Some(scope.clone());
4547            view.model.language = "python".into();
4548            view.model.name = "python-probes-v1".into();
4549        }
4550        let root = root();
4551        let path = root.join("query-index.python.bin");
4552        write_query_index(
4553            &coverage_index_sections(&report).unwrap(),
4554            &identity(),
4555            &path,
4556        )
4557        .unwrap();
4558        let container = QueryIndex::open(&path, &identity()).unwrap();
4559        let index = CoverageIndex::new(&container).unwrap();
4560        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
4561        let source_scope = projection.source_scope.unwrap();
4562        assert_eq!(source_scope.language, "python");
4563        assert_eq!(source_scope.model, "python-probes-v1");
4564        assert_eq!(source_scope.kind, "source-discovery");
4565        assert_eq!(source_scope.included, 1);
4566        assert_eq!(index.scope_entries(CoverageViewId::All).unwrap().len(), 1);
4567        fs::remove_dir_all(root).unwrap();
4568    }
4569
4570    #[test]
4571    fn a_scope_entry_carries_a_limitation_of_its_language_s_own_kind() {
4572        // Go records `loop-without-condition`; with a scope recorded for a Go
4573        // run, a kind this table did not name refused the whole index:
4574        // "invalid coverage index: coverage limitation kind".
4575        let mut report = report();
4576        let scope = serde_json::json!({
4577            "version": 1,
4578            "mode": "automatic",
4579            "roots": ["."],
4580            "entries": [{ "file": "mux.go", "status": "included", "reason": "Go application source" }]
4581        });
4582        for view in [
4583            &mut report.view,
4584            &mut report.filters.passed,
4585            &mut report.filters.failed,
4586        ] {
4587            view.scope = Some(scope.clone());
4588            view.model.language = "go".into();
4589            view.limitations = vec![serde_json::json!({
4590                "id": "go-loop-1",
4591                "kind": "loop-without-condition",
4592                "file": "mux.go",
4593                "line": 4,
4594                "column": 1,
4595                "source": "for {",
4596                "reason": "a loop with no condition has no decision to measure"
4597            })];
4598        }
4599        let root = root();
4600        let path = root.join("query-index.go.bin");
4601        write_query_index(
4602            &coverage_index_sections(&report).unwrap(),
4603            &identity(),
4604            &path,
4605        )
4606        .unwrap();
4607        let container = QueryIndex::open(&path, &identity()).unwrap();
4608        let index = CoverageIndex::new(&container).unwrap();
4609        let entries = index.scope_entries(CoverageViewId::All).unwrap();
4610        assert_eq!(entries.len(), 1);
4611        assert_eq!(entries[0].measurement_limitations, 1);
4612        assert_eq!(entries[0].limitation_kinds, ["unknown"]);
4613        fs::remove_dir_all(root).unwrap();
4614    }
4615
4616    #[test]
4617    fn compiler_owned_scope_round_trips_without_javascript_scope_fields() {
4618        let mut report = report();
4619        let scope = serde_json::json!({
4620            "language": "rust",
4621            "model": "rust-source-v1",
4622            "crate": "fixture",
4623            "measurementComplete": false
4624        });
4625        report.view.scope = Some(scope.clone());
4626        report.filters.passed.scope = Some(scope.clone());
4627        report.filters.failed.scope = Some(scope);
4628        let root = root();
4629        let path = root.join("query-index.v2.bin");
4630        write_query_index(
4631            &coverage_index_sections(&report).unwrap(),
4632            &identity(),
4633            &path,
4634        )
4635        .unwrap();
4636        let container = QueryIndex::open(&path, &identity()).unwrap();
4637        let index = CoverageIndex::new(&container).unwrap();
4638        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
4639        assert_eq!(
4640            projection.source_scope,
4641            Some(IndexedSourceScope {
4642                kind: "compiler".into(),
4643                language: "rust".into(),
4644                model: "rust-source-v1".into(),
4645                mode: None,
4646                roots: Vec::new(),
4647                unit: Some("fixture".into()),
4648                measurement_complete: Some(false),
4649                included: 0,
4650                excluded: 0,
4651                ambiguous: 0,
4652            })
4653        );
4654        assert!(index.scope_entries(CoverageViewId::All).unwrap().is_empty());
4655        fs::remove_dir_all(root).unwrap();
4656    }
4657}