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