Skip to main content

supercov_engine/
coverage_report.rs

1//! Language-neutral reconstruction of coverage views from frozen obligations
2//! and per-attempt evidence.
3//!
4//! This module deliberately knows nothing about JavaScript or any test runner.
5//! Language frontends provide the manifest and normalized evidence records;
6//! Rust owns merging, attempt outcomes, attribution confidence, filtering and
7//! every structural coverage verdict.
8
9use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
10use std::path::{Path, PathBuf};
11
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14use supercov_contracts::{COVERAGE_MODEL_SCHEMA_VERSION, FrontendRunDeclaration};
15
16use crate::coverage_analysis::{
17    AnalysisError, BranchCoverage, CoverageCoreInput, CoverageSummary, DecisionCoverage,
18    McdcVector, PointCoverage, PointKind, analyze_core, find_witnesses_for_conditions,
19};
20use crate::evidence_archive::{EvidenceArchiveEntry, read_archive};
21use crate::interned::{FastMap, Id, Interner};
22
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase", deny_unknown_fields)]
25pub struct DecisionMeta {
26    pub id: String,
27    pub file: String,
28    pub line: usize,
29    pub column: usize,
30    pub source: String,
31    pub conditions: Vec<String>,
32    pub kind: String,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(rename_all = "camelCase", deny_unknown_fields)]
37pub struct PointMeta {
38    pub id: String,
39    pub kind: PointKind,
40    pub file: String,
41    pub line: usize,
42    pub column: usize,
43    pub source: String,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub label: Option<String>,
46}
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(rename_all = "camelCase", deny_unknown_fields)]
50pub struct BranchAlternativeMeta {
51    pub id: String,
52    pub label: String,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "camelCase", deny_unknown_fields)]
57pub struct BranchMeta {
58    pub id: String,
59    pub kind: String,
60    pub file: String,
61    pub line: usize,
62    pub column: usize,
63    pub source: String,
64    pub alternatives: Vec<BranchAlternativeMeta>,
65}
66
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68#[serde(rename_all = "camelCase", deny_unknown_fields)]
69pub struct CoverageManifest {
70    pub decisions: Vec<DecisionMeta>,
71    pub points: Vec<PointMeta>,
72    pub branches: Vec<BranchMeta>,
73    #[serde(default, skip_serializing_if = "Vec::is_empty")]
74    pub limitations: Vec<Value>,
75    /// Obligation IDs the frontend declined to measure exactly. They stay in
76    /// the manifest so the report can say what was not measured, but they must
77    /// never be counted as uncovered.
78    #[serde(default, skip_serializing_if = "Vec::is_empty")]
79    pub unmeasured: Vec<String>,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub scope: Option<Value>,
82    /// Statements in test code that carry an assertion marker. Test code is
83    /// not measured, so these are no obligation; they say where a passing
84    /// assertion stood.
85    #[serde(default, skip_serializing_if = "Vec::is_empty")]
86    pub assertion_sites: Vec<PointMeta>,
87}
88
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90#[serde(rename_all = "camelCase", deny_unknown_fields)]
91pub struct DecisionSnapshot {
92    pub meta: DecisionMeta,
93    pub vectors: Vec<McdcVector>,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(rename_all = "camelCase", deny_unknown_fields)]
98pub struct RuntimeEvent {
99    #[serde(rename = "type")]
100    pub event_type: String,
101    pub id: String,
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub vector: Option<McdcVector>,
104    pub timestamp_ms: i64,
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub phase_id: Option<String>,
107    /// Legacy test-statement location retained for reading historical archives.
108    /// The assertion-map workflow does not emit test-statement markers.
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub statement_id: Option<String>,
111    pub environment: String,
112}
113
114/// One observed (side selected, result truthy) pair of a value-position logical expression.
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116#[serde(rename_all = "camelCase", deny_unknown_fields)]
117pub struct LogicalVector {
118    /// The right operand was evaluated (the left did not short-circuit).
119    pub right: bool,
120    /// The selected result was truthy.
121    pub truthy: bool,
122}
123
124/// Distinct outcomes of one `logical-value` branch within a test; gives per-operand outcomes
125/// once combined with the operator recorded in the manifest.
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127#[serde(rename_all = "camelCase", deny_unknown_fields)]
128pub struct LogicalSnapshot {
129    pub id: String,
130    pub vectors: Vec<LogicalVector>,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
134#[serde(rename_all = "camelCase", deny_unknown_fields)]
135pub struct RuntimeSnapshot {
136    #[serde(default)]
137    pub decisions: Vec<DecisionSnapshot>,
138    #[serde(default)]
139    pub hits: Vec<String>,
140    #[serde(default)]
141    pub events: Vec<RuntimeEvent>,
142    #[serde(default, skip_serializing_if = "Vec::is_empty")]
143    pub logicals: Vec<LogicalSnapshot>,
144    /// Every hit and decision vector of this snapshot is an explicit event of
145    /// this phase. A frontend that observes a whole phase at once -- Python
146    /// reads a phase's slot -- names the phase here instead of writing an
147    /// event per observation, which on a 3,900-test run was three quarters
148    /// of the evidence. The analysis reads it exactly as those events.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub phase_id: Option<String>,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
154#[serde(rename_all = "camelCase", deny_unknown_fields)]
155pub struct ExecutionScope {
156    pub version: usize,
157    pub run_id: String,
158    pub worker_id: String,
159    pub test_id: String,
160    pub test_key: String,
161    pub retry: usize,
162    pub attempt_id: String,
163}
164
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166#[serde(rename_all = "camelCase", deny_unknown_fields)]
167pub struct ServerRecord {
168    #[serde(rename = "type")]
169    pub record_type: String,
170    #[serde(skip_serializing_if = "Option::is_none")]
171    pub meta: Option<DecisionMeta>,
172    #[serde(skip_serializing_if = "Option::is_none")]
173    pub vector: Option<McdcVector>,
174    #[serde(skip_serializing_if = "Option::is_none")]
175    pub id: Option<String>,
176    #[serde(skip_serializing_if = "Option::is_none")]
177    pub timestamp_ms: Option<i64>,
178    #[serde(skip_serializing_if = "Option::is_none")]
179    pub phase_id: Option<String>,
180    /// The producing test statement, under this record's exact execution scope.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub statement_id: Option<String>,
183    #[serde(skip_serializing_if = "Option::is_none")]
184    pub scope: Option<ExecutionScope>,
185}
186
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
188#[serde(rename_all = "camelCase", deny_unknown_fields)]
189pub struct CoveragePhase {
190    pub id: String,
191    pub kind: String,
192    pub operation: String,
193    #[serde(skip_serializing_if = "Option::is_none")]
194    pub source: Option<String>,
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub caused_by_phase_id: Option<String>,
197    pub started_at_ms: i64,
198    #[serde(skip_serializing_if = "Option::is_none")]
199    pub ended_at_ms: Option<i64>,
200    #[serde(skip_serializing_if = "Option::is_none")]
201    pub status: Option<String>,
202    #[serde(skip_serializing_if = "Option::is_none")]
203    pub error: Option<String>,
204}
205
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
207#[serde(rename_all = "camelCase", deny_unknown_fields)]
208pub struct TestProvenance {
209    pub runner: String,
210    pub kind: String,
211    #[serde(skip_serializing_if = "Option::is_none")]
212    pub project: Option<String>,
213    pub source: String,
214}
215
216impl Default for TestProvenance {
217    fn default() -> Self {
218        Self {
219            runner: "unknown".into(),
220            kind: "unknown".into(),
221            project: None,
222            source: "unknown".into(),
223        }
224    }
225}
226
227#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
228#[serde(rename_all = "camelCase", deny_unknown_fields)]
229pub struct RawTestResult {
230    #[serde(skip_serializing_if = "Option::is_none")]
231    pub test_id: Option<String>,
232    #[serde(skip_serializing_if = "Option::is_none")]
233    pub scope: Option<ExecutionScope>,
234    pub test: String,
235    #[serde(skip_serializing_if = "Option::is_none")]
236    pub test_file: Option<String>,
237    #[serde(skip_serializing_if = "Option::is_none")]
238    pub title: Option<String>,
239    #[serde(skip_serializing_if = "Option::is_none")]
240    pub retry: Option<usize>,
241    #[serde(skip_serializing_if = "Option::is_none")]
242    pub status: Option<String>,
243    #[serde(skip_serializing_if = "Option::is_none")]
244    pub expected_status: Option<String>,
245    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
246    pub flaky: bool,
247    #[serde(default)]
248    pub provenance: TestProvenance,
249    #[serde(default = "default_test_role")]
250    pub role: String,
251    /// How exactly this test's coverage could be credited to it.
252    ///
253    /// `exact` is the ordinary case and the default, so a frontend that has
254    /// not been taught the difference keeps its behaviour. `run-wide` says the
255    /// test ran and reached code, and that nothing can say which code: a Go
256    /// test that called `t.Parallel()` stores into the same probe array as the
257    /// tests running beside it.
258    ///
259    /// The distinction is the whole point of the field. A test that reached
260    /// nothing and a test whose reach cannot be narrowed both have an empty
261    /// hit set, and reporting the second as the first is a wrong number
262    /// wearing the shape of a right one.
263    #[serde(default = "default_attribution")]
264    pub attribution: String,
265    #[serde(default)]
266    pub phases: Vec<CoveragePhase>,
267    #[serde(default)]
268    pub runtime: Vec<RuntimeSnapshot>,
269    #[serde(default)]
270    pub browser: Vec<RuntimeSnapshot>,
271    #[serde(default)]
272    pub server: Vec<ServerRecord>,
273}
274
275fn default_test_role() -> String {
276    "test".into()
277}
278
279fn default_attribution() -> String {
280    ATTRIBUTION_EXACT.into()
281}
282
283/// This test's coverage is its own: what it reached was credited to it.
284pub const ATTRIBUTION_EXACT: &str = "exact";
285
286/// This test ran, and what it reached was recorded against the run rather than
287/// against it. Its own reach is unknown, and bounded above by the run's.
288pub const ATTRIBUTION_RUN_WIDE: &str = "run-wide";
289
290/// What this test is recorded as reaching is really its own, and is not all of
291/// it: a lower bound, with the run's coverage as the upper one.
292///
293/// Ruby records a line against the first test that reaches it and never again,
294/// which is what makes its collection cheap. Every later test that runs the
295/// same line is recorded as having reached nothing there -- so a test's hits
296/// prove what it ran and its silence proves nothing.
297pub const ATTRIBUTION_PARTIAL: &str = "partial";
298
299/// Of two attributions for one test, the one that claims less.
300fn least_exact(left: &str, right: &str) -> String {
301    let rank = |attribution: &str| match attribution {
302        ATTRIBUTION_RUN_WIDE => 2,
303        ATTRIBUTION_PARTIAL => 1,
304        _ => 0,
305    };
306    if rank(right) > rank(left) {
307        right.to_owned()
308    } else {
309        left.to_owned()
310    }
311}
312
313/// Whether what this test is recorded as reaching is its own.
314///
315/// True for `exact` and for `partial`: both record real coverage of this
316/// test's, and a union over them is a union of things that happened. False
317/// only where the coverage went to the run instead, and counting the test in a
318/// percentage would divide by a test that contributes nothing.
319pub fn coverage_is_its_own(attribution: &str) -> bool {
320    attribution != ATTRIBUTION_RUN_WIDE
321}
322
323/// Whether this test's silence means it did not run the code.
324///
325/// Only `exact` earns that. Under `partial` a test that is recorded as
326/// reaching nothing may have run the same lines as the test that was credited
327/// with them, and under `run-wide` nothing was recorded at all -- so reading
328/// an absence as proof is how a change to code a test exercised comes back as
329/// "this test is unaffected".
330pub fn coverage_is_complete(attribution: &str) -> bool {
331    attribution == ATTRIBUTION_EXACT || attribution.is_empty()
332}
333
334#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
335#[serde(rename_all = "camelCase")]
336pub struct TestAttempt {
337    pub retry: usize,
338    pub status: String,
339    #[serde(skip_serializing_if = "Option::is_none")]
340    pub expected_status: Option<String>,
341}
342
343#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
344#[serde(rename_all = "camelCase")]
345pub struct CoverageConfidence {
346    pub level: String,
347    pub setup_only: bool,
348    pub background_only: bool,
349    pub asserted: bool,
350    pub tests: Vec<Id>,
351    pub asserted_tests: Vec<Id>,
352    pub runners: Vec<String>,
353    pub kinds: Vec<String>,
354    pub e2e: bool,
355}
356
357#[derive(Debug, Clone, PartialEq, Serialize)]
358#[serde(rename_all = "camelCase")]
359pub struct VectorObservation {
360    pub vector: McdcVector,
361    pub tests: Vec<Id>,
362    #[serde(skip_serializing_if = "Vec::is_empty")]
363    pub phases: Vec<Id>,
364    #[serde(skip_serializing_if = "Vec::is_empty")]
365    pub explicit_phases: Vec<Id>,
366    pub confidence: CoverageConfidence,
367}
368
369#[derive(Debug, Clone, PartialEq, Serialize)]
370#[serde(rename_all = "camelCase")]
371pub struct ConditionResult {
372    pub index: usize,
373    pub source: String,
374    pub covered: bool,
375    pub assertion_covered: bool,
376    #[serde(skip_serializing_if = "Option::is_none")]
377    pub witness: Option<[McdcVector; 2]>,
378    #[serde(skip_serializing_if = "Option::is_none")]
379    pub witness_tests: Option<[Vec<Id>; 2]>,
380}
381
382#[derive(Debug, Clone, PartialEq, Serialize)]
383#[serde(rename_all = "camelCase")]
384pub struct DecisionResult {
385    pub meta: DecisionMeta,
386    pub executed: bool,
387    pub covered: bool,
388    pub vectors: Vec<McdcVector>,
389    pub vector_observations: Vec<VectorObservation>,
390    pub conditions: Vec<ConditionResult>,
391    pub tests: Vec<Id>,
392    pub confidence: CoverageConfidence,
393}
394
395#[derive(Debug, Clone, PartialEq, Serialize)]
396#[serde(rename_all = "camelCase")]
397pub struct PointResult {
398    pub meta: PointMeta,
399    pub covered: bool,
400    #[serde(skip)]
401    pub measured: bool,
402    pub tests: Vec<Id>,
403    pub phases: Vec<Id>,
404    pub confidence: CoverageConfidence,
405}
406
407#[derive(Debug, Clone, PartialEq, Serialize)]
408#[serde(rename_all = "camelCase")]
409pub struct AlternativeResult {
410    pub id: String,
411    pub label: String,
412    pub covered: bool,
413    pub tests: Vec<Id>,
414    pub phases: Vec<Id>,
415    pub confidence: CoverageConfidence,
416}
417
418#[derive(Debug, Clone, PartialEq, Serialize)]
419#[serde(rename_all = "camelCase")]
420pub struct BranchResult {
421    pub meta: BranchMeta,
422    pub covered: bool,
423    pub alternatives: Vec<AlternativeResult>,
424}
425
426#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
427pub struct SourceLine {
428    pub file: Id,
429    pub line: usize,
430}
431
432/// One line's share of the points that sit on it, while the view is built.
433#[derive(Debug, Default)]
434struct LineAggregate {
435    covered: bool,
436    measured: bool,
437    /// Numbers of the relation each is drawn from, in no order.
438    tests: Vec<u32>,
439    phases: Vec<u32>,
440    explicit_phases: Vec<u32>,
441}
442
443#[derive(Debug, Clone, PartialEq, Serialize)]
444#[serde(rename_all = "camelCase")]
445pub struct LineResult {
446    pub file: String,
447    pub line: usize,
448    pub covered: bool,
449    /// False when every obligation on this line was declined, which keeps the
450    /// line addressable while leaving it out of the covered/total counts. Not
451    /// serialized: it decides a total, it is not a fact about the line worth
452    /// publishing, and the limitation records already say why.
453    #[serde(skip)]
454    pub measured: bool,
455    pub tests: Vec<Id>,
456    pub runners: Vec<String>,
457    pub kinds: Vec<String>,
458    #[serde(skip_serializing_if = "Option::is_none")]
459    pub exclusive_kind: Option<String>,
460    pub phases: Vec<Id>,
461    pub confidence: CoverageConfidence,
462}
463
464#[derive(Debug, Clone, PartialEq, Serialize)]
465#[serde(rename_all = "camelCase")]
466pub struct TestDecisionResult {
467    pub id: String,
468    pub vectors: Vec<McdcVector>,
469}
470
471#[derive(Debug, Clone, PartialEq, Serialize)]
472#[serde(rename_all = "camelCase")]
473pub struct TestCoverageResult {
474    pub id: String,
475    pub name: String,
476    #[serde(skip_serializing_if = "Option::is_none")]
477    pub file: Option<String>,
478    #[serde(skip_serializing_if = "Option::is_none")]
479    pub title: Option<String>,
480    pub retries: Vec<usize>,
481    pub attempts: Vec<TestAttempt>,
482    pub outcome: String,
483    pub provenance: TestProvenance,
484    pub role: String,
485    /// `exact`, or `run-wide` when the test ran but nothing can say what it
486    /// reached. An empty `hits` means "reached nothing" only under `exact`.
487    pub attribution: String,
488    pub hits: Vec<Id>,
489    pub decisions: Vec<TestDecisionResult>,
490    pub lines: Vec<SourceLine>,
491}
492
493#[derive(Debug, Clone, PartialEq, Serialize)]
494#[serde(rename_all = "camelCase")]
495pub struct TestFileResult {
496    pub file: String,
497    pub tests: Vec<String>,
498    pub runners: Vec<String>,
499    pub kinds: Vec<String>,
500    pub lines: Vec<SourceLine>,
501}
502
503#[derive(Debug, Clone, PartialEq, Serialize)]
504#[serde(rename_all = "camelCase")]
505pub struct PhaseResult {
506    #[serde(flatten)]
507    pub phase: CoveragePhase,
508    pub test: Id,
509    pub hits: Vec<Id>,
510    pub decisions: Vec<TestDecisionResult>,
511    pub lines: Vec<SourceLine>,
512    pub browser_events: usize,
513    pub server_events: usize,
514    pub explicit_events: usize,
515    pub inferred_events: usize,
516    pub explicit_browser_events: usize,
517    pub inferred_browser_events: usize,
518    pub explicit_server_events: usize,
519    pub inferred_server_events: usize,
520}
521
522#[derive(Debug, Clone, PartialEq, Serialize)]
523#[serde(rename_all = "camelCase")]
524pub struct DimensionCoverage {
525    #[serde(skip_serializing_if = "Option::is_none")]
526    pub kind: Option<String>,
527    #[serde(skip_serializing_if = "Option::is_none")]
528    pub runner: Option<String>,
529    pub tests: usize,
530    pub setups: usize,
531    /// How many of `tests` have coverage of their own. The summary below is
532    /// computed over exactly these: a test whose reach nothing can narrow
533    /// contributes no hits, and counting it would report a suite that covers
534    /// everything as covering nothing.
535    pub attributed: usize,
536    pub summary: CoverageSummary,
537}
538
539#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
540#[serde(rename_all = "camelCase")]
541pub struct CoverageModel {
542    pub language: String,
543    pub name: String,
544    pub completeness_meaning: String,
545    pub measured: Vec<String>,
546    pub not_measured: Vec<String>,
547}
548
549#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
550#[serde(rename_all = "camelCase", deny_unknown_fields)]
551pub struct CoverageModelDeclaration {
552    pub language: String,
553    pub variant: String,
554    pub name: String,
555    pub completeness_meaning: String,
556    pub measured: Vec<String>,
557    pub not_measured: Vec<String>,
558}
559
560#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
561#[serde(rename_all = "camelCase", deny_unknown_fields)]
562pub struct PersistedCoverageModel {
563    pub schema_version: u32,
564    pub language: String,
565    pub variant: String,
566    pub name: String,
567    pub completeness_meaning: String,
568    pub measured: Vec<String>,
569    pub not_measured: Vec<String>,
570}
571
572impl PersistedCoverageModel {
573    pub fn from_declaration(value: &CoverageModelDeclaration) -> Result<Self, &'static str> {
574        let persisted = Self {
575            schema_version: COVERAGE_MODEL_SCHEMA_VERSION,
576            language: value.language.clone(),
577            variant: value.variant.clone(),
578            name: value.name.clone(),
579            completeness_meaning: value.completeness_meaning.clone(),
580            measured: value.measured.clone(),
581            not_measured: value.not_measured.clone(),
582        };
583        persisted.clone().into_declaration()?;
584        Ok(persisted)
585    }
586
587    fn into_declaration(self) -> Result<CoverageModelDeclaration, &'static str> {
588        if self.schema_version != COVERAGE_MODEL_SCHEMA_VERSION {
589            return Err("unsupported coverage model schema");
590        }
591        let valid_identifier = |value: &str| {
592            (1..=supercov_contracts::COVERAGE_MODEL_MAX_IDENTIFIER_BYTES).contains(&value.len())
593                && value.as_bytes()[0].is_ascii_lowercase()
594                && value.bytes().all(|byte| {
595                    byte.is_ascii_lowercase()
596                        || byte.is_ascii_digit()
597                        || matches!(byte, b'.' | b'+' | b'-')
598                })
599        };
600        let valid_description = |value: &str| {
601            !value.is_empty()
602                && value.trim().len() == value.len()
603                && value.len() <= supercov_contracts::COVERAGE_MODEL_MAX_DESCRIPTION_BYTES
604                && !value.chars().any(char::is_control)
605        };
606        if !valid_identifier(&self.language)
607            || !valid_identifier(&self.variant)
608            || !valid_description(&self.name)
609            || !valid_description(&self.completeness_meaning)
610            || self.measured.is_empty()
611            || self.measured.len() > supercov_contracts::COVERAGE_MODEL_MAX_SURFACES_PER_LIST
612            || self.not_measured.len() > supercov_contracts::COVERAGE_MODEL_MAX_SURFACES_PER_LIST
613            || self
614                .measured
615                .iter()
616                .chain(&self.not_measured)
617                .any(|item| !valid_description(item))
618        {
619            return Err("invalid coverage model declaration");
620        }
621        let measured = self.measured.iter().collect::<BTreeSet<_>>();
622        let not_measured = self.not_measured.iter().collect::<BTreeSet<_>>();
623        if measured.len() != self.measured.len()
624            || not_measured.len() != self.not_measured.len()
625            || !measured.is_disjoint(&not_measured)
626        {
627            return Err("invalid coverage model surface partition");
628        }
629        Ok(CoverageModelDeclaration {
630            language: self.language,
631            variant: self.variant,
632            name: self.name,
633            completeness_meaning: self.completeness_meaning,
634            measured: self.measured,
635            not_measured: self.not_measured,
636        })
637    }
638}
639
640#[derive(Debug, Clone, PartialEq, Serialize)]
641#[serde(rename_all = "camelCase")]
642pub struct CoverageView {
643    pub generated_at: String,
644    pub variant: String,
645    #[serde(skip_serializing_if = "Option::is_none")]
646    pub scope: Option<Value>,
647    pub model: CoverageModel,
648    #[serde(skip_serializing_if = "Option::is_none")]
649    pub integrity: Option<Value>,
650    pub limitations: Vec<Value>,
651    #[serde(skip_serializing_if = "Option::is_none")]
652    pub transport: Option<TransportStats>,
653    pub summary: CoverageSummary,
654    pub coverage_by_kind: Vec<DimensionCoverage>,
655    pub coverage_by_runner: Vec<DimensionCoverage>,
656    pub decisions: Vec<DecisionResult>,
657    pub points: Vec<PointResult>,
658    pub branches: Vec<BranchResult>,
659    pub tests: Vec<TestCoverageResult>,
660    pub test_files: Vec<TestFileResult>,
661    pub phases: Vec<PhaseResult>,
662    pub lines: Vec<LineResult>,
663}
664
665#[derive(Debug, Clone, PartialEq, Serialize)]
666#[serde(rename_all = "camelCase")]
667pub struct CoverageFilters {
668    pub passed: CoverageView,
669    pub failed: CoverageView,
670}
671
672#[derive(Debug, Clone, PartialEq, Serialize)]
673#[serde(rename_all = "camelCase")]
674pub struct CoverageReport {
675    #[serde(flatten)]
676    pub view: CoverageView,
677    #[serde(skip_serializing_if = "Option::is_none")]
678    pub execution: Option<ExecutionResult>,
679    pub filters: CoverageFilters,
680}
681
682#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
683#[serde(rename_all = "camelCase")]
684pub struct ExecutionResult {
685    pub test_exit_code: Option<i32>,
686    pub valid: bool,
687}
688
689#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
690#[serde(rename_all = "camelCase")]
691pub struct TransportStats {
692    pub processes: usize,
693    pub child_launches: usize,
694    pub remote_launches: usize,
695    pub workspace_capabilities: usize,
696    /// Processes that ran the workspace without Supercov's settings -- in a
697    /// container or VM it was mounted into -- and set themselves up from it.
698    /// Their coverage counts for the run and is credited to no test.
699    pub guest_processes: usize,
700    pub scoped_server_records: usize,
701    pub background_server_records: usize,
702    pub corrupt_records: usize,
703    pub corrupt_files: usize,
704}
705
706#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
707#[serde(untagged)]
708enum ExecutionSafeArgument {
709    Text(String),
710    Digest(ExecutionArgumentDigest),
711}
712
713#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
714#[serde(rename_all = "camelCase", deny_unknown_fields)]
715struct ExecutionArgumentDigest {
716    bytes: usize,
717    sha256: String,
718}
719
720#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
721#[serde(rename_all = "camelCase", deny_unknown_fields)]
722struct ExecutionCommandSummary {
723    #[serde(default)]
724    executable: Option<ExecutionSafeArgument>,
725    arguments: Vec<ExecutionSafeArgument>,
726    argument_count: usize,
727}
728
729#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
730#[serde(
731    tag = "event",
732    rename_all = "kebab-case",
733    rename_all_fields = "camelCase",
734    deny_unknown_fields
735)]
736enum ExecutionTraceEvent {
737    Process {
738        at: String,
739        pid: u32,
740        ppid: u32,
741        cwd: String,
742        command: ExecutionCommandSummary,
743        #[serde(default)]
744        entrypoint: Option<String>,
745    },
746    ChildLaunch {
747        at: String,
748        pid: u32,
749        ppid: u32,
750        method: String,
751        command: ExecutionSafeArgument,
752    },
753    RemoteLaunch {
754        at: String,
755        pid: u32,
756        ppid: u32,
757        command: ExecutionCommandSummary,
758        guest_root: String,
759    },
760    WorkspaceCapability {
761        at: String,
762        pid: u32,
763        ppid: u32,
764        host_root: String,
765        guest_root: String,
766        cache_identities: Vec<String>,
767    },
768    GuestProcess {
769        at: String,
770        pid: u32,
771        ppid: u32,
772        guest_root: String,
773    },
774}
775
776impl ExecutionTraceEvent {
777    fn kind(&self) -> &'static str {
778        match self {
779            Self::Process { .. } => "process",
780            Self::ChildLaunch { .. } => "child-launch",
781            Self::RemoteLaunch { .. } => "remote-launch",
782            Self::WorkspaceCapability { .. } => "workspace-capability",
783            Self::GuestProcess { .. } => "guest-process",
784        }
785    }
786}
787
788#[derive(Debug, Clone, PartialEq, Deserialize)]
789#[serde(rename_all = "camelCase", deny_unknown_fields)]
790pub struct CoverageReportRequest {
791    pub run_id: String,
792    pub manifest: CoverageManifest,
793    pub raw_results: Vec<RawTestResult>,
794    pub generated_at: String,
795    #[serde(default, skip_serializing_if = "Option::is_none")]
796    pub coverage_model: Option<CoverageModelDeclaration>,
797    #[serde(skip_serializing_if = "Option::is_none")]
798    pub integrity: Option<Value>,
799    #[serde(default, deserialize_with = "deserialize_exit_code")]
800    pub test_exit_code: ExitCodeInput,
801}
802
803#[derive(Debug, Clone, PartialEq, Deserialize)]
804#[serde(rename_all = "camelCase", deny_unknown_fields)]
805pub struct ArchiveReportRequest {
806    pub archive_path: PathBuf,
807    pub run_id: String,
808    pub generated_at: String,
809    #[serde(skip_serializing_if = "Option::is_none")]
810    pub integrity: Option<Value>,
811    #[serde(default, deserialize_with = "deserialize_exit_code")]
812    pub test_exit_code: ExitCodeInput,
813}
814
815#[derive(Debug, Clone, PartialEq, Eq, Default)]
816pub enum ExitCodeInput {
817    #[default]
818    Missing,
819    Present(Option<i32>),
820}
821
822fn deserialize_exit_code<'de, D>(deserializer: D) -> Result<ExitCodeInput, D::Error>
823where
824    D: serde::Deserializer<'de>,
825{
826    Option::<i32>::deserialize(deserializer).map(ExitCodeInput::Present)
827}
828
829#[derive(Debug, Clone, PartialEq, Eq)]
830pub enum ReportError {
831    Analysis(AnalysisError),
832    DecisionAnalysis {
833        decision_id: String,
834        error: AnalysisError,
835    },
836    InvalidEvent(String),
837    InvalidServerRecord(String),
838    InvalidArchive(String),
839    MissingManifest,
840    InvalidJson {
841        path: String,
842        reason: String,
843    },
844    ScopeMismatch {
845        expected: String,
846        actual: String,
847    },
848    NoEvidence(String),
849}
850
851impl From<AnalysisError> for ReportError {
852    fn from(value: AnalysisError) -> Self {
853        Self::Analysis(value)
854    }
855}
856
857#[derive(Clone, Default)]
858struct OrderedVectors {
859    values: Vec<McdcVector>,
860    indexes: HashMap<String, usize>,
861}
862
863impl OrderedVectors {
864    fn insert(&mut self, vector: &McdcVector) -> usize {
865        let key = vector_key(vector);
866        if let Some(index) = self.indexes.get(&key) {
867            return *index;
868        }
869        let index = self.values.len();
870        self.values.push(vector.clone());
871        self.indexes.insert(key, index);
872        index
873    }
874}
875
876#[derive(Clone)]
877struct MutableObservation {
878    vector: McdcVector,
879    /// Numbers of the view's test, phase and explicit phase relations, as
880    /// they arrive: sorted and made unique when the view is written.
881    tests: Vec<u32>,
882    phases: Vec<u32>,
883    explicit_phases: Vec<u32>,
884}
885
886#[derive(Clone)]
887struct MutableTest {
888    id: String,
889    name: String,
890    file: Option<String>,
891    title: Option<String>,
892    retries: BTreeSet<usize>,
893    attempts: BTreeMap<usize, TestAttempt>,
894    unstarted: bool,
895    runner_reported_flaky: bool,
896    provenance: TestProvenance,
897    role: String,
898    attribution: String,
899    /// Hit numbers as they arrive, repeats included: sorted and made unique
900    /// once, when the view is written.
901    hits: Vec<usize>,
902    decisions: BTreeMap<String, OrderedVectors>,
903}
904
905#[derive(Clone)]
906struct MutablePhase {
907    phase: CoveragePhase,
908    test: Id,
909    hits: Vec<usize>,
910    decisions: BTreeMap<String, OrderedVectors>,
911    browser_events: usize,
912    server_events: usize,
913    explicit_events: usize,
914    inferred_events: usize,
915    explicit_browser_events: usize,
916    inferred_browser_events: usize,
917    explicit_server_events: usize,
918    inferred_server_events: usize,
919}
920
921fn vector_key(vector: &McdcVector) -> String {
922    let mut key = String::with_capacity(vector.values.len() + 2);
923    for value in &vector.values {
924        key.push(match value {
925            None => '-',
926            Some(false) => 'F',
927            Some(true) => 'T',
928        });
929    }
930    key.push(':');
931    key.push(if vector.outcome { 'T' } else { 'F' });
932    key
933}
934
935fn sorted<T: Clone + Ord>(values: &BTreeSet<T>) -> Vec<T> {
936    values.iter().cloned().collect()
937}
938
939fn record_attempt(test: &mut MutableTest, raw: &RawTestResult) {
940    let (Some(retry), Some(raw_status)) = (raw.retry, raw.status.as_ref()) else {
941        return;
942    };
943    let previous = test.attempts.get(&retry);
944    // A later record does not pass an attempt an earlier one failed: the same
945    // tests run twice under one identity fail if either execution did.
946    let status =
947        if raw_status == "unknown" || previous.is_some_and(|attempt| attempt.status == "failed") {
948            previous.map_or_else(|| raw_status.clone(), |attempt| attempt.status.clone())
949        } else {
950            raw_status.clone()
951        };
952    let expected_status = raw
953        .expected_status
954        .clone()
955        .or_else(|| previous.and_then(|attempt| attempt.expected_status.clone()));
956    test.attempts.insert(
957        retry,
958        TestAttempt {
959            retry,
960            status,
961            expected_status,
962        },
963    );
964}
965
966fn effective_attempt_status(attempt: &TestAttempt) -> &str {
967    if attempt.expected_status.as_deref() == Some("failed") {
968        match attempt.status.as_str() {
969            "failed" => "passed",
970            "passed" => "failed",
971            status => status,
972        }
973    } else {
974        attempt.status.as_str()
975    }
976}
977
978fn test_outcome(test: &MutableTest) -> String {
979    let Some(terminal) = test.attempts.values().next_back() else {
980        return if test.unstarted {
981            "unstarted".into()
982        } else {
983            "unknown".into()
984        };
985    };
986    let terminal_status = effective_attempt_status(terminal);
987    if terminal_status == "passed"
988        && (test.runner_reported_flaky
989            || test
990                .attempts
991                .values()
992                .take(test.attempts.len().saturating_sub(1))
993                .any(|attempt| effective_attempt_status(attempt) != "passed"))
994    {
995        "flaky".into()
996    } else {
997        terminal_status.into()
998    }
999}
1000
1001fn raw_test_id(raw: &RawTestResult) -> &str {
1002    raw.test_id.as_deref().unwrap_or(&raw.test)
1003}
1004
1005/// Borrowed rather than copied: a view only reads its results, and copying
1006/// every result of a 3,900-test run to build the passing view cost a sixth of
1007/// the analysis.
1008pub fn passing_coverage_results(raw_results: &[RawTestResult]) -> Vec<&RawTestResult> {
1009    let mut attempts: BTreeMap<(String, usize), (BTreeSet<String>, bool)> = BTreeMap::new();
1010    for raw in raw_results {
1011        let Some(retry) = raw.retry else {
1012            continue;
1013        };
1014        let entry = attempts
1015            .entry((raw_test_id(raw).into(), retry))
1016            .or_default();
1017        if let Some(status) = &raw.status {
1018            entry.0.insert(status.clone());
1019        }
1020        entry.1 |= raw.expected_status.as_deref() == Some("failed");
1021    }
1022    let mut terminal_retries = BTreeMap::<String, usize>::new();
1023    for (test, retry) in attempts.keys() {
1024        terminal_retries
1025            .entry(test.clone())
1026            .and_modify(|value| *value = (*value).max(*retry))
1027            .or_insert(*retry);
1028    }
1029    let accepted = terminal_retries
1030        .into_iter()
1031        .filter_map(|(test, retry)| {
1032            let (statuses, expected_failure) = attempts.get(&(test.clone(), retry))?;
1033            (statuses.contains("passed") && !expected_failure).then_some((test, retry))
1034        })
1035        .collect::<BTreeSet<_>>();
1036    raw_results
1037        .iter()
1038        .filter(|raw| {
1039            raw.retry
1040                .is_some_and(|retry| accepted.contains(&(raw_test_id(raw).into(), retry)))
1041        })
1042        .collect()
1043}
1044
1045pub fn failed_coverage_results(raw_results: &[RawTestResult]) -> Vec<&RawTestResult> {
1046    let mut attempts = BTreeMap::<(String, usize), Vec<&RawTestResult>>::new();
1047    for raw in raw_results {
1048        if let Some(retry) = raw.retry {
1049            attempts
1050                .entry((raw_test_id(raw).to_owned(), retry))
1051                .or_default()
1052                .push(raw);
1053        }
1054    }
1055    let failed = attempts
1056        .into_iter()
1057        .filter_map(|(identity, records)| {
1058            // Runner reporters carry expected-status semantics while hook
1059            // evidence records often do not. Treat reporter records as the
1060            // authority for the attempt outcome, then retain every companion
1061            // evidence record only after the attempt is classified.
1062            let authoritative = records
1063                .iter()
1064                .copied()
1065                .filter(|raw| raw.expected_status.is_some())
1066                .collect::<Vec<_>>();
1067            let authoritative = if authoritative.is_empty() {
1068                records
1069            } else {
1070                authoritative
1071            };
1072            authoritative
1073                .iter()
1074                .any(
1075                    |raw| match (raw.status.as_deref(), raw.expected_status.as_deref()) {
1076                        (Some("failed"), Some("failed")) => false,
1077                        (Some("passed"), Some("failed")) => true,
1078                        (Some("failed"), _) => true,
1079                        _ => false,
1080                    },
1081                )
1082                .then_some(identity)
1083        })
1084        .collect::<BTreeSet<_>>();
1085    raw_results
1086        .iter()
1087        .filter(|raw| {
1088            raw.retry
1089                .is_some_and(|retry| failed.contains(&(raw_test_id(raw).into(), retry)))
1090        })
1091        .collect()
1092}
1093
1094pub(crate) fn javascript_coverage_model() -> CoverageModelDeclaration {
1095    CoverageModelDeclaration {
1096        language: "javascript".into(),
1097        variant: "masking-short-circuit".into(),
1098        name: "coverage-completeness-v2".into(),
1099        completeness_meaning: "Every obligation in the measured model was observed by at least one existing test; test assertions and product correctness are separate assumptions.".into(),
1100        measured: [
1101            "executable source lines",
1102            "executable statements",
1103            "function entries",
1104            "true and false outcomes of if, ternary, while, do/while, and classic for decisions",
1105            "true and false outcomes of every atomic condition in those decisions",
1106            "masking MC/DC independence for every atomic condition in those decisions",
1107            "short-circuit and right-evaluated selections for &&, ||, and ?? value expressions, including JSX",
1108            "short-circuit and evaluated alternatives for logical assignments and optional chains",
1109            "provided and default-evaluated parameter and destructuring values",
1110            "try success and catch entry",
1111            "zero and entered for-in/for-of loops",
1112            "entered switch cases, defaults, and implicit no-match alternatives",
1113        ]
1114        .into_iter()
1115        .map(str::to_owned)
1116        .collect(),
1117        not_measured: [
1118            "all input values or semantic input partitions",
1119            "all execution paths or ordering/concurrency interleavings",
1120            "destructuring defaults in classic for initializers (reported as blockers when discovered)",
1121            "the internal statements and decisions of runtime-generated eval/Function source",
1122            "mutation score or assertion fault-detection strength",
1123        ]
1124        .into_iter()
1125        .map(str::to_owned)
1126        .collect(),
1127    }
1128}
1129
1130/// One file's counts, derived by the same function that produced the run's
1131/// totals.
1132///
1133/// Every feature that judges a run -- a threshold gate, a changed-line check,
1134/// an export, an HTML report -- has to agree with the summary it sits beside.
1135/// Re-deriving a file's denominator independently is how a gate and a report
1136/// come to disagree about the same run, so this filters the same results and
1137/// calls the same core.
1138pub fn coverage_summary_for_file(
1139    view: &CoverageView,
1140    file: &str,
1141) -> Result<CoverageSummary, ReportError> {
1142    let decisions = view
1143        .decisions
1144        .iter()
1145        .filter(|decision| decision.meta.file == file)
1146        .cloned()
1147        .collect::<Vec<_>>();
1148    let points = view
1149        .points
1150        .iter()
1151        .filter(|point| point.meta.file == file)
1152        .cloned()
1153        .collect::<Vec<_>>();
1154    let branches = view
1155        .branches
1156        .iter()
1157        .filter(|branch| branch.meta.file == file)
1158        .cloned()
1159        .collect::<Vec<_>>();
1160    let lines = view
1161        .lines
1162        .iter()
1163        .filter(|line| line.file == file)
1164        .cloned()
1165        .collect::<Vec<_>>();
1166    summary_for_results(&decisions, &points, &branches, &lines, None)
1167}
1168
1169/// The entries whose coverage a kind's row counts: every test of the view,
1170/// and the setup scopes of a kind that has tests. A kind's row counts both.
1171/// Leaving a test file's own setup out of this put one line in the `unit` row
1172/// and in `no test`, and the rows added up to more than the run's total. A
1173/// setup scope of a kind with no test has no row: a server started there is
1174/// in the total only, and that is what `no test` is for.
1175pub(crate) fn entries_in_kind_rows(view: &CoverageView) -> BTreeSet<String> {
1176    let with_tests = view
1177        .tests
1178        .iter()
1179        .filter(|test| test.role == "test")
1180        .map(|test| test.provenance.kind.as_str())
1181        .collect::<BTreeSet<_>>();
1182    view.tests
1183        .iter()
1184        .filter(|test| {
1185            coverage_is_its_own(&test.attribution)
1186                && (test.role == "test"
1187                    || (test.role == "setup" && with_tests.contains(test.provenance.kind.as_str())))
1188        })
1189        .map(|test| test.id.clone())
1190        .collect()
1191}
1192
1193/// What the tests of a view cover between them, leaving out what ran while
1194/// no test was running: start-up, module loading, work between tests.
1195pub(crate) fn summary_for_tests(view: &CoverageView) -> Result<CoverageSummary, ReportError> {
1196    let selected = entries_in_kind_rows(view);
1197    summary_for_results(
1198        &view.decisions,
1199        &view.points,
1200        &view.branches,
1201        &view.lines,
1202        Some(&selected),
1203    )
1204}
1205
1206fn summary_for_results(
1207    decisions: &[DecisionResult],
1208    points: &[PointResult],
1209    branches: &[BranchResult],
1210    lines: &[LineResult],
1211    test_ids: Option<&BTreeSet<String>>,
1212) -> Result<CoverageSummary, ReportError> {
1213    // Hashed once: every obligation asks it about each of its tests.
1214    let test_ids = test_ids.map(|ids| {
1215        ids.iter()
1216            .map(String::as_str)
1217            .collect::<crate::interned::FastSet<&str>>()
1218    });
1219    let includes = |tests: &[Id], covered: bool| {
1220        test_ids.as_ref().map_or(covered, |selected| {
1221            tests.iter().any(|test| selected.contains(test.as_str()))
1222        })
1223    };
1224    let input = CoverageCoreInput {
1225        decisions: decisions
1226            .iter()
1227            .map(|decision| DecisionCoverage {
1228                condition_count: decision.meta.conditions.len(),
1229                vectors: decision
1230                    .vector_observations
1231                    .iter()
1232                    .filter(|observation| includes(&observation.tests, true))
1233                    .map(|observation| observation.vector.clone())
1234                    .collect(),
1235            })
1236            .collect(),
1237        points: points
1238            .iter()
1239            .map(|point| PointCoverage {
1240                kind: point.meta.kind.clone(),
1241                covered: includes(&point.tests, point.covered),
1242            })
1243            .collect(),
1244        branches: branches
1245            .iter()
1246            .map(|branch| BranchCoverage {
1247                kind: branch.meta.kind.clone(),
1248                alternatives: branch
1249                    .alternatives
1250                    .iter()
1251                    .map(|alternative| includes(&alternative.tests, alternative.covered))
1252                    .collect(),
1253            })
1254            .collect(),
1255        // A line every frontend declined carries no coverage question, so it
1256        // is absent from the total rather than counted as uncovered.
1257        lines: lines
1258            .iter()
1259            .filter(|line| line.measured)
1260            .map(|line| includes(&line.tests, line.covered))
1261            .collect(),
1262    };
1263    Ok(analyze_core(&input)?.summary)
1264}
1265
1266/// Recompute every structural coverage metric for an arbitrary set of test,
1267/// setup, and background evidence identities. MC/DC witnesses are rebuilt
1268/// from the selected observations; existing aggregate verdicts are never
1269/// reused.
1270pub fn coverage_summary_for_tests(
1271    view: &CoverageView,
1272    test_ids: &BTreeSet<String>,
1273) -> Result<CoverageSummary, ReportError> {
1274    summary_for_results(
1275        &view.decisions,
1276        &view.points,
1277        &view.branches,
1278        &view.lines,
1279        Some(test_ids),
1280    )
1281}
1282
1283/// Whether a manifest limitation blocks measurement of the denominator, as
1284/// opposed to declaring a boundary of it. Absent means blocking.
1285pub fn blocking_limitation(limitation: &Value) -> bool {
1286    limitation
1287        .get("blocking")
1288        .and_then(Value::as_bool)
1289        .unwrap_or(true)
1290}
1291
1292fn hash_slot<'m, V: Default, S: std::hash::BuildHasher>(
1293    map: &'m mut HashMap<String, V, S>,
1294    key: &str,
1295) -> &'m mut V {
1296    if !map.contains_key(key) {
1297        map.insert(key.to_owned(), V::default());
1298    }
1299    map.get_mut(key).expect("slot was inserted")
1300}
1301
1302fn tree_slot<'m, V: Default>(map: &'m mut BTreeMap<String, V>, key: &str) -> &'m mut V {
1303    if !map.contains_key(key) {
1304        map.insert(key.to_owned(), V::default());
1305    }
1306    map.get_mut(key).expect("slot was inserted")
1307}
1308
1309/// The phase an event belongs to: its own, or the last to start before it.
1310fn correlate_event<'a>(
1311    event: &'a RuntimeEvent,
1312    ordered_phases: &'a [CoveragePhase],
1313) -> Option<&'a str> {
1314    event.phase_id.as_deref().or_else(|| {
1315        ordered_phases
1316            .iter()
1317            .take_while(|phase| phase.started_at_ms <= event.timestamp_ms)
1318            .last()
1319            .map(|phase| phase.id.as_str())
1320    })
1321}
1322
1323/// One lookup per hit while ingesting evidence. All hit relations share these
1324/// dense numbers, avoiding repeated string hashing and tree comparisons. Even
1325/// IDs absent from the manifest are retained; output restores lexical ordering.
1326#[derive(Default)]
1327struct HitIds {
1328    names: Vec<Id>,
1329    numbers: FastMap<String, usize>,
1330}
1331
1332impl HitIds {
1333    fn number(&mut self, name: &str, ids: &mut Interner) -> usize {
1334        if let Some(number) = self.numbers.get(name) {
1335            return *number;
1336        }
1337        let number = self.names.len();
1338        self.names.push(ids.id(name));
1339        self.numbers.insert(name.to_owned(), number);
1340        number
1341    }
1342
1343    /// Each hit number's position in id order: hits sort by these numbers
1344    /// instead of by comparing their text, per test and per phase.
1345    fn ranks(&self) -> Vec<u32> {
1346        let mut order = (0..self.names.len()).collect::<Vec<_>>();
1347        order.sort_unstable_by(|left, right| self.names[*left].cmp(&self.names[*right]));
1348        let mut rank = vec![0_u32; self.names.len()];
1349        for (position, number) in order.into_iter().enumerate() {
1350            rank[number] = position as u32;
1351        }
1352        rank
1353    }
1354
1355    /// `sorted`, by precomputed rank.
1356    fn sorted_by(&self, mut numbers: Vec<usize>, rank: &[u32]) -> Vec<Id> {
1357        numbers.sort_unstable_by_key(|number| rank[*number]);
1358        numbers.dedup();
1359        numbers
1360            .into_iter()
1361            .map(|number| self.names[number].clone())
1362            .collect()
1363    }
1364
1365    #[cfg(test)]
1366    fn sorted(&self, numbers: BTreeSet<usize>) -> Vec<Id> {
1367        let mut names = numbers
1368            .into_iter()
1369            .map(|n| self.names[n].clone())
1370            .collect::<Vec<_>>();
1371        names.sort_unstable();
1372        names
1373    }
1374}
1375
1376/// Which tests or phases reached each obligation. Both sides are numbered
1377/// while ingesting evidence, then restored to sorted ID sets for the report.
1378#[derive(Default)]
1379struct References {
1380    names: Vec<Id>,
1381    numbers: FastMap<Id, u32>,
1382    last: Option<u32>,
1383    by_obligation: Vec<Vec<u32>>,
1384}
1385
1386impl References {
1387    /// The number standing for a test or phase id. The same id usually
1388    /// arrives many times in a row, so the last one is checked first.
1389    fn number(&mut self, name: &str, ids: &mut Interner) -> u32 {
1390        if let Some(number) = self.last
1391            && self.names[number as usize] == name
1392        {
1393            return number;
1394        }
1395        let number = match self.numbers.get(name) {
1396            Some(number) => *number,
1397            None => {
1398                let number = self.names.len() as u32;
1399                let id = ids.id(name);
1400                self.names.push(id.clone());
1401                self.numbers.insert(id, number);
1402                number
1403            }
1404        };
1405        self.last = Some(number);
1406        number
1407    }
1408
1409    fn add(&mut self, obligation: usize, name: &str, ids: &mut Interner) {
1410        let number = self.number(name, ids);
1411        if self.by_obligation.len() <= obligation {
1412            self.by_obligation.resize_with(obligation + 1, Vec::new);
1413        }
1414        let reached = &mut self.by_obligation[obligation];
1415        if reached.last() != Some(&number) {
1416            reached.push(number);
1417        }
1418    }
1419
1420    fn into_relation(self, hits: &HitIds) -> Relation {
1421        let mut order = (0..self.names.len()).collect::<Vec<_>>();
1422        order.sort_unstable_by(|left, right| self.names[*left].cmp(&self.names[*right]));
1423        let mut rank = vec![0_u32; self.names.len()];
1424        for (position, number) in order.into_iter().enumerate() {
1425            rank[number] = position as u32;
1426        }
1427        let mut relation = Relation {
1428            names: self.names,
1429            rank,
1430            by_hit: HashMap::new(),
1431            none: Reached::default(),
1432        };
1433        for (obligation, reached) in self.by_obligation.into_iter().enumerate() {
1434            if !reached.is_empty() {
1435                let reached = relation.reached(reached);
1436                relation
1437                    .by_hit
1438                    .insert(hits.names[obligation].to_string(), reached);
1439            }
1440        }
1441        relation
1442    }
1443}
1444
1445/// A `References` restored for the report: what reached each obligation,
1446/// and the table its numbers index.
1447struct Relation {
1448    names: Vec<Id>,
1449    /// Each number's position in id order.
1450    rank: Vec<u32>,
1451    by_hit: HashMap<String, Reached>,
1452    none: Reached,
1453}
1454
1455impl Relation {
1456    /// What reached obligation `id`: nothing, for one no test reached.
1457    fn of(&self, id: &str) -> &Reached {
1458        self.by_hit.get(id).unwrap_or(&self.none)
1459    }
1460
1461    /// Numbers of this relation as the ids they stand for, in id order and
1462    /// once each: the set the report writes.
1463    fn reached(&self, mut numbers: Vec<u32>) -> Reached {
1464        numbers.sort_unstable_by_key(|number| self.rank[*number as usize]);
1465        numbers.dedup();
1466        Reached {
1467            names: numbers
1468                .iter()
1469                .map(|number| self.names[*number as usize].clone())
1470                .collect(),
1471            numbers,
1472        }
1473    }
1474}
1475
1476/// Which tests or phases reached one obligation: their ids in id order, and
1477/// beside each the number its relation gave it.
1478#[derive(Default)]
1479struct Reached {
1480    names: Vec<Id>,
1481    numbers: Vec<u32>,
1482}
1483
1484/// What confidence reads of one test.
1485struct TestTraits<'t> {
1486    setup: bool,
1487    background: bool,
1488    runner: &'t str,
1489    kind: &'t str,
1490}
1491
1492impl<'t> TestTraits<'t> {
1493    fn of(test: &'t MutableTest) -> Self {
1494        Self {
1495            setup: test.role == "setup",
1496            background: test.role == "background",
1497            runner: &test.provenance.runner,
1498            kind: &test.provenance.kind,
1499        }
1500    }
1501}
1502
1503/// How a point, alternative, line or vector was reached, from the tests
1504/// and phases that reached it: read from per-number tables, since a run
1505/// mentions its tests millions of times and a lookup per mention hashed an
1506/// id each time.
1507fn confidence_from(
1508    tests: &Reached,
1509    phases: &Reached,
1510    explicit: &Reached,
1511    test_traits: &[Option<TestTraits<'_>>],
1512    phase_kinds: &[Option<&str>],
1513    explicit_kinds: &[Option<&str>],
1514) -> CoverageConfidence {
1515    let mut has_test = false;
1516    let mut setup_roles = true;
1517    let mut background_roles = true;
1518    let mut runners = BTreeSet::new();
1519    let mut kinds = BTreeSet::new();
1520    for number in &tests.numbers {
1521        if let Some(test) = &test_traits[*number as usize] {
1522            has_test = true;
1523            setup_roles &= test.setup;
1524            background_roles &= test.background;
1525            runners.insert(test.runner);
1526            kinds.insert(test.kind);
1527        }
1528    }
1529    let mut has_phase = false;
1530    let mut setup_phases = true;
1531    let mut background_phases = true;
1532    for number in &phases.numbers {
1533        if let Some(kind) = phase_kinds[*number as usize] {
1534            has_phase = true;
1535            setup_phases &= kind == "setup";
1536            background_phases &= kind == "background";
1537        }
1538    }
1539    let has_action = explicit
1540        .numbers
1541        .iter()
1542        .any(|number| explicit_kinds[*number as usize] == Some("action"));
1543    let level = if tests.names.is_empty() {
1544        "unexecuted"
1545    } else if has_action {
1546        "action"
1547    } else {
1548        "executed"
1549    };
1550    CoverageConfidence {
1551        level: level.into(),
1552        setup_only: if has_phase {
1553            setup_phases
1554        } else {
1555            has_test && setup_roles
1556        },
1557        background_only: if has_phase {
1558            background_phases
1559        } else {
1560            has_test && background_roles
1561        },
1562        asserted: false,
1563        tests: tests.names.clone(),
1564        asserted_tests: vec![],
1565        runners: runners.into_iter().map(str::to_owned).collect(),
1566        e2e: kinds.contains("e2e"),
1567        kinds: kinds.into_iter().map(str::to_owned).collect(),
1568    }
1569}
1570
1571pub fn create_coverage_view(
1572    manifest: &CoverageManifest,
1573    raw_results: &[RawTestResult],
1574    generated_at: &str,
1575) -> Result<CoverageView, ReportError> {
1576    create_coverage_view_with_model(
1577        manifest,
1578        &raw_results.iter().collect::<Vec<_>>(),
1579        generated_at,
1580        &javascript_coverage_model(),
1581        &mut Interner::default(),
1582    )
1583}
1584
1585fn create_coverage_view_with_model(
1586    manifest: &CoverageManifest,
1587    raw_results: &[&RawTestResult],
1588    generated_at: &str,
1589    coverage_model: &CoverageModelDeclaration,
1590    ids: &mut Interner,
1591) -> Result<CoverageView, ReportError> {
1592    let mut decision_metadata = manifest.decisions.clone();
1593    let decision_indexes = decision_metadata
1594        .iter()
1595        .enumerate()
1596        .map(|(index, meta)| (meta.id.clone(), index))
1597        .collect::<HashMap<_, _>>();
1598    let manifest_files = manifest
1599        .decisions
1600        .iter()
1601        .map(|meta| meta.file.clone())
1602        .chain(manifest.points.iter().map(|meta| meta.file.clone()))
1603        .chain(manifest.branches.iter().map(|meta| meta.file.clone()))
1604        .chain(
1605            manifest
1606                .scope
1607                .as_ref()
1608                .and_then(|scope| scope.get("entries"))
1609                .and_then(Value::as_array)
1610                .into_iter()
1611                .flatten()
1612                .filter(|entry| entry.get("status").and_then(Value::as_str) == Some("included"))
1613                .filter_map(|entry| entry.get("file").and_then(Value::as_str).map(str::to_owned)),
1614        )
1615        .collect::<BTreeSet<_>>();
1616    let mut vectors_by_decision = FastMap::<String, Vec<MutableObservation>>::default();
1617    let mut vector_indexes = FastMap::<String, FastMap<String, usize>>::default();
1618    // Numbers of `tests_by_hit`'s tests, as they arrive.
1619    let mut tests_by_decision = FastMap::<String, Vec<u32>>::default();
1620    let mut tests_by_hit = References::default();
1621    let mut hit_ids = HitIds::default();
1622    let mut tests_by_id = FastMap::<Id, MutableTest>::default();
1623    let mut test_order = Vec::<Id>::new();
1624    let mut phases_by_id = FastMap::<Id, MutablePhase>::default();
1625    let mut phases_by_hit = References::default();
1626    let mut explicit_phases_by_hit = References::default();
1627
1628    for raw in raw_results {
1629        let id = ids.id(raw_test_id(raw));
1630        if !tests_by_id.contains_key(&id) {
1631            test_order.push(id.clone());
1632            tests_by_id.insert(
1633                id.clone(),
1634                MutableTest {
1635                    id: id.to_string(),
1636                    name: raw.test.clone(),
1637                    file: raw.test_file.clone(),
1638                    title: raw.title.clone(),
1639                    retries: raw.retry.into_iter().collect(),
1640                    attempts: BTreeMap::new(),
1641                    unstarted: raw.status.as_deref() == Some("unstarted"),
1642                    runner_reported_flaky: raw.flaky,
1643                    provenance: raw.provenance.clone(),
1644                    role: raw.role.clone(),
1645                    attribution: raw.attribution.clone(),
1646                    hits: Vec::new(),
1647                    decisions: BTreeMap::new(),
1648                },
1649            );
1650        }
1651        let test = tests_by_id.get_mut(&id).expect("test was inserted");
1652        // A test's records can disagree about how exactly its coverage is its
1653        // own, and the least exact one is true of the whole: Playwright's
1654        // outcome record says nothing about coverage and often arrives first,
1655        // before the record that says a worker could not be read.
1656        test.attribution = least_exact(&test.attribution, &raw.attribution);
1657        test.unstarted |= raw.status.as_deref() == Some("unstarted");
1658        if let Some(retry) = raw.retry {
1659            test.retries.insert(retry);
1660        }
1661        test.runner_reported_flaky |= raw.flaky;
1662        record_attempt(test, raw);
1663
1664        let mut ordered_phases = raw.phases.clone();
1665        ordered_phases.sort_by_key(|phase| phase.started_at_ms);
1666        for phase in &ordered_phases {
1667            phases_by_id.insert(
1668                ids.id(&phase.id),
1669                MutablePhase {
1670                    phase: phase.clone(),
1671                    test: id.clone(),
1672                    hits: Vec::new(),
1673                    decisions: BTreeMap::new(),
1674                    browser_events: 0,
1675                    server_events: 0,
1676                    explicit_events: 0,
1677                    inferred_events: 0,
1678                    explicit_browser_events: 0,
1679                    inferred_browser_events: 0,
1680                    explicit_server_events: 0,
1681                    inferred_server_events: 0,
1682                },
1683            );
1684        }
1685
1686        let correlate = |event: &RuntimeEvent| {
1687            event.phase_id.clone().or_else(|| {
1688                ordered_phases
1689                    .iter()
1690                    .take_while(|phase| phase.started_at_ms <= event.timestamp_ms)
1691                    .last()
1692                    .map(|phase| phase.id.clone())
1693            })
1694        };
1695
1696        let snapshots = raw
1697            .runtime
1698            .iter()
1699            .map(|snapshot| (snapshot, false))
1700            .chain(raw.browser.iter().map(|snapshot| (snapshot, true)));
1701        for (snapshot, browser) in snapshots {
1702            for decision in &snapshot.decisions {
1703                let Some(index) = decision_indexes.get(&decision.meta.id).copied() else {
1704                    if manifest_files.contains(&decision.meta.file) {
1705                        return Err(ReportError::InvalidServerRecord(format!(
1706                            "decision {} is absent from the frozen manifest",
1707                            decision.meta.id
1708                        )));
1709                    }
1710                    continue;
1711                };
1712                if decision_metadata[index] != decision.meta {
1713                    return Err(ReportError::InvalidServerRecord(format!(
1714                        "decision {} metadata differs from the frozen manifest",
1715                        decision.meta.id
1716                    )));
1717                }
1718                for vector in &decision.vectors {
1719                    let key = vector_key(vector);
1720                    let indexes = hash_slot(&mut vector_indexes, &decision.meta.id);
1721                    let observations = hash_slot(&mut vectors_by_decision, &decision.meta.id);
1722                    let observation_index = *indexes.entry(key).or_insert_with(|| {
1723                        observations.push(MutableObservation {
1724                            vector: vector.clone(),
1725                            tests: Vec::new(),
1726                            phases: Vec::new(),
1727                            explicit_phases: Vec::new(),
1728                        });
1729                        observations.len() - 1
1730                    });
1731                    observations[observation_index]
1732                        .tests
1733                        .push(tests_by_hit.number(&id, ids));
1734                    tree_slot(
1735                        &mut tests_by_id.get_mut(&id).expect("registered test").decisions,
1736                        &decision.meta.id,
1737                    )
1738                    .insert(vector);
1739                }
1740                if !decision.vectors.is_empty() {
1741                    hash_slot(&mut tests_by_decision, &decision.meta.id)
1742                        .push(tests_by_hit.number(&id, ids));
1743                }
1744            }
1745            let test_hits = &mut tests_by_id.get_mut(&id).expect("registered test").hits;
1746            for hit in &snapshot.hits {
1747                let hit = hit_ids.number(hit, ids);
1748                tests_by_hit.add(hit, &id, ids);
1749                test_hits.push(hit);
1750            }
1751            for event in &snapshot.events {
1752                let explicit = event.phase_id.is_some();
1753                let Some(phase_id) = correlate_event(event, &ordered_phases) else {
1754                    continue;
1755                };
1756                let Some(phase) = phases_by_id.get_mut(phase_id) else {
1757                    continue;
1758                };
1759                if event.environment == "browser" {
1760                    phase.browser_events += 1;
1761                    if explicit {
1762                        phase.explicit_browser_events += 1;
1763                    } else {
1764                        phase.inferred_browser_events += 1;
1765                    }
1766                } else {
1767                    phase.server_events += 1;
1768                    if explicit {
1769                        phase.explicit_server_events += 1;
1770                    } else {
1771                        phase.inferred_server_events += 1;
1772                    }
1773                }
1774                if explicit {
1775                    phase.explicit_events += 1;
1776                } else {
1777                    phase.inferred_events += 1;
1778                }
1779                if event.event_type == "hit" {
1780                    let hit = hit_ids.number(&event.id, ids);
1781                    phase.hits.push(hit);
1782                    phases_by_hit.add(hit, phase_id, ids);
1783                    if explicit {
1784                        explicit_phases_by_hit.add(hit, phase_id, ids);
1785                    }
1786                } else if event.event_type == "decision" {
1787                    let vector = event
1788                        .vector
1789                        .as_ref()
1790                        .ok_or_else(|| ReportError::InvalidEvent(event.id.clone()))?;
1791                    tree_slot(&mut phase.decisions, &event.id).insert(vector);
1792                    if let Some(index) = vector_indexes
1793                        .get(&event.id)
1794                        .and_then(|indexes| indexes.get(&vector_key(vector)))
1795                        .copied()
1796                        && let Some(observation) = vectors_by_decision
1797                            .get_mut(&event.id)
1798                            .and_then(|observations| observations.get_mut(index))
1799                    {
1800                        observation.phases.push(phases_by_hit.number(phase_id, ids));
1801                        if explicit {
1802                            observation
1803                                .explicit_phases
1804                                .push(explicit_phases_by_hit.number(phase_id, ids));
1805                        }
1806                    }
1807                } else {
1808                    return Err(ReportError::InvalidEvent(event.event_type.clone()));
1809                }
1810            }
1811            // A snapshot that names its phase: each hit and each decision
1812            // vector is an explicit event of it, counted and related exactly
1813            // as the event the frontend no longer writes would have been.
1814            if let Some(phase_id) = snapshot.phase_id.as_deref()
1815                && let Some(phase) = phases_by_id.get_mut(phase_id)
1816            {
1817                let observed = snapshot.hits.len()
1818                    + snapshot
1819                        .decisions
1820                        .iter()
1821                        .map(|decision| decision.vectors.len())
1822                        .sum::<usize>();
1823                if browser {
1824                    phase.browser_events += observed;
1825                    phase.explicit_browser_events += observed;
1826                } else {
1827                    phase.server_events += observed;
1828                    phase.explicit_server_events += observed;
1829                }
1830                phase.explicit_events += observed;
1831                for hit in &snapshot.hits {
1832                    let hit = hit_ids.number(hit, ids);
1833                    phase.hits.push(hit);
1834                    phases_by_hit.add(hit, phase_id, ids);
1835                    explicit_phases_by_hit.add(hit, phase_id, ids);
1836                }
1837                for decision in &snapshot.decisions {
1838                    let id = &decision.meta.id;
1839                    for vector in &decision.vectors {
1840                        tree_slot(&mut phase.decisions, id).insert(vector);
1841                        if let Some(index) = vector_indexes
1842                            .get(id)
1843                            .and_then(|indexes| indexes.get(&vector_key(vector)))
1844                            .copied()
1845                            && let Some(observation) = vectors_by_decision
1846                                .get_mut(id)
1847                                .and_then(|observations| observations.get_mut(index))
1848                        {
1849                            observation.phases.push(phases_by_hit.number(phase_id, ids));
1850                            observation
1851                                .explicit_phases
1852                                .push(explicit_phases_by_hit.number(phase_id, ids));
1853                        }
1854                    }
1855                }
1856            }
1857        }
1858
1859        for record in &raw.server {
1860            let (record_id, decision) = if record.record_type == "decision" {
1861                let meta = record
1862                    .meta
1863                    .as_ref()
1864                    .ok_or_else(|| ReportError::InvalidServerRecord("missing meta".into()))?;
1865                let vector = record
1866                    .vector
1867                    .as_ref()
1868                    .ok_or_else(|| ReportError::InvalidServerRecord("missing vector".into()))?;
1869                let Some(index) = decision_indexes.get(&meta.id).copied() else {
1870                    if manifest_files.contains(&meta.file) {
1871                        return Err(ReportError::InvalidServerRecord(format!(
1872                            "decision {} is absent from the frozen manifest",
1873                            meta.id
1874                        )));
1875                    }
1876                    continue;
1877                };
1878                if decision_metadata[index] != *meta {
1879                    return Err(ReportError::InvalidServerRecord(format!(
1880                        "decision {} metadata differs from the frozen manifest",
1881                        meta.id
1882                    )));
1883                }
1884                let key = vector_key(vector);
1885                let indexes = vector_indexes.entry(meta.id.clone()).or_default();
1886                let observations = vectors_by_decision.entry(meta.id.clone()).or_default();
1887                let index = *indexes.entry(key).or_insert_with(|| {
1888                    observations.push(MutableObservation {
1889                        vector: vector.clone(),
1890                        tests: Vec::new(),
1891                        phases: Vec::new(),
1892                        explicit_phases: Vec::new(),
1893                    });
1894                    observations.len() - 1
1895                });
1896                observations[index]
1897                    .tests
1898                    .push(tests_by_hit.number(&id, ids));
1899                tests_by_id
1900                    .get_mut(&id)
1901                    .expect("registered test")
1902                    .decisions
1903                    .entry(meta.id.clone())
1904                    .or_default()
1905                    .insert(vector);
1906                hash_slot(&mut tests_by_decision, &meta.id).push(tests_by_hit.number(&id, ids));
1907                (meta.id.clone(), Some(vector.clone()))
1908            } else if record.record_type == "hit" {
1909                let hit = record
1910                    .id
1911                    .as_ref()
1912                    .ok_or_else(|| ReportError::InvalidServerRecord("missing hit id".into()))?;
1913                let number = hit_ids.number(hit, ids);
1914                tests_by_hit.add(number, &id, ids);
1915                tests_by_id
1916                    .get_mut(&id)
1917                    .expect("registered test")
1918                    .hits
1919                    .push(number);
1920                (hit.clone(), None)
1921            } else {
1922                return Err(ReportError::InvalidServerRecord(record.record_type.clone()));
1923            };
1924            let Some(timestamp_ms) = record.timestamp_ms else {
1925                continue;
1926            };
1927            let event = RuntimeEvent {
1928                event_type: record.record_type.clone(),
1929                id: record_id,
1930                vector: decision,
1931                timestamp_ms,
1932                statement_id: record.statement_id.clone(),
1933                phase_id: record.phase_id.clone(),
1934                environment: "server".into(),
1935            };
1936            let explicit = event.phase_id.is_some();
1937            let phase_id = correlate(&event);
1938            let Some(phase_id) = phase_id else { continue };
1939            let Some(phase) = phases_by_id.get_mut(phase_id.as_str()) else {
1940                continue;
1941            };
1942            phase.server_events += 1;
1943            if explicit {
1944                phase.explicit_events += 1;
1945                phase.explicit_server_events += 1;
1946            } else {
1947                phase.inferred_events += 1;
1948                phase.inferred_server_events += 1;
1949            }
1950            if event.event_type == "hit" {
1951                let hit = hit_ids.number(&event.id, ids);
1952                phase.hits.push(hit);
1953                phases_by_hit.add(hit, &phase_id, ids);
1954                if explicit {
1955                    explicit_phases_by_hit.add(hit, &phase_id, ids);
1956                }
1957            } else if let Some(vector) = &event.vector {
1958                phase
1959                    .decisions
1960                    .entry(event.id.clone())
1961                    .or_default()
1962                    .insert(vector);
1963                if let Some(index) = vector_indexes
1964                    .get(&event.id)
1965                    .and_then(|indexes| indexes.get(&vector_key(vector)))
1966                    .copied()
1967                    && let Some(observation) = vectors_by_decision
1968                        .get_mut(&event.id)
1969                        .and_then(|observations| observations.get_mut(index))
1970                {
1971                    observation
1972                        .phases
1973                        .push(phases_by_hit.number(&phase_id, ids));
1974                    if explicit {
1975                        observation
1976                            .explicit_phases
1977                            .push(explicit_phases_by_hit.number(&phase_id, ids));
1978                    }
1979                }
1980            }
1981        }
1982    }
1983
1984    // Legacy confidence fields remain readable for archive compatibility.
1985    // Execution inside/before a passing assertion does not establish that
1986    // an assertion checks a statement. Only the agent-authored map awards it.
1987
1988    decision_metadata.sort_by(|left, right| {
1989        left.file
1990            .cmp(&right.file)
1991            .then(left.line.cmp(&right.line))
1992            .then(left.column.cmp(&right.column))
1993    });
1994    let tests_by_hit = tests_by_hit.into_relation(&hit_ids);
1995    let phases_by_hit = phases_by_hit.into_relation(&hit_ids);
1996    let explicit_phases_by_hit = explicit_phases_by_hit.into_relation(&hit_ids);
1997    // A frontend may decline one outcome of a branch (a block that can never
1998    // be entered, a rescue that can never be reached) or the whole branch;
1999    // a branch whose every outcome is declined is declined itself.
2000    let mut declined = manifest.unmeasured.iter().collect::<BTreeSet<_>>();
2001    for branch in &manifest.branches {
2002        if !branch.alternatives.is_empty()
2003            && branch
2004                .alternatives
2005                .iter()
2006                .all(|alternative| declined.contains(&alternative.id))
2007        {
2008            declined.insert(&branch.id);
2009        }
2010    }
2011    // What confidence asks of each test and phase a relation numbers, looked
2012    // up once per number rather than once per mention: a run's points and
2013    // lines mention tests millions of times, and each lookup hashed an id.
2014    let test_traits = tests_by_hit
2015        .names
2016        .iter()
2017        .map(|name| tests_by_id.get(name).map(TestTraits::of))
2018        .collect::<Vec<_>>();
2019    let phase_kind = |relation: &Relation| {
2020        relation
2021            .names
2022            .iter()
2023            .map(|name| {
2024                phases_by_id
2025                    .get(name)
2026                    .map(|phase| phase.phase.kind.as_str())
2027            })
2028            .collect::<Vec<_>>()
2029    };
2030    let phase_kinds = phase_kind(&phases_by_hit);
2031    let explicit_kinds = phase_kind(&explicit_phases_by_hit);
2032    let confidence = |tests: &Reached, phases: &Reached, explicit: &Reached| {
2033        confidence_from(
2034            tests,
2035            phases,
2036            explicit,
2037            &test_traits,
2038            &phase_kinds,
2039            &explicit_kinds,
2040        )
2041    };
2042    // A decision's two outcomes are branch outcomes. Python, Ruby and Rust
2043    // declare them as a branch of their own, `<decision>:outcome`; for a
2044    // decision declared without one, the branch is made here from the
2045    // decision's vectors, so every language counts and lists outcomes the
2046    // same way and no decision is counted twice.
2047    let declared_branches = manifest
2048        .branches
2049        .iter()
2050        .map(|branch| branch.id.as_str())
2051        .collect::<HashSet<_>>();
2052    let mut outcome_branches = Vec::new();
2053    let mut decisions = Vec::with_capacity(decision_metadata.len());
2054    for meta in decision_metadata {
2055        let mutable = vectors_by_decision.remove(&meta.id).unwrap_or_default();
2056        let outcome_id = format!("{}:outcome", meta.id);
2057        if !declared_branches.contains(outcome_id.as_str()) {
2058            let alternatives = [true, false]
2059                .into_iter()
2060                .map(|outcome| {
2061                    let (mut tests, mut phases, mut explicit) =
2062                        (Vec::new(), Vec::new(), Vec::new());
2063                    for observation in mutable
2064                        .iter()
2065                        .filter(|observation| observation.vector.outcome == outcome)
2066                    {
2067                        tests.extend(&observation.tests);
2068                        phases.extend(&observation.phases);
2069                        explicit.extend(&observation.explicit_phases);
2070                    }
2071                    let tests = tests_by_hit.reached(tests);
2072                    let phases = phases_by_hit.reached(phases);
2073                    let explicit = explicit_phases_by_hit.reached(explicit);
2074                    AlternativeResult {
2075                        id: format!("{outcome_id}:{outcome}"),
2076                        label: outcome.to_string(),
2077                        covered: !tests.names.is_empty(),
2078                        confidence: confidence(&tests, &phases, &explicit),
2079                        tests: tests.names,
2080                        phases: phases.names,
2081                    }
2082                })
2083                .collect::<Vec<_>>();
2084            outcome_branches.push(BranchResult {
2085                covered: alternatives.iter().all(|alternative| alternative.covered),
2086                meta: BranchMeta {
2087                    id: outcome_id,
2088                    kind: meta.kind.clone(),
2089                    file: meta.file.clone(),
2090                    line: meta.line,
2091                    column: meta.column,
2092                    source: meta.source.clone(),
2093                    alternatives: alternatives
2094                        .iter()
2095                        .map(|alternative| BranchAlternativeMeta {
2096                            id: alternative.id.clone(),
2097                            label: alternative.label.clone(),
2098                        })
2099                        .collect(),
2100                },
2101                alternatives,
2102            });
2103        }
2104        let mut observations = Vec::with_capacity(mutable.len());
2105        let mut observed_phases = Vec::new();
2106        let mut observed_explicit = Vec::new();
2107        for observation in mutable {
2108            let tests = tests_by_hit.reached(observation.tests);
2109            let phases = phases_by_hit.reached(observation.phases);
2110            let explicit = explicit_phases_by_hit.reached(observation.explicit_phases);
2111            observed_phases.extend(&phases.numbers);
2112            observed_explicit.extend(&explicit.numbers);
2113            observations.push(VectorObservation {
2114                vector: observation.vector,
2115                confidence: confidence(&tests, &phases, &explicit),
2116                tests: tests.names,
2117                phases: phases.names,
2118                explicit_phases: explicit.names,
2119            });
2120        }
2121        let vectors = observations
2122            .iter()
2123            .map(|observation| observation.vector.clone())
2124            .collect::<Vec<_>>();
2125        let witnesses =
2126            find_witnesses_for_conditions(&vectors, meta.conditions.len()).map_err(|error| {
2127                ReportError::DecisionAnalysis {
2128                    decision_id: meta.id.clone(),
2129                    error,
2130                }
2131            })?;
2132        let mut conditions = Vec::with_capacity(meta.conditions.len());
2133        for (index, source) in meta.conditions.iter().enumerate() {
2134            let witness = witnesses[index].map(|witness| {
2135                [
2136                    vectors[witness.first].clone(),
2137                    vectors[witness.second].clone(),
2138                ]
2139            });
2140            let witness_tests = witnesses[index].map(|witness| {
2141                [
2142                    observations[witness.first].tests.clone(),
2143                    observations[witness.second].tests.clone(),
2144                ]
2145            });
2146            let assertion_covered = false;
2147            conditions.push(ConditionResult {
2148                index,
2149                source: source.clone(),
2150                covered: witness.is_some(),
2151                assertion_covered,
2152                witness,
2153                witness_tests,
2154            });
2155        }
2156        let decision_tests =
2157            tests_by_hit.reached(tests_by_decision.remove(&meta.id).unwrap_or_default());
2158        let decision_confidence = confidence(
2159            &decision_tests,
2160            &phases_by_hit.reached(observed_phases),
2161            &explicit_phases_by_hit.reached(observed_explicit),
2162        );
2163        decisions.push(DecisionResult {
2164            executed: !vectors.is_empty(),
2165            covered: conditions.iter().all(|condition| condition.covered),
2166            meta,
2167            vectors,
2168            vector_observations: observations,
2169            conditions,
2170            tests: decision_tests.names,
2171            confidence: decision_confidence,
2172        });
2173    }
2174
2175    let points = manifest
2176        .points
2177        .iter()
2178        .cloned()
2179        .map(|meta| {
2180            let tests = tests_by_hit.of(&meta.id);
2181            let phases = phases_by_hit.of(&meta.id);
2182            let explicit = explicit_phases_by_hit.of(&meta.id);
2183            PointResult {
2184                measured: !declined.contains(&meta.id),
2185                covered: tests_by_hit.by_hit.contains_key(&meta.id),
2186                confidence: confidence(tests, phases, explicit),
2187                meta,
2188                tests: tests.names.clone(),
2189                phases: phases.names.clone(),
2190            }
2191        })
2192        .collect::<Vec<_>>();
2193
2194    let branches = manifest
2195        .branches
2196        .iter()
2197        .cloned()
2198        .map(|mut meta| {
2199            // A declined outcome leaves the denominator; the others stay.
2200            meta.alternatives
2201                .retain(|alternative| !declined.contains(&alternative.id));
2202            let alternatives = meta
2203                .alternatives
2204                .iter()
2205                .map(|alternative| {
2206                    let tests = tests_by_hit.of(&alternative.id);
2207                    let phases = phases_by_hit.of(&alternative.id);
2208                    let explicit = explicit_phases_by_hit.of(&alternative.id);
2209                    AlternativeResult {
2210                        id: alternative.id.clone(),
2211                        label: alternative.label.clone(),
2212                        covered: tests_by_hit.by_hit.contains_key(&alternative.id),
2213                        tests: tests.names.clone(),
2214                        phases: phases.names.clone(),
2215                        confidence: confidence(tests, phases, explicit),
2216                    }
2217                })
2218                .collect::<Vec<_>>();
2219            BranchResult {
2220                covered: alternatives.iter().all(|alternative| alternative.covered),
2221                meta,
2222                alternatives,
2223            }
2224        })
2225        .chain(outcome_branches)
2226        .collect::<Vec<_>>();
2227
2228    // Obligations the frontend declined to measure leave the covered/uncovered
2229    // denominator entirely. Counting them as uncovered would report a
2230    // measurement gap as a coverage gap — a wrong number, and wrong numbers get
2231    // trusted. They are reported separately instead, alongside the share of
2232    // obligations that were measured exactly.
2233    // Lines are folded from every point, declined ones included, so a file
2234    // Supercov could not measure still has addressable lines to report a
2235    // limitation against. Only what was measured decides the line's state and
2236    // whether it counts. A line gathers its points' test and phase numbers,
2237    // which sort and deduplicate as numbers.
2238    let mut line_aggregates = BTreeMap::<SourceLine, LineAggregate>::new();
2239    for point in &points {
2240        let aggregate = line_aggregates
2241            .entry(SourceLine {
2242                file: ids.id(&point.meta.file),
2243                line: point.meta.line,
2244            })
2245            .or_default();
2246        if declined.contains(&point.meta.id) {
2247            continue;
2248        }
2249        aggregate.measured = true;
2250        aggregate.covered |= point.covered;
2251        aggregate
2252            .tests
2253            .extend(&tests_by_hit.of(&point.meta.id).numbers);
2254        aggregate
2255            .phases
2256            .extend(&phases_by_hit.of(&point.meta.id).numbers);
2257        aggregate
2258            .explicit_phases
2259            .extend(&explicit_phases_by_hit.of(&point.meta.id).numbers);
2260    }
2261    let lines = line_aggregates
2262        .into_iter()
2263        .map(|(location, aggregate)| {
2264            let LineAggregate {
2265                covered,
2266                measured,
2267                tests,
2268                phases,
2269                explicit_phases,
2270            } = aggregate;
2271            let tests = tests_by_hit.reached(tests);
2272            let phases = phases_by_hit.reached(phases);
2273            let explicit = explicit_phases_by_hit.reached(explicit_phases);
2274            let traits = tests
2275                .numbers
2276                .iter()
2277                .filter_map(|number| test_traits[*number as usize].as_ref())
2278                .collect::<Vec<_>>();
2279            let runners = traits
2280                .iter()
2281                .map(|traits| traits.runner)
2282                .collect::<BTreeSet<_>>();
2283            let kinds = traits
2284                .iter()
2285                .map(|traits| traits.kind)
2286                .collect::<BTreeSet<_>>();
2287            LineResult {
2288                file: location.file.to_string(),
2289                line: location.line,
2290                covered,
2291                measured,
2292                confidence: confidence(&tests, &phases, &explicit),
2293                tests: tests.names,
2294                runners: runners.iter().map(|runner| (*runner).to_owned()).collect(),
2295                exclusive_kind: (kinds.len() == 1).then(|| (*kinds.first().unwrap()).to_owned()),
2296                phases: phases.names,
2297                kinds: kinds.iter().map(|kind| (*kind).to_owned()).collect(),
2298            }
2299        })
2300        .collect::<Vec<_>>();
2301    drop(test_traits);
2302
2303    // Where each hit sits, by hit number, as (file rank, line): a test's or
2304    // phase's lines sort and deduplicate as numbers, in the order the
2305    // `SourceLine`s they stand for sort in.
2306    let hit_ranks = hit_ids.ranks();
2307    let mut point_files = manifest
2308        .points
2309        .iter()
2310        .map(|point| ids.id(&point.file))
2311        .collect::<Vec<_>>();
2312    point_files.sort_unstable();
2313    point_files.dedup();
2314    let mut hit_locations = vec![None; hit_ids.names.len()];
2315    for point in &manifest.points {
2316        if let Some(number) = hit_ids.numbers.get(point.id.as_str()) {
2317            let file = point_files
2318                .binary_search_by(|file| file.as_str().cmp(&point.file))
2319                .expect("every point file is listed") as u32;
2320            hit_locations[*number] = Some((file, point.line));
2321        }
2322    }
2323    let lines_of = |hits: &[usize]| {
2324        let mut located = hits
2325            .iter()
2326            .filter_map(|hit| hit_locations[*hit])
2327            .collect::<Vec<_>>();
2328        located.sort_unstable();
2329        located.dedup();
2330        located
2331            .into_iter()
2332            .map(|(file, line)| SourceLine {
2333                file: point_files[file as usize].clone(),
2334                line,
2335            })
2336            .collect::<Vec<_>>()
2337    };
2338    test_order.sort_by(|left, right| tests_by_id[left].name.cmp(&tests_by_id[right].name));
2339    let tests = test_order
2340        .into_iter()
2341        .map(|id| {
2342            let test = tests_by_id.remove(&id).expect("test order references test");
2343            let outcome = test_outcome(&test);
2344            let lines = lines_of(&test.hits);
2345            let hits = hit_ids.sorted_by(test.hits, &hit_ranks);
2346            TestCoverageResult {
2347                id: test.id,
2348                name: test.name,
2349                file: test.file,
2350                title: test.title,
2351                retries: test.retries.into_iter().collect(),
2352                attempts: test.attempts.into_values().collect(),
2353                outcome,
2354                provenance: test.provenance,
2355                role: test.role,
2356                attribution: test.attribution,
2357                hits,
2358                decisions: test
2359                    .decisions
2360                    .into_iter()
2361                    .map(|(id, vectors)| TestDecisionResult {
2362                        id,
2363                        vectors: vectors.values,
2364                    })
2365                    .collect(),
2366                lines,
2367            }
2368        })
2369        .collect::<Vec<_>>();
2370
2371    let mut test_files = BTreeMap::<
2372        String,
2373        (
2374            BTreeSet<String>,
2375            BTreeSet<String>,
2376            BTreeSet<String>,
2377            BTreeSet<SourceLine>,
2378        ),
2379    >::new();
2380    for test in &tests {
2381        let aggregate = test_files
2382            .entry(
2383                test.file
2384                    .clone()
2385                    .unwrap_or_else(|| "(unknown test file)".into()),
2386            )
2387            .or_default();
2388        aggregate.0.insert(test.id.clone());
2389        aggregate.1.insert(test.provenance.runner.clone());
2390        aggregate.2.insert(test.provenance.kind.clone());
2391        aggregate.3.extend(test.lines.iter().cloned());
2392    }
2393    let test_files = test_files
2394        .into_iter()
2395        .map(|(file, (tests, runners, kinds, lines))| TestFileResult {
2396            file,
2397            tests: sorted(&tests),
2398            runners: sorted(&runners),
2399            kinds: sorted(&kinds),
2400            lines: lines.into_iter().collect(),
2401        })
2402        .collect::<Vec<_>>();
2403
2404    let mut phases = phases_by_id.into_values().collect::<Vec<_>>();
2405    phases.sort_by(|left, right| {
2406        left.phase
2407            .started_at_ms
2408            .cmp(&right.phase.started_at_ms)
2409            .then(left.phase.id.cmp(&right.phase.id))
2410    });
2411    let phases = phases
2412        .into_iter()
2413        .map(|phase| {
2414            let lines = lines_of(&phase.hits);
2415            let hits = hit_ids.sorted_by(phase.hits, &hit_ranks);
2416            PhaseResult {
2417                phase: phase.phase,
2418                test: phase.test,
2419                hits,
2420                decisions: phase
2421                    .decisions
2422                    .into_iter()
2423                    .map(|(id, vectors)| TestDecisionResult {
2424                        id,
2425                        vectors: vectors.values,
2426                    })
2427                    .collect(),
2428                lines,
2429                browser_events: phase.browser_events,
2430                server_events: phase.server_events,
2431                explicit_events: phase.explicit_events,
2432                inferred_events: phase.inferred_events,
2433                explicit_browser_events: phase.explicit_browser_events,
2434                inferred_browser_events: phase.inferred_browser_events,
2435                explicit_server_events: phase.explicit_server_events,
2436                inferred_server_events: phase.inferred_server_events,
2437            }
2438        })
2439        .collect::<Vec<_>>();
2440
2441    let total_obligations = decisions.len() + points.len() + branches.len();
2442    let (decisions, points, branches) = if declined.is_empty() {
2443        (decisions, points, branches)
2444    } else {
2445        (
2446            decisions
2447                .into_iter()
2448                .filter(|result| !declined.contains(&result.meta.id))
2449                .collect::<Vec<_>>(),
2450            points
2451                .into_iter()
2452                .filter(|result| !declined.contains(&result.meta.id))
2453                .collect::<Vec<_>>(),
2454            branches
2455                .into_iter()
2456                .filter(|result| !declined.contains(&result.meta.id))
2457                .collect::<Vec<_>>(),
2458        )
2459    };
2460    let measured_obligations = decisions.len() + points.len() + branches.len();
2461    let mut summary = summary_for_results(&decisions, &points, &branches, &lines, None)?;
2462    if total_obligations > measured_obligations {
2463        summary.unmeasured_obligations = Some(total_obligations - measured_obligations);
2464        summary.exact_fraction_pct = Some(if total_obligations == 0 {
2465            100.0
2466        } else {
2467            (measured_obligations as f64) * 100.0 / (total_obligations as f64)
2468        });
2469    }
2470    // A limitation that says `"blocking": false` is a declared boundary of
2471    // the denominator -- a macro the compiler expands, a const context no
2472    // probe can run in -- not a failure to measure what is inside it. Only a
2473    // blocking one makes the run incomplete. A limitation that says nothing
2474    // is blocking, so a frontend that has not been taught the difference
2475    // keeps its behaviour.
2476    if manifest.limitations.iter().any(blocking_limitation) {
2477        summary.coverage_complete = false;
2478        summary.completeness_blocked = Some(true);
2479    }
2480
2481    let dimension_coverage = |field: &str| -> Result<Vec<DimensionCoverage>, ReportError> {
2482        let values = tests
2483            .iter()
2484            .map(|test| {
2485                if field == "kind" {
2486                    test.provenance.kind.clone()
2487                } else {
2488                    test.provenance.runner.clone()
2489                }
2490            })
2491            .collect::<BTreeSet<_>>();
2492        values
2493            .into_iter()
2494            .map(|value| {
2495                let in_dimension = |test: &&TestCoverageResult| {
2496                    if field == "kind" {
2497                        test.provenance.kind == value
2498                    } else {
2499                        test.provenance.runner == value
2500                    }
2501                };
2502                // Coverage is summarised over the tests that have coverage of
2503                // their own. A Go test that called `t.Parallel()` reached real
2504                // code and contributes no hits, because nothing can say which
2505                // code -- so counting it here reported a package covered
2506                // entirely by parallel tests as covered 0%, which is a wrong
2507                // number rather than a missing one.
2508                let selected = tests
2509                    .iter()
2510                    .filter(in_dimension)
2511                    .filter(|test| coverage_is_its_own(&test.attribution))
2512                    .map(|test| test.id.clone())
2513                    .collect::<BTreeSet<_>>();
2514                let counted = tests
2515                    .iter()
2516                    .filter(in_dimension)
2517                    .map(|test| test.id.clone())
2518                    .collect::<BTreeSet<_>>();
2519                Ok(DimensionCoverage {
2520                    kind: (field == "kind").then(|| value.clone()),
2521                    runner: (field == "runner").then(|| value.clone()),
2522                    // Counted whether or not anything could be attributed to
2523                    // them: they ran.
2524                    tests: tests
2525                        .iter()
2526                        .filter(|test| counted.contains(&test.id) && test.role == "test")
2527                        .count(),
2528                    setups: tests
2529                        .iter()
2530                        .filter(|test| counted.contains(&test.id) && test.role == "setup")
2531                        .count(),
2532                    attributed: tests
2533                        .iter()
2534                        .filter(|test| selected.contains(&test.id) && test.role == "test")
2535                        .count(),
2536                    summary: summary_for_results(
2537                        &decisions,
2538                        &points,
2539                        &branches,
2540                        &lines,
2541                        Some(&selected),
2542                    )?,
2543                })
2544            })
2545            .collect()
2546    };
2547
2548    Ok(CoverageView {
2549        generated_at: generated_at.into(),
2550        variant: coverage_model.variant.clone(),
2551        scope: manifest.scope.clone(),
2552        model: CoverageModel {
2553            language: coverage_model.language.clone(),
2554            name: coverage_model.name.clone(),
2555            completeness_meaning: coverage_model.completeness_meaning.clone(),
2556            measured: coverage_model.measured.clone(),
2557            not_measured: coverage_model.not_measured.clone(),
2558        },
2559        integrity: None,
2560        limitations: manifest.limitations.clone(),
2561        transport: None,
2562        summary,
2563        coverage_by_kind: dimension_coverage("kind")?,
2564        coverage_by_runner: dimension_coverage("runner")?,
2565        decisions,
2566        points,
2567        branches,
2568        tests,
2569        test_files,
2570        phases,
2571        lines,
2572    })
2573}
2574
2575pub fn analyze_coverage_results(
2576    request: &CoverageReportRequest,
2577) -> Result<CoverageReport, ReportError> {
2578    if let Some(scope) = request
2579        .raw_results
2580        .iter()
2581        .filter_map(|raw| raw.scope.as_ref())
2582        .find(|scope| scope.run_id != request.run_id)
2583    {
2584        return Err(ReportError::ScopeMismatch {
2585            expected: request.run_id.clone(),
2586            actual: scope.run_id.clone(),
2587        });
2588    }
2589    if request.raw_results.is_empty() {
2590        return Err(ReportError::NoEvidence(request.run_id.clone()));
2591    }
2592    let default_model = javascript_coverage_model();
2593    let coverage_model = request.coverage_model.as_ref().unwrap_or(&default_model);
2594    PersistedCoverageModel::from_declaration(coverage_model).map_err(|reason| {
2595        ReportError::InvalidJson {
2596            path: "coverage-model.json".into(),
2597            reason: reason.into(),
2598        }
2599    })?;
2600    // The three views are built side by side: each reads the same evidence
2601    // and nothing the others write. Each holds one copy of each id it names.
2602    // They do not share copies: two threads cloning the same ids contend on
2603    // their counts, which made each view twice as slow as building it alone.
2604    let all = request.raw_results.iter().collect::<Vec<_>>();
2605    let passing = passing_coverage_results(&request.raw_results);
2606    let failing = failed_coverage_results(&request.raw_results);
2607    let build = |results: &[&RawTestResult]| {
2608        create_coverage_view_with_model(
2609            &request.manifest,
2610            results,
2611            &request.generated_at,
2612            coverage_model,
2613            &mut Interner::default(),
2614        )
2615    };
2616    let (view, passed, failed) = std::thread::scope(|scope| {
2617        let passed = scope.spawn(|| build(&passing));
2618        let failed = scope.spawn(|| build(&failing));
2619        let view = build(&all);
2620        (
2621            view,
2622            passed
2623                .join()
2624                .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
2625            failed
2626                .join()
2627                .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
2628        )
2629    });
2630    let (view, passed, failed) = (view?, passed?, failed?);
2631    let execution = match request.test_exit_code {
2632        ExitCodeInput::Missing => None,
2633        ExitCodeInput::Present(test_exit_code) => Some(ExecutionResult {
2634            valid: test_exit_code == Some(0),
2635            test_exit_code,
2636        }),
2637    };
2638    let mut view = view;
2639    let mut passed = passed;
2640    let mut failed = failed;
2641    if let Some(integrity) = &request.integrity {
2642        view.integrity = Some(integrity.clone());
2643        passed.integrity = Some(integrity.clone());
2644        failed.integrity = Some(integrity.clone());
2645    }
2646    Ok(CoverageReport {
2647        view,
2648        execution,
2649        filters: CoverageFilters { passed, failed },
2650    })
2651}
2652
2653fn parse_entry<T: for<'de> Deserialize<'de>>(
2654    entry: &EvidenceArchiveEntry,
2655) -> Result<T, ReportError> {
2656    serde_json::from_slice(&entry.contents).map_err(|error| ReportError::InvalidJson {
2657        path: entry.path.clone(),
2658        reason: error.to_string(),
2659    })
2660}
2661
2662fn parse_json_lines<'a, T: for<'de> Deserialize<'de>>(
2663    entries: impl Iterator<Item = &'a EvidenceArchiveEntry>,
2664) -> Result<Vec<T>, ReportError> {
2665    let mut records = Vec::new();
2666    for entry in entries {
2667        let Some(contents) = entry.contents.strip_suffix(b"\n") else {
2668            return Err(ReportError::InvalidJson {
2669                path: entry.path.clone(),
2670                reason: "recognized JSONL evidence must end with a newline".into(),
2671            });
2672        };
2673        if contents.is_empty() {
2674            return Err(ReportError::InvalidJson {
2675                path: entry.path.clone(),
2676                reason: "recognized JSONL evidence must contain at least one record".into(),
2677            });
2678        }
2679        for (index, line) in contents.split(|byte| *byte == b'\n').enumerate() {
2680            if line.is_empty() {
2681                return Err(ReportError::InvalidJson {
2682                    path: entry.path.clone(),
2683                    reason: format!("blank JSONL record at line {}", index + 1),
2684                });
2685            }
2686            records.push(serde_json::from_slice(line).map_err(|error| {
2687                ReportError::InvalidJson {
2688                    path: entry.path.clone(),
2689                    reason: format!("invalid JSONL record at line {}: {error}", index + 1),
2690                }
2691            })?);
2692        }
2693    }
2694    Ok(records)
2695}
2696
2697/// Server evidence is appended by application processes Supercov does not
2698/// control — including pool VMs restored from one snapshot, whose clones can
2699/// tear a shared shard. A torn line is one lost record, not a lost run: it is
2700/// skipped and counted, and the report says so through the existing
2701/// CORRUPT_EVIDENCE_RECORDS diagnostic and the blocking-limitation total.
2702struct TolerantJsonLines<T> {
2703    records: Vec<T>,
2704    corrupt_records: usize,
2705    corrupt_files: usize,
2706}
2707
2708fn parse_server_json_lines<'a, T: for<'de> Deserialize<'de>>(
2709    entries: impl Iterator<Item = &'a EvidenceArchiveEntry>,
2710) -> TolerantJsonLines<T> {
2711    let mut parsed = TolerantJsonLines {
2712        records: Vec::new(),
2713        corrupt_records: 0,
2714        corrupt_files: 0,
2715    };
2716    for entry in entries {
2717        let mut corrupt_here = 0;
2718        for line in entry.contents.split(|byte| *byte == b'\n') {
2719            if line.is_empty() {
2720                continue;
2721            }
2722            match serde_json::from_slice(line) {
2723                Ok(record) => parsed.records.push(record),
2724                Err(_) => corrupt_here += 1,
2725            }
2726        }
2727        if corrupt_here > 0 {
2728            parsed.corrupt_records += corrupt_here;
2729            parsed.corrupt_files += 1;
2730        }
2731    }
2732    parsed
2733}
2734
2735fn is_mcdc_result(path: &str) -> bool {
2736    path == "mcdc.json" || path.ends_with("/mcdc.json")
2737}
2738
2739fn is_mcdc_journal(path: &str) -> bool {
2740    path == "mcdc.jsonl" || path.ends_with(".mcdc.jsonl")
2741}
2742
2743pub fn analyze_coverage_archive(
2744    request: &ArchiveReportRequest,
2745) -> Result<CoverageReport, ReportError> {
2746    let entries = read_archive(Path::new(&request.archive_path))
2747        .map_err(|error| ReportError::InvalidArchive(error.to_string()))?;
2748    let manifest = entries
2749        .iter()
2750        .find(|entry| entry.path == "manifest.json")
2751        .ok_or(ReportError::MissingManifest)
2752        .and_then(parse_entry::<CoverageManifest>)?;
2753    let mut raw_results = entries
2754        .iter()
2755        .filter(|entry| is_mcdc_result(&entry.path))
2756        .map(parse_entry::<RawTestResult>)
2757        .collect::<Result<Vec<_>, _>>()?;
2758    let journal_results = parse_json_lines::<RawTestResult>(
2759        entries.iter().filter(|entry| is_mcdc_journal(&entry.path)),
2760    )?;
2761    raw_results.extend(journal_results);
2762
2763    let scoped = parse_server_json_lines::<ServerRecord>(entries.iter().filter(|entry| {
2764        entry.path.starts_with("server/")
2765            && !entry.path.starts_with("server/background/")
2766            && entry.path.ends_with(".jsonl")
2767    }));
2768    let scoped_records = scoped.records;
2769    // Each server record joins the first result with its scope, once. A
2770    // linear search per record and a linear duplicate check per result made
2771    // this quadratic: supergateway's e2e servers spent most of a 20 s report
2772    // preparation, and of publication, comparing scopes.
2773    let mut by_scope = std::collections::HashMap::<&ExecutionScope, usize>::new();
2774    for (index, raw) in raw_results.iter().enumerate() {
2775        if let Some(scope) = &raw.scope {
2776            by_scope.entry(scope).or_insert(index);
2777        }
2778    }
2779    let by_scope: std::collections::HashMap<ExecutionScope, usize> = by_scope
2780        .into_iter()
2781        .map(|(scope, index)| (scope.clone(), index))
2782        .collect();
2783    let mut seen = std::collections::HashMap::<usize, std::collections::HashSet<Vec<u8>>>::new();
2784    for record in &scoped_records {
2785        let Some(scope) = &record.scope else { continue };
2786        let Some(&index) = by_scope.get(scope) else {
2787            continue;
2788        };
2789        let raw = &mut raw_results[index];
2790        let known = seen.entry(index).or_insert_with(|| {
2791            raw.server
2792                .iter()
2793                .filter_map(|existing| serde_json::to_vec(existing).ok())
2794                .collect()
2795        });
2796        let Ok(key) = serde_json::to_vec(record) else {
2797            if !raw.server.contains(record) {
2798                raw.server.push(record.clone());
2799            }
2800            continue;
2801        };
2802        if known.insert(key) {
2803            raw.server.push(record.clone());
2804        }
2805    }
2806
2807    let background = parse_server_json_lines::<ServerRecord>(entries.iter().filter(|entry| {
2808        entry.path.starts_with("server/background/") && entry.path.ends_with(".jsonl")
2809    }));
2810    let background_records = background.records;
2811    if !background_records.is_empty() {
2812        raw_results.push(RawTestResult {
2813            test_id: Some(format!("background:{}", request.run_id)),
2814            scope: None,
2815            test: "Background / unattributed".into(),
2816            test_file: None,
2817            title: Some("Background / unattributed".into()),
2818            retry: None,
2819            status: Some("unknown".into()),
2820            expected_status: None,
2821            flaky: false,
2822            provenance: TestProvenance {
2823                runner: "background".into(),
2824                kind: "background".into(),
2825                project: None,
2826                source: "explicit".into(),
2827            },
2828            role: "background".into(),
2829            attribution: ATTRIBUTION_EXACT.into(),
2830            phases: vec![],
2831            runtime: vec![],
2832            browser: vec![],
2833            server: background_records.clone(),
2834        });
2835    }
2836
2837    // Execution traces are appended by the launch observer inside application
2838    // processes, so they share the clone hazard of server evidence.
2839    let execution =
2840        parse_server_json_lines::<ExecutionTraceEvent>(entries.iter().filter(|entry| {
2841            entry.path.starts_with("execution.") && entry.path.ends_with(".jsonl")
2842        }));
2843    let execution_events = execution.records;
2844    let count_event = |name: &str| {
2845        execution_events
2846            .iter()
2847            .filter(|event| event.kind() == name)
2848            .count()
2849    };
2850    let transport = TransportStats {
2851        processes: count_event("process"),
2852        child_launches: count_event("child-launch"),
2853        remote_launches: count_event("remote-launch"),
2854        workspace_capabilities: count_event("workspace-capability"),
2855        guest_processes: count_event("guest-process"),
2856        scoped_server_records: scoped_records.len(),
2857        background_server_records: background_records.len(),
2858        corrupt_records: scoped.corrupt_records
2859            + background.corrupt_records
2860            + execution.corrupt_records,
2861        corrupt_files: scoped.corrupt_files + background.corrupt_files + execution.corrupt_files,
2862    };
2863    let frontend = entries
2864        .iter()
2865        .find(|entry| entry.path == "frontend.json")
2866        .ok_or_else(|| ReportError::InvalidArchive("missing frontend.json".into()))
2867        .and_then(parse_entry::<FrontendRunDeclaration>)?;
2868    let persisted = entries
2869        .iter()
2870        .find(|entry| entry.path == "coverage-model.json")
2871        .ok_or_else(|| ReportError::InvalidArchive("missing coverage-model.json".into()))
2872        .and_then(parse_entry::<PersistedCoverageModel>)?;
2873    let coverage_model =
2874        persisted
2875            .into_declaration()
2876            .map_err(|reason| ReportError::InvalidJson {
2877                path: "coverage-model.json".into(),
2878                reason: reason.into(),
2879            })?;
2880    if frontend.language != coverage_model.language {
2881        return Err(ReportError::InvalidArchive(format!(
2882            "frontend language {} differs from coverage model language {}",
2883            frontend.language, coverage_model.language
2884        )));
2885    }
2886    separate_repeated_executions(&mut raw_results);
2887    release_leaked_phases(&mut raw_results);
2888    let normalized = CoverageReportRequest {
2889        run_id: request.run_id.clone(),
2890        manifest,
2891        raw_results,
2892        generated_at: request.generated_at.clone(),
2893        coverage_model: Some(coverage_model),
2894        integrity: request.integrity.clone(),
2895        test_exit_code: request.test_exit_code.clone(),
2896    };
2897    // Everything is parsed out of the archive's bytes -- 385 MB on a
2898    // 3,900-test run -- and nothing reads them again, so they need not stay
2899    // resident while the views are built beside what was parsed from them.
2900    drop(entries);
2901    analyze_frontend_request(&frontend, &normalized, transport)
2902}
2903
2904/// Give a test that ran again under the same identity phases of its own.
2905///
2906/// A runner's attempt counter lives in its process, so a command that runs the
2907/// same tests twice -- ms runs Jest once in Node's environment and once in the
2908/// edge runtime's -- mints the same attempt, and the same phase ids, twice.
2909/// Every such run was refused whole ("duplicate frontend phase ID"). A record
2910/// that declares a phase an earlier record already declared is another
2911/// execution: its phases, and its own references to them, are renamed apart.
2912/// Both executions stay one attempt, whose outcome folds as any attempt's does.
2913fn separate_repeated_executions(raw_results: &mut [RawTestResult]) {
2914    let mut declared = BTreeSet::<String>::new();
2915    let mut executions = BTreeMap::<String, usize>::new();
2916    for raw in raw_results.iter_mut() {
2917        let repeated = raw.phases.iter().any(|phase| declared.contains(&phase.id));
2918        if !repeated {
2919            declared.extend(raw.phases.iter().map(|phase| phase.id.clone()));
2920            continue;
2921        }
2922        let mut renamed = BTreeMap::<String, String>::new();
2923        for phase in &raw.phases {
2924            let count = executions.entry(phase.id.clone()).or_insert(1);
2925            let fresh = loop {
2926                *count += 1;
2927                let candidate = format!("{}~{}", phase.id, count);
2928                if !declared.contains(&candidate) {
2929                    break candidate;
2930                }
2931            };
2932            renamed.insert(phase.id.clone(), fresh);
2933        }
2934        let rename = |phase: &mut Option<String>| {
2935            if let Some(fresh) = phase.as_ref().and_then(|id| renamed.get(id)) {
2936                *phase = Some(fresh.clone());
2937            }
2938        };
2939        for phase in &mut raw.phases {
2940            phase.id = renamed[&phase.id].clone();
2941            rename(&mut phase.caused_by_phase_id);
2942        }
2943        for snapshot in raw.runtime.iter_mut().chain(raw.browser.iter_mut()) {
2944            rename(&mut snapshot.phase_id);
2945            for event in &mut snapshot.events {
2946                rename(&mut event.phase_id);
2947            }
2948        }
2949        for record in &mut raw.server {
2950            rename(&mut record.phase_id);
2951        }
2952        declared.extend(renamed.into_values());
2953    }
2954}
2955
2956/// Untag evidence that names another test's phase.
2957///
2958/// Work a test starts can finish after it: axios's HTTP/2 upload tests leave a
2959/// stream settling, and 2.0.1's runtime tagged what it ran with the ended
2960/// test's assertion phase, inside the next test's record. Three such events
2961/// in 2,201 records made the whole run unreadable ("unknown frontend phase
2962/// reference"). A phase another record of the same run declares is not
2963/// corruption: the event keeps its hit in the record that holds it and loses
2964/// the phase it cannot belong to. A phase no record declares is still refused.
2965fn release_leaked_phases(raw_results: &mut [RawTestResult]) {
2966    let declared = raw_results
2967        .iter()
2968        .flat_map(|raw| raw.phases.iter().map(|phase| phase.id.clone()))
2969        .collect::<BTreeSet<_>>();
2970    for raw in raw_results.iter_mut() {
2971        let own = raw
2972            .phases
2973            .iter()
2974            .map(|phase| phase.id.clone())
2975            .collect::<BTreeSet<_>>();
2976        let leaked = |phase: &mut Option<String>| {
2977            if phase
2978                .as_ref()
2979                .is_some_and(|id| !own.contains(id) && declared.contains(id))
2980            {
2981                *phase = None;
2982            }
2983        };
2984        for snapshot in raw.runtime.iter_mut().chain(raw.browser.iter_mut()) {
2985            leaked(&mut snapshot.phase_id);
2986            for event in &mut snapshot.events {
2987                leaked(&mut event.phase_id);
2988            }
2989        }
2990        for record in &mut raw.server {
2991            leaked(&mut record.phase_id);
2992        }
2993    }
2994}
2995
2996/// The analysis of a frontend run, from its request as an archive holds it:
2997/// what `analyze_coverage_archive` does once it has parsed the archive, and
2998/// what a run that still holds the request it archived calls instead of
2999/// reading the archive back.
3000pub fn analyze_frontend_request(
3001    frontend: &FrontendRunDeclaration,
3002    normalized: &CoverageReportRequest,
3003    transport: TransportStats,
3004) -> Result<CoverageReport, ReportError> {
3005    let mut report = crate::frontend_protocol::analyze_frontend_results(frontend, normalized)
3006        .map_err(|error| ReportError::InvalidArchive(error.to_string()))?;
3007    report.view.transport = Some(transport.clone());
3008    report.filters.passed.transport = Some(transport.clone());
3009    report.filters.failed.transport = Some(transport);
3010    Ok(report)
3011}
3012
3013impl TransportStats {
3014    /// An archive with no launch-observer or server evidence: every frontend
3015    /// but JavaScript's.
3016    pub fn none() -> Self {
3017        Self {
3018            processes: 0,
3019            child_launches: 0,
3020            remote_launches: 0,
3021            workspace_capabilities: 0,
3022            guest_processes: 0,
3023            scoped_server_records: 0,
3024            background_server_records: 0,
3025            corrupt_records: 0,
3026            corrupt_files: 0,
3027        }
3028    }
3029}
3030
3031#[cfg(test)]
3032mod tests {
3033    use std::{
3034        fs,
3035        sync::atomic::{AtomicU64, Ordering},
3036        time::SystemTime,
3037    };
3038
3039    use crate::evidence_archive::{EvidenceArchiveEntry, write_archive};
3040
3041    use super::*;
3042
3043    #[test]
3044    fn a_view_holds_one_copy_of_each_id_it_names() {
3045        // What made analysis fit in memory: a view names each test at every
3046        // point, line and confidence it reached, and must share one copy of
3047        // the name rather than hold one per mention. A change that copies ids
3048        // again fails here before it shows up as gigabytes. The full and the
3049        // passing view are built side by side, each with its own copy.
3050        let root = std::env::temp_dir().join(format!(
3051            "supercov-shared-ids-{}-{}",
3052            std::process::id(),
3053            std::time::SystemTime::now()
3054                .duration_since(std::time::UNIX_EPOCH)
3055                .unwrap()
3056                .as_nanos()
3057        ));
3058        let directory = crate::run_store::create_analyzable_test_run(&root, "shared");
3059        let run = crate::run_store::discover_runs(&root)
3060            .unwrap()
3061            .runs
3062            .remove(0);
3063        let report = crate::run_store::analyze_stored_run(&run).unwrap();
3064        let _ = directory;
3065        for view in [&report.view, &report.filters.passed] {
3066            let mentions = view
3067                .points
3068                .iter()
3069                .flat_map(|point| point.tests.iter().chain(&point.confidence.tests))
3070                .chain(view.lines.iter().flat_map(|line| &line.tests))
3071                .collect::<Vec<_>>();
3072            assert!(
3073                mentions.len() >= 2,
3074                "the fixture names its test in several places"
3075            );
3076            let first = mentions[0];
3077            for mention in &mentions {
3078                assert_eq!(*mention, first);
3079                assert!(
3080                    mention.same_allocation(first),
3081                    "every mention shares one copy"
3082                );
3083            }
3084        }
3085        fs::remove_dir_all(root).unwrap();
3086    }
3087
3088    #[test]
3089    fn references_numbered_as_they_arrive_come_out_as_the_sets_inserted_directly() {
3090        // Out of order, repeated, interleaved across obligations, and sharing
3091        // long prefixes, as test and phase ids do.
3092        let arrivals = [
3093            ("py:statement:b", "h11/tests/test_x.py::test_b[2-50]"),
3094            ("py:statement:a", "h11/tests/test_x.py::test_b[2-50]"),
3095            ("py:statement:b", "h11/tests/test_x.py::test_a[1-50]"),
3096            ("py:statement:b", "h11/tests/test_x.py::test_b[2-50]"),
3097            ("py:statement:a", "h11/tests/test_x.py::test_b[10-50]"),
3098            ("py:statement:b", "h11/tests/test_x.py::test_a[1-50]"),
3099            ("py:statement:c", "python-phase:9"),
3100            ("py:statement:c", "python-phase:10"),
3101            ("py:statement:b", "h11/tests/test_x.py::test_b[2-50]"),
3102        ];
3103        let mut ids = Interner::default();
3104        let mut hits = HitIds::default();
3105        let mut numbered = References::default();
3106        // A hit known to another relation must not become covered here.
3107        hits.number("unused", &mut ids);
3108        let mut direct = HashMap::<String, BTreeSet<String>>::new();
3109        for (obligation, name) in arrivals {
3110            let hit = hits.number(obligation, &mut ids);
3111            numbered.add(hit, name, &mut ids);
3112            direct
3113                .entry(obligation.to_owned())
3114                .or_default()
3115                .insert(name.to_owned());
3116        }
3117        let numbered = numbered
3118            .into_relation(&hits)
3119            .by_hit
3120            .into_iter()
3121            .map(|(obligation, reached)| {
3122                let names = reached
3123                    .names
3124                    .into_iter()
3125                    .map(String::from)
3126                    .collect::<Vec<_>>();
3127                let mut sorted_names = names.clone();
3128                sorted_names.sort();
3129                sorted_names.dedup();
3130                assert_eq!(
3131                    names, sorted_names,
3132                    "a relation lists its ids once, in order"
3133                );
3134                (obligation, names.into_iter().collect())
3135            })
3136            .collect::<HashMap<_, BTreeSet<String>>>();
3137        assert_eq!(numbered, direct);
3138        assert_eq!(
3139            hits.sorted((0..hits.names.len()).collect()),
3140            [
3141                "py:statement:a",
3142                "py:statement:b",
3143                "py:statement:c",
3144                "unused"
3145            ]
3146            .map(Id::from)
3147        );
3148    }
3149
3150    static ARCHIVE_ID: AtomicU64 = AtomicU64::new(0);
3151
3152    fn point(id: &str, line: usize) -> PointMeta {
3153        PointMeta {
3154            id: id.into(),
3155            kind: PointKind::Statement,
3156            file: "src/app.js".into(),
3157            line,
3158            column: 0,
3159            source: "work();".into(),
3160            label: None,
3161        }
3162    }
3163
3164    fn raw(id: &str, retry: usize, status: &str, hits: &[&str]) -> RawTestResult {
3165        RawTestResult {
3166            test_id: Some(id.into()),
3167            scope: None,
3168            test: id.into(),
3169            test_file: Some("tests/app.test.js".into()),
3170            title: None,
3171            retry: Some(retry),
3172            status: Some(status.into()),
3173            expected_status: None,
3174            flaky: false,
3175            provenance: TestProvenance {
3176                runner: "node:test".into(),
3177                kind: "unit".into(),
3178                project: None,
3179                source: "runner-default".into(),
3180            },
3181            role: "test".into(),
3182            attribution: crate::coverage_report::ATTRIBUTION_EXACT.into(),
3183            phases: vec![],
3184            runtime: vec![RuntimeSnapshot {
3185                decisions: vec![],
3186                hits: hits.iter().map(|hit| (*hit).into()).collect(),
3187                events: vec![],
3188                logicals: vec![],
3189                phase_id: None,
3190            }],
3191            browser: vec![],
3192            server: vec![],
3193        }
3194    }
3195
3196    #[test]
3197    fn declined_obligations_are_unmeasured_never_uncovered() {
3198        // Two statements, neither executed. One of them Supercov declined to
3199        // measure. The declined one must not appear as a coverage gap: it
3200        // leaves the denominator and is reported as unmeasured instead.
3201        let point = |id: &str, line: usize| PointMeta {
3202            id: id.into(),
3203            kind: PointKind::Statement,
3204            file: "src/app.js".into(),
3205            line,
3206            column: 0,
3207            source: "work();".into(),
3208            label: None,
3209        };
3210        let measured_only = CoverageManifest {
3211            decisions: vec![],
3212            points: vec![point("measured", 1)],
3213            branches: vec![],
3214            limitations: vec![],
3215            unmeasured: Vec::new(),
3216            scope: None,
3217            assertion_sites: Vec::new(),
3218        };
3219        let with_declined = CoverageManifest {
3220            decisions: vec![],
3221            points: vec![point("measured", 1), point("declined", 2)],
3222            branches: vec![],
3223            limitations: vec![],
3224            unmeasured: vec!["declined".into()],
3225            scope: None,
3226            assertion_sites: Vec::new(),
3227        };
3228
3229        let baseline =
3230            create_coverage_view(&measured_only, &[raw("test", 0, "passed", &[])], "time").unwrap();
3231        let view =
3232            create_coverage_view(&with_declined, &[raw("test", 0, "passed", &[])], "time").unwrap();
3233
3234        // The declined statement never inflates the uncovered count.
3235        assert_eq!(
3236            view.summary.statements.total, baseline.summary.statements.total,
3237            "a declined obligation stayed in the covered/uncovered denominator"
3238        );
3239        assert_eq!(view.summary.unmeasured_obligations, Some(1));
3240        assert_eq!(view.summary.exact_fraction_pct, Some(50.0));
3241
3242        // Its line leaves the line total too, but not the report: the line is
3243        // still there to hang a limitation on, and it is neither covered nor
3244        // uncovered.
3245        assert_eq!(
3246            view.summary.lines.total, baseline.summary.lines.total,
3247            "a declined obligation kept its line in the line denominator"
3248        );
3249        let declined_line = view
3250            .lines
3251            .iter()
3252            .find(|line| line.line == 2)
3253            .expect("the declined line stays addressable");
3254        assert!(!declined_line.measured);
3255        assert!(!declined_line.covered);
3256
3257        // A fully measured run keeps its previous output exactly: the new
3258        // fields are absent, not zero, so existing consumers see no change.
3259        assert_eq!(baseline.summary.unmeasured_obligations, None);
3260        assert_eq!(baseline.summary.exact_fraction_pct, None);
3261        let encoded = serde_json::to_string(&baseline.summary).unwrap();
3262        assert!(
3263            !encoded.contains("unmeasured") && !encoded.contains("exactFraction"),
3264            "a fully measured summary must serialize unchanged: {encoded}"
3265        );
3266    }
3267
3268    #[test]
3269    fn a_declined_line_that_executed_is_neither_covered_nor_uncovered() {
3270        // The subtle case: the statement ran, but Supercov could not measure
3271        // it, so its line has no coverage question to answer. Counting it as
3272        // covered would inflate the ratio with a line nothing verified.
3273        let point = |id: &str| PointMeta {
3274            id: id.into(),
3275            kind: PointKind::Statement,
3276            file: "src/app.js".into(),
3277            line: 1,
3278            column: 0,
3279            source: "work();".into(),
3280            label: None,
3281        };
3282        let manifest = CoverageManifest {
3283            decisions: vec![],
3284            points: vec![point("declined")],
3285            branches: vec![],
3286            limitations: vec![],
3287            unmeasured: vec!["declined".into()],
3288            scope: None,
3289            assertion_sites: Vec::new(),
3290        };
3291        let view = create_coverage_view(
3292            &manifest,
3293            &[raw("test", 0, "passed", &["declined"])],
3294            "time",
3295        )
3296        .unwrap();
3297
3298        assert_eq!(view.summary.lines.total, 0);
3299        assert_eq!(view.summary.lines.covered, 0);
3300        let line = view.lines.first().expect("the line stays addressable");
3301        assert!(!line.measured);
3302        assert!(!line.covered, "an unmeasured line is not covered either");
3303    }
3304
3305    #[test]
3306    fn report_retains_unexecuted_manifest_conditions() {
3307        let manifest = CoverageManifest {
3308            unmeasured: Vec::new(),
3309            decisions: vec![DecisionMeta {
3310                id: "decision".into(),
3311                file: "src/app.js".into(),
3312                line: 1,
3313                column: 0,
3314                source: "left && right".into(),
3315                conditions: vec!["left".into(), "right".into()],
3316                kind: "if".into(),
3317            }],
3318            points: vec![],
3319            branches: vec![],
3320            limitations: vec![],
3321            scope: None,
3322            assertion_sites: Vec::new(),
3323        };
3324        let view =
3325            create_coverage_view(&manifest, &[raw("test", 0, "passed", &[])], "time").unwrap();
3326        assert_eq!(view.summary.conditions, 2);
3327        assert_eq!(view.summary.covered_conditions, 0);
3328        assert_eq!(view.decisions[0].conditions.len(), 2);
3329    }
3330
3331    #[test]
3332    fn frozen_manifest_ignores_out_of_scope_synthetic_decisions() {
3333        let manifest = CoverageManifest {
3334            unmeasured: Vec::new(),
3335            decisions: vec![DecisionMeta {
3336                id: "application-decision".into(),
3337                file: "src/app.js".into(),
3338                line: 1,
3339                column: 0,
3340                source: "left && right".into(),
3341                conditions: vec!["left".into(), "right".into()],
3342                kind: "if".into(),
3343            }],
3344            points: vec![],
3345            branches: vec![],
3346            limitations: vec![],
3347            scope: None,
3348            assertion_sites: Vec::new(),
3349        };
3350        let mut attempt = raw("test", 0, "passed", &[]);
3351        attempt.runtime[0].decisions.push(DecisionSnapshot {
3352            meta: DecisionMeta {
3353                id: "synthetic-fixture".into(),
3354                file: "fixtures/generated.js".into(),
3355                line: 1,
3356                column: 0,
3357                source: "a && b && c".into(),
3358                conditions: vec!["a".into(), "b".into(), "c".into()],
3359                kind: "if".into(),
3360            },
3361            vectors: vec![McdcVector {
3362                values: vec![Some(true), Some(true), Some(true)],
3363                outcome: true,
3364            }],
3365        });
3366
3367        let view = create_coverage_view(&manifest, &[attempt], "time").unwrap();
3368        assert_eq!(view.decisions.len(), 1);
3369        assert_eq!(view.decisions[0].meta.id, "application-decision");
3370        assert!(view.decisions[0].vectors.is_empty());
3371    }
3372
3373    #[test]
3374    fn frozen_manifest_rejects_in_scope_unknown_or_changed_decisions() {
3375        let expected = DecisionMeta {
3376            id: "application-decision".into(),
3377            file: "src/app.js".into(),
3378            line: 1,
3379            column: 0,
3380            source: "left && right".into(),
3381            conditions: vec!["left".into(), "right".into()],
3382            kind: "if".into(),
3383        };
3384        let manifest = CoverageManifest {
3385            unmeasured: Vec::new(),
3386            decisions: vec![expected.clone()],
3387            points: vec![],
3388            branches: vec![],
3389            limitations: vec![],
3390            scope: Some(serde_json::json!({
3391                "entries": [{ "file": "src/empty.js", "status": "included" }]
3392            })),
3393            assertion_sites: Vec::new(),
3394        };
3395        let vector = McdcVector {
3396            values: vec![Some(true), Some(true)],
3397            outcome: true,
3398        };
3399
3400        let mut unknown = raw("test", 0, "passed", &[]);
3401        unknown.runtime[0].decisions.push(DecisionSnapshot {
3402            meta: DecisionMeta {
3403                id: "unknown-decision".into(),
3404                file: "src/empty.js".into(),
3405                ..expected.clone()
3406            },
3407            vectors: vec![vector.clone()],
3408        });
3409        assert!(matches!(
3410            create_coverage_view(&manifest, &[unknown], "time"),
3411            Err(ReportError::InvalidServerRecord(reason))
3412                if reason.contains("absent from the frozen manifest")
3413        ));
3414
3415        let mut changed = raw("test", 0, "passed", &[]);
3416        changed.runtime[0].decisions.push(DecisionSnapshot {
3417            meta: DecisionMeta {
3418                source: "left || right".into(),
3419                ..expected
3420            },
3421            vectors: vec![vector],
3422        });
3423        assert!(matches!(
3424            create_coverage_view(&manifest, &[changed], "time"),
3425            Err(ReportError::InvalidServerRecord(reason))
3426                if reason.contains("differs from the frozen manifest")
3427        ));
3428    }
3429
3430    #[test]
3431    fn neither_timestamp_nor_explicit_phase_links_award_assertion_credit() {
3432        let manifest = CoverageManifest {
3433            unmeasured: Vec::new(),
3434            decisions: vec![],
3435            points: vec![point("hit", 1)],
3436            branches: vec![],
3437            limitations: vec![],
3438            scope: None,
3439            assertion_sites: Vec::new(),
3440        };
3441        let phase = CoveragePhase {
3442            id: "assertion".into(),
3443            kind: "assertion".into(),
3444            operation: "equal".into(),
3445            source: None,
3446            caused_by_phase_id: None,
3447            started_at_ms: 100,
3448            ended_at_ms: Some(120),
3449            status: Some("passed".into()),
3450            error: None,
3451        };
3452        let mut attempt = raw("test", 0, "passed", &["hit"]);
3453        attempt.phases.push(phase.clone());
3454        attempt.runtime[0].events.push(RuntimeEvent {
3455            event_type: "hit".into(),
3456            id: "hit".into(),
3457            vector: None,
3458            timestamp_ms: 110,
3459            phase_id: None,
3460            statement_id: None,
3461            environment: "server".into(),
3462        });
3463        let inferred = create_coverage_view(&manifest, &[attempt.clone()], "time").unwrap();
3464        assert_eq!(inferred.points[0].confidence.level, "executed");
3465        assert!(!inferred.points[0].confidence.asserted);
3466
3467        attempt.runtime[0].events[0].phase_id = Some(phase.id);
3468        let explicit = create_coverage_view(&manifest, &[attempt], "time").unwrap();
3469        assert_eq!(explicit.points[0].confidence.level, "executed");
3470        assert!(!explicit.points[0].confidence.asserted);
3471    }
3472
3473    #[test]
3474    fn verified_view_uses_only_the_terminal_successful_attempt() {
3475        let manifest = CoverageManifest {
3476            unmeasured: Vec::new(),
3477            decisions: vec![],
3478            points: vec![point("failed", 1), point("passed", 2), point("expected", 3)],
3479            branches: vec![],
3480            limitations: vec![],
3481            scope: None,
3482            assertion_sites: Vec::new(),
3483        };
3484        let failed = raw("flaky", 0, "failed", &["failed"]);
3485        let mut passed = raw("flaky", 1, "passed", &["passed"]);
3486        passed.flaky = true;
3487        let mut expected = raw("expected-failure", 0, "passed", &["expected"]);
3488        expected.expected_status = Some("failed".into());
3489        let request = CoverageReportRequest {
3490            run_id: "run".into(),
3491            manifest,
3492            raw_results: vec![failed, passed, expected],
3493            generated_at: "time".into(),
3494            coverage_model: None,
3495            integrity: None,
3496            test_exit_code: ExitCodeInput::Missing,
3497        };
3498        let report = analyze_coverage_results(&request).unwrap();
3499        assert!(!report.filters.passed.points[0].covered);
3500        assert!(report.filters.passed.points[1].covered);
3501        assert!(!report.filters.passed.points[2].covered);
3502        assert!(report.filters.failed.points[0].covered);
3503        assert_eq!(
3504            report
3505                .view
3506                .tests
3507                .iter()
3508                .find(|test| test.name == "expected-failure")
3509                .unwrap()
3510                .outcome,
3511            "failed"
3512        );
3513        assert_eq!(report.view.tests[1].outcome, "flaky");
3514    }
3515
3516    #[test]
3517    fn expected_failure_is_a_green_outcome_but_not_verified_or_failed_coverage() {
3518        let mut expected = raw("expected-failure", 0, "failed", &["expected"]);
3519        expected.expected_status = Some("failed".into());
3520        let companion = raw("expected-failure", 0, "failed", &["expected"]);
3521        let request = CoverageReportRequest {
3522            run_id: "run".into(),
3523            manifest: CoverageManifest {
3524                unmeasured: Vec::new(),
3525                decisions: vec![],
3526                points: vec![point("expected", 1)],
3527                branches: vec![],
3528                limitations: vec![],
3529                scope: None,
3530                assertion_sites: Vec::new(),
3531            },
3532            raw_results: vec![companion, expected],
3533            generated_at: "time".into(),
3534            coverage_model: None,
3535            integrity: None,
3536            test_exit_code: ExitCodeInput::Missing,
3537        };
3538        let report = analyze_coverage_results(&request).unwrap();
3539        assert_eq!(report.view.tests[0].outcome, "passed");
3540        assert!(!report.filters.passed.points[0].covered);
3541        assert!(!report.filters.failed.points[0].covered);
3542    }
3543
3544    #[test]
3545    fn selected_but_unstarted_test_is_not_an_invented_attempt() {
3546        let mut unstarted = raw("unstarted", 0, "unstarted", &[]);
3547        unstarted.scope = None;
3548        unstarted.retry = None;
3549        unstarted.runtime.clear();
3550        let request = CoverageReportRequest {
3551            run_id: "run".into(),
3552            manifest: CoverageManifest {
3553                unmeasured: Vec::new(),
3554                decisions: vec![],
3555                points: vec![],
3556                branches: vec![],
3557                limitations: vec![],
3558                scope: None,
3559                assertion_sites: Vec::new(),
3560            },
3561            raw_results: vec![unstarted],
3562            generated_at: "time".into(),
3563            coverage_model: None,
3564            integrity: None,
3565            test_exit_code: ExitCodeInput::Present(Some(100)),
3566        };
3567        let report = analyze_coverage_results(&request).unwrap();
3568        assert_eq!(report.view.tests[0].outcome, "unstarted");
3569        assert!(report.view.tests[0].attempts.is_empty());
3570        assert!(report.filters.passed.tests.is_empty());
3571        assert!(report.filters.failed.tests.is_empty());
3572    }
3573
3574    fn archive(mut entries: Vec<EvidenceArchiveEntry>) -> PathBuf {
3575        let nonce = SystemTime::now()
3576            .duration_since(SystemTime::UNIX_EPOCH)
3577            .unwrap()
3578            .as_nanos();
3579        let root = std::env::temp_dir().join(format!(
3580            "supercov-rust-report-{}-{nonce}-{}",
3581            std::process::id(),
3582            ARCHIVE_ID.fetch_add(1, Ordering::Relaxed)
3583        ));
3584        fs::create_dir_all(&root).unwrap();
3585        let path = root.join("evidence.raw.gz");
3586        if !entries
3587            .iter()
3588            .any(|entry| entry.path == "coverage-model.json")
3589        {
3590            entries.push(EvidenceArchiveEntry {
3591                path: "coverage-model.json".into(),
3592                contents: serde_json::to_vec(
3593                    &PersistedCoverageModel::from_declaration(&javascript_coverage_model())
3594                        .unwrap(),
3595                )
3596                .unwrap(),
3597            });
3598        }
3599        if !entries.iter().any(|entry| entry.path == "frontend.json") {
3600            entries.push(EvidenceArchiveEntry {
3601                path: "frontend.json".into(),
3602                contents: serde_json::to_vec(&serde_json::json!({
3603                    "protocolVersion": 2,
3604                    "frontendId": "javascript",
3605                    "frontendVersion": "fixture-v1",
3606                    "language": "javascript",
3607                    "structuralSource": "owned-probes",
3608                    "runners": [{
3609                        "runner": "node:test",
3610                        "executionModel": "serial-in-process",
3611                        "attribution": {
3612                            "run": "exact",
3613                            "worker": "unavailable",
3614                            "test": "exact",
3615                            "retry": "exact",
3616                            "phase": "exact",
3617                            "action": "exact",
3618                            "assertion": "exact"
3619                        },
3620                        "limitations": [{
3621                            "id": "fixture-worker-unavailable",
3622                            "scopes": ["worker"],
3623                            "reason": "The fixture does not require worker identity"
3624                        }]
3625                    }],
3626                    "structuralLimitations": []
3627                }))
3628                .unwrap(),
3629            });
3630        }
3631        write_archive(entries, &path).unwrap();
3632        path
3633    }
3634
3635    #[test]
3636    fn archive_analysis_rejects_any_malformed_recognized_jsonl() {
3637        let manifest = CoverageManifest {
3638            unmeasured: Vec::new(),
3639            decisions: vec![],
3640            points: vec![point("background-hit", 1), point("test-hit", 2)],
3641            branches: vec![],
3642            limitations: vec![],
3643            scope: None,
3644            assertion_sites: Vec::new(),
3645        };
3646        // Declare exactly the observed runners: the journal's node:test and the
3647        // synthesized background runner, shaped as the JavaScript run declares it.
3648        let unattributed = |axis: &str| {
3649            serde_json::json!({
3650                "id": format!("background-no-{axis}"),
3651                "scopes": [axis],
3652                "reason": format!("Runner background did not expose exact {axis} identity for every result")
3653            })
3654        };
3655        let frontend = serde_json::json!({
3656            "protocolVersion": 2,
3657            "frontendId": "javascript",
3658            "frontendVersion": "fixture-v1",
3659            "language": "javascript",
3660            "structuralSource": "owned-probes",
3661            "runners": [
3662                {
3663                    "runner": "node:test",
3664                    "executionModel": "serial-in-process",
3665                    "attribution": {
3666                        "run": "exact", "worker": "unavailable", "test": "exact", "retry": "exact",
3667                        "phase": "exact", "action": "exact", "assertion": "exact"
3668                    },
3669                    "limitations": [{
3670                        "id": "fixture-worker-unavailable",
3671                        "scopes": ["worker"],
3672                        "reason": "The fixture does not require worker identity"
3673                    }]
3674                },
3675                {
3676                    "runner": "background",
3677                    "executionModel": "parallel-unattributed",
3678                    "attribution": {
3679                        "run": "exact", "worker": "unavailable", "test": "unavailable", "retry": "unavailable",
3680                        "phase": "unavailable", "action": "unavailable", "assertion": "unavailable"
3681                    },
3682                    "limitations": [
3683                        unattributed("worker"), unattributed("test"), unattributed("retry"),
3684                        unattributed("phase"), unattributed("action"), unattributed("assertion")
3685                    ]
3686                }
3687            ],
3688            "structuralLimitations": []
3689        });
3690        let path = archive(vec![
3691            EvidenceArchiveEntry {
3692                path: "manifest.json".into(),
3693                contents: serde_json::to_vec(&manifest).unwrap(),
3694            },
3695            EvidenceArchiveEntry {
3696                path: "frontend.json".into(),
3697                contents: serde_json::to_vec(&frontend).unwrap(),
3698            },
3699            EvidenceArchiveEntry {
3700                path: "playwright-worker-1.mcdc.jsonl".into(),
3701                contents: {
3702                    let mut contents =
3703                        serde_json::to_vec(&raw("journal-test", 0, "passed", &["test-hit"]))
3704                            .unwrap();
3705                    contents.extend_from_slice(b"\npartial-final-line");
3706                    contents
3707                },
3708            },
3709            EvidenceArchiveEntry {
3710                path: "server/background/worker.jsonl".into(),
3711                contents: b"{\"type\":\"hit\",\"id\":\"background-hit\"}\nnot-json\n".to_vec(),
3712            },
3713        ]);
3714        let result = analyze_coverage_archive(&ArchiveReportRequest {
3715            archive_path: path.clone(),
3716            run_id: "run".into(),
3717            generated_at: "time".into(),
3718            integrity: None,
3719            test_exit_code: ExitCodeInput::Missing,
3720        });
3721        assert!(matches!(
3722            result,
3723            Err(ReportError::InvalidJson { path, .. })
3724                if path == "playwright-worker-1.mcdc.jsonl"
3725        ));
3726        fs::remove_dir_all(path.parent().unwrap()).unwrap();
3727    }
3728
3729    #[test]
3730    fn a_torn_background_record_is_counted_not_fatal() {
3731        // Pool VMs restored from one snapshot are clones with the same pid and
3732        // cached shard path; their appends over a shared mount tear lines. One
3733        // torn line is one lost record: the report must still build, count it,
3734        // and surface it through the corrupt-evidence accounting.
3735        let manifest = CoverageManifest {
3736            unmeasured: Vec::new(),
3737            decisions: vec![],
3738            points: vec![],
3739            branches: vec![],
3740            limitations: vec![],
3741            scope: None,
3742            assertion_sites: Vec::new(),
3743        };
3744        // Declare exactly the observed runners: the journal's node:test and the
3745        // synthesized background runner, shaped as the JavaScript run declares it.
3746        let unattributed = |axis: &str| {
3747            serde_json::json!({
3748                "id": format!("background-no-{axis}"),
3749                "scopes": [axis],
3750                "reason": format!("Runner background did not expose exact {axis} identity for every result")
3751            })
3752        };
3753        let frontend = serde_json::json!({
3754            "protocolVersion": 2,
3755            "frontendId": "javascript",
3756            "frontendVersion": "fixture-v1",
3757            "language": "javascript",
3758            "structuralSource": "owned-probes",
3759            "runners": [
3760                {
3761                    "runner": "node:test",
3762                    "executionModel": "serial-in-process",
3763                    "attribution": {
3764                        "run": "exact", "worker": "unavailable", "test": "exact", "retry": "exact",
3765                        "phase": "exact", "action": "exact", "assertion": "exact"
3766                    },
3767                    "limitations": [{
3768                        "id": "fixture-worker-unavailable",
3769                        "scopes": ["worker"],
3770                        "reason": "The fixture does not require worker identity"
3771                    }]
3772                },
3773                {
3774                    "runner": "background",
3775                    "executionModel": "parallel-unattributed",
3776                    "attribution": {
3777                        "run": "exact", "worker": "unavailable", "test": "unavailable", "retry": "unavailable",
3778                        "phase": "unavailable", "action": "unavailable", "assertion": "unavailable"
3779                    },
3780                    "limitations": [
3781                        unattributed("worker"), unattributed("test"), unattributed("retry"),
3782                        unattributed("phase"), unattributed("action"), unattributed("assertion")
3783                    ]
3784                }
3785            ],
3786            "structuralLimitations": []
3787        });
3788        let path = archive(vec![
3789            EvidenceArchiveEntry {
3790                path: "manifest.json".into(),
3791                contents: serde_json::to_vec(&manifest).unwrap(),
3792            },
3793            EvidenceArchiveEntry {
3794                path: "frontend.json".into(),
3795                contents: serde_json::to_vec(&frontend).unwrap(),
3796            },
3797            EvidenceArchiveEntry {
3798                path: "playwright-worker-1.mcdc.jsonl".into(),
3799                contents: {
3800                    let mut contents =
3801                        serde_json::to_vec(&raw("journal-test", 0, "passed", &["test-hit"]))
3802                            .unwrap();
3803                    contents.push(b'\n');
3804                    contents
3805                },
3806            },
3807            EvidenceArchiveEntry {
3808                path: "execution.37360-1.168.jsonl".into(),
3809                contents: b"418836ceb3ac9b6277f\"}}\n".to_vec(),
3810            },
3811            EvidenceArchiveEntry {
3812                path: "server/background/process-5118-a1b2c3d4-0.jsonl".into(),
3813                contents: concat!(
3814                    "{\"type\":\"hit\",\"id\":\"background-hit\"}\n",
3815                    "{\"type\":\"decision\",\"meta\":{\"id\":\"torn\",\"file\":\"app/rou{\"type\":\"hit\",\"id\":\"other-clone\"}\n",
3816                    "{\"type\":\"hit\",\"id\":\"after-tear\"}\n",
3817                )
3818                .as_bytes()
3819                .to_vec(),
3820            },
3821        ]);
3822        let report = analyze_coverage_archive(&ArchiveReportRequest {
3823            archive_path: path.clone(),
3824            run_id: "run".into(),
3825            generated_at: "time".into(),
3826            integrity: None,
3827            test_exit_code: ExitCodeInput::Missing,
3828        })
3829        .expect("a torn evidence line must not fail the whole run");
3830        let transport = report.view.transport.expect("transport stats");
3831        assert_eq!(transport.corrupt_records, 2);
3832        assert_eq!(transport.corrupt_files, 2);
3833        assert_eq!(transport.background_server_records, 2);
3834        fs::remove_dir_all(path.parent().unwrap()).unwrap();
3835    }
3836
3837    #[test]
3838    fn archive_analysis_rejects_cross_run_evidence() {
3839        let manifest = CoverageManifest {
3840            unmeasured: Vec::new(),
3841            decisions: vec![],
3842            points: vec![],
3843            branches: vec![],
3844            limitations: vec![],
3845            scope: None,
3846            assertion_sites: Vec::new(),
3847        };
3848        let mut result = raw("test", 0, "passed", &[]);
3849        result.scope = Some(ExecutionScope {
3850            version: 1,
3851            run_id: "other-run".into(),
3852            worker_id: "worker".into(),
3853            test_id: "test".into(),
3854            test_key: "key".into(),
3855            retry: 0,
3856            attempt_id: "attempt".into(),
3857        });
3858        let path = archive(vec![
3859            EvidenceArchiveEntry {
3860                path: "manifest.json".into(),
3861                contents: serde_json::to_vec(&manifest).unwrap(),
3862            },
3863            EvidenceArchiveEntry {
3864                path: "worker/mcdc.json".into(),
3865                contents: serde_json::to_vec(&result).unwrap(),
3866            },
3867        ]);
3868        assert!(matches!(
3869            analyze_coverage_archive(&ArchiveReportRequest {
3870                archive_path: path.clone(),
3871                run_id: "run".into(),
3872                generated_at: "time".into(),
3873                integrity: None,
3874                test_exit_code: ExitCodeInput::Missing,
3875            }),
3876            Err(ReportError::InvalidArchive(reason))
3877                if reason.contains("expected=run actual=other-run")
3878        ));
3879        fs::remove_dir_all(path.parent().unwrap()).unwrap();
3880    }
3881
3882    #[test]
3883    fn coverage_model_vectors_are_strict_and_language_binding_is_fatal() {
3884        let vectors: Value = serde_json::from_str(include_str!(
3885            "../test-assets/coverage-model-v1/vectors.json"
3886        ))
3887        .unwrap();
3888        for value in vectors["valid"].as_array().unwrap() {
3889            let model: PersistedCoverageModel = serde_json::from_value(value.clone()).unwrap();
3890            model.into_declaration().unwrap();
3891        }
3892        for vector in vectors["invalid"].as_array().unwrap() {
3893            let value = vector["value"].clone();
3894            if let Ok(model) = serde_json::from_value::<PersistedCoverageModel>(value) {
3895                assert!(
3896                    model.into_declaration().is_err(),
3897                    "accepted invalid model vector: {}",
3898                    vector["reason"]
3899                );
3900            }
3901        }
3902
3903        let manifest = CoverageManifest {
3904            unmeasured: Vec::new(),
3905            decisions: vec![],
3906            points: vec![],
3907            branches: vec![],
3908            limitations: vec![],
3909            scope: None,
3910            assertion_sites: Vec::new(),
3911        };
3912        let path = archive(vec![
3913            EvidenceArchiveEntry {
3914                path: "coverage-model.json".into(),
3915                contents: serde_json::to_vec(&PersistedCoverageModel {
3916                    schema_version: COVERAGE_MODEL_SCHEMA_VERSION,
3917                    language: "rust".into(),
3918                    variant: "rust-source-v1".into(),
3919                    name: "Rust source coverage".into(),
3920                    completeness_meaning: "Every Rust obligation was satisfied.".into(),
3921                    measured: vec!["Rust statements".into()],
3922                    not_measured: vec![],
3923                })
3924                .unwrap(),
3925            },
3926            EvidenceArchiveEntry {
3927                path: "manifest.json".into(),
3928                contents: serde_json::to_vec(&manifest).unwrap(),
3929            },
3930        ]);
3931        assert!(matches!(
3932            analyze_coverage_archive(&ArchiveReportRequest {
3933                archive_path: path.clone(),
3934                run_id: "run".into(),
3935                generated_at: "time".into(),
3936                integrity: None,
3937                test_exit_code: ExitCodeInput::Missing,
3938            }),
3939            Err(ReportError::InvalidArchive(reason))
3940                if reason.contains("javascript differs from coverage model language rust")
3941        ));
3942        fs::remove_dir_all(path.parent().unwrap()).unwrap();
3943    }
3944
3945    #[test]
3946    fn explicit_null_exit_code_remains_distinct_from_an_absent_exit_code() {
3947        let request: CoverageReportRequest = serde_json::from_value(serde_json::json!({
3948            "runId": "run",
3949            "manifest": { "decisions": [], "points": [], "branches": [] },
3950            "rawResults": [{
3951                "test": "test",
3952                "status": "passed",
3953                "browser": [],
3954                "server": []
3955            }],
3956            "generatedAt": "time",
3957            "testExitCode": null
3958        }))
3959        .unwrap();
3960        let report = analyze_coverage_results(&request).unwrap();
3961        assert_eq!(
3962            report.execution,
3963            Some(ExecutionResult {
3964                test_exit_code: None,
3965                valid: false,
3966            })
3967        );
3968    }
3969    #[test]
3970    fn a_phase_leaked_from_another_test_is_untagged_and_an_unknown_one_is_kept() {
3971        let record = |test: &str, phases: &[&str], events: &[(&str, &str)]| -> RawTestResult {
3972            serde_json::from_value(serde_json::json!({
3973                "test": test,
3974                "phases": phases.iter().map(|id| serde_json::json!({
3975                    "id": id, "kind": "assertion", "operation": "assert.ok", "startedAtMs": 0
3976                })).collect::<Vec<_>>(),
3977                "runtime": [{
3978                    "events": events.iter().map(|(id, phase)| serde_json::json!({
3979                        "type": "hit", "id": id, "timestampMs": 0, "phaseId": phase, "environment": "server"
3980                    })).collect::<Vec<_>>()
3981                }]
3982            }))
3983            .unwrap()
3984        };
3985        let mut results = vec![
3986            record(
3987                "upload",
3988                &["a-0:assertion:1"],
3989                &[("own", "a-0:assertion:1")],
3990            ),
3991            // The stream the upload left settling ran during the next test.
3992            record(
3993                "form data",
3994                &["b-0:assertion:1"],
3995                &[
3996                    ("late", "a-0:assertion:1"),
3997                    ("mine", "b-0:assertion:1"),
3998                    ("corrupt", "z-0:assertion:9"),
3999                ],
4000            ),
4001        ];
4002        release_leaked_phases(&mut results);
4003        let phases = |raw: &RawTestResult| {
4004            raw.runtime[0]
4005                .events
4006                .iter()
4007                .map(|event| (event.id.clone(), event.phase_id.clone()))
4008                .collect::<Vec<_>>()
4009        };
4010        assert_eq!(
4011            phases(&results[0]),
4012            [("own".into(), Some("a-0:assertion:1".into()))]
4013        );
4014        assert_eq!(
4015            phases(&results[1]),
4016            [
4017                ("late".into(), None),
4018                ("mine".into(), Some("b-0:assertion:1".into())),
4019                // No record declares it: that is corruption, and it is refused later.
4020                ("corrupt".into(), Some("z-0:assertion:9".into())),
4021            ]
4022        );
4023    }
4024
4025    #[test]
4026    fn a_test_run_twice_under_one_identity_keeps_both_executions_apart() {
4027        // ms runs its Jest suite twice, in Node's environment and the edge
4028        // runtime's; each process numbers the same test's attempt 0.
4029        let record = |status: &str, events: &[(&str, &str)]| -> RawTestResult {
4030            serde_json::from_value(serde_json::json!({
4031                "test": "parse",
4032                "testId": "parse",
4033                "retry": 0,
4034                "status": status,
4035                "phases": [
4036                    { "id": "t-0:assertion:1", "kind": "assertion", "operation": "expect", "startedAtMs": 0 },
4037                    { "id": "t-0:assertion:2", "kind": "assertion", "operation": "expect", "startedAtMs": 0, "causedByPhaseId": "t-0:assertion:1" }
4038                ],
4039                "runtime": [{
4040                    "events": events.iter().map(|(id, phase)| serde_json::json!({
4041                        "type": "hit", "id": id, "timestampMs": 0, "phaseId": phase, "environment": "server"
4042                    })).collect::<Vec<_>>()
4043                }]
4044            }))
4045            .unwrap()
4046        };
4047        let mut results = vec![
4048            record("failed", &[("node", "t-0:assertion:1")]),
4049            record("passed", &[("edge", "t-0:assertion:2")]),
4050            record("passed", &[("third", "t-0:assertion:1")]),
4051        ];
4052        separate_repeated_executions(&mut results);
4053        let ids = |raw: &RawTestResult| {
4054            raw.phases
4055                .iter()
4056                .map(|phase| (phase.id.clone(), phase.caused_by_phase_id.clone()))
4057                .collect::<Vec<_>>()
4058        };
4059        let events = |raw: &RawTestResult| {
4060            raw.runtime[0]
4061                .events
4062                .iter()
4063                .map(|event| event.phase_id.clone().unwrap())
4064                .collect::<Vec<_>>()
4065        };
4066        assert_eq!(
4067            ids(&results[0]),
4068            [
4069                ("t-0:assertion:1".into(), None),
4070                ("t-0:assertion:2".into(), Some("t-0:assertion:1".into()))
4071            ]
4072        );
4073        assert_eq!(
4074            ids(&results[1]),
4075            [
4076                ("t-0:assertion:1~2".into(), None),
4077                ("t-0:assertion:2~2".into(), Some("t-0:assertion:1~2".into()))
4078            ]
4079        );
4080        assert_eq!(events(&results[1]), ["t-0:assertion:2~2"]);
4081        assert_eq!(events(&results[2]), ["t-0:assertion:1~3"]);
4082
4083        let mut test = MutableTest {
4084            id: "parse".into(),
4085            name: "parse".into(),
4086            file: None,
4087            title: None,
4088            retries: BTreeSet::new(),
4089            attempts: BTreeMap::new(),
4090            unstarted: false,
4091            runner_reported_flaky: false,
4092            provenance: TestProvenance::default(),
4093            role: "test".into(),
4094            attribution: "exact".into(),
4095            hits: Vec::new(),
4096            decisions: BTreeMap::new(),
4097        };
4098        for raw in &results {
4099            record_attempt(&mut test, raw);
4100        }
4101        assert_eq!(
4102            test_outcome(&test),
4103            "failed",
4104            "a failed execution fails the attempt"
4105        );
4106    }
4107
4108    #[test]
4109    fn a_dimension_is_summarised_over_the_tests_it_can_describe() {
4110        // A test whose reach nothing recorded contributes no hits. Counting it
4111        // in the denominator of a coverage percentage reported a package
4112        // covered entirely by parallel tests as covered 0.00% -- a wrong
4113        // number, which is worse than a missing one, because it reads as a
4114        // suite that tests nothing.
4115        let exact = |id: &str, kind: &str| TestCoverageResult {
4116            id: id.into(),
4117            name: id.into(),
4118            file: None,
4119            title: None,
4120            retries: vec![],
4121            attempts: vec![],
4122            outcome: "passed".into(),
4123            provenance: TestProvenance {
4124                runner: "go-test".into(),
4125                kind: kind.into(),
4126                project: None,
4127                source: String::new(),
4128            },
4129            role: "test".into(),
4130            attribution: ATTRIBUTION_EXACT.into(),
4131            hits: vec![],
4132            decisions: vec![],
4133            lines: vec![],
4134        };
4135        let mut run_wide = exact("parallel", "unit");
4136        run_wide.attribution = ATTRIBUTION_RUN_WIDE.into();
4137
4138        // Whose coverage it is, and whether all of it is there, are separate
4139        // questions, and conflating them gets one of them wrong.
4140        //
4141        // `partial` coverage is the test's own -- Ruby credits a line to the
4142        // first test that reaches it, and that crediting is true -- so it
4143        // counts in a percentage, and a union over such tests is a union of
4144        // things that happened. What it cannot support is the opposite
4145        // inference: that a test not recorded against a line did not run it.
4146        assert!(coverage_is_its_own(&exact("serial", "unit").attribution));
4147        assert!(coverage_is_its_own(ATTRIBUTION_PARTIAL));
4148        assert!(!coverage_is_its_own(&run_wide.attribution));
4149
4150        assert!(coverage_is_complete(ATTRIBUTION_EXACT));
4151        assert!(!coverage_is_complete(ATTRIBUTION_PARTIAL));
4152        assert!(!coverage_is_complete(ATTRIBUTION_RUN_WIDE));
4153
4154        // A test's records merge to the least exact claim among them, in
4155        // whichever order they arrive.
4156        for (left, right, merged) in [
4157            (ATTRIBUTION_EXACT, ATTRIBUTION_PARTIAL, ATTRIBUTION_PARTIAL),
4158            (ATTRIBUTION_PARTIAL, ATTRIBUTION_EXACT, ATTRIBUTION_PARTIAL),
4159            (
4160                ATTRIBUTION_PARTIAL,
4161                ATTRIBUTION_RUN_WIDE,
4162                ATTRIBUTION_RUN_WIDE,
4163            ),
4164            (ATTRIBUTION_EXACT, ATTRIBUTION_EXACT, ATTRIBUTION_EXACT),
4165        ] {
4166            assert_eq!(least_exact(left, right), merged);
4167        }
4168
4169        // And a frontend that has never heard of the field keeps its meaning:
4170        // absent is exact, so nothing already measured changes shape.
4171        assert!(coverage_is_its_own(""));
4172        assert!(coverage_is_complete(""));
4173    }
4174}