Skip to main content

supercov_engine/
coverage_index.rs

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