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    fn string(&self, id: u32) -> Result<String, CoverageIndexError> {
2598        let record = self.index.record(SECTION_STRINGS, u64::from(id))?;
2599        if record[12..].iter().any(|byte| *byte != 0) {
2600            return Err(CoverageIndexError::InvalidRecord("string reserved bytes"));
2601        }
2602        let offset = get_u64(record, 0);
2603        let length = u64::from(get_u32(record, 8));
2604        let value = self.index.bytes(SECTION_STRING_BYTES, offset, length)?;
2605        std::str::from_utf8(value)
2606            .map(str::to_owned)
2607            .map_err(|_| CoverageIndexError::InvalidUtf8)
2608    }
2609
2610    pub fn summary(&self, view: CoverageViewId) -> Result<CoverageSummary, CoverageIndexError> {
2611        let descriptor = self.index.descriptor(SECTION_VIEW_SUMMARIES)?;
2612        if descriptor.count != 3 {
2613            return Err(CoverageIndexError::InvalidRecord("summary view count"));
2614        }
2615        let mut found = None;
2616        for index in 0..descriptor.count {
2617            let record = self.index.record(SECTION_VIEW_SUMMARIES, index)?;
2618            if CoverageViewId::try_from(record[0])? != view {
2619                continue;
2620            }
2621            if record[3] != 0 || record[12..16].iter().any(|byte| *byte != 0) {
2622                return Err(CoverageIndexError::InvalidRecord("summary reserved bytes"));
2623            }
2624            self.string(get_u32(record, 4))?;
2625            self.string(get_u32(record, 8))?;
2626            let count = |offset: usize| -> Result<CoverageCount, CoverageIndexError> {
2627                let covered = usize::try_from(get_u64(record, offset))
2628                    .map_err(|_| CoverageIndexError::SizeOverflow)?;
2629                let total = usize::try_from(get_u64(record, offset + 8))
2630                    .map_err(|_| CoverageIndexError::SizeOverflow)?;
2631                if covered > total {
2632                    return Err(CoverageIndexError::InvalidRecord("covered exceeds total"));
2633                }
2634                Ok(CoverageCount {
2635                    covered,
2636                    total,
2637                    percentage: percentage(covered, total),
2638                })
2639            };
2640            let value = |offset: usize| -> Result<usize, CoverageIndexError> {
2641                usize::try_from(get_u64(record, offset))
2642                    .map_err(|_| CoverageIndexError::SizeOverflow)
2643            };
2644            let conditions = value(40)?;
2645            let covered_conditions = value(48)?;
2646            if covered_conditions > conditions {
2647                return Err(CoverageIndexError::InvalidRecord(
2648                    "covered conditions exceed total",
2649                ));
2650            }
2651            let decisions = value(16)?;
2652            let executed_decisions = value(24)?;
2653            let covered_decisions = value(32)?;
2654            if covered_decisions > executed_decisions || executed_decisions > decisions {
2655                return Err(CoverageIndexError::InvalidRecord("decision count ordering"));
2656            }
2657            let summary = CoverageSummary {
2658                unmeasured_obligations: None,
2659                exact_fraction_pct: None,
2660                decisions,
2661                executed_decisions,
2662                covered_decisions,
2663                conditions,
2664                covered_conditions,
2665                condition_coverage_pct: percentage(covered_conditions, conditions),
2666                lines: count(56)?,
2667                statements: count(72)?,
2668                functions: count(88)?,
2669                branches: count(104)?,
2670                decision_outcomes: count(120)?,
2671                condition_outcomes: count(136)?,
2672                value_selections: count(152)?,
2673                coverage_complete: bool_field(record[1])?,
2674                completeness_blocked: match record[2] {
2675                    0 => None,
2676                    1 => Some(false),
2677                    2 => Some(true),
2678                    _ => return Err(CoverageIndexError::InvalidRecord("optional boolean")),
2679                },
2680            };
2681            if found.replace(summary).is_some() {
2682                return Err(CoverageIndexError::InvalidRecord("duplicate coverage view"));
2683            }
2684        }
2685        found.ok_or(CoverageIndexError::InvalidRecord("missing coverage view"))
2686    }
2687
2688    pub fn file_gaps(
2689        &self,
2690        view: CoverageViewId,
2691        kind: Option<&str>,
2692        runner: Option<&str>,
2693    ) -> Result<Vec<IndexedFileGap>, CoverageIndexError> {
2694        let descriptor = self.index.descriptor(SECTION_FILE_GAPS)?;
2695        let mut gaps = Vec::new();
2696        for index in 0..descriptor.count {
2697            let record = self.index.record(SECTION_FILE_GAPS, index)?;
2698            if CoverageViewId::try_from(record[0])? != view {
2699                continue;
2700            }
2701            if record[1..4].iter().any(|byte| *byte != 0)
2702                || record[60..64].iter().any(|byte| *byte != 0)
2703            {
2704                return Err(CoverageIndexError::InvalidRecord("file-gap reserved bytes"));
2705            }
2706            let number = |offset: usize| -> Result<usize, CoverageIndexError> {
2707                usize::try_from(get_u64(record, offset))
2708                    .map_err(|_| CoverageIndexError::SizeOverflow)
2709            };
2710            let mask = get_u32(record, 56);
2711            if mask & !15 != 0 {
2712                return Err(CoverageIndexError::InvalidRecord("limitation mask"));
2713            }
2714            let measurement_limitations = number(48)?;
2715            if (measurement_limitations == 0) != (mask == 0) {
2716                return Err(CoverageIndexError::InvalidRecord(
2717                    "limitation count and kinds disagree",
2718                ));
2719            }
2720            let uncovered_lines = number(8)?;
2721            let uncovered_statements = number(16)?;
2722            let uncovered_functions = number(24)?;
2723            let missing_branches = number(32)?;
2724            let missing_mcdc_conditions = number(40)?;
2725            let score = number(64)?;
2726            let expected_score = uncovered_lines
2727                + uncovered_functions * 2
2728                + missing_branches * 2
2729                + missing_mcdc_conditions * 3
2730                + measurement_limitations * 3;
2731            if score != expected_score {
2732                return Err(CoverageIndexError::InvalidRecord("file-gap score"));
2733            }
2734            let record_kind = self.optional_string(get_u32(record, 72))?;
2735            let record_runner = self.optional_string(get_u32(record, 76))?;
2736            if record_kind.as_deref() != kind || record_runner.as_deref() != runner {
2737                continue;
2738            }
2739            let mut limitation_kinds = Vec::new();
2740            for (bit, kind) in [
2741                (1, "dynamic-code"),
2742                (2, "semantic-safety"),
2743                (4, "source-scope"),
2744                (8, "unknown"),
2745            ] {
2746                if mask & bit != 0 {
2747                    limitation_kinds.push(kind.into());
2748                }
2749            }
2750            let totals = IndexedGapDimensions {
2751                lines: number(160)?,
2752                statements: number(168)?,
2753                functions: number(176)?,
2754                branches: number(184)?,
2755                mcdc_conditions: number(192)?,
2756            };
2757            let covered = |total: usize, missing: usize| {
2758                total
2759                    .checked_sub(missing)
2760                    .ok_or(CoverageIndexError::InvalidRecord("file-gap totals"))
2761            };
2762            gaps.push(IndexedFileGap {
2763                view,
2764                file: self.string(get_u32(record, 4))?,
2765                uncovered_lines,
2766                uncovered_statements,
2767                uncovered_functions,
2768                missing_branches,
2769                missing_mcdc_conditions,
2770                measurement_limitations,
2771                limitation_kinds,
2772                covered_by_other_tests: IndexedGapDimensions {
2773                    lines: number(80)?,
2774                    statements: number(88)?,
2775                    functions: number(96)?,
2776                    branches: number(104)?,
2777                    mcdc_conditions: number(112)?,
2778                },
2779                uncovered_everywhere: IndexedGapDimensions {
2780                    lines: number(120)?,
2781                    statements: number(128)?,
2782                    functions: number(136)?,
2783                    branches: number(144)?,
2784                    mcdc_conditions: number(152)?,
2785                },
2786                totals: totals.clone(),
2787                covered: IndexedGapDimensions {
2788                    lines: covered(totals.lines, uncovered_lines)?,
2789                    statements: covered(totals.statements, uncovered_statements)?,
2790                    functions: covered(totals.functions, uncovered_functions)?,
2791                    branches: covered(totals.branches, missing_branches)?,
2792                    mcdc_conditions: covered(totals.mcdc_conditions, missing_mcdc_conditions)?,
2793                },
2794                score,
2795            });
2796        }
2797        gaps.sort_by(|left, right| {
2798            right
2799                .score
2800                .cmp(&left.score)
2801                .then_with(|| left.file.cmp(&right.file))
2802        });
2803        Ok(gaps)
2804    }
2805
2806    fn optional_string(&self, id: u32) -> Result<Option<String>, CoverageIndexError> {
2807        if id == NO_STRING {
2808            Ok(None)
2809        } else {
2810            self.string(id).map(Some)
2811        }
2812    }
2813
2814    fn relation_ids(&self, offset: u64, count: u64) -> Result<Vec<Id>, CoverageIndexError> {
2815        Ok(self
2816            .relation_strings(offset, count)?
2817            .into_iter()
2818            .map(Id::from)
2819            .collect())
2820    }
2821
2822    fn relation_strings(&self, offset: u64, count: u64) -> Result<Vec<String>, CoverageIndexError> {
2823        let end = offset
2824            .checked_add(count)
2825            .ok_or(CoverageIndexError::SizeOverflow)?;
2826        let descriptor = self.index.descriptor(SECTION_STRING_RELATIONS)?;
2827        if end > descriptor.count {
2828            return Err(CoverageIndexError::InvalidRecord("string relation range"));
2829        }
2830        (offset..end)
2831            .map(|index| {
2832                let record = self.index.record(SECTION_STRING_RELATIONS, index)?;
2833                self.string(get_u32(record, 0))
2834            })
2835            .collect()
2836    }
2837
2838    pub fn projection(
2839        &self,
2840        view: CoverageViewId,
2841        kind: Option<&str>,
2842        runner: Option<&str>,
2843    ) -> Result<IndexedProjection, CoverageIndexError> {
2844        let descriptor = self.index.descriptor(SECTION_PROJECTIONS)?;
2845        let mut found = None;
2846        for index in 0..descriptor.count {
2847            let record = self.index.record(SECTION_PROJECTIONS, index)?;
2848            if CoverageViewId::try_from(record[0])? != view {
2849                continue;
2850            }
2851            if record[38..40].iter().any(|byte| *byte != 0)
2852                || record[518..520].iter().any(|byte| *byte != 0)
2853            {
2854                return Err(CoverageIndexError::InvalidRecord(
2855                    "projection reserved bytes",
2856                ));
2857            }
2858            let record_kind = self.optional_string(get_u32(record, 4))?;
2859            let record_runner = self.optional_string(get_u32(record, 8))?;
2860            if record_kind.as_deref() != kind || record_runner.as_deref() != runner {
2861                continue;
2862            }
2863            if found.is_some() {
2864                return Err(CoverageIndexError::InvalidRecord(
2865                    "duplicate coverage projection",
2866                ));
2867            }
2868            let number = |offset: usize| -> Result<usize, CoverageIndexError> {
2869                usize::try_from(get_u64(record, offset))
2870                    .map_err(|_| CoverageIndexError::SizeOverflow)
2871            };
2872            let limitations = number(192)?;
2873            let evidence_corruptions = number(200)?;
2874            let blocking = number(208)?;
2875            let declared = number(528)?;
2876            if blocking + declared != limitations + evidence_corruptions {
2877                return Err(CoverageIndexError::InvalidRecord(
2878                    "measurement blocking count",
2879                ));
2880            }
2881            let mut transport_values = (0..8)
2882                .map(|index| number(408 + index * 8))
2883                .collect::<Result<Vec<_>, _>>()?;
2884            transport_values.push(number(536)?);
2885            let transport = if bool_field(record[1])? {
2886                Some(TransportStats {
2887                    processes: transport_values[0],
2888                    child_launches: transport_values[1],
2889                    remote_launches: transport_values[2],
2890                    workspace_capabilities: transport_values[3],
2891                    guest_processes: transport_values[8],
2892                    scoped_server_records: transport_values[4],
2893                    background_server_records: transport_values[5],
2894                    corrupt_records: transport_values[6],
2895                    corrupt_files: transport_values[7],
2896                })
2897            } else {
2898                if transport_values.iter().any(|value| *value != 0) {
2899                    return Err(CoverageIndexError::InvalidRecord("transport presence flag"));
2900                }
2901                None
2902            };
2903            let has_scope = bool_field(record[2])?;
2904            let scope_kind = match record[3] {
2905                0 => None,
2906                1 => Some((ScopeKind::SourceDiscovery, "source-discovery")),
2907                2 => Some((ScopeKind::Compiler, "compiler")),
2908                _ => return Err(CoverageIndexError::InvalidRecord("coverage scope kind")),
2909            };
2910            let scope_mode = self.optional_string(get_u32(record, 16))?;
2911            let scope_language = self.optional_string(get_u32(record, 504))?;
2912            let scope_model = self.optional_string(get_u32(record, 508))?;
2913            let scope_unit = self.optional_string(get_u32(record, 512))?;
2914            let has_measurement_complete = bool_field(record[516])?;
2915            let measurement_complete = bool_field(record[517])?;
2916            if !has_measurement_complete && measurement_complete {
2917                return Err(CoverageIndexError::InvalidRecord(
2918                    "scope measurement completeness flag",
2919                ));
2920            }
2921            if has_scope
2922                != (scope_kind.is_some() && scope_language.is_some() && scope_model.is_some())
2923            {
2924                return Err(CoverageIndexError::InvalidRecord("scope presence flag"));
2925            }
2926            let source_scope = if let Some((kind, kind_name)) = scope_kind {
2927                match kind {
2928                    ScopeKind::SourceDiscovery => {
2929                        if scope_mode.is_none() || scope_unit.is_some() || has_measurement_complete
2930                        {
2931                            return Err(CoverageIndexError::InvalidRecord(
2932                                "source-discovery scope shape",
2933                            ));
2934                        }
2935                    }
2936                    ScopeKind::Compiler => {
2937                        if scope_mode.is_some()
2938                            || scope_unit.is_none()
2939                            || !has_measurement_complete
2940                            || get_u32(record, 32) != 0
2941                            || number(480)? != 0
2942                            || number(488)? != 0
2943                            || number(496)? != 0
2944                        {
2945                            return Err(CoverageIndexError::InvalidRecord("compiler scope shape"));
2946                        }
2947                    }
2948                }
2949                Some(IndexedSourceScope {
2950                    kind: kind_name.into(),
2951                    language: scope_language.expect("validated scope language"),
2952                    model: scope_model.expect("validated scope model"),
2953                    mode: scope_mode,
2954                    roots: self
2955                        .relation_strings(get_u64(record, 24), u64::from(get_u32(record, 32)))?,
2956                    unit: scope_unit,
2957                    measurement_complete: has_measurement_complete.then_some(measurement_complete),
2958                    included: number(480)?,
2959                    excluded: number(488)?,
2960                    ambiguous: number(496)?,
2961                })
2962            } else {
2963                if get_u32(record, 32) != 0
2964                    || scope_mode.is_some()
2965                    || scope_language.is_some()
2966                    || scope_model.is_some()
2967                    || scope_unit.is_some()
2968                    || has_measurement_complete
2969                    || number(480)? != 0
2970                    || number(488)? != 0
2971                    || number(496)? != 0
2972                {
2973                    return Err(CoverageIndexError::InvalidRecord("absent scope data"));
2974                }
2975                None
2976            };
2977            let empty_evidence_tests = number(472)?;
2978            let first_empty_evidence_test = self.optional_string(get_u32(record, 20))?;
2979            if (empty_evidence_tests == 0) != first_empty_evidence_test.is_none() {
2980                return Err(CoverageIndexError::InvalidRecord(
2981                    "empty-evidence diagnostic identity",
2982                ));
2983            }
2984            found = Some(IndexedProjection {
2985                view,
2986                kind: record_kind,
2987                runner: record_runner,
2988                generated_at: self.string(get_u32(record, 12))?,
2989                summary: decode_summary(record, 36, 40)?,
2990                measurement: IndexedMeasurement {
2991                    complete: blocking == 0,
2992                    limitations,
2993                    evidence_corruptions,
2994                    blocking,
2995                    declared,
2996                    files: number(216)?,
2997                    by_kind: IndexedMeasurementKinds {
2998                        dynamic_code: number(224)?,
2999                        semantic_safety: number(232)?,
3000                        source_scope: number(240)?,
3001                    },
3002                },
3003                attribution: IndexedAttribution {
3004                    browser_explicit: number(248)?,
3005                    browser_fallback: number(256)?,
3006                    server_explicit: number(264)?,
3007                    server_fallback: number(272)?,
3008                },
3009                transport,
3010                empty_evidence_tests,
3011                first_empty_evidence_test,
3012                confidence: IndexedSummaryConfidence {
3013                    lines: IndexedConfidenceLines {
3014                        unexecuted: number(280)?,
3015                        executed: number(288)?,
3016                        action: number(296)?,
3017                        asserted: number(304)?,
3018                    },
3019                    assertion_covered_mcdc_conditions: number(312)?,
3020                },
3021                files_with_gaps: number(320)?,
3022                files_with_coverage_gaps: number(328)?,
3023                tests: number(336)?,
3024                setups: number(344)?,
3025                test_outcomes: {
3026                    let mut outcomes = IndexedOutcomeCounts {
3027                        passed: number(352)?,
3028                        failed: number(360)?,
3029                        flaky: number(368)?,
3030                        skipped: number(376)?,
3031                        timed_out: number(384)?,
3032                        interrupted: number(392)?,
3033                        unknown: number(400)?,
3034                        unstarted: number(520)?,
3035                        todo: 0,
3036                    };
3037                    // The projection record has no slot left, so todo is the
3038                    // tests no other outcome counts; zero in older indexes.
3039                    outcomes.todo = number(336)?.saturating_sub(
3040                        outcomes.passed
3041                            + outcomes.failed
3042                            + outcomes.flaky
3043                            + outcomes.skipped
3044                            + outcomes.timed_out
3045                            + outcomes.interrupted
3046                            + outcomes.unknown
3047                            + outcomes.unstarted,
3048                    );
3049                    outcomes
3050                },
3051                source_scope,
3052            });
3053        }
3054        found.ok_or(CoverageIndexError::InvalidRecord(
3055            "missing coverage projection",
3056        ))
3057    }
3058
3059    pub fn decision_gaps(
3060        &self,
3061        view: CoverageViewId,
3062        kind: Option<&str>,
3063        runner: Option<&str>,
3064        file: &str,
3065    ) -> Result<Vec<IndexedDecisionGap>, CoverageIndexError> {
3066        let descriptor = self.index.descriptor(SECTION_DECISION_GAPS)?;
3067        let mut decisions = Vec::new();
3068        for index in 0..descriptor.count {
3069            let record = self.index.record(SECTION_DECISION_GAPS, index)?;
3070            if CoverageViewId::try_from(record[0])? != view {
3071                continue;
3072            }
3073            if record[1..4].iter().any(|byte| *byte != 0)
3074                || record[28..32].iter().any(|byte| *byte != 0)
3075                || record[64..].iter().any(|byte| *byte != 0)
3076            {
3077                return Err(CoverageIndexError::InvalidRecord(
3078                    "decision-gap reserved bytes",
3079                ));
3080            }
3081            let record_kind = self.optional_string(get_u32(record, 4))?;
3082            let record_runner = self.optional_string(get_u32(record, 8))?;
3083            if record_kind.as_deref() != kind || record_runner.as_deref() != runner {
3084                continue;
3085            }
3086            let record_file = self.string(get_u32(record, 16))?;
3087            if record_file != file {
3088                continue;
3089            }
3090            let number = |offset: usize| -> Result<usize, CoverageIndexError> {
3091                usize::try_from(get_u64(record, offset))
3092                    .map_err(|_| CoverageIndexError::SizeOverflow)
3093            };
3094            let conditions = number(48)?;
3095            let missing_conditions = number(56)?;
3096            if conditions == 0 || missing_conditions > conditions {
3097                return Err(CoverageIndexError::InvalidRecord(
3098                    "decision condition counts",
3099                ));
3100            }
3101            decisions.push(IndexedDecisionGap {
3102                view,
3103                file: record_file,
3104                id: self.string(get_u32(record, 12))?,
3105                line: number(32)?,
3106                column: number(40)?,
3107                kind: self.string(get_u32(record, 20))?,
3108                conditions,
3109                missing_conditions,
3110                source: self.string(get_u32(record, 24))?,
3111            });
3112        }
3113        Ok(decisions)
3114    }
3115
3116    pub fn dimensions(
3117        &self,
3118        view: CoverageViewId,
3119        dimension: CoverageDimension,
3120    ) -> Result<Vec<IndexedDimensionCoverage>, CoverageIndexError> {
3121        let descriptor = self.index.descriptor(SECTION_DIMENSIONS)?;
3122        let mut values = Vec::new();
3123        for index in 0..descriptor.count {
3124            let record = self.index.record(SECTION_DIMENSIONS, index)?;
3125            if CoverageViewId::try_from(record[0])? != view {
3126                continue;
3127            }
3128            let record_dimension = match record[1] {
3129                0 => CoverageDimension::Kind,
3130                1 => CoverageDimension::Runner,
3131                2 => CoverageDimension::Tests,
3132                _ => return Err(CoverageIndexError::InvalidRecord("dimension type")),
3133            };
3134            if record_dimension != dimension {
3135                continue;
3136            }
3137            if record[26..32].iter().any(|byte| *byte != 0) {
3138                return Err(CoverageIndexError::InvalidRecord(
3139                    "dimension reserved bytes",
3140                ));
3141            }
3142            let name = self.string(get_u32(record, 4))?;
3143            values.push(IndexedDimensionCoverage {
3144                kind: (dimension == CoverageDimension::Kind).then(|| name.clone()),
3145                runner: (dimension == CoverageDimension::Runner).then_some(name),
3146                tests: usize::try_from(get_u64(record, 8))
3147                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3148                setups: usize::try_from(get_u64(record, 16))
3149                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3150                attributed: usize::try_from(get_u64(record, 184))
3151                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3152                summary: decode_summary(record, 24, 32)?,
3153            });
3154        }
3155        Ok(values)
3156    }
3157
3158    pub fn scope_entries(
3159        &self,
3160        view: CoverageViewId,
3161    ) -> Result<Vec<IndexedScopeEntry>, CoverageIndexError> {
3162        let descriptor = self.index.descriptor(SECTION_SCOPE_ENTRIES)?;
3163        let mut entries = Vec::new();
3164        for index in 0..descriptor.count {
3165            let record = self.index.record(SECTION_SCOPE_ENTRIES, index)?;
3166            if CoverageViewId::try_from(record[0])? != view {
3167                continue;
3168            }
3169            if record[2..4].iter().any(|byte| *byte != 0)
3170                || record[28..].iter().any(|byte| *byte != 0)
3171            {
3172                return Err(CoverageIndexError::InvalidRecord(
3173                    "source-scope reserved bytes",
3174                ));
3175            }
3176            let status = match record[1] {
3177                0 => "included",
3178                1 => "excluded",
3179                2 => "ambiguous",
3180                _ => return Err(CoverageIndexError::InvalidRecord("source-scope status")),
3181            };
3182            let measurement_limitations = usize::try_from(get_u64(record, 16))
3183                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3184            let mask = get_u32(record, 24);
3185            if mask & !15 != 0 || (measurement_limitations == 0) != (mask == 0) {
3186                return Err(CoverageIndexError::InvalidRecord(
3187                    "source-scope limitation annotation",
3188                ));
3189            }
3190            let mut limitation_kinds = Vec::new();
3191            for (bit, kind) in [
3192                (1, "dynamic-code"),
3193                (2, "semantic-safety"),
3194                (4, "source-scope"),
3195                (8, "unknown"),
3196            ] {
3197                if mask & bit != 0 {
3198                    limitation_kinds.push(kind.into());
3199                }
3200            }
3201            entries.push(IndexedScopeEntry {
3202                file: self.string(get_u32(record, 4))?,
3203                status: status.into(),
3204                reason: self.string(get_u32(record, 8))?,
3205                package_root: self.optional_string(get_u32(record, 12))?,
3206                measurement_limitations,
3207                limitation_kinds,
3208            });
3209        }
3210        Ok(entries)
3211    }
3212
3213    fn confidence(
3214        &self,
3215        index: u64,
3216    ) -> Result<crate::coverage_report::CoverageConfidence, CoverageIndexError> {
3217        let record = self.index.record(SECTION_CONFIDENCE, index)?;
3218        if record[2..8].iter().any(|byte| *byte != 0)
3219            || record[72..].iter().any(|byte| *byte != 0)
3220            || record[1] & !15 != 0
3221        {
3222            return Err(CoverageIndexError::InvalidRecord("confidence record"));
3223        }
3224        let values = (0..4)
3225            .map(|index| {
3226                self.relation_strings(
3227                    get_u64(record, 8 + index * 16),
3228                    get_u64(record, 16 + index * 16),
3229                )
3230            })
3231            .collect::<Result<Vec<_>, _>>()?;
3232        Ok(crate::coverage_report::CoverageConfidence {
3233            level: match record[0] {
3234                0 => "unexecuted",
3235                1 => "executed",
3236                2 => "action",
3237                3 => "asserted",
3238                _ => return Err(CoverageIndexError::InvalidRecord("confidence level")),
3239            }
3240            .into(),
3241            setup_only: record[1] & 1 != 0,
3242            background_only: record[1] & 2 != 0,
3243            asserted: record[1] & 4 != 0,
3244            e2e: record[1] & 8 != 0,
3245            tests: values[0].iter().map(Id::from).collect(),
3246            asserted_tests: values[1].iter().map(Id::from).collect(),
3247            runners: values[2].clone(),
3248            kinds: values[3].clone(),
3249        })
3250    }
3251
3252    pub fn line(
3253        &self,
3254        view: CoverageViewId,
3255        file: &str,
3256        line: usize,
3257    ) -> Result<Option<IndexedLine>, CoverageIndexError> {
3258        let descriptor = self.index.descriptor(SECTION_LINES)?;
3259        let mut found = None;
3260        for index in 0..descriptor.count {
3261            let record = self.index.record(SECTION_LINES, index)?;
3262            if CoverageViewId::try_from(record[0])? != view {
3263                continue;
3264            }
3265            if record[3] != 0 || record[56..].iter().any(|byte| *byte != 0) {
3266                return Err(CoverageIndexError::InvalidRecord("line record"));
3267            }
3268            let record_file = self.string(get_u32(record, 4))?;
3269            let record_line = usize::try_from(get_u64(record, 8))
3270                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3271            if record_file != file || record_line != line {
3272                continue;
3273            }
3274            if found.is_some() {
3275                return Err(CoverageIndexError::InvalidRecord("duplicate line"));
3276            }
3277            found = Some(IndexedLine {
3278                file: record_file,
3279                line: record_line,
3280                covered: bool_field(record[1])?,
3281                measured: !bool_field(record[2])?,
3282                tests: self.relation_strings(get_u64(record, 16), get_u64(record, 24))?,
3283                phases: self.relation_strings(get_u64(record, 32), get_u64(record, 40))?,
3284                confidence: self.confidence(get_u64(record, 48))?,
3285            });
3286        }
3287        Ok(found)
3288    }
3289
3290    pub fn lines(&self, view: CoverageViewId) -> Result<Vec<IndexedLine>, CoverageIndexError> {
3291        let descriptor = self.index.descriptor(SECTION_LINES)?;
3292        let mut lines = Vec::new();
3293        for index in 0..descriptor.count {
3294            let record = self.index.record(SECTION_LINES, index)?;
3295            if CoverageViewId::try_from(record[0])? != view {
3296                continue;
3297            }
3298            if record[3] != 0 || record[56..].iter().any(|byte| *byte != 0) {
3299                return Err(CoverageIndexError::InvalidRecord("line record"));
3300            }
3301            lines.push(IndexedLine {
3302                file: self.string(get_u32(record, 4))?,
3303                line: usize::try_from(get_u64(record, 8))
3304                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3305                covered: bool_field(record[1])?,
3306                measured: !bool_field(record[2])?,
3307                tests: self.relation_strings(get_u64(record, 16), get_u64(record, 24))?,
3308                phases: self.relation_strings(get_u64(record, 32), get_u64(record, 40))?,
3309                confidence: self.confidence(get_u64(record, 48))?,
3310            });
3311        }
3312        Ok(lines)
3313    }
3314
3315    pub fn test_summaries(
3316        &self,
3317        view: CoverageViewId,
3318    ) -> Result<Vec<IndexedTestSummary>, CoverageIndexError> {
3319        let descriptor = self.index.descriptor(SECTION_TEST_SUMMARIES)?;
3320        let mut tests = Vec::new();
3321        for index in 0..descriptor.count {
3322            let record = self.index.record(SECTION_TEST_SUMMARIES, index)?;
3323            if CoverageViewId::try_from(record[0])? != view {
3324                continue;
3325            }
3326            if record[36..].iter().any(|byte| *byte != 0) {
3327                return Err(CoverageIndexError::InvalidRecord("test summary record"));
3328            }
3329            tests.push(IndexedTestSummary {
3330                id: self.string(get_u32(record, 4))?,
3331                name: self.string(get_u32(record, 8))?,
3332                file: self.optional_string(get_u32(record, 12))?,
3333                title: self.optional_string(get_u32(record, 16))?,
3334                role: match record[1] {
3335                    0 => "test",
3336                    1 => "setup",
3337                    2 => "background",
3338                    _ => return Err(CoverageIndexError::InvalidRecord("test role")),
3339                }
3340                .into(),
3341                attribution: match record[3] {
3342                    0 => crate::coverage_report::ATTRIBUTION_EXACT,
3343                    1 => crate::coverage_report::ATTRIBUTION_RUN_WIDE,
3344                    2 => crate::coverage_report::ATTRIBUTION_PARTIAL,
3345                    3 => crate::coverage_report::ATTRIBUTION_BY_TIME,
3346                    _ => return Err(CoverageIndexError::InvalidRecord("test attribution")),
3347                }
3348                .into(),
3349                outcome: match record[2] {
3350                    0 => "passed",
3351                    1 => "failed",
3352                    2 => "flaky",
3353                    3 => "skipped",
3354                    4 => "timedOut",
3355                    5 => "interrupted",
3356                    6 => "unknown",
3357                    7 => "unstarted",
3358                    8 => "todo",
3359                    _ => return Err(CoverageIndexError::InvalidRecord("test outcome")),
3360                }
3361                .into(),
3362                provenance: crate::coverage_report::TestProvenance {
3363                    runner: self.string(get_u32(record, 20))?,
3364                    kind: self.string(get_u32(record, 24))?,
3365                    project: self.optional_string(get_u32(record, 28))?,
3366                    source: self.string(get_u32(record, 32))?,
3367                },
3368            });
3369        }
3370        Ok(tests)
3371    }
3372
3373    fn test_vector(&self, index: u64) -> Result<McdcVector, CoverageIndexError> {
3374        let record = self.index.record(SECTION_TEST_VECTORS, index)?;
3375        if record[1..8].iter().any(|byte| *byte != 0) {
3376            return Err(CoverageIndexError::InvalidRecord("test vector record"));
3377        }
3378        let offset = get_u64(record, 8);
3379        let count = get_u64(record, 16);
3380        let descriptor = self.index.descriptor(SECTION_VECTOR_VALUES)?;
3381        let end = offset
3382            .checked_add(count)
3383            .ok_or(CoverageIndexError::InvalidRecord("vector value range"))?;
3384        if end > descriptor.count {
3385            return Err(CoverageIndexError::InvalidRecord("vector value range"));
3386        }
3387        let mut values = Vec::with_capacity(
3388            usize::try_from(count).map_err(|_| CoverageIndexError::SizeOverflow)?,
3389        );
3390        for index in offset..end {
3391            values.push(match self.index.record(SECTION_VECTOR_VALUES, index)?[0] {
3392                0 => None,
3393                1 => Some(false),
3394                2 => Some(true),
3395                _ => return Err(CoverageIndexError::InvalidRecord("vector value")),
3396            });
3397        }
3398        Ok(McdcVector {
3399            values,
3400            outcome: bool_field(record[0])?,
3401        })
3402    }
3403
3404    pub fn test_details(
3405        &self,
3406        view: CoverageViewId,
3407    ) -> Result<Vec<IndexedTestDetail>, CoverageIndexError> {
3408        let summaries = self.test_summaries(view)?;
3409        let positions = summaries
3410            .iter()
3411            .enumerate()
3412            .map(|(index, test)| (test.id.clone(), index))
3413            .collect::<HashMap<_, _>>();
3414        if positions.len() != summaries.len() {
3415            return Err(CoverageIndexError::InvalidRecord("duplicate test summary"));
3416        }
3417        let mut details = summaries
3418            .into_iter()
3419            .map(|summary| IndexedTestDetail {
3420                summary,
3421                retries: Vec::new(),
3422                attempts: Vec::new(),
3423                hits: Vec::new(),
3424                decisions: Vec::new(),
3425                lines: Vec::new(),
3426            })
3427            .collect::<Vec<_>>();
3428        let position = |record: &[u8]| -> Result<Option<usize>, CoverageIndexError> {
3429            if CoverageViewId::try_from(record[0])? != view {
3430                return Ok(None);
3431            }
3432            let id = self.string(get_u32(record, 4))?;
3433            positions
3434                .get(&id)
3435                .copied()
3436                .map(Some)
3437                .ok_or(CoverageIndexError::InvalidRecord("unknown test relation"))
3438        };
3439        let descriptor = self.index.descriptor(SECTION_TEST_RETRIES)?;
3440        for index in 0..descriptor.count {
3441            let record = self.index.record(SECTION_TEST_RETRIES, index)?;
3442            if record[1..4].iter().any(|byte| *byte != 0) {
3443                return Err(CoverageIndexError::InvalidRecord("test retry record"));
3444            }
3445            if let Some(position) = position(record)? {
3446                details[position].retries.push(
3447                    usize::try_from(get_u64(record, 8))
3448                        .map_err(|_| CoverageIndexError::SizeOverflow)?,
3449                );
3450            }
3451        }
3452        let descriptor = self.index.descriptor(SECTION_TEST_ATTEMPTS)?;
3453        for index in 0..descriptor.count {
3454            let record = self.index.record(SECTION_TEST_ATTEMPTS, index)?;
3455            if record[1..4].iter().any(|byte| *byte != 0) {
3456                return Err(CoverageIndexError::InvalidRecord("test attempt record"));
3457            }
3458            if let Some(position) = position(record)? {
3459                details[position]
3460                    .attempts
3461                    .push(crate::coverage_report::TestAttempt {
3462                        retry: usize::try_from(get_u64(record, 8))
3463                            .map_err(|_| CoverageIndexError::SizeOverflow)?,
3464                        status: self.string(get_u32(record, 16))?,
3465                        expected_status: self.optional_string(get_u32(record, 20))?,
3466                    });
3467            }
3468        }
3469        let descriptor = self.index.descriptor(SECTION_TEST_LINES)?;
3470        for index in 0..descriptor.count {
3471            let record = self.index.record(SECTION_TEST_LINES, index)?;
3472            if record[1..4].iter().any(|byte| *byte != 0)
3473                || record[12..16].iter().any(|byte| *byte != 0)
3474            {
3475                return Err(CoverageIndexError::InvalidRecord("test line record"));
3476            }
3477            if let Some(position) = position(record)? {
3478                details[position]
3479                    .lines
3480                    .push(crate::coverage_report::SourceLine {
3481                        file: self.string(get_u32(record, 8))?.into(),
3482                        line: usize::try_from(get_u64(record, 16))
3483                            .map_err(|_| CoverageIndexError::SizeOverflow)?,
3484                    });
3485            }
3486        }
3487        let descriptor = self.index.descriptor(SECTION_TEST_HITS)?;
3488        for index in 0..descriptor.count {
3489            let record = self.index.record(SECTION_TEST_HITS, index)?;
3490            if record[1..4].iter().any(|byte| *byte != 0)
3491                || record[12..].iter().any(|byte| *byte != 0)
3492            {
3493                return Err(CoverageIndexError::InvalidRecord("test hit record"));
3494            }
3495            if let Some(position) = position(record)? {
3496                details[position]
3497                    .hits
3498                    .push(self.string(get_u32(record, 8))?);
3499            }
3500        }
3501        let descriptor = self.index.descriptor(SECTION_TEST_DECISIONS)?;
3502        let vectors = self.index.descriptor(SECTION_TEST_VECTORS)?.count;
3503        for index in 0..descriptor.count {
3504            let record = self.index.record(SECTION_TEST_DECISIONS, index)?;
3505            if record[1..4].iter().any(|byte| *byte != 0)
3506                || record[12..16].iter().any(|byte| *byte != 0)
3507            {
3508                return Err(CoverageIndexError::InvalidRecord("test decision record"));
3509            }
3510            if let Some(position) = position(record)? {
3511                let offset = get_u64(record, 16);
3512                let count = get_u64(record, 24);
3513                let end = offset
3514                    .checked_add(count)
3515                    .ok_or(CoverageIndexError::InvalidRecord("test vector range"))?;
3516                if end > vectors {
3517                    return Err(CoverageIndexError::InvalidRecord("test vector range"));
3518                }
3519                let mut observed = Vec::with_capacity(
3520                    usize::try_from(count).map_err(|_| CoverageIndexError::SizeOverflow)?,
3521                );
3522                for vector in offset..end {
3523                    observed.push(self.test_vector(vector)?);
3524                }
3525                details[position]
3526                    .decisions
3527                    .push(crate::coverage_report::TestDecisionResult {
3528                        id: self.string(get_u32(record, 8))?,
3529                        vectors: observed,
3530                    });
3531            }
3532        }
3533        Ok(details)
3534    }
3535
3536    pub fn hit_metadata(
3537        &self,
3538        view: CoverageViewId,
3539    ) -> Result<Vec<IndexedHitMetadata>, CoverageIndexError> {
3540        let descriptor = self.index.descriptor(SECTION_HIT_METADATA)?;
3541        let mut metadata = Vec::new();
3542        for index in 0..descriptor.count {
3543            let record = self.index.record(SECTION_HIT_METADATA, index)?;
3544            if CoverageViewId::try_from(record[0])? != view {
3545                continue;
3546            }
3547            if record[2..4].iter().any(|byte| *byte != 0)
3548                || record[12..16].iter().any(|byte| *byte != 0)
3549            {
3550                return Err(CoverageIndexError::InvalidRecord("hit metadata record"));
3551            }
3552            let obligation = match record[1] {
3553                0 => "statement",
3554                1 => "function",
3555                2 => "branch",
3556                _ => return Err(CoverageIndexError::InvalidRecord("hit obligation")),
3557            };
3558            let metadata_label = self.optional_string(get_u32(record, 36))?;
3559            metadata.push(IndexedHitMetadata {
3560                id: self.string(get_u32(record, 4))?,
3561                obligation: obligation.into(),
3562                file: self.string(get_u32(record, 8))?,
3563                line: usize::try_from(get_u64(record, 16))
3564                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3565                column: usize::try_from(get_u64(record, 24))
3566                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3567                branch_kind: self.optional_string(get_u32(record, 32))?,
3568                label: (obligation != "branch")
3569                    .then_some(metadata_label.clone())
3570                    .flatten(),
3571                alternative: self.optional_string(get_u32(record, 40))?,
3572                parent_id: (obligation == "branch").then_some(metadata_label).flatten(),
3573                source: self.string(get_u32(record, 44))?,
3574                tests: self.relation_strings(get_u64(record, 48), get_u64(record, 56))?,
3575            });
3576        }
3577        Ok(metadata)
3578    }
3579
3580    pub fn limitations(
3581        &self,
3582        view: CoverageViewId,
3583    ) -> Result<Vec<IndexedLimitation>, CoverageIndexError> {
3584        let descriptor = self.index.descriptor(SECTION_LIMITATIONS)?;
3585        let mut limitations = Vec::new();
3586        for index in 0..descriptor.count {
3587            let record = self.index.record(SECTION_LIMITATIONS, index)?;
3588            if CoverageViewId::try_from(record[0])? != view {
3589                continue;
3590            }
3591            if record[2..4].iter().any(|byte| *byte != 0)
3592                || record[40..].iter().any(|byte| *byte != 0)
3593            {
3594                return Err(CoverageIndexError::InvalidRecord("limitation record"));
3595            }
3596            limitations.push(IndexedLimitation {
3597                id: self.string(get_u32(record, 4))?,
3598                kind: self.string(get_u32(record, 8))?,
3599                file: self.string(get_u32(record, 12))?,
3600                source: self.string(get_u32(record, 16))?,
3601                reason: self.string(get_u32(record, 20))?,
3602                line: usize::try_from(get_u64(record, 24))
3603                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3604                column: usize::try_from(get_u64(record, 32))
3605                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3606                blocking: bool_field(record[1])?,
3607            });
3608        }
3609        Ok(limitations)
3610    }
3611
3612    pub fn decision_metadata(
3613        &self,
3614        view: CoverageViewId,
3615    ) -> Result<Vec<crate::coverage_report::DecisionMeta>, CoverageIndexError> {
3616        let descriptor = self.index.descriptor(SECTION_DECISION_METADATA)?;
3617        let mut metadata = Vec::new();
3618        for index in 0..descriptor.count {
3619            let record = self.index.record(SECTION_DECISION_METADATA, index)?;
3620            if CoverageViewId::try_from(record[0])? != view {
3621                continue;
3622            }
3623            if record[1..4].iter().any(|byte| *byte != 0)
3624                || record[20..24].iter().any(|byte| *byte != 0)
3625                || record[56..].iter().any(|byte| *byte != 0)
3626            {
3627                return Err(CoverageIndexError::InvalidRecord(
3628                    "decision metadata record",
3629                ));
3630            }
3631            metadata.push(crate::coverage_report::DecisionMeta {
3632                id: self.string(get_u32(record, 4))?,
3633                file: self.string(get_u32(record, 8))?,
3634                source: self.string(get_u32(record, 12))?,
3635                kind: self.string(get_u32(record, 16))?,
3636                line: usize::try_from(get_u64(record, 24))
3637                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3638                column: usize::try_from(get_u64(record, 32))
3639                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3640                conditions: self.relation_strings(get_u64(record, 40), get_u64(record, 48))?,
3641            });
3642        }
3643        Ok(metadata)
3644    }
3645
3646    fn decision_vector_observation(
3647        &self,
3648        index: u64,
3649    ) -> Result<crate::coverage_report::VectorObservation, CoverageIndexError> {
3650        let record = self
3651            .index
3652            .record(SECTION_DECISION_VECTOR_OBSERVATIONS, index)?;
3653        Ok(crate::coverage_report::VectorObservation {
3654            confidence: self.confidence(get_u64(record, 0))?,
3655            vector: self.test_vector(get_u64(record, 8))?,
3656            tests: self.relation_ids(get_u64(record, 16), get_u64(record, 24))?,
3657            phases: self.relation_ids(get_u64(record, 32), get_u64(record, 40))?,
3658            explicit_phases: self.relation_ids(get_u64(record, 48), get_u64(record, 56))?,
3659        })
3660    }
3661
3662    fn decision_condition(
3663        &self,
3664        index: u64,
3665    ) -> Result<crate::coverage_report::ConditionResult, CoverageIndexError> {
3666        let record = self.index.record(SECTION_DECISION_CONDITIONS, index)?;
3667        if record[0] & !7 != 0 || record[1..4].iter().any(|byte| *byte != 0) {
3668            return Err(CoverageIndexError::InvalidRecord(
3669                "decision condition record",
3670            ));
3671        }
3672        let has_witness = record[0] & 4 != 0;
3673        let witness = if has_witness {
3674            Some([
3675                self.test_vector(get_u64(record, 16))?,
3676                self.test_vector(get_u64(record, 24))?,
3677            ])
3678        } else {
3679            None
3680        };
3681        let first_tests = self.relation_strings(get_u64(record, 32), get_u64(record, 40))?;
3682        let second_tests = self.relation_strings(get_u64(record, 48), get_u64(record, 56))?;
3683        if !has_witness && (!first_tests.is_empty() || !second_tests.is_empty()) {
3684            return Err(CoverageIndexError::InvalidRecord(
3685                "condition witness tests without witness",
3686            ));
3687        }
3688        Ok(crate::coverage_report::ConditionResult {
3689            index: usize::try_from(get_u64(record, 8))
3690                .map_err(|_| CoverageIndexError::SizeOverflow)?,
3691            source: self.string(get_u32(record, 4))?,
3692            covered: record[0] & 1 != 0,
3693            assertion_covered: record[0] & 2 != 0,
3694            witness,
3695            witness_tests: has_witness.then_some([
3696                first_tests.into_iter().map(Id::from).collect(),
3697                second_tests.into_iter().map(Id::from).collect(),
3698            ]),
3699        })
3700    }
3701
3702    pub fn decision_details(
3703        &self,
3704        view: CoverageViewId,
3705    ) -> Result<Vec<crate::coverage_report::DecisionResult>, CoverageIndexError> {
3706        let metadata = self
3707            .decision_metadata(view)?
3708            .into_iter()
3709            .map(|meta| (meta.id.clone(), meta))
3710            .collect::<HashMap<_, _>>();
3711        let descriptor = self.index.descriptor(SECTION_DECISION_DETAILS)?;
3712        let observation_count = self
3713            .index
3714            .descriptor(SECTION_DECISION_VECTOR_OBSERVATIONS)?
3715            .count;
3716        let condition_count = self.index.descriptor(SECTION_DECISION_CONDITIONS)?.count;
3717        let mut decisions = Vec::new();
3718        for index in 0..descriptor.count {
3719            let record = self.index.record(SECTION_DECISION_DETAILS, index)?;
3720            if CoverageViewId::try_from(record[0])? != view {
3721                continue;
3722            }
3723            if record[1] & !3 != 0 || record[2..4].iter().any(|byte| *byte != 0) {
3724                return Err(CoverageIndexError::InvalidRecord("decision detail record"));
3725            }
3726            let executed = record[1] & 1 != 0;
3727            let covered = record[1] & 2 != 0;
3728            if covered && !executed {
3729                return Err(CoverageIndexError::InvalidRecord(
3730                    "covered unexecuted decision",
3731                ));
3732            }
3733            let range = |offset: usize,
3734                         available: u64,
3735                         label: &'static str|
3736             -> Result<std::ops::Range<u64>, CoverageIndexError> {
3737                let start = get_u64(record, offset);
3738                let count = get_u64(record, offset + 8);
3739                let end = start
3740                    .checked_add(count)
3741                    .ok_or(CoverageIndexError::InvalidRecord(label))?;
3742                if end > available {
3743                    return Err(CoverageIndexError::InvalidRecord(label));
3744                }
3745                Ok(start..end)
3746            };
3747            let observations = range(32, observation_count, "decision observation range")?
3748                .map(|index| self.decision_vector_observation(index))
3749                .collect::<Result<Vec<_>, _>>()?;
3750            let conditions = range(48, condition_count, "decision condition range")?
3751                .map(|index| self.decision_condition(index))
3752                .collect::<Result<Vec<_>, _>>()?;
3753            let id = self.string(get_u32(record, 4))?;
3754            let meta = metadata
3755                .get(&id)
3756                .cloned()
3757                .ok_or(CoverageIndexError::InvalidRecord(
3758                    "missing decision metadata",
3759                ))?;
3760            if conditions.len() != meta.conditions.len()
3761                || conditions.iter().enumerate().any(|(index, condition)| {
3762                    condition.index != index || condition.source != meta.conditions[index]
3763                })
3764            {
3765                return Err(CoverageIndexError::InvalidRecord(
3766                    "decision condition denominator",
3767                ));
3768            }
3769            decisions.push(crate::coverage_report::DecisionResult {
3770                meta,
3771                executed,
3772                covered,
3773                vectors: observations
3774                    .iter()
3775                    .map(|observation| observation.vector.clone())
3776                    .collect(),
3777                vector_observations: observations,
3778                conditions,
3779                tests: self.relation_ids(get_u64(record, 16), get_u64(record, 24))?,
3780                confidence: self.confidence(get_u64(record, 8))?,
3781            });
3782        }
3783        Ok(decisions)
3784    }
3785
3786    pub fn phase_summaries(
3787        &self,
3788        view: CoverageViewId,
3789    ) -> Result<Vec<IndexedPhaseSummary>, CoverageIndexError> {
3790        let descriptor = self.index.descriptor(SECTION_PHASE_SUMMARIES)?;
3791        let mut phases = Vec::new();
3792        for index in 0..descriptor.count {
3793            let record = self.index.record(SECTION_PHASE_SUMMARIES, index)?;
3794            if CoverageViewId::try_from(record[0])? != view {
3795                continue;
3796            }
3797            if record[1..4].iter().any(|byte| *byte != 0)
3798                || record[48..].iter().any(|byte| *byte != 0)
3799            {
3800                return Err(CoverageIndexError::InvalidRecord("phase summary record"));
3801            }
3802            phases.push(IndexedPhaseSummary {
3803                id: self.string(get_u32(record, 4))?,
3804                kind: self.string(get_u32(record, 8))?,
3805                operation: self.string(get_u32(record, 12))?,
3806                source: self.optional_string(get_u32(record, 16))?,
3807                test: self.string(get_u32(record, 20))?,
3808                status: self.optional_string(get_u32(record, 24))?,
3809                caused_by_phase_id: self.optional_string(get_u32(record, 28))?,
3810                lines: usize::try_from(get_u64(record, 32))
3811                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3812                decisions: usize::try_from(get_u64(record, 40))
3813                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3814            });
3815        }
3816        Ok(phases)
3817    }
3818
3819    pub fn anchors(
3820        &self,
3821        view: CoverageViewId,
3822        file: &str,
3823        line: usize,
3824    ) -> Result<Vec<IndexedAnchor>, CoverageIndexError> {
3825        let descriptor = self.index.descriptor(SECTION_ANCHORS)?;
3826        let mut anchors = Vec::new();
3827        for index in 0..descriptor.count {
3828            let record = self.index.record(SECTION_ANCHORS, index)?;
3829            if CoverageViewId::try_from(record[0])? != view {
3830                continue;
3831            }
3832            if record[3] != 0 || record[12..16].iter().any(|byte| *byte != 0) {
3833                return Err(CoverageIndexError::InvalidRecord("anchor record"));
3834            }
3835            let record_file = self.string(get_u32(record, 8))?;
3836            let record_line = usize::try_from(get_u64(record, 16))
3837                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3838            if record_file != file || record_line != line {
3839                continue;
3840            }
3841            let total = usize::try_from(get_u64(record, 32))
3842                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3843            let covered_conditions = usize::try_from(get_u64(record, 40))
3844                .map_err(|_| CoverageIndexError::SizeOverflow)?;
3845            let (kind, conditions, covered_conditions) = match record[1] {
3846                0 => {
3847                    if total == 0 || covered_conditions > total {
3848                        return Err(CoverageIndexError::InvalidRecord(
3849                            "decision anchor conditions",
3850                        ));
3851                    }
3852                    ("decision", Some(total), Some(covered_conditions))
3853                }
3854                1 => ("branch", None, None),
3855                2 => ("statement", None, None),
3856                3 => ("function", None, None),
3857                _ => return Err(CoverageIndexError::InvalidRecord("anchor kind")),
3858            };
3859            if kind != "decision" && (total != 0 || covered_conditions.is_some()) {
3860                return Err(CoverageIndexError::InvalidRecord("anchor conditions"));
3861            }
3862            anchors.push(IndexedAnchor {
3863                kind: kind.into(),
3864                id: self.string(get_u32(record, 4))?,
3865                file: record_file,
3866                line: record_line,
3867                column: usize::try_from(get_u64(record, 24))
3868                    .map_err(|_| CoverageIndexError::SizeOverflow)?,
3869                covered: bool_field(record[2])?,
3870                conditions,
3871                covered_conditions,
3872                tests: self.relation_strings(get_u64(record, 48), get_u64(record, 56))?,
3873            });
3874        }
3875        anchors.sort_by_key(|anchor| anchor.column);
3876        Ok(anchors)
3877    }
3878
3879    pub fn snapshot(&self) -> Result<IndexedCoverageSnapshot, CoverageIndexError> {
3880        Ok(IndexedCoverageSnapshot {
3881            all_summary: self.summary(CoverageViewId::All)?,
3882            passed_summary: self.summary(CoverageViewId::Passed)?,
3883            failed_summary: self.summary(CoverageViewId::Failed)?,
3884            all_files: self.file_gaps(CoverageViewId::All, None, None)?,
3885            passed_files: self.file_gaps(CoverageViewId::Passed, None, None)?,
3886            failed_files: self.file_gaps(CoverageViewId::Failed, None, None)?,
3887        })
3888    }
3889}
3890
3891fn bool_field(value: u8) -> Result<bool, CoverageIndexError> {
3892    match value {
3893        0 => Ok(false),
3894        1 => Ok(true),
3895        _ => Err(CoverageIndexError::InvalidRecord("boolean")),
3896    }
3897}
3898
3899fn decode_summary(
3900    record: &[u8],
3901    flags_offset: usize,
3902    base: usize,
3903) -> Result<CoverageSummary, CoverageIndexError> {
3904    let number = |offset: usize| -> Result<usize, CoverageIndexError> {
3905        usize::try_from(get_u64(record, offset)).map_err(|_| CoverageIndexError::SizeOverflow)
3906    };
3907    let count = |offset: usize| -> Result<CoverageCount, CoverageIndexError> {
3908        let covered = number(offset)?;
3909        let total = number(offset + 8)?;
3910        if covered > total {
3911            return Err(CoverageIndexError::InvalidRecord("covered exceeds total"));
3912        }
3913        Ok(CoverageCount {
3914            covered,
3915            total,
3916            percentage: percentage(covered, total),
3917        })
3918    };
3919    let decisions = number(base)?;
3920    let executed_decisions = number(base + 8)?;
3921    let covered_decisions = number(base + 16)?;
3922    let conditions = number(base + 24)?;
3923    let covered_conditions = number(base + 32)?;
3924    if covered_decisions > executed_decisions
3925        || executed_decisions > decisions
3926        || covered_conditions > conditions
3927    {
3928        return Err(CoverageIndexError::InvalidRecord("summary count ordering"));
3929    }
3930    Ok(CoverageSummary {
3931        unmeasured_obligations: None,
3932        exact_fraction_pct: None,
3933        decisions,
3934        executed_decisions,
3935        covered_decisions,
3936        conditions,
3937        covered_conditions,
3938        condition_coverage_pct: percentage(covered_conditions, conditions),
3939        lines: count(base + 40)?,
3940        statements: count(base + 56)?,
3941        functions: count(base + 72)?,
3942        branches: count(base + 88)?,
3943        decision_outcomes: count(base + 104)?,
3944        condition_outcomes: count(base + 120)?,
3945        value_selections: count(base + 136)?,
3946        coverage_complete: bool_field(record[flags_offset])?,
3947        completeness_blocked: match record[flags_offset + 1] {
3948            0 => None,
3949            1 => Some(false),
3950            2 => Some(true),
3951            _ => return Err(CoverageIndexError::InvalidRecord("optional boolean")),
3952        },
3953    })
3954}
3955
3956fn percentage(covered: usize, total: usize) -> f64 {
3957    if total == 0 {
3958        100.0
3959    } else {
3960        ((covered as f64 / total as f64) * 10_000.0).round() / 100.0
3961    }
3962}
3963
3964#[cfg(test)]
3965mod tests {
3966    use std::{
3967        fs,
3968        path::PathBuf,
3969        sync::atomic::{AtomicU64, Ordering},
3970        time::{SystemTime, UNIX_EPOCH},
3971    };
3972
3973    use crate::{
3974        coverage_analysis::{McdcVector, PointKind},
3975        coverage_report::{
3976            CoverageManifest, CoverageReportRequest, DecisionMeta, ExitCodeInput, PointMeta,
3977            RawTestResult, RuntimeSnapshot, TestProvenance, analyze_coverage_results,
3978        },
3979        query_index::{QueryIndexIdentity, write_query_index},
3980    };
3981
3982    use super::*;
3983
3984    static ROOT_SEQUENCE: AtomicU64 = AtomicU64::new(0);
3985
3986    fn root() -> PathBuf {
3987        let nonce = SystemTime::now()
3988            .duration_since(UNIX_EPOCH)
3989            .unwrap()
3990            .as_nanos();
3991        let root = std::env::temp_dir().join(format!(
3992            "supercov-coverage-index-{}-{nonce}-{}",
3993            std::process::id(),
3994            ROOT_SEQUENCE.fetch_add(1, Ordering::Relaxed),
3995        ));
3996        fs::create_dir_all(&root).unwrap();
3997        root
3998    }
3999
4000    fn identity() -> QueryIndexIdentity {
4001        QueryIndexIdentity {
4002            evidence_sha256: [1; 32],
4003            evidence_bytes: 100,
4004            analysis_sha256: [2; 32],
4005            producer_sha256: [3; 32],
4006            archive_schema_version: 2,
4007        }
4008    }
4009
4010    fn report() -> CoverageReport {
4011        let decision = DecisionMeta {
4012            id: "d".into(),
4013            file: "src/a.js".into(),
4014            line: 1,
4015            column: 1,
4016            source: "a && b".into(),
4017            conditions: vec!["a".into(), "b".into()],
4018            kind: "if".into(),
4019        };
4020        analyze_coverage_results(&CoverageReportRequest {
4021            run_id: "run".into(),
4022            manifest: CoverageManifest {
4023                unmeasured: Vec::new(),
4024                decisions: vec![decision.clone()],
4025                points: vec![PointMeta {
4026                    id: "point".into(),
4027                    kind: PointKind::Statement,
4028                    file: "src/a.js".into(),
4029                    line: 2,
4030                    column: 3,
4031                    source: "work();".into(),
4032                    label: None,
4033                }],
4034                branches: Vec::new(),
4035                limitations: vec![serde_json::json!({
4036                    "id": "dynamic",
4037                    "kind": "dynamic-code",
4038                    "file": "src/a.js",
4039                    "line": 3,
4040                    "column": 1,
4041                    "source": "eval(code)",
4042                    "reason": "dynamic source"
4043                })],
4044                scope: None,
4045                assertion_sites: Vec::new(),
4046            },
4047            raw_results: vec![RawTestResult {
4048                test_id: Some("test".into()),
4049                scope: None,
4050                test: "test".into(),
4051                test_file: Some("tests/a.js".into()),
4052                title: None,
4053                retry: Some(0),
4054                status: Some("passed".into()),
4055                expected_status: None,
4056                flaky: false,
4057                provenance: TestProvenance {
4058                    runner: "node:test".into(),
4059                    kind: "unit".into(),
4060                    project: None,
4061                    source: "runner-default".into(),
4062                },
4063                role: "test".into(),
4064                attribution: crate::coverage_report::ATTRIBUTION_EXACT.into(),
4065                phases: Vec::new(),
4066                runtime: vec![RuntimeSnapshot {
4067                    decisions: vec![crate::coverage_report::DecisionSnapshot {
4068                        meta: decision,
4069                        vectors: vec![McdcVector {
4070                            values: vec![Some(false), None],
4071                            outcome: false,
4072                        }],
4073                    }],
4074                    hits: vec!["point".into()],
4075                    events: Vec::new(),
4076                    logicals: Vec::new(),
4077                    phase_id: None,
4078                }],
4079                browser: Vec::new(),
4080                server: Vec::new(),
4081            }],
4082            generated_at: "time".into(),
4083            coverage_model: None,
4084            integrity: None,
4085            test_exit_code: ExitCodeInput::Present(Some(0)),
4086        })
4087        .unwrap()
4088    }
4089
4090    fn report_attributed(attribution: &str) -> CoverageReport {
4091        let mut report = report();
4092        for view in [
4093            &mut report.view,
4094            &mut report.filters.passed,
4095            &mut report.filters.failed,
4096        ] {
4097            for test in &mut view.tests {
4098                test.attribution = attribution.to_owned();
4099            }
4100        }
4101        report
4102    }
4103
4104    #[test]
4105    fn declined_lines_and_points_are_not_reported_as_coverage_gaps() {
4106        let mut report = report();
4107        for line in &mut report.view.lines {
4108            line.measured = false;
4109            line.covered = false;
4110            line.tests.clear();
4111        }
4112        for point in &mut report.view.points {
4113            point.measured = false;
4114            point.covered = false;
4115            point.tests.clear();
4116        }
4117        let selected = Selected::default();
4118        for filter in [None, Some(&selected)] {
4119            let gaps = file_gaps(&report.view, filter).unwrap();
4120            let (_, gap) = &gaps[0];
4121            assert_eq!(gap.uncovered_lines, 0);
4122            assert_eq!(gap.uncovered_statements, 0);
4123            assert_eq!(gap.uncovered_functions, 0);
4124            assert_eq!(gap.uncovered_everywhere[0..3], [0, 0, 0]);
4125            assert_eq!(gap.measurement_limitations, 1);
4126        }
4127        // Actual missed obligations must still appear.
4128        report.view.lines[0].measured = true;
4129        report.view.points[0].measured = true;
4130        let gaps = file_gaps(&report.view, None).unwrap();
4131        assert_eq!(gaps[0].1.uncovered_lines, 1);
4132        assert_eq!(gaps[0].1.uncovered_statements, 1);
4133    }
4134
4135    #[test]
4136    fn a_test_keeps_the_attribution_it_was_written_with() {
4137        // Attribution rides in a byte the reader used to refuse outright, so a
4138        // value that does not survive the trip is not a wrong number on a
4139        // report -- it is a run that will not open. Only `exact` was ever
4140        // written by a test, which left the other two arms of both the encoder
4141        // and the decoder standing on the claim that they matched.
4142        let root = root();
4143        for attribution in [
4144            crate::coverage_report::ATTRIBUTION_EXACT,
4145            crate::coverage_report::ATTRIBUTION_RUN_WIDE,
4146            crate::coverage_report::ATTRIBUTION_PARTIAL,
4147        ] {
4148            let report = report_attributed(attribution);
4149            let path = root.join(format!("query-index-{attribution}.v1.bin"));
4150            write_query_index(
4151                &coverage_index_sections(&report).unwrap(),
4152                &identity(),
4153                &path,
4154            )
4155            .unwrap();
4156            let container = QueryIndex::open(&path, &identity()).unwrap();
4157            let index = CoverageIndex::new(&container).unwrap();
4158            let tests = index.test_summaries(CoverageViewId::All).unwrap();
4159            assert_eq!(tests.len(), 1);
4160            assert_eq!(
4161                tests[0].attribution, attribution,
4162                "written as `{attribution}` and read back as `{}`",
4163                tests[0].attribution
4164            );
4165        }
4166    }
4167
4168    #[test]
4169    fn an_attribution_the_byte_has_no_room_for_is_refused_at_the_write() {
4170        // Refusing here is what keeps the reserved byte honest: a value nobody
4171        // taught the encoder must not be written as some neighbouring one and
4172        // read back as a measurement.
4173        let error = coverage_index_sections(&report_attributed("probably-exact")).unwrap_err();
4174        assert!(
4175            matches!(error, CoverageIndexError::InvalidRecord("test attribution")),
4176            "{error:?}"
4177        );
4178    }
4179
4180    // The same run is named over and over -- a filtered view repeats the
4181    // relation of the view it filters, and one list of tests covers many lines
4182    // of the file they exercise. Storing each naming separately made this the
4183    // largest section in the container: 61 MB of a 210 MB index.
4184    #[test]
4185    fn a_relation_named_twice_is_stored_once() {
4186        let mut strings = StringTable::default();
4187        let mut relations = StringRelations::default();
4188        let run = || ["alpha".to_string(), "beta".to_string(), "gamma".to_string()];
4189
4190        let first = relations.push(run(), &mut strings).unwrap();
4191        let second = relations.push(run(), &mut strings).unwrap();
4192        assert_eq!(first, second, "the second naming points at the first run");
4193        assert_eq!(relations.values.len(), 3, "and nothing was appended for it");
4194
4195        // A different run still gets its own storage, after the one already
4196        // there -- readers reach a run only by (offset, count), so the
4197        // existing pair must keep meaning what it meant.
4198        let other = relations
4199            .push(["alpha".to_string(), "delta".to_string()], &mut strings)
4200            .unwrap();
4201        assert_eq!(other, (3, 2));
4202        assert_eq!(relations.values.len(), 5);
4203
4204        // A prefix of a stored run is a different run, and is stored as one
4205        // rather than aliasing into the middle of another.
4206        let prefix = relations.push(["alpha".to_string()], &mut strings).unwrap();
4207        assert_eq!(prefix, (5, 1));
4208
4209        // What each pair resolves to is what was pushed.
4210        let read = |(offset, count): (u64, u64)| {
4211            relations.values[offset as usize..(offset + count) as usize].to_vec()
4212        };
4213        assert_eq!(read(first), read(second));
4214        assert_eq!(read(first).len(), 3);
4215        assert_ne!(read(first), read(other));
4216    }
4217
4218    #[test]
4219    fn shared_id_relations_match_text_relations_across_allocations() {
4220        let mut shared_strings = StringTable::default();
4221        let mut text_strings = StringTable::default();
4222        let mut shared_relations = StringRelations::default();
4223        let mut text_relations = StringRelations::default();
4224        let original: Vec<Id> = ["", "test::a[1]", "test::a[10]", "unicodé ✓"]
4225            .into_iter()
4226            .map(Id::from)
4227            .collect();
4228        let copies = original.clone();
4229        let separate: Vec<Id> = original.iter().map(|id| Id::from(id.as_str())).collect();
4230        for values in [&original[..], &copies, &separate, &separate[1..], &[]] {
4231            assert_eq!(
4232                shared_relations
4233                    .push_ids(values, &mut shared_strings)
4234                    .unwrap(),
4235                text_relations.push(values, &mut text_strings).unwrap(),
4236            );
4237        }
4238        // The table owns references to cached allocations even after callers
4239        // drop theirs, so a later ID cannot reuse an earlier cache address.
4240        drop(original);
4241        drop(copies);
4242        drop(separate);
4243        for value in ["new", "test::a[1]", ""] {
4244            let id = Id::from(value);
4245            assert_eq!(
4246                shared_strings.intern_shared(&id).unwrap(),
4247                text_strings.intern(value).unwrap(),
4248            );
4249        }
4250        assert_eq!(shared_relations.values, text_relations.values);
4251        assert_eq!(shared_strings.strings, text_strings.strings);
4252    }
4253
4254    #[test]
4255    fn typed_columns_round_trip_all_outcome_views_without_json() {
4256        let report = report();
4257        let root = root();
4258        let path = root.join("query-index.v1.bin");
4259        write_query_index(
4260            &coverage_index_sections(&report).unwrap(),
4261            &identity(),
4262            &path,
4263        )
4264        .unwrap();
4265        let container = QueryIndex::open(&path, &identity()).unwrap();
4266        let index = CoverageIndex::new(&container).unwrap();
4267        assert_eq!(
4268            index.model().unwrap(),
4269            IndexedCoverageModel {
4270                schema_version: COVERAGE_MODEL_SCHEMA_VERSION,
4271                variant: report.view.variant.clone(),
4272                name: report.view.model.name.clone(),
4273                completeness_meaning: report.view.model.completeness_meaning.clone(),
4274                measured: report.view.model.measured.clone(),
4275                not_measured: report.view.model.not_measured.clone(),
4276            }
4277        );
4278        for (id, view) in [
4279            (CoverageViewId::All, &report.view),
4280            (CoverageViewId::Passed, &report.filters.passed),
4281            (CoverageViewId::Failed, &report.filters.failed),
4282        ] {
4283            assert_eq!(index.summary(id).unwrap(), view.summary);
4284        }
4285        let gaps = index.file_gaps(CoverageViewId::All, None, None).unwrap();
4286        assert_eq!(gaps.len(), 1);
4287        assert_eq!(gaps[0].file, "src/a.js");
4288        assert_eq!(gaps[0].missing_mcdc_conditions, 2);
4289        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
4290        assert_eq!(projection.summary, report.view.summary);
4291        assert_eq!(projection.tests, 1);
4292        assert_eq!(projection.setups, 0);
4293        assert_eq!(projection.test_outcomes.passed, 1);
4294        assert!(projection.source_scope.is_none());
4295        let line = index
4296            .line(CoverageViewId::All, "src/a.js", 2)
4297            .unwrap()
4298            .unwrap();
4299        assert!(line.covered);
4300        assert_eq!(line.tests, ["test"]);
4301        assert_eq!(line.confidence.level, "executed");
4302        let tests = index.test_summaries(CoverageViewId::All).unwrap();
4303        assert_eq!(tests.len(), 1);
4304        assert_eq!(tests[0].provenance.runner, "node:test");
4305        // The decision, and its two outcomes as a branch.
4306        let anchors = index.anchors(CoverageViewId::All, "src/a.js", 1).unwrap();
4307        assert_eq!(anchors.len(), 2);
4308        let decision = anchors
4309            .iter()
4310            .filter(|anchor| anchor.kind == "decision")
4311            .collect::<Vec<_>>();
4312        assert_eq!(decision.len(), 1);
4313        assert_eq!(decision[0].conditions, Some(2));
4314        assert_eq!(decision[0].tests, ["test"]);
4315        assert!(anchors.iter().any(|anchor| anchor.kind == "branch"));
4316        let point = index.anchors(CoverageViewId::All, "src/a.js", 2).unwrap();
4317        assert_eq!(point.len(), 1);
4318        assert_eq!(point[0].kind, "statement");
4319        assert_eq!(point[0].tests, ["test"]);
4320        let details = index.test_details(CoverageViewId::All).unwrap();
4321        assert_eq!(details.len(), 1);
4322        assert_eq!(details[0].retries, [0]);
4323        assert_eq!(details[0].attempts.len(), 1);
4324        assert_eq!(details[0].hits, ["point"]);
4325        assert_eq!(details[0].lines.len(), 1);
4326        assert_eq!(details[0].lines[0].line, 2);
4327        assert_eq!(details[0].decisions.len(), 1);
4328        assert_eq!(details[0].decisions[0].vectors.len(), 1);
4329        assert_eq!(
4330            details[0].decisions[0].vectors[0].values,
4331            [Some(false), None]
4332        );
4333        let hits = index.hit_metadata(CoverageViewId::All).unwrap();
4334        // The point, and the decision's two outcomes.
4335        assert_eq!(hits.len(), 3);
4336        let hits = hits
4337            .into_iter()
4338            .filter(|hit| hit.obligation != "branch")
4339            .collect::<Vec<_>>();
4340        assert_eq!(hits.len(), 1);
4341        assert_eq!(hits[0].id, "point");
4342        assert_eq!(hits[0].source, "work();");
4343        assert_eq!(hits[0].tests, ["test"]);
4344        let decisions = index.decision_metadata(CoverageViewId::All).unwrap();
4345        assert_eq!(decisions.len(), 1);
4346        assert_eq!(decisions[0].conditions, ["a", "b"]);
4347        assert_eq!(
4348            index.decision_details(CoverageViewId::All).unwrap(),
4349            report.view.decisions
4350        );
4351        let limitations = index.limitations(CoverageViewId::All).unwrap();
4352        assert_eq!(limitations.len(), 1);
4353        assert_eq!(limitations[0].kind, "dynamic-code");
4354        assert_eq!(limitations[0].line, 3);
4355        fs::remove_dir_all(root).unwrap();
4356    }
4357
4358    #[test]
4359    fn index_preserves_catalogued_unstarted_tests_without_attempts() {
4360        let report = analyze_coverage_results(&CoverageReportRequest {
4361            run_id: "run".into(),
4362            manifest: CoverageManifest {
4363                unmeasured: Vec::new(),
4364                decisions: Vec::new(),
4365                points: Vec::new(),
4366                branches: Vec::new(),
4367                limitations: Vec::new(),
4368                scope: None,
4369                assertion_sites: Vec::new(),
4370            },
4371            raw_results: vec![RawTestResult {
4372                test_id: Some("unstarted".into()),
4373                scope: None,
4374                test: "unstarted".into(),
4375                test_file: Some("tests/a.rs".into()),
4376                title: None,
4377                retry: None,
4378                status: Some("unstarted".into()),
4379                expected_status: Some("passed".into()),
4380                flaky: false,
4381                provenance: TestProvenance {
4382                    runner: "rust-nextest".into(),
4383                    kind: "unit".into(),
4384                    project: None,
4385                    source: "selected-but-not-started".into(),
4386                },
4387                role: "test".into(),
4388                attribution: crate::coverage_report::ATTRIBUTION_EXACT.into(),
4389                phases: Vec::new(),
4390                runtime: Vec::new(),
4391                browser: Vec::new(),
4392                server: Vec::new(),
4393            }],
4394            generated_at: "time".into(),
4395            coverage_model: None,
4396            integrity: None,
4397            test_exit_code: ExitCodeInput::Present(Some(100)),
4398        })
4399        .unwrap();
4400        let root = root();
4401        let path = root.join("query-index.v1.bin");
4402        write_query_index(
4403            &coverage_index_sections(&report).unwrap(),
4404            &identity(),
4405            &path,
4406        )
4407        .unwrap();
4408        let container = QueryIndex::open(&path, &identity()).unwrap();
4409        let index = CoverageIndex::new(&container).unwrap();
4410        let summaries = index.test_summaries(CoverageViewId::All).unwrap();
4411        assert_eq!(summaries.len(), 1);
4412        assert_eq!(summaries[0].outcome, "unstarted");
4413        let details = index.test_details(CoverageViewId::All).unwrap();
4414        assert!(details[0].retries.is_empty());
4415        assert!(details[0].attempts.is_empty());
4416        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
4417        assert_eq!(projection.tests, 1);
4418        assert_eq!(projection.test_outcomes.unstarted, 1);
4419        fs::remove_dir_all(root).unwrap();
4420    }
4421
4422    #[test]
4423    fn source_discovery_scope_preserves_python_language() {
4424        let mut report = report();
4425        let scope = serde_json::json!({
4426            "version": 1,
4427            "mode": "automatic",
4428            "roots": ["."],
4429            "entries": [{
4430                "file": "src/a.py",
4431                "status": "included",
4432                "reason": "python source",
4433                "packageRoot": "."
4434            }]
4435        });
4436        for view in [
4437            &mut report.view,
4438            &mut report.filters.passed,
4439            &mut report.filters.failed,
4440        ] {
4441            view.scope = Some(scope.clone());
4442            view.model.language = "python".into();
4443            view.model.name = "python-probes-v1".into();
4444        }
4445        let root = root();
4446        let path = root.join("query-index.python.bin");
4447        write_query_index(
4448            &coverage_index_sections(&report).unwrap(),
4449            &identity(),
4450            &path,
4451        )
4452        .unwrap();
4453        let container = QueryIndex::open(&path, &identity()).unwrap();
4454        let index = CoverageIndex::new(&container).unwrap();
4455        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
4456        let source_scope = projection.source_scope.unwrap();
4457        assert_eq!(source_scope.language, "python");
4458        assert_eq!(source_scope.model, "python-probes-v1");
4459        assert_eq!(source_scope.kind, "source-discovery");
4460        assert_eq!(source_scope.included, 1);
4461        assert_eq!(index.scope_entries(CoverageViewId::All).unwrap().len(), 1);
4462        fs::remove_dir_all(root).unwrap();
4463    }
4464
4465    #[test]
4466    fn a_scope_entry_carries_a_limitation_of_its_language_s_own_kind() {
4467        // Go records `loop-without-condition`; with a scope recorded for a Go
4468        // run, a kind this table did not name refused the whole index:
4469        // "invalid coverage index: coverage limitation kind".
4470        let mut report = report();
4471        let scope = serde_json::json!({
4472            "version": 1,
4473            "mode": "automatic",
4474            "roots": ["."],
4475            "entries": [{ "file": "mux.go", "status": "included", "reason": "Go application source" }]
4476        });
4477        for view in [
4478            &mut report.view,
4479            &mut report.filters.passed,
4480            &mut report.filters.failed,
4481        ] {
4482            view.scope = Some(scope.clone());
4483            view.model.language = "go".into();
4484            view.limitations = vec![serde_json::json!({
4485                "id": "go-loop-1",
4486                "kind": "loop-without-condition",
4487                "file": "mux.go",
4488                "line": 4,
4489                "column": 1,
4490                "source": "for {",
4491                "reason": "a loop with no condition has no decision to measure"
4492            })];
4493        }
4494        let root = root();
4495        let path = root.join("query-index.go.bin");
4496        write_query_index(
4497            &coverage_index_sections(&report).unwrap(),
4498            &identity(),
4499            &path,
4500        )
4501        .unwrap();
4502        let container = QueryIndex::open(&path, &identity()).unwrap();
4503        let index = CoverageIndex::new(&container).unwrap();
4504        let entries = index.scope_entries(CoverageViewId::All).unwrap();
4505        assert_eq!(entries.len(), 1);
4506        assert_eq!(entries[0].measurement_limitations, 1);
4507        assert_eq!(entries[0].limitation_kinds, ["unknown"]);
4508        fs::remove_dir_all(root).unwrap();
4509    }
4510
4511    #[test]
4512    fn compiler_owned_scope_round_trips_without_javascript_scope_fields() {
4513        let mut report = report();
4514        let scope = serde_json::json!({
4515            "language": "rust",
4516            "model": "rust-source-v1",
4517            "crate": "fixture",
4518            "measurementComplete": false
4519        });
4520        report.view.scope = Some(scope.clone());
4521        report.filters.passed.scope = Some(scope.clone());
4522        report.filters.failed.scope = Some(scope);
4523        let root = root();
4524        let path = root.join("query-index.v2.bin");
4525        write_query_index(
4526            &coverage_index_sections(&report).unwrap(),
4527            &identity(),
4528            &path,
4529        )
4530        .unwrap();
4531        let container = QueryIndex::open(&path, &identity()).unwrap();
4532        let index = CoverageIndex::new(&container).unwrap();
4533        let projection = index.projection(CoverageViewId::All, None, None).unwrap();
4534        assert_eq!(
4535            projection.source_scope,
4536            Some(IndexedSourceScope {
4537                kind: "compiler".into(),
4538                language: "rust".into(),
4539                model: "rust-source-v1".into(),
4540                mode: None,
4541                roots: Vec::new(),
4542                unit: Some("fixture".into()),
4543                measurement_complete: Some(false),
4544                included: 0,
4545                excluded: 0,
4546                ambiguous: 0,
4547            })
4548        );
4549        assert!(index.scope_entries(CoverageViewId::All).unwrap().is_empty());
4550        fs::remove_dir_all(root).unwrap();
4551    }
4552}