Skip to main content

supercov_engine/
coverage_query.rs

1//! Language-neutral coverage query operators.
2//!
3//! Querying is deliberately separated from the CLI and storage container.
4//! This module accepts the frozen analyzed view and owns structural query
5//! semantics shared by every language frontend.
6
7use std::collections::{BTreeMap, BTreeSet, HashMap};
8
9use serde::{Deserialize, Serialize};
10
11use crate::interned::Id;
12use crate::{
13    agent_json::pagination,
14    coverage_analysis::{CoverageSummary, is_independence_pair},
15    coverage_index::{
16        CoverageDimension, CoverageIndex, CoverageIndexError, CoverageViewId, IndexedCoverageModel,
17        IndexedDecisionGap, IndexedDimensionCoverage, IndexedFileGap, IndexedGapDimensions,
18        IndexedHitMetadata, IndexedMeasurement, IndexedOutcomeCounts, IndexedScopeEntry,
19        IndexedSourceScope, IndexedSummaryConfidence, IndexedTestSummary,
20    },
21    coverage_report::{
22        CoverageConfidence, CoverageView, DecisionMeta, ReportError, SourceLine, TestAttempt,
23        TestProvenance, TransportStats, coverage_summary_for_tests,
24    },
25};
26use supercov_contracts::AgentPagination;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
29#[serde(rename_all = "lowercase")]
30pub enum MinimizeMetric {
31    All,
32    Lines,
33    Statements,
34    Functions,
35    Branches,
36    Mcdc,
37}
38
39#[derive(Debug, Clone, PartialEq, Serialize)]
40#[serde(rename_all = "camelCase")]
41pub struct MinimumTestSetResult {
42    pub optimal: bool,
43    #[serde(serialize_with = "crate::coverage_analysis::serialize_javascript_number")]
44    pub target: f64,
45    pub metric: MinimizeMetric,
46    pub selected: Vec<String>,
47    pub expanded: Vec<String>,
48    pub summary: CoverageSummary,
49    pub explored_states: usize,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
53pub struct CoverageMinimizedTest {
54    pub id: String,
55    pub name: String,
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub file: Option<String>,
58    pub runner: String,
59    pub kind: String,
60}
61
62#[derive(Debug, Clone, PartialEq, Serialize)]
63#[serde(rename_all = "camelCase")]
64pub struct CoverageMinimizeData {
65    pub run: String,
66    pub filters: CoverageQueryFilters,
67    pub optimal: bool,
68    #[serde(serialize_with = "crate::coverage_analysis::serialize_javascript_number")]
69    pub target: f64,
70    pub metric: MinimizeMetric,
71    pub selected: Vec<String>,
72    pub expanded: Vec<String>,
73    pub summary: CoverageSummary,
74    pub explored_states: usize,
75    pub selected_count: usize,
76    pub total_candidate_tests: usize,
77    pub tests: Vec<CoverageMinimizedTest>,
78}
79
80#[derive(Debug, Clone, Copy)]
81pub struct CoverageMinimizeQueryOptions<'a> {
82    pub run: &'a str,
83    pub view_id: CoverageViewId,
84    pub kind: Option<&'a str>,
85    pub runner: Option<&'a str>,
86    pub target: f64,
87    pub metric: MinimizeMetric,
88    pub max_states: usize,
89    pub offset: usize,
90    pub limit: usize,
91}
92
93pub fn coverage_minimize_query(
94    view: &CoverageView,
95    options: CoverageMinimizeQueryOptions<'_>,
96) -> Result<(CoverageMinimizeData, AgentPagination), QueryError> {
97    if options.limit == 0 {
98        return Err(QueryError::InvalidPagination);
99    }
100    let selected_ids = if options.kind.is_none() && options.runner.is_none() {
101        None
102    } else {
103        let ids = view
104            .tests
105            .iter()
106            .filter(|test| {
107                options.kind.is_none_or(|kind| test.provenance.kind == kind)
108                    && options
109                        .runner
110                        .is_none_or(|runner| test.provenance.runner == runner)
111            })
112            .map(|test| test.id.clone())
113            .collect::<BTreeSet<_>>();
114        if ids.is_empty() {
115            return Err(QueryError::TestFilterEmpty {
116                kind: options.kind.map(str::to_owned),
117                runner: options.runner.map(str::to_owned),
118            });
119        }
120        Some(ids)
121    };
122    let mut solver_view = view.clone();
123    if let Some(selected) = &selected_ids {
124        solver_view.tests.retain(|test| selected.contains(&test.id));
125    }
126    let minimized = minimum_test_set(
127        &solver_view,
128        options.target,
129        options.metric,
130        options.max_states,
131    )?;
132    let selected_details = minimized
133        .selected
134        .iter()
135        .map(|id| {
136            let test = view
137                .tests
138                .iter()
139                .find(|test| test.id == *id)
140                .ok_or(QueryError::InvalidRecordSelection)?;
141            Ok(CoverageMinimizedTest {
142                id: id.clone(),
143                name: test.name.clone(),
144                file: test.file.clone(),
145                runner: test.provenance.runner.clone(),
146                kind: test.provenance.kind.clone(),
147            })
148        })
149        .collect::<Result<Vec<_>, QueryError>>()?;
150    let total = selected_details.len();
151    let tests = selected_details
152        .iter()
153        .skip(options.offset)
154        .take(options.limit)
155        .cloned()
156        .collect::<Vec<_>>();
157    let returned = tests.len();
158    let total_candidate_tests = solver_view
159        .tests
160        .iter()
161        .filter(|test| test.role == "test")
162        .count();
163    Ok((
164        CoverageMinimizeData {
165            run: options.run.into(),
166            filters: query_filters(options.view_id, options.kind, options.runner),
167            optimal: minimized.optimal,
168            target: minimized.target,
169            metric: minimized.metric,
170            selected: minimized.selected,
171            expanded: minimized.expanded,
172            summary: minimized.summary,
173            explored_states: minimized.explored_states,
174            selected_count: total,
175            total_candidate_tests,
176            tests,
177        },
178        pagination(options.offset, options.limit, returned, total),
179    ))
180}
181
182#[derive(Debug)]
183pub enum QueryError {
184    InvalidTarget(f64),
185    UnattributedEvidence,
186    TargetUnreachable {
187        metric: MinimizeMetric,
188        target: f64,
189        reachable: f64,
190    },
191    ComplexityLimit {
192        candidate_tests: usize,
193        obligations: usize,
194        explored_states: usize,
195        max_states: usize,
196        target: f64,
197        metric: MinimizeMetric,
198    },
199    Analysis(ReportError),
200    Index(CoverageIndexError),
201    InvalidPagination,
202    TestFilterEmpty {
203        kind: Option<String>,
204        runner: Option<String>,
205    },
206    TestNotFound(String),
207    DecisionNotFound(String),
208    SourceNotFound(String),
209    AmbiguousSelector {
210        selector: String,
211        matches: Vec<String>,
212    },
213    InvalidRecordSelection,
214    ScopeUnavailable,
215}
216
217impl From<ReportError> for QueryError {
218    fn from(value: ReportError) -> Self {
219        Self::Analysis(value)
220    }
221}
222
223impl From<CoverageIndexError> for QueryError {
224    fn from(value: CoverageIndexError) -> Self {
225        Self::Index(value)
226    }
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
230#[serde(rename_all = "camelCase")]
231pub struct CoverageQueryFilters {
232    pub outcome: String,
233    pub kind: Option<String>,
234    pub runner: Option<String>,
235}
236
237#[derive(Debug, Clone, PartialEq, Serialize)]
238#[serde(rename_all = "camelCase")]
239pub struct CoverageFilesData {
240    pub run: String,
241    pub filters: CoverageQueryFilters,
242    pub metric: MinimizeMetric,
243    pub files: Vec<IndexedFileGap>,
244}
245
246#[derive(Debug, Clone, PartialEq, Serialize)]
247#[serde(rename_all = "camelCase")]
248pub struct CoverageGapsData {
249    pub run: String,
250    pub filters: CoverageQueryFilters,
251    pub metric: MinimizeMetric,
252    pub gaps: Vec<IndexedFileGap>,
253}
254
255#[derive(Debug, Clone, PartialEq, Serialize)]
256#[serde(rename_all = "camelCase")]
257pub struct CoverageKindsData {
258    pub run: String,
259    pub filters: CoverageQueryFilters,
260    pub kinds: Vec<IndexedDimensionCoverage>,
261}
262
263#[derive(Debug, Clone, PartialEq, Serialize)]
264#[serde(rename_all = "camelCase")]
265pub struct CoverageRunnersData {
266    pub run: String,
267    pub filters: CoverageQueryFilters,
268    pub runners: Vec<IndexedDimensionCoverage>,
269}
270
271/// Tests by how completely their coverage is their own.
272#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
273#[serde(rename_all = "camelCase")]
274pub struct TestAttributionCounts {
275    /// Credited with exactly what they reached.
276    pub exact: usize,
277    /// Credited with some of what they reached, and no way to say how much.
278    pub partial: usize,
279    /// Credited with none of it; what they reached is in the run's totals.
280    pub run_wide: usize,
281}
282
283impl TestAttributionCounts {
284    pub fn total(&self) -> usize {
285        self.exact + self.partial + self.run_wide
286    }
287}
288
289#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
290#[serde(rename_all = "camelCase")]
291pub struct CoverageDiagnostic {
292    pub code: String,
293    pub severity: String,
294    pub message: String,
295}
296
297#[derive(Debug, Clone, PartialEq, Serialize)]
298#[serde(rename_all = "camelCase")]
299pub struct CoverageSummaryData {
300    pub test_kind_sources: BTreeMap<String, usize>,
301    #[serde(skip_serializing_if = "Option::is_none")]
302    pub assertion_coverage: Option<serde_json::Value>,
303    pub run: String,
304    #[serde(default)]
305    pub command: Vec<String>,
306    #[serde(default, skip_serializing_if = "Vec::is_empty")]
307    pub hints: Vec<String>,
308    #[serde(skip_serializing_if = "Option::is_none")]
309    pub workspace: Option<String>,
310    pub filters: CoverageQueryFilters,
311    pub model: IndexedCoverageModel,
312    pub generated_at: String,
313    pub valid: bool,
314    #[serde(skip_serializing_if = "Option::is_none")]
315    pub test_exit_code: Option<i32>,
316    pub stale: bool,
317    pub stale_reasons: Vec<String>,
318    pub structurally_complete: bool,
319    pub complete: bool,
320    pub coverage: CoverageSummary,
321    pub measurement: IndexedMeasurement,
322    pub coverage_by_kind: Vec<IndexedDimensionCoverage>,
323    /// What the tests cover between them. `coverage` less this ran while no
324    /// test was running, which is why a run with one kind of test can show a
325    /// total above that kind's own.
326    #[serde(skip_serializing_if = "Option::is_none")]
327    pub coverage_by_tests: Option<CoverageSummary>,
328    #[serde(skip_serializing_if = "Option::is_none")]
329    pub e2e_gap_context: Option<CoverageKindGapContext>,
330    pub coverage_by_runner: Vec<IndexedDimensionCoverage>,
331    pub attribution: crate::coverage_index::IndexedAttribution,
332    /// How completely each test's coverage could be credited to it.
333    ///
334    /// Counted here rather than stored, because the per-test answer is already
335    /// in the run and a total is a read of it. A run written before the field
336    /// existed reports every test as exact, which is what its records say.
337    pub test_attribution: TestAttributionCounts,
338    #[serde(skip_serializing_if = "Option::is_none")]
339    pub transport: Option<TransportStats>,
340    pub diagnostics: Vec<CoverageDiagnostic>,
341    #[serde(skip_serializing_if = "Option::is_none")]
342    pub confidence: Option<IndexedSummaryConfidence>,
343    pub files_with_gaps: usize,
344    pub files_with_coverage_gaps: usize,
345    pub files_with_measurement_limitations: usize,
346    pub tests: usize,
347    pub setups: usize,
348    pub test_outcomes: IndexedOutcomeCounts,
349    #[serde(skip_serializing_if = "Option::is_none")]
350    pub source_scope: Option<IndexedSourceScope>,
351    /// Where the files discovery could not classify are, and the roots that
352    /// would settle them.
353    #[serde(skip_serializing_if = "Option::is_none")]
354    pub unclassified_source: Option<UnclassifiedSource>,
355}
356
357/// One row of the scope overview: the files of one place that share a status
358/// and the reason for it.
359#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
360#[serde(rename_all = "camelCase")]
361pub struct ScopeGroup {
362    pub status: String,
363    pub directory: String,
364    pub reason: String,
365    pub files: usize,
366}
367
368#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
369#[serde(rename_all = "camelCase")]
370pub struct ScopeDirectory {
371    pub directory: String,
372    pub files: usize,
373}
374
375/// The unclassified files of a run by where they are, and the source roots
376/// to name if they are the project's own code: the roots discovery found
377/// plus each of those places.
378#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
379#[serde(rename_all = "camelCase")]
380pub struct UnclassifiedSource {
381    pub directories: Vec<ScopeDirectory>,
382    pub roots: Vec<String>,
383}
384
385/// Where a reader would look for a file: the directory at the top of the
386/// project, or of its package in a workspace. A file that sits at that top
387/// is in `.`.
388fn scope_directory(entry: &IndexedScopeEntry) -> String {
389    let package = entry.package_root.as_deref().filter(|root| *root != ".");
390    let local = package
391        .and_then(|root| entry.file.strip_prefix(root))
392        .and_then(|rest| rest.strip_prefix('/'))
393        .unwrap_or(&entry.file);
394    match (package, local.split_once('/')) {
395        (Some(package), Some((first, _))) => format!("{package}/{first}"),
396        (Some(package), None) => package.to_owned(),
397        (None, Some((first, _))) => first.to_owned(),
398        (None, None) => ".".to_owned(),
399    }
400}
401
402fn scope_status_rank(status: &str) -> u8 {
403    match status {
404        "ambiguous" => 0,
405        "included" => 1,
406        "excluded" => 2,
407        _ => 3,
408    }
409}
410
411/// Every scope entry, grouped. 845 entries took five pages to read and an
412/// `awk` to see that 79 of 89 unclassified files were one directory.
413pub fn scope_groups(entries: &[IndexedScopeEntry]) -> Vec<ScopeGroup> {
414    let mut groups = BTreeMap::<(u8, String, String, String), usize>::new();
415    for entry in entries {
416        *groups
417            .entry((
418                scope_status_rank(&entry.status),
419                entry.status.clone(),
420                scope_directory(entry),
421                entry.reason.clone(),
422            ))
423            .or_default() += 1;
424    }
425    let mut groups = groups
426        .into_iter()
427        .map(|((rank, status, directory, reason), files)| {
428            (
429                rank,
430                ScopeGroup {
431                    status,
432                    directory,
433                    reason,
434                    files,
435                },
436            )
437        })
438        .collect::<Vec<_>>();
439    groups.sort_by(|(left_rank, left), (right_rank, right)| {
440        left_rank
441            .cmp(right_rank)
442            .then_with(|| right.files.cmp(&left.files))
443            .then_with(|| left.directory.cmp(&right.directory))
444            .then_with(|| left.reason.cmp(&right.reason))
445    });
446    groups.into_iter().map(|(_, group)| group).collect()
447}
448
449pub fn unclassified_source(
450    roots: &[String],
451    entries: &[IndexedScopeEntry],
452) -> Option<UnclassifiedSource> {
453    let mut places = BTreeMap::<String, usize>::new();
454    let mut named = Vec::<(String, usize)>::new();
455    for entry in entries.iter().filter(|entry| entry.status == "ambiguous") {
456        let directory = scope_directory(entry);
457        *places.entry(directory.clone()).or_default() += 1;
458        // A file at the top is named itself; naming `.` would take the tests
459        // and the configuration with it.
460        let root = if entry.file.contains('/') && directory != "." {
461            directory
462        } else {
463            entry.file.clone()
464        };
465        match named.iter_mut().find(|(name, _)| *name == root) {
466            Some((_, files)) => *files += 1,
467            None => named.push((root, 1)),
468        }
469    }
470    if places.is_empty() {
471        return None;
472    }
473    let mut directories = places
474        .into_iter()
475        .map(|(directory, files)| ScopeDirectory { directory, files })
476        .collect::<Vec<_>>();
477    directories.sort_by(|left, right| {
478        right
479            .files
480            .cmp(&left.files)
481            .then_with(|| left.directory.cmp(&right.directory))
482    });
483    named.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));
484    let mut all = roots.to_vec();
485    for (root, _) in named {
486        if !all.contains(&root) {
487            all.push(root);
488        }
489    }
490    Some(UnclassifiedSource {
491        directories,
492        roots: all,
493    })
494}
495
496#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
497#[serde(rename_all = "camelCase")]
498pub struct CoverageKindGapContext {
499    pub kind: String,
500    pub other_kinds: Vec<String>,
501    pub covered_elsewhere: IndexedGapDimensions,
502    pub uncovered_everywhere: IndexedGapDimensions,
503}
504
505#[derive(Debug, Clone)]
506pub struct CoverageSummaryQueryOptions<'a> {
507    pub run: &'a str,
508    pub view: CoverageViewId,
509    pub kind: Option<&'a str>,
510    pub runner: Option<&'a str>,
511    pub valid: bool,
512    pub test_exit_code: Option<i32>,
513    pub stale: bool,
514    pub stale_reasons: Vec<String>,
515}
516
517#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
518pub struct ScopeCounts {
519    pub included: usize,
520    pub excluded: usize,
521    pub ambiguous: usize,
522}
523
524#[derive(Debug, Clone, PartialEq, Serialize)]
525#[serde(rename_all = "camelCase")]
526pub struct CoverageScopeData {
527    pub run: String,
528    pub filters: CoverageQueryFilters,
529    pub kind: String,
530    pub language: String,
531    pub model: String,
532    #[serde(skip_serializing_if = "Option::is_none")]
533    pub mode: Option<String>,
534    pub roots: Vec<String>,
535    #[serde(skip_serializing_if = "Option::is_none")]
536    pub unit: Option<String>,
537    #[serde(skip_serializing_if = "Option::is_none")]
538    pub measurement_complete: Option<bool>,
539    pub counts: ScopeCounts,
540    pub measurement: IndexedMeasurement,
541    /// Every entry of the scope, grouped; `entries` is one page of them.
542    pub groups: Vec<ScopeGroup>,
543    #[serde(skip_serializing_if = "Option::is_none")]
544    pub unclassified_source: Option<UnclassifiedSource>,
545    pub entries: Vec<IndexedScopeEntry>,
546}
547
548#[derive(Debug, Clone, Copy)]
549pub struct CoverageScopeQueryOptions<'a> {
550    pub run: &'a str,
551    pub view: CoverageViewId,
552    pub kind: Option<&'a str>,
553    pub runner: Option<&'a str>,
554    pub offset: usize,
555    pub limit: usize,
556}
557
558#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
559pub struct CoverageLocation {
560    pub file: String,
561    pub line: usize,
562}
563
564#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
565pub struct CoverageCoveringTest {
566    pub id: String,
567    pub name: String,
568    pub provenance: TestProvenance,
569}
570
571#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
572#[serde(rename_all = "camelCase")]
573pub struct CoverageCoveringPhase {
574    pub id: String,
575    pub kind: String,
576    pub operation: String,
577    #[serde(skip_serializing_if = "Option::is_none")]
578    pub source: Option<String>,
579    pub test: String,
580    #[serde(skip_serializing_if = "Option::is_none")]
581    pub status: Option<String>,
582    #[serde(skip_serializing_if = "Option::is_none")]
583    pub caused_by_phase_id: Option<String>,
584}
585
586#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
587#[serde(rename_all = "camelCase")]
588pub struct CoverageAnchor {
589    pub kind: String,
590    pub id: String,
591    pub column: usize,
592    pub covered: bool,
593    #[serde(skip_serializing_if = "Option::is_none")]
594    pub source: Option<String>,
595    #[serde(skip_serializing_if = "Option::is_none")]
596    pub missing: Option<String>,
597    pub covering_tests: usize,
598    #[serde(skip_serializing_if = "Option::is_none")]
599    pub covered_conditions: Option<usize>,
600    #[serde(skip_serializing_if = "Option::is_none")]
601    pub conditions: Option<usize>,
602}
603
604#[derive(Debug, Clone, PartialEq, Serialize)]
605#[serde(rename_all = "camelCase")]
606pub struct CoverageCoversLineData {
607    pub run: String,
608    pub filters: CoverageQueryFilters,
609    pub location: CoverageLocation,
610    #[serde(skip_serializing_if = "Option::is_none")]
611    pub source: Option<String>,
612    #[serde(skip_serializing_if = "Option::is_none")]
613    pub source_origin: Option<String>,
614    pub covered: bool,
615    pub confidence: CoverageConfidence,
616    pub total_tests: usize,
617    pub total_phases: usize,
618    pub total_anchored: usize,
619    pub covered_anchored: usize,
620    pub total_limitations: usize,
621    pub total_remaining: usize,
622    pub tests: Vec<CoverageCoveringTest>,
623    pub phases: Vec<CoverageCoveringPhase>,
624    pub anchored: Vec<CoverageAnchor>,
625    pub limitations: Vec<CoverageFileLimitation>,
626    pub remaining: Vec<CoverageFileObligation>,
627    /// The run's saved assertion assessment for this place, attached by the
628    /// CLI when the run has one.
629    #[serde(skip_serializing_if = "Option::is_none")]
630    pub assertions: Option<serde_json::Value>,
631}
632
633#[derive(Debug, Clone, PartialEq, Serialize)]
634#[serde(rename_all = "camelCase")]
635pub struct CoverageCoversAnchorsData {
636    pub run: String,
637    pub filters: CoverageQueryFilters,
638    pub location: CoverageLocation,
639    #[serde(skip_serializing_if = "Option::is_none")]
640    pub source: Option<String>,
641    #[serde(skip_serializing_if = "Option::is_none")]
642    pub source_origin: Option<String>,
643    pub line_obligation: bool,
644    pub anchored: Vec<CoverageAnchor>,
645    pub total_anchored: usize,
646    pub covered_anchored: usize,
647    pub total_limitations: usize,
648    pub limitations: Vec<CoverageFileLimitation>,
649    pub total_remaining: usize,
650    pub remaining: Vec<CoverageFileObligation>,
651    pub total_tests: usize,
652    pub tests: Vec<CoverageCoveringTest>,
653    /// The run's saved assertion assessment for this place, attached by the
654    /// CLI when the run has one.
655    #[serde(skip_serializing_if = "Option::is_none")]
656    pub assertions: Option<serde_json::Value>,
657}
658
659#[derive(Debug, Clone, PartialEq, Serialize)]
660#[serde(untagged)]
661pub enum CoverageCoversData {
662    Line(CoverageCoversLineData),
663    Anchors(CoverageCoversAnchorsData),
664}
665
666#[derive(Debug, Clone, Copy)]
667pub struct CoverageCoversQueryOptions<'a> {
668    pub run: &'a str,
669    pub view: CoverageViewId,
670    pub kind: Option<&'a str>,
671    pub runner: Option<&'a str>,
672    pub file: &'a str,
673    pub line: usize,
674    pub offset: usize,
675    pub limit: usize,
676}
677
678fn query_filters(
679    view: CoverageViewId,
680    kind: Option<&str>,
681    runner: Option<&str>,
682) -> CoverageQueryFilters {
683    CoverageQueryFilters {
684        outcome: match view {
685            CoverageViewId::All => "all",
686            CoverageViewId::Passed => "passed",
687            CoverageViewId::Failed => "failed",
688        }
689        .into(),
690        kind: kind.map(str::to_owned),
691        runner: runner.map(str::to_owned),
692    }
693}
694
695fn selected_test_ids(
696    tests: &[IndexedTestSummary],
697    kind: Option<&str>,
698    runner: Option<&str>,
699) -> Result<Option<BTreeSet<String>>, QueryError> {
700    if kind.is_none() && runner.is_none() {
701        return Ok(None);
702    }
703    let selected = tests
704        .iter()
705        .filter(|test| {
706            kind.is_none_or(|kind| test.provenance.kind == kind)
707                && runner.is_none_or(|runner| test.provenance.runner == runner)
708        })
709        .map(|test| test.id.clone())
710        .collect::<BTreeSet<_>>();
711    if selected.is_empty() {
712        return Err(QueryError::TestFilterEmpty {
713            kind: kind.map(str::to_owned),
714            runner: runner.map(str::to_owned),
715        });
716    }
717    Ok(Some(selected))
718}
719
720pub fn coverage_covers_query(
721    index: &CoverageIndex<'_>,
722    options: CoverageCoversQueryOptions<'_>,
723) -> Result<(CoverageCoversData, AgentPagination), QueryError> {
724    if options.limit == 0 {
725        return Err(QueryError::InvalidPagination);
726    }
727    let tests = index.test_summaries(options.view)?;
728    let selected = selected_test_ids(&tests, options.kind, options.runner)?;
729    let selected_includes = |id: &str| selected.as_ref().is_none_or(|ids| ids.contains(id));
730    let filters = query_filters(options.view, options.kind, options.runner);
731    let location = CoverageLocation {
732        file: options.file.into(),
733        line: options.line,
734    };
735    let metadata = index
736        .hit_metadata(options.view)?
737        .into_iter()
738        .map(|value| (value.id.clone(), value))
739        .collect::<HashMap<_, _>>();
740    let decisions = index
741        .decision_details(options.view)?
742        .into_iter()
743        .map(|value| (value.meta.id.clone(), value))
744        .collect::<HashMap<_, _>>();
745    let anchors = index.anchors(options.view, options.file, options.line)?;
746    let tests_by_id = tests
747        .iter()
748        .map(|test| (test.id.clone(), test.clone()))
749        .collect::<HashMap<_, _>>();
750    let mut anchor_test_ids = anchors
751        .iter()
752        .flat_map(|anchor| anchor.tests.iter())
753        .filter(|id| selected_includes(id))
754        .cloned()
755        .collect::<BTreeSet<_>>();
756    for anchor in anchors.iter().filter(|anchor| anchor.kind == "branch") {
757        anchor_test_ids.extend(
758            metadata
759                .values()
760                .filter(|detail| detail.parent_id.as_deref() == Some(anchor.id.as_str()))
761                .flat_map(|detail| detail.tests.iter())
762                .filter(|id| selected_includes(id))
763                .cloned(),
764        );
765    }
766    let all_anchor_tests = anchor_test_ids
767        .iter()
768        .map(|id| {
769            let test = tests_by_id.get(id);
770            CoverageCoveringTest {
771                id: id.clone(),
772                name: test.map_or_else(|| id.clone(), |test| test.name.clone()),
773                provenance: test
774                    .map_or_else(TestProvenance::default, |test| test.provenance.clone()),
775            }
776        })
777        .collect::<Vec<_>>();
778    let total_anchor_tests = all_anchor_tests.len();
779    let anchor_tests_page = all_anchor_tests
780        .iter()
781        .skip(options.offset)
782        .take(options.limit)
783        .cloned()
784        .collect::<Vec<_>>();
785    let render_anchor = |anchor: crate::coverage_index::IndexedAnchor| {
786        let branch_alternatives = if anchor.kind == "branch" {
787            metadata
788                .values()
789                .filter(|detail| {
790                    detail.obligation == "branch"
791                        && detail.parent_id.as_deref() == Some(anchor.id.as_str())
792                })
793                .collect::<Vec<_>>()
794        } else {
795            Vec::new()
796        };
797        let branch_tests = branch_alternatives
798            .iter()
799            .flat_map(|detail| detail.tests.iter())
800            .filter(|test| selected_includes(test))
801            .cloned()
802            .collect::<BTreeSet<_>>();
803        let covering_tests = if anchor.kind == "branch" {
804            branch_tests.len()
805        } else {
806            anchor
807                .tests
808                .iter()
809                .filter(|test| selected_includes(test))
810                .count()
811        };
812        let detail = metadata.get(&anchor.id);
813        let decision = decisions
814            .get(&anchor.id)
815            .cloned()
816            .map(|decision| selected_decision(decision, selected.as_ref()));
817        let conditions = decision.as_ref().map_or(anchor.conditions, |decision| {
818            Some(decision.conditions.len())
819        });
820        let covered_conditions = decision
821            .as_ref()
822            .map_or(anchor.covered_conditions, |decision| {
823                Some(
824                    decision
825                        .conditions
826                        .iter()
827                        .filter(|condition| condition.covered)
828                        .count(),
829                )
830            });
831        let covered = match anchor.kind.as_str() {
832            "decision" => conditions == covered_conditions,
833            "branch" if !branch_alternatives.is_empty() => branch_alternatives
834                .iter()
835                .all(|detail| detail.tests.iter().any(|test| selected_includes(test))),
836            "branch" => anchor.covered,
837            _ => covering_tests > 0,
838        };
839        let branch_source = branch_alternatives
840            .first()
841            .map(|detail| detail.source.clone());
842        let missing_branch_alternatives = branch_alternatives
843            .iter()
844            .filter(|detail| !detail.tests.iter().any(|test| selected_includes(test)))
845            .filter_map(|detail| detail.alternative.clone())
846            .collect::<Vec<_>>();
847        CoverageAnchor {
848            kind: anchor.kind,
849            id: anchor.id,
850            column: anchor.column,
851            covered,
852            source: decision
853                .as_ref()
854                .map(|decision| decision.meta.source.clone())
855                .or(branch_source)
856                .or_else(|| {
857                    detail.map(|detail| {
858                        detail
859                            .label
860                            .clone()
861                            .unwrap_or_else(|| detail.source.clone())
862                    })
863                })
864                .and_then(|source| compact_source(&source)),
865            missing: if missing_branch_alternatives.is_empty() {
866                detail.and_then(|detail| detail.alternative.clone())
867            } else {
868                Some(missing_branch_alternatives.join("; "))
869            },
870            covering_tests,
871            covered_conditions,
872            conditions,
873        }
874    };
875    let rendered_anchors = anchors.into_iter().map(render_anchor).collect::<Vec<_>>();
876    let total_anchored = rendered_anchors.len();
877    let covered_anchored = rendered_anchors
878        .iter()
879        .filter(|anchor| anchor.covered)
880        .count();
881    let all_limitations = index
882        .limitations(options.view)?
883        .into_iter()
884        .filter(|limitation| limitation.file == options.file && limitation.line == options.line)
885        .map(|limitation| CoverageFileLimitation {
886            id: limitation.id,
887            kind: limitation.kind,
888            file: limitation.file,
889            line: limitation.line,
890            column: limitation.column,
891            source: limitation.source,
892            reason: limitation.reason,
893            blocking: limitation.blocking,
894            effect: "outside-measured-denominator".into(),
895        })
896        .collect::<Vec<_>>();
897    let total_limitations = all_limitations.len();
898    let limitations_page = all_limitations
899        .iter()
900        .skip(options.offset)
901        .take(options.limit)
902        .cloned()
903        .collect::<Vec<_>>();
904    let (file_detail, _) = coverage_file_detail_query(
905        index,
906        CoverageFileDetailOptions {
907            run: options.run,
908            view: options.view,
909            kind: options.kind,
910            runner: options.runner,
911            selector: options.file,
912            metric: MinimizeMetric::All,
913            offset: 0,
914            limit: usize::MAX,
915        },
916    )?;
917    let gap_line = file_detail
918        .gap_lines
919        .into_iter()
920        .find(|gap| gap.line == options.line);
921    // Covered lines are absent from the gap projection, but their anchored
922    // statement/branch/decision metadata still carries the source snippet.
923    // Prefer the exact gap-line text when present and otherwise retain that
924    // anchored source so a successful line query never contradicts itself by
925    // claiming the source is unavailable while printing it below.
926    let source = gap_line
927        .as_ref()
928        .and_then(|gap| gap.source.clone())
929        .or_else(|| {
930            rendered_anchors
931                .iter()
932                .filter_map(|anchor| anchor.source.clone())
933                .min_by_key(|source| source.len())
934        });
935    let all_remaining = gap_line.map_or_else(Vec::new, |gap| gap.obligations);
936    let total_remaining = all_remaining.len();
937    let remaining_page = all_remaining
938        .iter()
939        .skip(options.offset)
940        .take(options.limit)
941        .cloned()
942        .collect::<Vec<_>>();
943    let Some(line) = index.line(options.view, options.file, options.line)? else {
944        let anchored = rendered_anchors
945            .iter()
946            .skip(options.offset)
947            .take(options.limit)
948            .cloned()
949            .collect::<Vec<_>>();
950        let total = total_anchored.max(total_limitations).max(total_remaining);
951        let total = total.max(total_anchor_tests);
952        let returned = anchored
953            .len()
954            .max(limitations_page.len())
955            .max(remaining_page.len())
956            .max(anchor_tests_page.len());
957        return Ok((
958            CoverageCoversData::Anchors(CoverageCoversAnchorsData {
959                run: options.run.into(),
960                filters,
961                location,
962                source,
963                source_origin: None,
964                line_obligation: false,
965                anchored,
966                total_anchored,
967                covered_anchored,
968                total_limitations,
969                limitations: limitations_page,
970                total_remaining,
971                remaining: remaining_page,
972                total_tests: total_anchor_tests,
973                tests: anchor_tests_page,
974                assertions: None,
975            }),
976            pagination(options.offset, options.limit, returned, total),
977        ));
978    };
979    let all_tests = line
980        .tests
981        .iter()
982        .filter(|id| selected_includes(id))
983        .map(|id| {
984            let test = tests_by_id.get(id);
985            CoverageCoveringTest {
986                id: id.clone(),
987                name: test.map_or_else(|| id.clone(), |test| test.name.clone()),
988                provenance: test
989                    .map_or_else(TestProvenance::default, |test| test.provenance.clone()),
990            }
991        })
992        .collect::<Vec<_>>();
993    let phases_by_id = index
994        .phase_summaries(options.view)?
995        .into_iter()
996        .map(|phase| (phase.id.clone(), phase))
997        .collect::<HashMap<_, _>>();
998    let all_phases = line
999        .phases
1000        .iter()
1001        .filter_map(|id| phases_by_id.get(id))
1002        .filter(|phase| selected_includes(&phase.test))
1003        .map(|phase| CoverageCoveringPhase {
1004            id: phase.id.clone(),
1005            kind: phase.kind.clone(),
1006            operation: phase.operation.clone(),
1007            source: phase.source.clone(),
1008            test: phase.test.clone(),
1009            status: phase.status.clone(),
1010            caused_by_phase_id: phase.caused_by_phase_id.clone(),
1011        })
1012        .collect::<Vec<_>>();
1013    let tests_page = all_tests
1014        .iter()
1015        .skip(options.offset)
1016        .take(options.limit)
1017        .cloned()
1018        .collect::<Vec<_>>();
1019    let phases_page = all_phases
1020        .iter()
1021        .skip(options.offset)
1022        .take(options.limit)
1023        .cloned()
1024        .collect::<Vec<_>>();
1025    let anchored_page = rendered_anchors
1026        .into_iter()
1027        .skip(options.offset)
1028        .take(options.limit)
1029        .collect::<Vec<_>>();
1030    let total = all_tests
1031        .len()
1032        .max(all_phases.len())
1033        .max(total_anchored)
1034        .max(total_limitations)
1035        .max(total_remaining);
1036    let returned = tests_page
1037        .len()
1038        .max(phases_page.len())
1039        .max(anchored_page.len())
1040        .max(limitations_page.len())
1041        .max(remaining_page.len());
1042    Ok((
1043        CoverageCoversData::Line(CoverageCoversLineData {
1044            run: options.run.into(),
1045            filters,
1046            location,
1047            source,
1048            source_origin: None,
1049            covered: line.tests.iter().any(|test| selected_includes(test)),
1050            confidence: line.confidence,
1051            total_tests: all_tests.len(),
1052            total_phases: all_phases.len(),
1053            total_anchored,
1054            covered_anchored,
1055            total_limitations,
1056            total_remaining,
1057            tests: tests_page,
1058            phases: phases_page,
1059            anchored: anchored_page,
1060            limitations: limitations_page,
1061            remaining: remaining_page,
1062            assertions: None,
1063        }),
1064        pagination(options.offset, options.limit, returned, total),
1065    ))
1066}
1067
1068#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1069pub struct CoverageTestMatch {
1070    pub id: String,
1071    pub name: String,
1072    pub outcome: String,
1073    pub provenance: TestProvenance,
1074}
1075
1076#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1077#[serde(rename_all = "camelCase")]
1078pub struct CoverageHitDetail {
1079    pub id: String,
1080    pub obligation: String,
1081    #[serde(skip_serializing_if = "Option::is_none")]
1082    pub branch_kind: Option<String>,
1083    #[serde(skip_serializing_if = "Option::is_none")]
1084    pub file: Option<String>,
1085    #[serde(skip_serializing_if = "Option::is_none")]
1086    pub line: Option<usize>,
1087    #[serde(skip_serializing_if = "Option::is_none")]
1088    pub column: Option<usize>,
1089    #[serde(skip_serializing_if = "Option::is_none")]
1090    pub label: Option<String>,
1091    #[serde(skip_serializing_if = "Option::is_none")]
1092    pub alternative: Option<String>,
1093}
1094
1095#[derive(Debug, Clone, PartialEq, Serialize)]
1096pub struct CoverageTestDecision {
1097    pub id: String,
1098    pub vectors: Vec<crate::coverage_analysis::McdcVector>,
1099    pub meta: DecisionMeta,
1100}
1101
1102#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1103#[serde(rename_all = "camelCase")]
1104pub struct CoverageTestPhase {
1105    pub id: String,
1106    pub kind: String,
1107    pub operation: String,
1108    #[serde(skip_serializing_if = "Option::is_none")]
1109    pub source: Option<String>,
1110    #[serde(skip_serializing_if = "Option::is_none")]
1111    pub status: Option<String>,
1112    #[serde(skip_serializing_if = "Option::is_none")]
1113    pub caused_by_phase_id: Option<String>,
1114    pub lines: usize,
1115    pub decisions: usize,
1116}
1117
1118#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1119pub struct CoverageTestTotals {
1120    pub lines: usize,
1121    pub hits: usize,
1122    pub decisions: usize,
1123    pub phases: usize,
1124}
1125
1126#[derive(Debug, Clone, PartialEq, Serialize)]
1127#[serde(rename_all = "camelCase")]
1128pub struct CoverageSelectedTest {
1129    pub id: String,
1130    pub name: String,
1131    #[serde(skip_serializing_if = "Option::is_none")]
1132    pub file: Option<String>,
1133    #[serde(skip_serializing_if = "Option::is_none")]
1134    pub title: Option<String>,
1135    pub retries: Vec<usize>,
1136    pub attempts: Vec<TestAttempt>,
1137    pub outcome: String,
1138    pub provenance: TestProvenance,
1139    pub role: String,
1140    /// `exact`, or `run-wide` when this test ran and nothing can say what it
1141    /// reached. Under `run-wide` the totals below are zero because the test
1142    /// has no coverage of its own, not because it reached nothing.
1143    pub attribution: String,
1144    pub hits: Vec<String>,
1145    pub decisions: Vec<CoverageTestDecision>,
1146    pub lines: Vec<SourceLine>,
1147    pub hit_details: Vec<CoverageHitDetail>,
1148    pub phases: Vec<CoverageTestPhase>,
1149    pub totals: CoverageTestTotals,
1150}
1151
1152#[derive(Debug, Clone, PartialEq, Serialize)]
1153pub struct CoverageTestMatchesData {
1154    pub run: String,
1155    pub filters: CoverageQueryFilters,
1156    pub tests: Vec<CoverageTestMatch>,
1157}
1158
1159#[derive(Debug, Clone, PartialEq, Serialize)]
1160#[serde(rename_all = "camelCase")]
1161pub struct CoverageTestDetailData {
1162    pub run: String,
1163    pub filters: CoverageQueryFilters,
1164    pub pagination_applies_to: String,
1165    pub tests: Vec<CoverageSelectedTest>,
1166}
1167
1168#[derive(Debug, Clone, PartialEq, Serialize)]
1169#[serde(untagged)]
1170pub enum CoverageTestData {
1171    Matches(CoverageTestMatchesData),
1172    Detail(CoverageTestDetailData),
1173}
1174
1175#[derive(Debug, Clone, Copy)]
1176pub struct CoverageTestQueryOptions<'a> {
1177    pub run: &'a str,
1178    pub view: CoverageViewId,
1179    pub kind: Option<&'a str>,
1180    pub runner: Option<&'a str>,
1181    pub selector: &'a str,
1182    pub offset: usize,
1183    pub limit: usize,
1184}
1185
1186fn hit_detail(id: &str, metadata: Option<&IndexedHitMetadata>) -> CoverageHitDetail {
1187    match metadata {
1188        Some(metadata) => CoverageHitDetail {
1189            id: id.into(),
1190            obligation: metadata.obligation.clone(),
1191            branch_kind: metadata.branch_kind.clone(),
1192            file: Some(metadata.file.clone()),
1193            line: Some(metadata.line),
1194            column: Some(metadata.column),
1195            label: metadata.label.clone(),
1196            alternative: metadata.alternative.clone(),
1197        },
1198        None => CoverageHitDetail {
1199            id: id.into(),
1200            obligation: "unknown".into(),
1201            branch_kind: None,
1202            file: None,
1203            line: None,
1204            column: None,
1205            label: None,
1206            alternative: None,
1207        },
1208    }
1209}
1210
1211pub fn coverage_test_query(
1212    index: &CoverageIndex<'_>,
1213    options: CoverageTestQueryOptions<'_>,
1214) -> Result<(CoverageTestData, AgentPagination), QueryError> {
1215    if options.limit == 0 {
1216        return Err(QueryError::InvalidPagination);
1217    }
1218    let tests = index.test_details(options.view)?;
1219    let summaries = tests
1220        .iter()
1221        .map(|test| test.summary.clone())
1222        .collect::<Vec<_>>();
1223    let selected = selected_test_ids(&summaries, options.kind, options.runner)?;
1224    let selector = options.selector.to_lowercase();
1225    let matches = tests
1226        .into_iter()
1227        .filter(|test| {
1228            selected
1229                .as_ref()
1230                .is_none_or(|ids| ids.contains(&test.summary.id))
1231        })
1232        .filter(|test| {
1233            test.summary.id == selector || test.summary.name.to_lowercase().contains(&selector)
1234        })
1235        .collect::<Vec<_>>();
1236    if matches.is_empty() {
1237        return Err(QueryError::TestNotFound(options.selector.into()));
1238    }
1239    let filters = query_filters(options.view, options.kind, options.runner);
1240    if matches.len() > 1 {
1241        let total = matches.len();
1242        let page = matches
1243            .into_iter()
1244            .skip(options.offset)
1245            .take(options.limit)
1246            .map(|test| CoverageTestMatch {
1247                id: test.summary.id,
1248                name: test.summary.name,
1249                outcome: test.summary.outcome,
1250                provenance: test.summary.provenance,
1251            })
1252            .collect::<Vec<_>>();
1253        let returned = page.len();
1254        return Ok((
1255            CoverageTestData::Matches(CoverageTestMatchesData {
1256                run: options.run.into(),
1257                filters,
1258                tests: page,
1259            }),
1260            pagination(options.offset, options.limit, returned, total),
1261        ));
1262    }
1263    let test = matches.into_iter().next().expect("one test match");
1264    let metadata = index
1265        .hit_metadata(options.view)?
1266        .into_iter()
1267        .map(|metadata| (metadata.id.clone(), metadata))
1268        .collect::<HashMap<_, _>>();
1269    let decisions = index
1270        .decision_metadata(options.view)?
1271        .into_iter()
1272        .map(|decision| (decision.id.clone(), decision))
1273        .collect::<HashMap<_, _>>();
1274    let all_phases = index
1275        .phase_summaries(options.view)?
1276        .into_iter()
1277        .filter(|phase| phase.test == test.summary.id)
1278        .map(|phase| CoverageTestPhase {
1279            id: phase.id,
1280            kind: phase.kind,
1281            operation: phase.operation,
1282            source: phase.source,
1283            status: phase.status,
1284            caused_by_phase_id: phase.caused_by_phase_id,
1285            lines: phase.lines,
1286            decisions: phase.decisions,
1287        })
1288        .collect::<Vec<_>>();
1289    let totals = CoverageTestTotals {
1290        lines: test.lines.len(),
1291        hits: test.hits.len(),
1292        decisions: test.decisions.len(),
1293        phases: all_phases.len(),
1294    };
1295    let total = totals
1296        .lines
1297        .max(totals.hits)
1298        .max(totals.decisions)
1299        .max(totals.phases);
1300    let lines = test
1301        .lines
1302        .iter()
1303        .skip(options.offset)
1304        .take(options.limit)
1305        .cloned()
1306        .collect::<Vec<_>>();
1307    let hits = test
1308        .hits
1309        .iter()
1310        .skip(options.offset)
1311        .take(options.limit)
1312        .cloned()
1313        .collect::<Vec<_>>();
1314    let hit_details = test
1315        .hits
1316        .iter()
1317        .skip(options.offset)
1318        .take(options.limit)
1319        .map(|id| hit_detail(id, metadata.get(id)))
1320        .collect::<Vec<_>>();
1321    let test_decisions = test
1322        .decisions
1323        .iter()
1324        .skip(options.offset)
1325        .take(options.limit)
1326        .map(|decision| {
1327            Ok(CoverageTestDecision {
1328                id: decision.id.clone(),
1329                vectors: decision.vectors.clone(),
1330                meta: decisions
1331                    .get(&decision.id)
1332                    .cloned()
1333                    .ok_or(QueryError::InvalidRecordSelection)?,
1334            })
1335        })
1336        .collect::<Result<Vec<_>, QueryError>>()?;
1337    let phases = all_phases
1338        .into_iter()
1339        .skip(options.offset)
1340        .take(options.limit)
1341        .collect::<Vec<_>>();
1342    let returned = lines
1343        .len()
1344        .max(hits.len())
1345        .max(test_decisions.len())
1346        .max(phases.len());
1347    Ok((
1348        CoverageTestData::Detail(CoverageTestDetailData {
1349            run: options.run.into(),
1350            filters,
1351            pagination_applies_to:
1352                "lines, hits/hitDetails, decisions, and phases independently within the test".into(),
1353            tests: vec![CoverageSelectedTest {
1354                id: test.summary.id,
1355                name: test.summary.name,
1356                file: test.summary.file,
1357                title: test.summary.title,
1358                retries: test.retries,
1359                attempts: test.attempts,
1360                outcome: test.summary.outcome,
1361                provenance: test.summary.provenance,
1362                role: test.summary.role,
1363                attribution: test.summary.attribution,
1364                hits,
1365                decisions: test_decisions,
1366                lines,
1367                hit_details,
1368                phases,
1369                totals,
1370            }],
1371        }),
1372        pagination(options.offset, options.limit, returned, total),
1373    ))
1374}
1375
1376#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1377pub struct CoverageDecisionMatch {
1378    pub id: String,
1379    pub file: String,
1380    pub line: usize,
1381    pub column: usize,
1382    pub source: String,
1383}
1384
1385#[derive(Debug, Clone, PartialEq, Serialize)]
1386#[serde(rename_all = "camelCase")]
1387pub struct CoverageDecisionCondition {
1388    pub index: usize,
1389    pub source: String,
1390    pub covered: bool,
1391    #[serde(skip_serializing_if = "Option::is_none")]
1392    pub assertion_covered: Option<bool>,
1393    #[serde(skip_serializing_if = "Option::is_none")]
1394    pub witness: Option<[crate::coverage_analysis::McdcVector; 2]>,
1395    #[serde(skip_serializing_if = "Option::is_none")]
1396    pub witness_tests: Option<[Vec<Id>; 2]>,
1397}
1398
1399#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1400#[serde(rename_all = "camelCase")]
1401pub struct CoverageDecisionTotals {
1402    pub conditions: usize,
1403    pub vector_observations: usize,
1404    pub tests: usize,
1405}
1406
1407#[derive(Debug, Clone, PartialEq, Serialize)]
1408#[serde(rename_all = "camelCase")]
1409pub struct CoverageSelectedDecision {
1410    pub meta: DecisionMeta,
1411    pub executed: bool,
1412    pub covered: bool,
1413    pub vectors: Vec<crate::coverage_analysis::McdcVector>,
1414    pub vector_observations: Vec<crate::coverage_report::VectorObservation>,
1415    pub conditions: Vec<CoverageDecisionCondition>,
1416    pub tests: Vec<Id>,
1417    pub confidence: CoverageConfidence,
1418    pub totals: CoverageDecisionTotals,
1419}
1420
1421#[derive(Debug, Clone, PartialEq, Serialize)]
1422pub struct CoverageDecisionMatchesData {
1423    pub run: String,
1424    pub filters: CoverageQueryFilters,
1425    pub decisions: Vec<CoverageDecisionMatch>,
1426}
1427
1428#[derive(Debug, Clone, PartialEq, Serialize)]
1429#[serde(rename_all = "camelCase")]
1430pub struct CoverageDecisionDetailData {
1431    pub run: String,
1432    pub filters: CoverageQueryFilters,
1433    pub pagination_applies_to: String,
1434    pub decisions: Vec<CoverageSelectedDecision>,
1435}
1436
1437#[derive(Debug, Clone, PartialEq, Serialize)]
1438#[serde(untagged)]
1439pub enum CoverageDecisionData {
1440    Matches(CoverageDecisionMatchesData),
1441    Detail(CoverageDecisionDetailData),
1442}
1443
1444#[derive(Debug, Clone, Copy)]
1445pub struct CoverageDecisionQueryOptions<'a> {
1446    pub run: &'a str,
1447    pub view: CoverageViewId,
1448    pub kind: Option<&'a str>,
1449    pub runner: Option<&'a str>,
1450    pub selector: &'a str,
1451    pub offset: usize,
1452    pub limit: usize,
1453}
1454
1455fn selector_location(selector: &str) -> Option<(&str, usize)> {
1456    let (prefix, last) = selector.rsplit_once(':')?;
1457    let last = last.parse::<usize>().ok()?;
1458    if let Some((file, possible_line)) = prefix.rsplit_once(':')
1459        && let Ok(line) = possible_line.parse::<usize>()
1460    {
1461        return Some((file, line));
1462    }
1463    Some((prefix, last))
1464}
1465
1466fn selected_decision(
1467    decision: crate::coverage_report::DecisionResult,
1468    selected: Option<&BTreeSet<String>>,
1469) -> crate::coverage_report::DecisionResult {
1470    let Some(selected) = selected else {
1471        return decision;
1472    };
1473    let vector_observations = decision
1474        .vector_observations
1475        .into_iter()
1476        .filter_map(|mut observation| {
1477            observation
1478                .tests
1479                .retain(|test| selected.contains(test.as_str()));
1480            (!observation.tests.is_empty()).then_some(observation)
1481        })
1482        .collect::<Vec<_>>();
1483    let vectors = vector_observations
1484        .iter()
1485        .map(|observation| observation.vector.clone())
1486        .collect::<Vec<_>>();
1487    let conditions = decision
1488        .meta
1489        .conditions
1490        .iter()
1491        .enumerate()
1492        .map(|(index, source)| {
1493            let mut witness = None;
1494            let mut witness_tests = None;
1495            'pairs: for left in 0..vector_observations.len() {
1496                for right in (left + 1)..vector_observations.len() {
1497                    let first = &vector_observations[left];
1498                    let second = &vector_observations[right];
1499                    if is_independence_pair(&first.vector, &second.vector, index) {
1500                        witness = Some([first.vector.clone(), second.vector.clone()]);
1501                        witness_tests = Some([first.tests.clone(), second.tests.clone()]);
1502                        break 'pairs;
1503                    }
1504                }
1505            }
1506            crate::coverage_report::ConditionResult {
1507                index,
1508                source: source.clone(),
1509                covered: witness.is_some(),
1510                assertion_covered: false,
1511                witness,
1512                witness_tests,
1513            }
1514        })
1515        .collect::<Vec<_>>();
1516    crate::coverage_report::DecisionResult {
1517        meta: decision.meta,
1518        executed: !vectors.is_empty(),
1519        covered: conditions.iter().all(|condition| condition.covered),
1520        vectors,
1521        vector_observations,
1522        conditions,
1523        tests: decision
1524            .tests
1525            .into_iter()
1526            .filter(|test| selected.contains(test.as_str()))
1527            .collect(),
1528        confidence: decision.confidence,
1529    }
1530}
1531
1532pub fn coverage_decision_query(
1533    index: &CoverageIndex<'_>,
1534    options: CoverageDecisionQueryOptions<'_>,
1535) -> Result<(CoverageDecisionData, AgentPagination), QueryError> {
1536    if options.limit == 0 {
1537        return Err(QueryError::InvalidPagination);
1538    }
1539    let tests = index.test_summaries(options.view)?;
1540    let selected = selected_test_ids(&tests, options.kind, options.runner)?;
1541    let decisions = index.decision_details(options.view)?;
1542    let mut matches = decisions
1543        .into_iter()
1544        .filter(|decision| decision.meta.id == options.selector)
1545        .collect::<Vec<_>>();
1546    if matches.is_empty()
1547        && let Some((file, line)) = selector_location(options.selector)
1548    {
1549        matches = index
1550            .decision_details(options.view)?
1551            .into_iter()
1552            .filter(|decision| decision.meta.file == file && decision.meta.line == line)
1553            .collect();
1554    }
1555    if matches.is_empty() {
1556        return Err(QueryError::DecisionNotFound(options.selector.into()));
1557    }
1558    let filters = query_filters(options.view, options.kind, options.runner);
1559    if matches.len() > 1 {
1560        let total = matches.len();
1561        let page = matches
1562            .into_iter()
1563            .skip(options.offset)
1564            .take(options.limit)
1565            .map(|decision| CoverageDecisionMatch {
1566                id: decision.meta.id,
1567                file: decision.meta.file,
1568                line: decision.meta.line,
1569                column: decision.meta.column,
1570                source: decision.meta.source,
1571            })
1572            .collect::<Vec<_>>();
1573        let returned = page.len();
1574        return Ok((
1575            CoverageDecisionData::Matches(CoverageDecisionMatchesData {
1576                run: options.run.into(),
1577                filters,
1578                decisions: page,
1579            }),
1580            pagination(options.offset, options.limit, returned, total),
1581        ));
1582    }
1583    let filtered = selected_decision(
1584        matches.into_iter().next().expect("one decision match"),
1585        selected.as_ref(),
1586    );
1587    let totals = CoverageDecisionTotals {
1588        conditions: filtered.conditions.len(),
1589        vector_observations: filtered.vector_observations.len(),
1590        tests: filtered.tests.len(),
1591    };
1592    let total = totals
1593        .conditions
1594        .max(totals.vector_observations)
1595        .max(totals.tests);
1596    let vector_observations = filtered
1597        .vector_observations
1598        .iter()
1599        .skip(options.offset)
1600        .take(options.limit)
1601        .cloned()
1602        .collect::<Vec<_>>();
1603    let vectors = vector_observations
1604        .iter()
1605        .map(|observation| observation.vector.clone())
1606        .collect::<Vec<_>>();
1607    let conditions = filtered
1608        .conditions
1609        .iter()
1610        .skip(options.offset)
1611        .take(options.limit)
1612        .map(|condition| CoverageDecisionCondition {
1613            index: condition.index,
1614            source: condition.source.clone(),
1615            covered: condition.covered,
1616            assertion_covered: selected.is_none().then_some(condition.assertion_covered),
1617            witness: condition.witness.clone(),
1618            witness_tests: condition.witness_tests.clone(),
1619        })
1620        .collect::<Vec<_>>();
1621    let tests = filtered
1622        .tests
1623        .iter()
1624        .skip(options.offset)
1625        .take(options.limit)
1626        .cloned()
1627        .collect::<Vec<_>>();
1628    let returned = vector_observations
1629        .len()
1630        .max(conditions.len())
1631        .max(tests.len());
1632    Ok((
1633        CoverageDecisionData::Detail(CoverageDecisionDetailData {
1634            run: options.run.into(),
1635            filters,
1636            pagination_applies_to:
1637                "conditions, vectorObservations, and tests independently within each decision"
1638                    .into(),
1639            decisions: vec![CoverageSelectedDecision {
1640                meta: filtered.meta,
1641                executed: filtered.executed,
1642                covered: filtered.covered,
1643                vectors,
1644                vector_observations,
1645                conditions,
1646                tests,
1647                confidence: filtered.confidence,
1648                totals,
1649            }],
1650        }),
1651        pagination(options.offset, options.limit, returned, total),
1652    ))
1653}
1654
1655#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1656pub struct CoverageOtherTest {
1657    pub id: String,
1658    pub name: String,
1659}
1660
1661#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1662#[serde(rename_all = "camelCase")]
1663pub struct CoverageOtherCoverage {
1664    pub covered_elsewhere: bool,
1665    pub kinds: Vec<String>,
1666    pub runners: Vec<String>,
1667    pub tests: Vec<CoverageOtherTest>,
1668}
1669
1670#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1671#[serde(rename_all = "camelCase")]
1672pub struct CoverageLineObligation {
1673    pub kind: String,
1674    pub id: String,
1675    pub line: usize,
1676    pub other_coverage: CoverageOtherCoverage,
1677}
1678
1679#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1680#[serde(rename_all = "camelCase")]
1681pub struct CoveragePointObligation {
1682    pub kind: String,
1683    pub id: String,
1684    pub line: usize,
1685    pub column: usize,
1686    pub source: String,
1687    pub other_coverage: CoverageOtherCoverage,
1688}
1689
1690#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1691#[serde(rename_all = "camelCase")]
1692pub struct CoverageBranchObligation {
1693    pub kind: String,
1694    pub id: String,
1695    pub line: usize,
1696    pub column: usize,
1697    pub source: String,
1698    pub missing: String,
1699    pub other_coverage: CoverageOtherCoverage,
1700}
1701
1702#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1703#[serde(rename_all = "camelCase")]
1704pub struct CoverageMcdcObligation {
1705    pub kind: String,
1706    pub id: String,
1707    pub line: usize,
1708    pub column: usize,
1709    pub decision: String,
1710    pub missing_condition: String,
1711    #[serde(skip)]
1712    pub condition_index: usize,
1713    pub observed_vectors: Vec<String>,
1714    pub other_coverage: CoverageOtherCoverage,
1715}
1716
1717#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1718#[serde(untagged)]
1719pub enum CoverageFileObligation {
1720    Line(CoverageLineObligation),
1721    Point(CoveragePointObligation),
1722    Branch(CoverageBranchObligation),
1723    Mcdc(CoverageMcdcObligation),
1724}
1725
1726impl CoverageFileObligation {
1727    fn line(&self) -> usize {
1728        match self {
1729            Self::Line(value) => value.line,
1730            Self::Point(value) => value.line,
1731            Self::Branch(value) => value.line,
1732            Self::Mcdc(value) => value.line,
1733        }
1734    }
1735
1736    fn kind(&self) -> &str {
1737        match self {
1738            Self::Line(value) => &value.kind,
1739            Self::Point(value) => &value.kind,
1740            Self::Branch(value) => &value.kind,
1741            Self::Mcdc(value) => &value.kind,
1742        }
1743    }
1744}
1745
1746#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1747pub struct CoverageFileLimitation {
1748    pub id: String,
1749    pub kind: String,
1750    pub file: String,
1751    pub line: usize,
1752    pub column: usize,
1753    pub source: String,
1754    pub reason: String,
1755    pub blocking: bool,
1756    pub effect: String,
1757}
1758
1759#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1760#[serde(rename_all = "camelCase")]
1761pub struct CoverageFileCounts {
1762    /// Measured lines in the file, and how many the selected tests covered:
1763    /// the file's own line coverage, comparable with other tools'.
1764    pub total_lines: usize,
1765    pub covered_lines: usize,
1766    pub uncovered_lines: usize,
1767    pub uncovered_statements: usize,
1768    pub uncovered_functions: usize,
1769    pub missing_branches: usize,
1770    pub missing_mcdc_conditions: usize,
1771    pub measurement_limitations: usize,
1772}
1773
1774#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1775#[serde(rename_all = "camelCase")]
1776pub struct CoverageFileGapLine {
1777    pub line: usize,
1778    pub state: String,
1779    #[serde(skip_serializing_if = "Option::is_none")]
1780    pub source: Option<String>,
1781    pub obligations: Vec<CoverageFileObligation>,
1782    pub limitations: Vec<CoverageFileLimitation>,
1783}
1784
1785#[derive(Debug, Clone, PartialEq, Serialize)]
1786#[serde(rename_all = "camelCase")]
1787pub struct CoverageFileDetailData {
1788    pub run: String,
1789    pub filters: CoverageQueryFilters,
1790    pub file: String,
1791    pub metric: MinimizeMetric,
1792    pub counts: CoverageFileCounts,
1793    pub total_tests: usize,
1794    pub total_obligations: usize,
1795    pub total_gap_lines: usize,
1796    pub gap_lines: Vec<CoverageFileGapLine>,
1797    pub total_limitations: usize,
1798    /// The run's saved assertion assessment for this place, attached by the
1799    /// CLI when the run has one.
1800    #[serde(skip_serializing_if = "Option::is_none")]
1801    pub assertions: Option<serde_json::Value>,
1802}
1803
1804#[derive(Debug, Clone, Copy)]
1805pub struct CoverageFileDetailOptions<'a> {
1806    pub run: &'a str,
1807    pub view: CoverageViewId,
1808    pub kind: Option<&'a str>,
1809    pub runner: Option<&'a str>,
1810    pub selector: &'a str,
1811    pub metric: MinimizeMetric,
1812    pub offset: usize,
1813    pub limit: usize,
1814}
1815
1816fn other_coverage<T: AsRef<str>>(
1817    test_ids: &[T],
1818    selected: Option<&BTreeSet<String>>,
1819    tests: &HashMap<String, IndexedTestSummary>,
1820) -> CoverageOtherCoverage {
1821    let covered = selected.map_or_else(Vec::new, |selected| {
1822        test_ids
1823            .iter()
1824            .filter(|id| !selected.contains(id.as_ref()))
1825            .filter_map(|id| tests.get(id.as_ref()))
1826            .collect::<Vec<_>>()
1827    });
1828    CoverageOtherCoverage {
1829        covered_elsewhere: !covered.is_empty(),
1830        kinds: covered
1831            .iter()
1832            .map(|test| test.provenance.kind.clone())
1833            .collect::<BTreeSet<_>>()
1834            .into_iter()
1835            .collect(),
1836        runners: covered
1837            .iter()
1838            .map(|test| test.provenance.runner.clone())
1839            .collect::<BTreeSet<_>>()
1840            .into_iter()
1841            .collect(),
1842        tests: covered
1843            .into_iter()
1844            .map(|test| CoverageOtherTest {
1845                id: test.id.clone(),
1846                name: test.name.clone(),
1847            })
1848            .collect(),
1849    }
1850}
1851
1852fn vector_text(vector: &crate::coverage_analysis::McdcVector) -> String {
1853    let values = vector
1854        .values
1855        .iter()
1856        .map(|value| match value {
1857            None => '-',
1858            Some(false) => 'F',
1859            Some(true) => 'T',
1860        })
1861        .collect::<String>();
1862    format!("{values} -> {}", if vector.outcome { 'T' } else { 'F' })
1863}
1864
1865fn obligation_matches_metric(obligation: &CoverageFileObligation, metric: MinimizeMetric) -> bool {
1866    metric == MinimizeMetric::All
1867        || matches!(
1868            (obligation.kind(), metric),
1869            ("line", MinimizeMetric::Lines)
1870                | ("statement", MinimizeMetric::Statements)
1871                | ("function", MinimizeMetric::Functions)
1872                | ("branch", MinimizeMetric::Branches)
1873                | ("mcdc", MinimizeMetric::Mcdc)
1874        )
1875}
1876
1877fn compact_source(value: &str) -> Option<String> {
1878    let line = value.lines().find(|line| !line.trim().is_empty())?.trim();
1879    let compact = line.split_whitespace().collect::<Vec<_>>().join(" ");
1880    if compact.is_empty() {
1881        None
1882    } else if compact.chars().count() > 120 {
1883        Some(format!(
1884            "{}…",
1885            compact.chars().take(119).collect::<String>()
1886        ))
1887    } else {
1888        Some(compact)
1889    }
1890}
1891
1892fn obligation_source(obligation: &CoverageFileObligation) -> Option<String> {
1893    match obligation {
1894        CoverageFileObligation::Line(_) => None,
1895        CoverageFileObligation::Point(value) => compact_source(&value.source),
1896        CoverageFileObligation::Branch(value) => compact_source(&value.source),
1897        CoverageFileObligation::Mcdc(value) => compact_source(&value.decision),
1898    }
1899}
1900
1901pub fn coverage_file_detail_query(
1902    index: &CoverageIndex<'_>,
1903    options: CoverageFileDetailOptions<'_>,
1904) -> Result<(CoverageFileDetailData, AgentPagination), QueryError> {
1905    if options.limit == 0 {
1906        return Err(QueryError::InvalidPagination);
1907    }
1908    let test_details = index.test_details(options.view)?;
1909    let test_summaries = test_details
1910        .iter()
1911        .map(|test| test.summary.clone())
1912        .collect::<Vec<_>>();
1913    let selected = selected_test_ids(&test_summaries, options.kind, options.runner)?;
1914    let tests_by_id = test_summaries
1915        .into_iter()
1916        .map(|test| (test.id.clone(), test))
1917        .collect::<HashMap<_, _>>();
1918    let lines = index.lines(options.view)?;
1919    let limitation_records = index.limitations(options.view)?;
1920    let files = lines
1921        .iter()
1922        .map(|line| line.file.as_str())
1923        .chain(
1924            limitation_records
1925                .iter()
1926                .map(|limitation| limitation.file.as_str()),
1927        )
1928        .collect::<BTreeSet<_>>();
1929    let file = if files.contains(options.selector) {
1930        options.selector.to_owned()
1931    } else {
1932        let matches = files
1933            .into_iter()
1934            .filter(|file| file.contains(options.selector))
1935            .collect::<Vec<_>>();
1936        if matches.is_empty() {
1937            return Err(QueryError::SourceNotFound(options.selector.into()));
1938        }
1939        if matches.len() != 1 {
1940            return Err(QueryError::AmbiguousSelector {
1941                selector: options.selector.into(),
1942                matches: matches.into_iter().map(str::to_owned).collect(),
1943            });
1944        }
1945        matches[0].to_owned()
1946    };
1947    let selected_includes = |tests: &[String]| {
1948        selected.as_ref().map_or(!tests.is_empty(), |selected| {
1949            tests.iter().any(|test| selected.contains(test))
1950        })
1951    };
1952    let total_lines = lines
1953        .iter()
1954        .filter(|line| line.measured && line.file == file)
1955        .count();
1956    let uncovered_lines = lines
1957        .iter()
1958        .filter(|line| line.measured && line.file == file && !selected_includes(&line.tests))
1959        .map(|line| {
1960            CoverageFileObligation::Line(CoverageLineObligation {
1961                kind: "line".into(),
1962                id: format!("line:{}:{}", line.file, line.line),
1963                line: line.line,
1964                other_coverage: other_coverage(&line.tests, selected.as_ref(), &tests_by_id),
1965            })
1966        })
1967        .collect::<Vec<_>>();
1968    let metadata = index.hit_metadata(options.view)?;
1969    let statements = metadata
1970        .iter()
1971        .filter(|point| {
1972            point.file == file
1973                && point.obligation == "statement"
1974                && !selected_includes(&point.tests)
1975        })
1976        .map(|point| {
1977            CoverageFileObligation::Point(CoveragePointObligation {
1978                kind: "statement".into(),
1979                id: point.id.clone(),
1980                line: point.line,
1981                column: point.column,
1982                source: point.label.clone().unwrap_or_else(|| point.source.clone()),
1983                other_coverage: other_coverage(&point.tests, selected.as_ref(), &tests_by_id),
1984            })
1985        })
1986        .collect::<Vec<_>>();
1987    let functions = metadata
1988        .iter()
1989        .filter(|point| {
1990            point.file == file && point.obligation == "function" && !selected_includes(&point.tests)
1991        })
1992        .map(|point| {
1993            CoverageFileObligation::Point(CoveragePointObligation {
1994                kind: "function".into(),
1995                id: point.id.clone(),
1996                line: point.line,
1997                column: point.column,
1998                source: point.label.clone().unwrap_or_else(|| point.source.clone()),
1999                other_coverage: other_coverage(&point.tests, selected.as_ref(), &tests_by_id),
2000            })
2001        })
2002        .collect::<Vec<_>>();
2003    let branches = metadata
2004        .iter()
2005        .filter(|branch| {
2006            branch.file == file
2007                && branch.obligation == "branch"
2008                && !selected_includes(&branch.tests)
2009        })
2010        .map(|branch| {
2011            CoverageFileObligation::Branch(CoverageBranchObligation {
2012                kind: "branch".into(),
2013                id: branch.id.clone(),
2014                line: branch.line,
2015                column: branch.column,
2016                source: branch.source.clone(),
2017                missing: branch.alternative.clone().unwrap_or_default(),
2018                other_coverage: other_coverage(&branch.tests, selected.as_ref(), &tests_by_id),
2019            })
2020        })
2021        .collect::<Vec<_>>();
2022    // A line ran when anything anchored on it was observed. A line inside a
2023    // multi-line expression has no line obligation of its own, so this is
2024    // what tells one that never ran from one that ran part of the way.
2025    let observed_lines = metadata
2026        .iter()
2027        .filter(|point| point.file == file && selected_includes(&point.tests))
2028        .map(|point| point.line)
2029        .collect::<BTreeSet<_>>();
2030    let original_decisions = index.decision_details(options.view)?;
2031    let mut mcdc = Vec::new();
2032    for original in original_decisions
2033        .iter()
2034        .filter(|decision| decision.meta.file == file)
2035    {
2036        let filtered = selected_decision(original.clone(), selected.as_ref());
2037        for condition in filtered
2038            .conditions
2039            .iter()
2040            .filter(|condition| !condition.covered)
2041        {
2042            let original_tests = original.conditions[condition.index]
2043                .witness_tests
2044                .clone()
2045                .unwrap_or_default()
2046                .into_iter()
2047                .flatten()
2048                .collect::<Vec<_>>();
2049            mcdc.push(CoverageFileObligation::Mcdc(CoverageMcdcObligation {
2050                kind: "mcdc".into(),
2051                id: original.meta.id.clone(),
2052                line: original.meta.line,
2053                column: original.meta.column,
2054                decision: original.meta.source.clone(),
2055                missing_condition: condition.source.clone(),
2056                condition_index: condition.index,
2057                observed_vectors: filtered
2058                    .vector_observations
2059                    .iter()
2060                    .map(|observation| vector_text(&observation.vector))
2061                    .collect(),
2062                other_coverage: other_coverage(&original_tests, selected.as_ref(), &tests_by_id),
2063            }));
2064        }
2065    }
2066    let mut obligations = uncovered_lines
2067        .iter()
2068        .chain(statements.iter())
2069        .chain(functions.iter())
2070        .chain(branches.iter())
2071        .chain(mcdc.iter())
2072        .filter(|obligation| obligation_matches_metric(obligation, options.metric))
2073        .cloned()
2074        .collect::<Vec<_>>();
2075    obligations.sort_by(|left, right| {
2076        left.line()
2077            .cmp(&right.line())
2078            .then_with(|| left.kind().cmp(right.kind()))
2079    });
2080    let mut limitations = limitation_records
2081        .into_iter()
2082        .filter(|limitation| limitation.file == file)
2083        .map(|limitation| CoverageFileLimitation {
2084            id: limitation.id,
2085            kind: limitation.kind,
2086            file: limitation.file,
2087            line: limitation.line,
2088            column: limitation.column,
2089            source: limitation.source,
2090            reason: limitation.reason,
2091            blocking: limitation.blocking,
2092            effect: "outside-measured-denominator".into(),
2093        })
2094        .collect::<Vec<_>>();
2095    limitations.sort_by(|left, right| {
2096        left.line
2097            .cmp(&right.line)
2098            .then_with(|| left.column.cmp(&right.column))
2099            .then_with(|| left.id.cmp(&right.id))
2100    });
2101    let total_tests = test_details
2102        .iter()
2103        .filter(|test| {
2104            selected
2105                .as_ref()
2106                .is_none_or(|selected| selected.contains(&test.summary.id))
2107                && test.lines.iter().any(|line| line.file == file)
2108        })
2109        .count();
2110    let total_obligations = obligations.len();
2111    let total_limitations = limitations.len();
2112    let mut grouped =
2113        BTreeMap::<usize, (Vec<CoverageFileObligation>, Vec<CoverageFileLimitation>)>::new();
2114    for obligation in obligations {
2115        grouped
2116            .entry(obligation.line())
2117            .or_default()
2118            .0
2119            .push(obligation);
2120    }
2121    for limitation in limitations {
2122        grouped
2123            .entry(limitation.line)
2124            .or_default()
2125            .1
2126            .push(limitation);
2127    }
2128    let gap_lines = grouped
2129        .into_iter()
2130        .map(|(line, (obligations, limitations))| {
2131            let source = obligations.iter().find_map(obligation_source).or_else(|| {
2132                limitations
2133                    .iter()
2134                    .find_map(|value| compact_source(&value.source))
2135            });
2136            // An MC/DC condition can be evaluated without anything on its own
2137            // line being recorded, so only branch and point gaps can say a
2138            // line never ran.
2139            let never_ran = !observed_lines.contains(&line)
2140                && !obligations.is_empty()
2141                && obligations
2142                    .iter()
2143                    .all(|value| !matches!(value, CoverageFileObligation::Mcdc(_)));
2144            let state = if never_ran
2145                || obligations
2146                    .iter()
2147                    .any(|value| matches!(value, CoverageFileObligation::Line(_)))
2148            {
2149                "missing"
2150            } else if !obligations.is_empty() || observed_lines.contains(&line) {
2151                // A line that ran with part of it outside measurement ran part
2152                // of the way, as its line view says.
2153                "part"
2154            } else {
2155                "limited"
2156            };
2157            CoverageFileGapLine {
2158                line,
2159                state: state.into(),
2160                source,
2161                obligations,
2162                limitations,
2163            }
2164        })
2165        .collect::<Vec<_>>();
2166    let total_gap_lines = gap_lines.len();
2167    let selected_gap_lines = gap_lines
2168        .into_iter()
2169        .skip(options.offset)
2170        .take(options.limit)
2171        .collect::<Vec<_>>();
2172    let returned = selected_gap_lines.len();
2173    Ok((
2174        CoverageFileDetailData {
2175            run: options.run.into(),
2176            filters: query_filters(options.view, options.kind, options.runner),
2177            file,
2178            metric: options.metric,
2179            counts: CoverageFileCounts {
2180                total_lines,
2181                covered_lines: total_lines - uncovered_lines.len(),
2182                uncovered_lines: uncovered_lines.len(),
2183                uncovered_statements: statements.len(),
2184                uncovered_functions: functions.len(),
2185                missing_branches: branches.len(),
2186                missing_mcdc_conditions: mcdc.len(),
2187                measurement_limitations: total_limitations,
2188            },
2189            total_tests,
2190            total_obligations,
2191            total_gap_lines,
2192            gap_lines: selected_gap_lines,
2193            total_limitations,
2194            assertions: None,
2195        },
2196        pagination(options.offset, options.limit, returned, total_gap_lines),
2197    ))
2198}
2199
2200#[derive(Debug, Clone, PartialEq, Serialize)]
2201pub struct CoverageDiffDelta {
2202    #[serde(serialize_with = "crate::coverage_analysis::serialize_javascript_number")]
2203    pub lines: f64,
2204    #[serde(serialize_with = "crate::coverage_analysis::serialize_javascript_number")]
2205    pub branches: f64,
2206    #[serde(serialize_with = "crate::coverage_analysis::serialize_javascript_number")]
2207    pub mcdc: f64,
2208}
2209
2210#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2211#[serde(rename_all = "camelCase")]
2212pub struct CoverageDiffSide {
2213    pub line_count: usize,
2214    pub branch_count: usize,
2215    pub mcdc_count: usize,
2216    pub lines: Vec<String>,
2217    pub branches: Vec<String>,
2218    pub mcdc: Vec<String>,
2219}
2220
2221#[derive(Debug, Clone, PartialEq, Serialize)]
2222pub struct CoverageDiffData {
2223    pub filters: CoverageQueryFilters,
2224    pub older: String,
2225    pub newer: String,
2226    pub delta: CoverageDiffDelta,
2227    pub gained: CoverageDiffSide,
2228    pub lost: CoverageDiffSide,
2229}
2230
2231#[derive(Debug, Clone, Copy)]
2232pub struct CoverageDiffQueryOptions<'a> {
2233    pub older_run: &'a str,
2234    pub newer_run: &'a str,
2235    pub view: CoverageViewId,
2236    pub kind: Option<&'a str>,
2237    pub runner: Option<&'a str>,
2238    pub offset: usize,
2239    pub limit: usize,
2240}
2241
2242struct DiffSnapshot {
2243    summary: CoverageSummary,
2244    lines: BTreeSet<String>,
2245    branches: HashMap<String, String>,
2246    mcdc: HashMap<String, String>,
2247}
2248
2249fn diff_snapshot(
2250    index: &CoverageIndex<'_>,
2251    view: CoverageViewId,
2252) -> Result<DiffSnapshot, QueryError> {
2253    let summary = index.summary(view)?;
2254    let lines = index
2255        .lines(view)?
2256        .into_iter()
2257        .filter(|line| line.covered)
2258        .map(|line| format!("{}:{}", line.file, line.line))
2259        .collect();
2260    let branches = index
2261        .hit_metadata(view)?
2262        .into_iter()
2263        .filter(|metadata| metadata.obligation == "branch" && !metadata.tests.is_empty())
2264        .map(|metadata| {
2265            let parent = metadata
2266                .parent_id
2267                .ok_or(QueryError::InvalidRecordSelection)?;
2268            Ok((
2269                format!("{parent}:{}", metadata.id),
2270                format!(
2271                    "{}:{} {}",
2272                    metadata.file,
2273                    metadata.line,
2274                    metadata.alternative.unwrap_or_default()
2275                ),
2276            ))
2277        })
2278        .collect::<Result<HashMap<_, _>, QueryError>>()?;
2279    let mcdc = index
2280        .decision_details(view)?
2281        .into_iter()
2282        .flat_map(|decision| {
2283            decision
2284                .conditions
2285                .into_iter()
2286                .filter(|condition| condition.covered)
2287                .map(move |condition| {
2288                    (
2289                        format!("{}:c{}", decision.meta.id, condition.index),
2290                        format!(
2291                            "{}:{} C{} {}",
2292                            decision.meta.file,
2293                            decision.meta.line,
2294                            condition.index + 1,
2295                            condition.source
2296                        ),
2297                    )
2298                })
2299        })
2300        .collect();
2301    Ok(DiffSnapshot {
2302        summary,
2303        lines,
2304        branches,
2305        mcdc,
2306    })
2307}
2308
2309fn js_string_cmp(left: &str, right: &str) -> std::cmp::Ordering {
2310    left.encode_utf16().cmp(right.encode_utf16())
2311}
2312
2313fn rounded_delta(newer: f64, older: f64) -> f64 {
2314    ((newer - older) * 100.0).round() / 100.0
2315}
2316
2317pub fn coverage_diff_query(
2318    older: &CoverageIndex<'_>,
2319    newer: &CoverageIndex<'_>,
2320    options: CoverageDiffQueryOptions<'_>,
2321) -> Result<(CoverageDiffData, AgentPagination), QueryError> {
2322    if options.limit == 0 {
2323        return Err(QueryError::InvalidPagination);
2324    }
2325    let older = diff_snapshot(older, options.view)?;
2326    let newer = diff_snapshot(newer, options.view)?;
2327    let mut gained_lines = newer
2328        .lines
2329        .difference(&older.lines)
2330        .cloned()
2331        .collect::<Vec<_>>();
2332    let mut lost_lines = older
2333        .lines
2334        .difference(&newer.lines)
2335        .cloned()
2336        .collect::<Vec<_>>();
2337    let mut gained_branches = newer
2338        .branches
2339        .iter()
2340        .filter(|(id, _)| !older.branches.contains_key(*id))
2341        .map(|(_, label)| label.clone())
2342        .collect::<Vec<_>>();
2343    let mut lost_branches = older
2344        .branches
2345        .iter()
2346        .filter(|(id, _)| !newer.branches.contains_key(*id))
2347        .map(|(_, label)| label.clone())
2348        .collect::<Vec<_>>();
2349    let mut gained_mcdc = newer
2350        .mcdc
2351        .iter()
2352        .filter(|(id, _)| !older.mcdc.contains_key(*id))
2353        .map(|(_, label)| label.clone())
2354        .collect::<Vec<_>>();
2355    let mut lost_mcdc = older
2356        .mcdc
2357        .iter()
2358        .filter(|(id, _)| !newer.mcdc.contains_key(*id))
2359        .map(|(_, label)| label.clone())
2360        .collect::<Vec<_>>();
2361    for values in [
2362        &mut gained_lines,
2363        &mut lost_lines,
2364        &mut gained_branches,
2365        &mut lost_branches,
2366        &mut gained_mcdc,
2367        &mut lost_mcdc,
2368    ] {
2369        values.sort_by(|left, right| js_string_cmp(left, right));
2370    }
2371    let total = [
2372        gained_lines.len(),
2373        gained_branches.len(),
2374        gained_mcdc.len(),
2375        lost_lines.len(),
2376        lost_branches.len(),
2377        lost_mcdc.len(),
2378    ]
2379    .into_iter()
2380    .max()
2381    .unwrap_or(0);
2382    let page = |values: &[String]| {
2383        values
2384            .iter()
2385            .skip(options.offset)
2386            .take(options.limit)
2387            .cloned()
2388            .collect::<Vec<_>>()
2389    };
2390    let gained = CoverageDiffSide {
2391        line_count: gained_lines.len(),
2392        branch_count: gained_branches.len(),
2393        mcdc_count: gained_mcdc.len(),
2394        lines: page(&gained_lines),
2395        branches: page(&gained_branches),
2396        mcdc: page(&gained_mcdc),
2397    };
2398    let lost = CoverageDiffSide {
2399        line_count: lost_lines.len(),
2400        branch_count: lost_branches.len(),
2401        mcdc_count: lost_mcdc.len(),
2402        lines: page(&lost_lines),
2403        branches: page(&lost_branches),
2404        mcdc: page(&lost_mcdc),
2405    };
2406    let returned = [
2407        gained.lines.len(),
2408        gained.branches.len(),
2409        gained.mcdc.len(),
2410        lost.lines.len(),
2411        lost.branches.len(),
2412        lost.mcdc.len(),
2413    ]
2414    .into_iter()
2415    .max()
2416    .unwrap_or(0);
2417    Ok((
2418        CoverageDiffData {
2419            filters: query_filters(options.view, options.kind, options.runner),
2420            older: options.older_run.into(),
2421            newer: options.newer_run.into(),
2422            delta: CoverageDiffDelta {
2423                lines: rounded_delta(
2424                    newer.summary.lines.percentage,
2425                    older.summary.lines.percentage,
2426                ),
2427                branches: rounded_delta(
2428                    newer.summary.branches.percentage,
2429                    older.summary.branches.percentage,
2430                ),
2431                mcdc: rounded_delta(
2432                    newer.summary.condition_coverage_pct,
2433                    older.summary.condition_coverage_pct,
2434                ),
2435            },
2436            gained,
2437            lost,
2438        },
2439        pagination(options.offset, options.limit, returned, total),
2440    ))
2441}
2442
2443pub fn coverage_scope_query(
2444    index: &CoverageIndex<'_>,
2445    options: CoverageScopeQueryOptions<'_>,
2446) -> Result<(CoverageScopeData, AgentPagination), QueryError> {
2447    if options.limit == 0 {
2448        return Err(QueryError::InvalidPagination);
2449    }
2450    let projection = index.projection(options.view, options.kind, options.runner)?;
2451    let scope = projection
2452        .source_scope
2453        .ok_or(QueryError::ScopeUnavailable)?;
2454    let mut entries = index.scope_entries(options.view)?;
2455    entries.sort_by(|left, right| {
2456        scope_status_rank(&left.status)
2457            .cmp(&scope_status_rank(&right.status))
2458            .then_with(|| left.file.cmp(&right.file))
2459    });
2460    let groups = scope_groups(&entries);
2461    let unclassified = unclassified_source(&scope.roots, &entries);
2462    let total = entries.len();
2463    let selected = entries
2464        .into_iter()
2465        .skip(options.offset)
2466        .take(options.limit)
2467        .collect::<Vec<_>>();
2468    let returned = selected.len();
2469    Ok((
2470        CoverageScopeData {
2471            run: options.run.into(),
2472            filters: CoverageQueryFilters {
2473                outcome: match options.view {
2474                    CoverageViewId::All => "all",
2475                    CoverageViewId::Passed => "passed",
2476                    CoverageViewId::Failed => "failed",
2477                }
2478                .into(),
2479                kind: options.kind.map(str::to_owned),
2480                runner: options.runner.map(str::to_owned),
2481            },
2482            kind: scope.kind,
2483            language: scope.language,
2484            model: scope.model,
2485            mode: scope.mode,
2486            roots: scope.roots,
2487            unit: scope.unit,
2488            measurement_complete: scope.measurement_complete,
2489            counts: ScopeCounts {
2490                included: scope.included,
2491                excluded: scope.excluded,
2492                ambiguous: scope.ambiguous,
2493            },
2494            measurement: projection.measurement,
2495            groups,
2496            unclassified_source: unclassified,
2497            entries: selected,
2498        },
2499        pagination(options.offset, options.limit, returned, total),
2500    ))
2501}
2502
2503pub fn coverage_summary_query(
2504    index: &CoverageIndex<'_>,
2505    options: CoverageSummaryQueryOptions<'_>,
2506) -> Result<CoverageSummaryData, QueryError> {
2507    let projection = index.projection(options.view, options.kind, options.runner)?;
2508    let mut test_kind_sources = BTreeMap::new();
2509    for test in index.test_summaries(options.view)?.iter().filter(|t| {
2510        t.role == "test"
2511            && options.kind.is_none_or(|k| t.provenance.kind == k)
2512            && options.runner.is_none_or(|r| t.provenance.runner == r)
2513    }) {
2514        *test_kind_sources
2515            .entry(test.provenance.source.clone())
2516            .or_insert(0) += 1;
2517    }
2518    let mut diagnostics = Vec::new();
2519    let mut transport_blockers = 0usize;
2520    if projection.empty_evidence_tests > 0 {
2521        diagnostics.push(CoverageDiagnostic {
2522            code: "TEST_EVIDENCE_MISSING".into(),
2523            severity: "warning".into(),
2524            message: format!(
2525                "{} test(s) recorded assertion phases but attributed zero coverage evidence; possible causes include checks of uninstrumented data, shared setup, lost async context or missing probe transport. First: {}",
2526                projection.empty_evidence_tests,
2527                projection.first_empty_evidence_test.as_deref().unwrap_or("unknown")
2528            ),
2529        });
2530    }
2531    if let Some(transport) = &projection.transport {
2532        if transport.corrupt_records > 0 {
2533            transport_blockers += 1;
2534            diagnostics.push(CoverageDiagnostic {
2535                code: "CORRUPT_EVIDENCE_RECORDS".into(),
2536                severity: "error".into(),
2537                message: format!(
2538                    "{} malformed evidence record(s) in {} file(s) were excluded; coverage is incomplete.",
2539                    transport.corrupt_records, transport.corrupt_files
2540                ),
2541            });
2542        }
2543        if transport.remote_launches > 0
2544            && transport.scoped_server_records == 0
2545            && transport.background_server_records == 0
2546            && projection.attribution.server_explicit == 0
2547            && projection.attribution.server_fallback == 0
2548        {
2549            transport_blockers += 1;
2550            diagnostics.push(CoverageDiagnostic {
2551                code: "REMOTE_SERVER_EVIDENCE_MISSING".into(),
2552                severity: "error".into(),
2553                message: "Remote launches were supervised, but neither scoped nor background server evidence returned. Supercov refuses to describe this measurement as complete.".into(),
2554            });
2555        }
2556    }
2557    let coverage_by_kind = index.dimensions(options.view, CoverageDimension::Kind)?;
2558    let coverage_by_runner = index.dimensions(options.view, CoverageDimension::Runner)?;
2559    let coverage_by_tests = if options.kind.is_none() && options.runner.is_none() {
2560        index
2561            .dimensions(options.view, CoverageDimension::Tests)?
2562            .into_iter()
2563            .next()
2564            .filter(|tests| tests.tests + tests.setups > 0)
2565            .map(|tests| tests.summary)
2566    } else {
2567        None
2568    };
2569    let other_e2e_kinds = coverage_by_kind
2570        .iter()
2571        .filter(|dimension| dimension.tests > 0)
2572        .filter_map(|dimension| dimension.kind.clone())
2573        .filter(|kind| kind != "e2e")
2574        .collect::<Vec<_>>();
2575    let e2e_observed = coverage_by_kind
2576        .iter()
2577        .any(|dimension| dimension.tests > 0 && dimension.kind.as_deref() == Some("e2e"));
2578    let e2e_gap_context = if options.kind.is_none()
2579        && options.runner.is_none()
2580        && e2e_observed
2581        && !other_e2e_kinds.is_empty()
2582    {
2583        let mut covered_elsewhere = IndexedGapDimensions {
2584            lines: 0,
2585            statements: 0,
2586            functions: 0,
2587            branches: 0,
2588            mcdc_conditions: 0,
2589        };
2590        let mut uncovered_everywhere = covered_elsewhere.clone();
2591        for gap in index.file_gaps(options.view, Some("e2e"), None)? {
2592            covered_elsewhere.lines += gap.covered_by_other_tests.lines;
2593            covered_elsewhere.statements += gap.covered_by_other_tests.statements;
2594            covered_elsewhere.functions += gap.covered_by_other_tests.functions;
2595            covered_elsewhere.branches += gap.covered_by_other_tests.branches;
2596            covered_elsewhere.mcdc_conditions += gap.covered_by_other_tests.mcdc_conditions;
2597            uncovered_everywhere.lines += gap.uncovered_everywhere.lines;
2598            uncovered_everywhere.statements += gap.uncovered_everywhere.statements;
2599            uncovered_everywhere.functions += gap.uncovered_everywhere.functions;
2600            uncovered_everywhere.branches += gap.uncovered_everywhere.branches;
2601            uncovered_everywhere.mcdc_conditions += gap.uncovered_everywhere.mcdc_conditions;
2602        }
2603        Some(CoverageKindGapContext {
2604            kind: "e2e".into(),
2605            other_kinds: other_e2e_kinds,
2606            covered_elsewhere,
2607            uncovered_everywhere,
2608        })
2609    } else {
2610        None
2611    };
2612    let filters = CoverageQueryFilters {
2613        outcome: match options.view {
2614            CoverageViewId::All => "all",
2615            CoverageViewId::Passed => "passed",
2616            CoverageViewId::Failed => "failed",
2617        }
2618        .into(),
2619        kind: options.kind.map(str::to_owned),
2620        runner: options.runner.map(str::to_owned),
2621    };
2622    let mut measurement = projection.measurement.clone();
2623    if transport_blockers > 0 {
2624        measurement.complete = false;
2625        measurement.limitations = measurement.limitations.saturating_add(transport_blockers);
2626        measurement.blocking = measurement.blocking.saturating_add(transport_blockers);
2627    }
2628    let structurally_complete = projection.summary.coverage_complete && measurement.complete;
2629    let complete = options.view == CoverageViewId::Passed
2630        && options.valid
2631        && !options.stale
2632        && structurally_complete;
2633    Ok(CoverageSummaryData {
2634        test_kind_sources,
2635        assertion_coverage: None,
2636        run: options.run.into(),
2637        command: Vec::new(),
2638        hints: Vec::new(),
2639        workspace: None,
2640        filters,
2641        model: index.model()?,
2642        generated_at: projection.generated_at,
2643        valid: options.valid,
2644        test_exit_code: options.test_exit_code,
2645        stale: options.stale,
2646        stale_reasons: options.stale_reasons,
2647        structurally_complete,
2648        complete,
2649        coverage: projection.summary,
2650        measurement,
2651        coverage_by_kind,
2652        coverage_by_tests,
2653        e2e_gap_context,
2654        coverage_by_runner,
2655        attribution: projection.attribution,
2656        test_attribution: {
2657            let mut counts = TestAttributionCounts::default();
2658            for test in index
2659                .test_summaries(options.view)?
2660                .iter()
2661                .filter(|test| test.role == "test")
2662            {
2663                match test.attribution.as_str() {
2664                    crate::coverage_report::ATTRIBUTION_RUN_WIDE => counts.run_wide += 1,
2665                    crate::coverage_report::ATTRIBUTION_PARTIAL => counts.partial += 1,
2666                    _ => counts.exact += 1,
2667                }
2668            }
2669            counts
2670        },
2671        transport: projection.transport,
2672        diagnostics,
2673        confidence: (options.kind.is_none() && options.runner.is_none())
2674            .then_some(projection.confidence),
2675        files_with_gaps: projection.files_with_gaps,
2676        files_with_coverage_gaps: projection.files_with_coverage_gaps,
2677        files_with_measurement_limitations: projection.measurement.files,
2678        tests: projection.tests,
2679        setups: projection.setups,
2680        test_outcomes: projection.test_outcomes,
2681        unclassified_source: match &projection.source_scope {
2682            Some(scope) if scope.ambiguous > 0 => {
2683                unclassified_source(&scope.roots, &index.scope_entries(options.view)?)
2684            }
2685            _ => None,
2686        },
2687        source_scope: projection.source_scope,
2688    })
2689}
2690
2691#[derive(Debug, Clone, PartialEq)]
2692pub enum CoverageDimensionQueryData {
2693    Kinds(CoverageKindsData),
2694    Runners(CoverageRunnersData),
2695}
2696
2697/// Coverage of one directory: what its files have to cover, how much of it
2698/// is covered, and how much of it each kind of test covers.
2699#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2700#[serde(rename_all = "camelCase")]
2701pub struct CoverageArea {
2702    pub directory: String,
2703    pub files: usize,
2704    pub totals: IndexedGapDimensions,
2705    pub covered: IndexedGapDimensions,
2706    pub by_kind: Vec<CoverageAreaKind>,
2707}
2708
2709#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2710#[serde(rename_all = "camelCase")]
2711pub struct CoverageAreaKind {
2712    pub kind: String,
2713    pub covered: IndexedGapDimensions,
2714}
2715
2716#[derive(Debug, Clone, PartialEq, Serialize)]
2717#[serde(rename_all = "camelCase")]
2718pub struct CoverageAreasData {
2719    pub run: String,
2720    pub filters: CoverageQueryFilters,
2721    pub metric: MinimizeMetric,
2722    pub depth: usize,
2723    /// The kinds each area is split by, in the order of `byKind`. Empty when
2724    /// the query already names one kind or runner.
2725    pub kinds: Vec<String>,
2726    pub areas: Vec<CoverageArea>,
2727}
2728
2729#[derive(Debug, Clone, Copy)]
2730pub struct CoverageAreasQueryOptions<'a> {
2731    pub run: &'a str,
2732    pub view: CoverageViewId,
2733    pub metric: MinimizeMetric,
2734    pub kind: Option<&'a str>,
2735    pub runner: Option<&'a str>,
2736    pub depth: usize,
2737    pub offset: usize,
2738    pub limit: usize,
2739}
2740
2741/// The directory a file is counted under: its first `depth` folders, or all
2742/// of them when it has fewer. A file at the top of the project is in `.`.
2743fn area_directory(file: &str, depth: usize) -> String {
2744    let mut folders = file.split('/').collect::<Vec<_>>();
2745    folders.pop();
2746    if folders.is_empty() {
2747        ".".into()
2748    } else {
2749        folders[..folders.len().min(depth)].join("/")
2750    }
2751}
2752
2753fn add_dimensions(sum: &mut IndexedGapDimensions, value: &IndexedGapDimensions) {
2754    sum.lines += value.lines;
2755    sum.statements += value.statements;
2756    sum.functions += value.functions;
2757    sum.branches += value.branches;
2758    sum.mcdc_conditions += value.mcdc_conditions;
2759}
2760
2761const NO_DIMENSIONS: IndexedGapDimensions = IndexedGapDimensions {
2762    lines: 0,
2763    statements: 0,
2764    functions: 0,
2765    branches: 0,
2766    mcdc_conditions: 0,
2767};
2768
2769/// One metric of a file's or a directory's counts; `all` reads as lines.
2770pub fn dimension_for_metric(dimensions: &IndexedGapDimensions, metric: MinimizeMetric) -> usize {
2771    match metric {
2772        MinimizeMetric::All | MinimizeMetric::Lines => dimensions.lines,
2773        MinimizeMetric::Statements => dimensions.statements,
2774        MinimizeMetric::Functions => dimensions.functions,
2775        MinimizeMetric::Branches => dimensions.branches,
2776        MinimizeMetric::Mcdc => dimensions.mcdc_conditions,
2777    }
2778}
2779
2780/// Coverage by directory, split by test kind. "Where is the coverage" was the
2781/// first question after a full run, and answering it took an LCOV export and
2782/// a script: listings named files only and carried no totals.
2783pub fn coverage_areas_query(
2784    index: &CoverageIndex<'_>,
2785    options: CoverageAreasQueryOptions<'_>,
2786) -> Result<(CoverageAreasData, AgentPagination), QueryError> {
2787    if options.limit == 0 || options.depth == 0 {
2788        return Err(QueryError::InvalidPagination);
2789    }
2790    let files = index.file_gaps(options.view, options.kind, options.runner)?;
2791    if (options.kind.is_some() || options.runner.is_some()) && files.is_empty() {
2792        return Err(QueryError::TestFilterEmpty {
2793            kind: options.kind.map(str::to_owned),
2794            runner: options.runner.map(str::to_owned),
2795        });
2796    }
2797    let kinds = if options.kind.is_none() && options.runner.is_none() {
2798        index
2799            .dimensions(options.view, CoverageDimension::Kind)?
2800            .into_iter()
2801            .filter(|kind| kind.tests > 0 && kind.attributed > 0)
2802            .filter_map(|kind| kind.kind)
2803            .collect::<Vec<_>>()
2804    } else {
2805        Vec::new()
2806    };
2807    let mut areas = BTreeMap::<String, CoverageArea>::new();
2808    for file in &files {
2809        let directory = area_directory(&file.file, options.depth);
2810        let area = areas
2811            .entry(directory.clone())
2812            .or_insert_with(|| CoverageArea {
2813                directory,
2814                files: 0,
2815                totals: NO_DIMENSIONS,
2816                covered: NO_DIMENSIONS,
2817                by_kind: kinds
2818                    .iter()
2819                    .map(|kind| CoverageAreaKind {
2820                        kind: kind.clone(),
2821                        covered: NO_DIMENSIONS,
2822                    })
2823                    .collect(),
2824            });
2825        area.files += 1;
2826        add_dimensions(&mut area.totals, &file.totals);
2827        add_dimensions(&mut area.covered, &file.covered);
2828    }
2829    for (position, kind) in kinds.iter().enumerate() {
2830        for file in index.file_gaps(options.view, Some(kind), None)? {
2831            if let Some(area) = areas.get_mut(&area_directory(&file.file, options.depth)) {
2832                add_dimensions(&mut area.by_kind[position].covered, &file.covered);
2833            }
2834        }
2835    }
2836    let mut areas = areas.into_values().collect::<Vec<_>>();
2837    areas.sort_by(|left, right| {
2838        dimension_for_metric(&right.totals, options.metric)
2839            .cmp(&dimension_for_metric(&left.totals, options.metric))
2840            .then_with(|| left.directory.cmp(&right.directory))
2841    });
2842    let total = areas.len();
2843    let page = areas
2844        .into_iter()
2845        .skip(options.offset)
2846        .take(options.limit)
2847        .collect::<Vec<_>>();
2848    let returned = page.len();
2849    Ok((
2850        CoverageAreasData {
2851            run: options.run.into(),
2852            filters: CoverageQueryFilters {
2853                outcome: match options.view {
2854                    CoverageViewId::All => "all",
2855                    CoverageViewId::Passed => "passed",
2856                    CoverageViewId::Failed => "failed",
2857                }
2858                .into(),
2859                kind: options.kind.map(str::to_owned),
2860                runner: options.runner.map(str::to_owned),
2861            },
2862            metric: options.metric,
2863            depth: options.depth,
2864            kinds,
2865            areas: page,
2866        },
2867        pagination(options.offset, options.limit, returned, total),
2868    ))
2869}
2870
2871#[derive(Debug, Clone, PartialEq)]
2872pub enum CoverageFileQueryData {
2873    Files(CoverageFilesData),
2874    Gaps(CoverageGapsData),
2875}
2876
2877#[derive(Debug, Clone, PartialEq)]
2878pub struct CoverageFileQueryResult {
2879    pub data: CoverageFileQueryData,
2880    pub pagination: AgentPagination,
2881}
2882
2883#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2884#[serde(rename_all = "lowercase")]
2885pub enum DecisionSort {
2886    Location,
2887    Missing,
2888}
2889
2890#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2891#[serde(rename_all = "camelCase")]
2892pub struct DecisionGapTotals {
2893    pub decisions: usize,
2894    pub decisions_with_missing_conditions: usize,
2895    pub conditions: usize,
2896    pub missing_conditions: usize,
2897}
2898
2899#[derive(Debug, Clone, PartialEq, Serialize)]
2900#[serde(rename_all = "camelCase")]
2901pub struct CoverageFileDecisionsData {
2902    pub run: String,
2903    pub filters: CoverageQueryFilters,
2904    pub file: String,
2905    pub group: String,
2906    pub sort: DecisionSort,
2907    pub totals: DecisionGapTotals,
2908    pub decisions: Vec<IndexedDecisionGap>,
2909}
2910
2911#[derive(Debug, Clone, Copy)]
2912pub struct CoverageFileDecisionsOptions<'a> {
2913    pub run: &'a str,
2914    pub view: CoverageViewId,
2915    pub kind: Option<&'a str>,
2916    pub runner: Option<&'a str>,
2917    pub file: &'a str,
2918    pub sort: DecisionSort,
2919    pub offset: usize,
2920    pub limit: usize,
2921}
2922
2923#[derive(Debug, Clone)]
2924pub struct CoverageDimensionQueryOptions<'a> {
2925    pub run: &'a str,
2926    pub view: CoverageViewId,
2927    pub dimension: CoverageDimension,
2928    pub filters: CoverageQueryFilters,
2929    pub offset: usize,
2930    pub limit: usize,
2931}
2932
2933pub fn coverage_dimension_query(
2934    index: &CoverageIndex<'_>,
2935    options: CoverageDimensionQueryOptions<'_>,
2936) -> Result<(CoverageDimensionQueryData, AgentPagination), QueryError> {
2937    let CoverageDimensionQueryOptions {
2938        run,
2939        view,
2940        dimension,
2941        filters,
2942        offset,
2943        limit,
2944    } = options;
2945    if limit == 0 {
2946        return Err(QueryError::InvalidPagination);
2947    }
2948    let values = index.dimensions(view, dimension)?;
2949    let total = values.len();
2950    let selected = values
2951        .into_iter()
2952        .skip(offset)
2953        .take(limit)
2954        .collect::<Vec<_>>();
2955    let returned = selected.len();
2956    let data = match dimension {
2957        // The tests together are one entry of the summary, never a listing.
2958        CoverageDimension::Kind | CoverageDimension::Tests => {
2959            CoverageDimensionQueryData::Kinds(CoverageKindsData {
2960                run: run.into(),
2961                filters,
2962                kinds: selected,
2963            })
2964        }
2965        CoverageDimension::Runner => CoverageDimensionQueryData::Runners(CoverageRunnersData {
2966            run: run.into(),
2967            filters,
2968            runners: selected,
2969        }),
2970    };
2971    Ok((data, pagination(offset, limit, returned, total)))
2972}
2973
2974#[derive(Debug, Clone, Copy)]
2975pub struct CoverageFileQueryOptions<'a> {
2976    pub run: &'a str,
2977    pub view: CoverageViewId,
2978    pub metric: MinimizeMetric,
2979    pub gaps_only: bool,
2980    pub kind: Option<&'a str>,
2981    pub runner: Option<&'a str>,
2982    pub offset: usize,
2983    pub limit: usize,
2984}
2985
2986fn gap_metric_value(gap: &IndexedFileGap, metric: MinimizeMetric) -> usize {
2987    match metric {
2988        MinimizeMetric::All => gap.score,
2989        MinimizeMetric::Lines => gap.uncovered_lines,
2990        MinimizeMetric::Statements => gap.uncovered_statements,
2991        MinimizeMetric::Functions => gap.uncovered_functions,
2992        MinimizeMetric::Branches => gap.missing_branches,
2993        MinimizeMetric::Mcdc => gap.missing_mcdc_conditions,
2994    }
2995}
2996
2997fn has_gap_for_metric(gap: &IndexedFileGap, metric: MinimizeMetric) -> bool {
2998    match metric {
2999        MinimizeMetric::All => {
3000            gap.uncovered_lines > 0
3001                || gap.uncovered_statements > 0
3002                || gap.uncovered_functions > 0
3003                || gap.missing_branches > 0
3004                || gap.missing_mcdc_conditions > 0
3005        }
3006        _ => gap_metric_value(gap, metric) > 0,
3007    }
3008}
3009
3010pub fn coverage_file_decisions_query(
3011    index: &CoverageIndex<'_>,
3012    options: CoverageFileDecisionsOptions<'_>,
3013) -> Result<(CoverageFileDecisionsData, AgentPagination), QueryError> {
3014    if options.limit == 0 {
3015        return Err(QueryError::InvalidPagination);
3016    }
3017    let all = index.decision_gaps(options.view, options.kind, options.runner, options.file)?;
3018    if (options.kind.is_some() || options.runner.is_some()) && all.is_empty() {
3019        // A file with no decisions is valid, so consult the file projection to
3020        // distinguish it from a nonexistent test provenance projection.
3021        if index
3022            .file_gaps(options.view, options.kind, options.runner)?
3023            .is_empty()
3024        {
3025            return Err(QueryError::TestFilterEmpty {
3026                kind: options.kind.map(str::to_owned),
3027                runner: options.runner.map(str::to_owned),
3028            });
3029        }
3030    }
3031    let totals = DecisionGapTotals {
3032        decisions: all.len(),
3033        decisions_with_missing_conditions: all
3034            .iter()
3035            .filter(|decision| decision.missing_conditions > 0)
3036            .count(),
3037        conditions: all.iter().map(|decision| decision.conditions).sum(),
3038        missing_conditions: all.iter().map(|decision| decision.missing_conditions).sum(),
3039    };
3040    let mut missing = all
3041        .into_iter()
3042        .filter(|decision| decision.missing_conditions > 0)
3043        .collect::<Vec<_>>();
3044    missing.sort_by(|left, right| match options.sort {
3045        DecisionSort::Missing => right
3046            .missing_conditions
3047            .cmp(&left.missing_conditions)
3048            .then_with(|| left.line.cmp(&right.line))
3049            .then_with(|| left.column.cmp(&right.column)),
3050        DecisionSort::Location => left
3051            .line
3052            .cmp(&right.line)
3053            .then_with(|| left.column.cmp(&right.column))
3054            .then_with(|| left.id.cmp(&right.id)),
3055    });
3056    let total = missing.len();
3057    let rows = missing
3058        .into_iter()
3059        .skip(options.offset)
3060        .take(options.limit)
3061        .collect::<Vec<_>>();
3062    let returned = rows.len();
3063    let filters = CoverageQueryFilters {
3064        outcome: match options.view {
3065            CoverageViewId::All => "all",
3066            CoverageViewId::Passed => "passed",
3067            CoverageViewId::Failed => "failed",
3068        }
3069        .into(),
3070        kind: options.kind.map(str::to_owned),
3071        runner: options.runner.map(str::to_owned),
3072    };
3073    Ok((
3074        CoverageFileDecisionsData {
3075            run: options.run.into(),
3076            filters,
3077            file: options.file.into(),
3078            group: "decision".into(),
3079            sort: options.sort,
3080            totals,
3081            decisions: rows,
3082        },
3083        pagination(options.offset, options.limit, returned, total),
3084    ))
3085}
3086
3087pub fn coverage_file_query(
3088    index: &CoverageIndex<'_>,
3089    options: CoverageFileQueryOptions<'_>,
3090) -> Result<CoverageFileQueryResult, QueryError> {
3091    let CoverageFileQueryOptions {
3092        run,
3093        view,
3094        metric,
3095        gaps_only,
3096        kind,
3097        runner,
3098        offset,
3099        limit,
3100    } = options;
3101    if limit == 0 {
3102        return Err(QueryError::InvalidPagination);
3103    }
3104    let mut files = index.file_gaps(view, kind, runner)?;
3105    if (kind.is_some() || runner.is_some()) && files.is_empty() {
3106        return Err(QueryError::TestFilterEmpty {
3107            kind: kind.map(str::to_owned),
3108            runner: runner.map(str::to_owned),
3109        });
3110    }
3111    if gaps_only {
3112        files.retain(|gap| has_gap_for_metric(gap, metric) || gap.measurement_limitations > 0);
3113    }
3114    files.sort_by(|left, right| {
3115        gap_metric_value(right, metric)
3116            .cmp(&gap_metric_value(left, metric))
3117            .then_with(|| {
3118                right
3119                    .measurement_limitations
3120                    .cmp(&left.measurement_limitations)
3121            })
3122            .then_with(|| left.file.cmp(&right.file))
3123    });
3124    let total = files.len();
3125    let page = files
3126        .into_iter()
3127        .skip(offset)
3128        .take(limit)
3129        .collect::<Vec<_>>();
3130    let page_info = pagination(offset, limit, page.len(), total);
3131    let filters = CoverageQueryFilters {
3132        outcome: match view {
3133            CoverageViewId::All => "all",
3134            CoverageViewId::Passed => "passed",
3135            CoverageViewId::Failed => "failed",
3136        }
3137        .into(),
3138        kind: kind.map(str::to_owned),
3139        runner: runner.map(str::to_owned),
3140    };
3141    let data = if gaps_only {
3142        CoverageFileQueryData::Gaps(CoverageGapsData {
3143            run: run.into(),
3144            filters,
3145            metric,
3146            gaps: page,
3147        })
3148    } else {
3149        CoverageFileQueryData::Files(CoverageFilesData {
3150            run: run.into(),
3151            filters,
3152            metric,
3153            files: page,
3154        })
3155    };
3156    Ok(CoverageFileQueryResult {
3157        data,
3158        pagination: page_info,
3159    })
3160}
3161
3162#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3163enum ObligationMetric {
3164    Lines,
3165    Statements,
3166    Functions,
3167    Branches,
3168    Mcdc,
3169}
3170
3171impl ObligationMetric {
3172    fn selected(self, metric: MinimizeMetric) -> bool {
3173        metric == MinimizeMetric::All
3174            || matches!(
3175                (self, metric),
3176                (Self::Lines, MinimizeMetric::Lines)
3177                    | (Self::Statements, MinimizeMetric::Statements)
3178                    | (Self::Functions, MinimizeMetric::Functions)
3179                    | (Self::Branches, MinimizeMetric::Branches)
3180                    | (Self::Mcdc, MinimizeMetric::Mcdc)
3181            )
3182    }
3183
3184    fn public(self) -> MinimizeMetric {
3185        match self {
3186            Self::Lines => MinimizeMetric::Lines,
3187            Self::Statements => MinimizeMetric::Statements,
3188            Self::Functions => MinimizeMetric::Functions,
3189            Self::Branches => MinimizeMetric::Branches,
3190            Self::Mcdc => MinimizeMetric::Mcdc,
3191        }
3192    }
3193}
3194
3195#[derive(Clone)]
3196struct Obligation {
3197    id: String,
3198    metric: ObligationMetric,
3199    /// Any one complete option satisfies this obligation.
3200    options: Vec<Vec<String>>,
3201}
3202
3203struct ObligationModel {
3204    obligations: Vec<Obligation>,
3205    setup_by_file: BTreeMap<String, Vec<String>>,
3206    tests_by_file: BTreeMap<String, Vec<String>>,
3207    background: Vec<String>,
3208}
3209
3210impl ObligationModel {
3211    fn expand(&self, selected: &BTreeSet<String>) -> BTreeSet<String> {
3212        let mut expanded = selected.clone();
3213        expanded.extend(self.background.iter().cloned());
3214        for (file, setup_ids) in &self.setup_by_file {
3215            if self
3216                .tests_by_file
3217                .get(file)
3218                .is_some_and(|tests| tests.iter().any(|id| selected.contains(id)))
3219            {
3220                expanded.extend(setup_ids.iter().cloned());
3221            }
3222        }
3223        expanded
3224    }
3225}
3226
3227fn deduplicate_options(options: impl IntoIterator<Item = Vec<String>>) -> Vec<Vec<String>> {
3228    let mut unique = BTreeMap::<String, Vec<String>>::new();
3229    for mut option in options {
3230        option.sort();
3231        option.dedup();
3232        let key = option.join("\0");
3233        unique.entry(key).or_insert(option);
3234    }
3235    unique.into_values().collect()
3236}
3237
3238fn evidence_choices(
3239    ids: &[Id],
3240    tests: &HashMap<&str, &crate::coverage_report::TestCoverageResult>,
3241    candidates: &BTreeSet<String>,
3242    tests_by_file: &BTreeMap<String, Vec<String>>,
3243) -> Vec<Vec<String>> {
3244    let mut choices = Vec::new();
3245    for id in ids {
3246        let Some(test) = tests.get(id.as_str()) else {
3247            continue;
3248        };
3249        if test.role == "background" {
3250            choices.push(Vec::new());
3251        } else if test.role == "setup" {
3252            if let Some(file) = &test.file {
3253                choices.extend(
3254                    tests_by_file
3255                        .get(file)
3256                        .into_iter()
3257                        .flatten()
3258                        .map(|candidate| vec![candidate.clone()]),
3259                );
3260            }
3261        } else if candidates.contains(id.as_str()) {
3262            choices.push(vec![id.to_string()]);
3263        }
3264    }
3265    deduplicate_options(choices)
3266}
3267
3268fn build_obligations(view: &CoverageView, candidates: &BTreeSet<String>) -> ObligationModel {
3269    let tests = view
3270        .tests
3271        .iter()
3272        .map(|test| (test.id.as_str(), test))
3273        .collect::<HashMap<_, _>>();
3274    let mut tests_by_file = BTreeMap::<String, Vec<String>>::new();
3275    let mut setup_by_file = BTreeMap::<String, Vec<String>>::new();
3276    let mut background = Vec::new();
3277    for test in &view.tests {
3278        match test.role.as_str() {
3279            "test" if candidates.contains(&test.id) => {
3280                if let Some(file) = &test.file {
3281                    tests_by_file
3282                        .entry(file.clone())
3283                        .or_default()
3284                        .push(test.id.clone());
3285                }
3286            }
3287            "setup" => {
3288                if let Some(file) = &test.file {
3289                    setup_by_file
3290                        .entry(file.clone())
3291                        .or_default()
3292                        .push(test.id.clone());
3293                }
3294            }
3295            "background" => background.push(test.id.clone()),
3296            _ => {}
3297        }
3298    }
3299    let choices = |ids: &[Id]| evidence_choices(ids, &tests, candidates, &tests_by_file);
3300    let mut obligations = Vec::new();
3301    let mut unique_lines = BTreeMap::new();
3302    for line in &view.lines {
3303        unique_lines.insert((line.file.as_str(), line.line), line);
3304    }
3305    for ((file, line), result) in unique_lines {
3306        obligations.push(Obligation {
3307            id: format!("line:{file}:{line}"),
3308            metric: ObligationMetric::Lines,
3309            options: choices(&result.tests),
3310        });
3311    }
3312    for point in &view.points {
3313        let (kind, metric) = match point.meta.kind {
3314            crate::coverage_analysis::PointKind::Statement => {
3315                ("statement", ObligationMetric::Statements)
3316            }
3317            crate::coverage_analysis::PointKind::Function => {
3318                ("function", ObligationMetric::Functions)
3319            }
3320        };
3321        obligations.push(Obligation {
3322            id: format!("{kind}:{}", point.meta.id),
3323            metric,
3324            options: choices(&point.tests),
3325        });
3326    }
3327    for branch in &view.branches {
3328        for alternative in &branch.alternatives {
3329            obligations.push(Obligation {
3330                id: format!("branch:{}:{}", branch.meta.id, alternative.id),
3331                metric: ObligationMetric::Branches,
3332                options: choices(&alternative.tests),
3333            });
3334        }
3335    }
3336    for decision in &view.decisions {
3337        for condition in 0..decision.meta.conditions.len() {
3338            let mut options = Vec::new();
3339            for left in 0..decision.vector_observations.len() {
3340                for right in (left + 1)..decision.vector_observations.len() {
3341                    let first = &decision.vector_observations[left];
3342                    let second = &decision.vector_observations[right];
3343                    if !is_independence_pair(&first.vector, &second.vector, condition) {
3344                        continue;
3345                    }
3346                    for first_choice in choices(&first.tests) {
3347                        for second_choice in choices(&second.tests) {
3348                            let mut combined = first_choice.clone();
3349                            combined.extend(second_choice);
3350                            options.push(combined);
3351                        }
3352                    }
3353                }
3354            }
3355            obligations.push(Obligation {
3356                id: format!("mcdc:{}:{condition}", decision.meta.id),
3357                metric: ObligationMetric::Mcdc,
3358                options: deduplicate_options(options),
3359            });
3360        }
3361    }
3362    ObligationModel {
3363        obligations,
3364        setup_by_file,
3365        tests_by_file,
3366        background,
3367    }
3368}
3369
3370fn percentage(metric: ObligationMetric, summary: &CoverageSummary) -> f64 {
3371    match metric {
3372        ObligationMetric::Lines => summary.lines.percentage,
3373        ObligationMetric::Statements => summary.statements.percentage,
3374        ObligationMetric::Functions => summary.functions.percentage,
3375        ObligationMetric::Branches => summary.branches.percentage,
3376        ObligationMetric::Mcdc => summary.condition_coverage_pct,
3377    }
3378}
3379
3380fn obligation_satisfied(obligation: &Obligation, selected: &BTreeSet<String>) -> bool {
3381    obligation
3382        .options
3383        .iter()
3384        .any(|option| option.iter().all(|test| selected.contains(test)))
3385}
3386
3387struct Search<'a> {
3388    obligations: &'a [Obligation],
3389    skip_limits: BTreeMap<ObligationMetric, usize>,
3390    best: BTreeSet<String>,
3391    explored_states: usize,
3392    max_states: usize,
3393    seen: BTreeSet<String>,
3394    candidate_tests: usize,
3395    target: f64,
3396    metric: MinimizeMetric,
3397}
3398
3399impl Search<'_> {
3400    fn visit(
3401        &mut self,
3402        selected: BTreeSet<String>,
3403        skipped: BTreeSet<String>,
3404        skipped_by_metric: BTreeMap<ObligationMetric, usize>,
3405    ) -> Result<(), QueryError> {
3406        self.explored_states += 1;
3407        if self.explored_states > self.max_states {
3408            return Err(QueryError::ComplexityLimit {
3409                candidate_tests: self.candidate_tests,
3410                obligations: self.obligations.len(),
3411                explored_states: self.explored_states,
3412                max_states: self.max_states,
3413                target: self.target,
3414                metric: self.metric,
3415            });
3416        }
3417        if selected.len() >= self.best.len() {
3418            return Ok(());
3419        }
3420        let state_key = format!(
3421            "{}|{}",
3422            selected.iter().cloned().collect::<Vec<_>>().join(","),
3423            skipped.iter().cloned().collect::<Vec<_>>().join(",")
3424        );
3425        if !self.seen.insert(state_key) {
3426            return Ok(());
3427        }
3428        let mut unmet = self
3429            .obligations
3430            .iter()
3431            .filter(|obligation| {
3432                !skipped.contains(&obligation.id) && !obligation_satisfied(obligation, &selected)
3433            })
3434            .collect::<Vec<_>>();
3435        if unmet.is_empty() {
3436            self.best = selected;
3437            return Ok(());
3438        }
3439        unmet.sort_by(|left, right| {
3440            let feasible = |obligation: &Obligation| {
3441                obligation
3442                    .options
3443                    .iter()
3444                    .filter(|option| option.iter().any(|test| !selected.contains(test)))
3445                    .count()
3446            };
3447            feasible(left)
3448                .cmp(&feasible(right))
3449                .then_with(|| left.id.cmp(&right.id))
3450        });
3451        let obligation = unmet[0];
3452        let mut additions = deduplicate_options(obligation.options.iter().filter_map(|option| {
3453            let addition = option
3454                .iter()
3455                .filter(|test| !selected.contains(*test))
3456                .cloned()
3457                .collect::<Vec<_>>();
3458            (!addition.is_empty()).then_some(addition)
3459        }));
3460        additions.sort_by(|left, right| {
3461            left.len()
3462                .cmp(&right.len())
3463                .then_with(|| left.join("\0").cmp(&right.join("\0")))
3464        });
3465        for addition in additions {
3466            if selected.len() + addition.len() >= self.best.len() {
3467                continue;
3468            }
3469            let mut next = selected.clone();
3470            next.extend(addition);
3471            self.visit(next, skipped.clone(), skipped_by_metric.clone())?;
3472        }
3473        let skipped_count = skipped_by_metric
3474            .get(&obligation.metric)
3475            .copied()
3476            .unwrap_or(0);
3477        if skipped_count
3478            < self
3479                .skip_limits
3480                .get(&obligation.metric)
3481                .copied()
3482                .unwrap_or(0)
3483        {
3484            let mut next_skipped = skipped;
3485            next_skipped.insert(obligation.id.clone());
3486            let mut next_counts = skipped_by_metric;
3487            next_counts.insert(obligation.metric, skipped_count + 1);
3488            self.visit(selected, next_skipped, next_counts)?;
3489        }
3490        Ok(())
3491    }
3492}
3493
3494pub fn minimum_test_set(
3495    view: &CoverageView,
3496    target: f64,
3497    metric: MinimizeMetric,
3498    max_states: usize,
3499) -> Result<MinimumTestSetResult, QueryError> {
3500    use crate::coverage_report::coverage_is_complete;
3501    if !target.is_finite() || !(0.0..=100.0).contains(&target) {
3502        return Err(QueryError::InvalidTarget(target));
3503    }
3504    if view.tests.iter().any(|test| {
3505        test.role == "background" && (!test.hits.is_empty() || !test.decisions.is_empty())
3506    }) {
3507        return Err(QueryError::UnattributedEvidence);
3508    }
3509    // And a test whose own coverage nothing recorded cannot be minimized
3510    // around either. Its empty hit set would read as a test that adds nothing
3511    // to any set, so the smallest set would drop it -- and what it covers is
3512    // precisely what nothing knows. The check above catches this whenever the
3513    // run-wide record holds anything, which is nearly always; this catches the
3514    // case where those tests happened to reach nothing measured.
3515    if view
3516        .tests
3517        .iter()
3518        .any(|test| test.role == "test" && !coverage_is_complete(&test.attribution))
3519    {
3520        return Err(QueryError::UnattributedEvidence);
3521    }
3522    let candidate_tests = view
3523        .tests
3524        .iter()
3525        .filter(|test| test.role == "test")
3526        .map(|test| test.id.clone())
3527        .collect::<BTreeSet<_>>();
3528    let model = build_obligations(view, &candidate_tests);
3529    let obligations = model
3530        .obligations
3531        .iter()
3532        .filter(|obligation| obligation.metric.selected(metric))
3533        .cloned()
3534        .collect::<Vec<_>>();
3535    let mut totals = BTreeMap::<ObligationMetric, usize>::new();
3536    for obligation in &obligations {
3537        *totals.entry(obligation.metric).or_default() += 1;
3538    }
3539    let metrics = [
3540        ObligationMetric::Lines,
3541        ObligationMetric::Statements,
3542        ObligationMetric::Functions,
3543        ObligationMetric::Branches,
3544        ObligationMetric::Mcdc,
3545    ]
3546    .into_iter()
3547    .filter(|candidate| candidate.selected(metric))
3548    .collect::<Vec<_>>();
3549    let skip_limits = metrics
3550        .iter()
3551        .map(|selected_metric| {
3552            let total = totals.get(selected_metric).copied().unwrap_or(0);
3553            let required = ((total as f64 * target) / 100.0).ceil() as usize;
3554            (*selected_metric, total.saturating_sub(required))
3555        })
3556        .collect::<BTreeMap<_, _>>();
3557    let full_expanded = model.expand(&candidate_tests);
3558    let full_summary = coverage_summary_for_tests(view, &full_expanded)?;
3559    for selected_metric in &metrics {
3560        let reachable = percentage(*selected_metric, &full_summary);
3561        if reachable + 1e-9 < target {
3562            return Err(QueryError::TargetUnreachable {
3563                metric: selected_metric.public(),
3564                target,
3565                reachable,
3566            });
3567        }
3568    }
3569    let mut search = Search {
3570        obligations: &obligations,
3571        skip_limits,
3572        best: candidate_tests.clone(),
3573        explored_states: 0,
3574        max_states,
3575        seen: BTreeSet::new(),
3576        candidate_tests: candidate_tests.len(),
3577        target,
3578        metric,
3579    };
3580    search.visit(BTreeSet::new(), BTreeSet::new(), BTreeMap::new())?;
3581    let expanded = model.expand(&search.best);
3582    let summary = coverage_summary_for_tests(view, &expanded)?;
3583    Ok(MinimumTestSetResult {
3584        optimal: true,
3585        target,
3586        metric,
3587        selected: search.best.into_iter().collect(),
3588        expanded: expanded.into_iter().collect(),
3589        summary,
3590        explored_states: search.explored_states,
3591    })
3592}
3593
3594#[cfg(test)]
3595mod tests {
3596    use crate::{
3597        coverage_analysis::McdcVector,
3598        coverage_report::{
3599            CoverageManifest, CoverageReport, CoverageReportRequest, DecisionMeta, ExitCodeInput,
3600            RawTestResult, RuntimeSnapshot, TestProvenance, analyze_coverage_results,
3601        },
3602    };
3603
3604    use super::*;
3605
3606    fn scope_entry(
3607        file: &str,
3608        status: &str,
3609        reason: &str,
3610        package: Option<&str>,
3611    ) -> IndexedScopeEntry {
3612        IndexedScopeEntry {
3613            file: file.into(),
3614            status: status.into(),
3615            reason: reason.into(),
3616            package_root: package.map(str::to_owned),
3617            measurement_limitations: 0,
3618            limitation_kinds: Vec::new(),
3619        }
3620    }
3621
3622    #[test]
3623    fn a_scope_is_grouped_by_place_and_names_the_roots_that_settle_it() {
3624        let unclassified = "unclassified first-party source";
3625        let entries = [
3626            scope_entry("components/a.tsx", "ambiguous", unclassified, None),
3627            scope_entry("components/ui/b.tsx", "ambiguous", unclassified, None),
3628            scope_entry("proxy.ts", "ambiguous", unclassified, None),
3629            scope_entry(
3630                "app/page.tsx",
3631                "included",
3632                "discovered package source root",
3633                None,
3634            ),
3635            scope_entry(
3636                "tests/a.test.ts",
3637                "excluded",
3638                "test or fixture source",
3639                None,
3640            ),
3641            scope_entry(
3642                "next.config.ts",
3643                "excluded",
3644                "build/test/tool configuration",
3645                None,
3646            ),
3647            scope_entry(
3648                "packages/ui/extra/c.ts",
3649                "ambiguous",
3650                unclassified,
3651                Some("packages/ui"),
3652            ),
3653            scope_entry(
3654                "packages/ui/src/d.ts",
3655                "included",
3656                "discovered package source root",
3657                Some("packages/ui"),
3658            ),
3659        ];
3660        let groups = scope_groups(&entries)
3661            .into_iter()
3662            .map(|group| (group.files, group.status, group.directory))
3663            .collect::<Vec<_>>();
3664        assert_eq!(
3665            groups,
3666            [
3667                (2, "ambiguous".to_owned(), "components".to_owned()),
3668                (1, "ambiguous".into(), ".".into()),
3669                (1, "ambiguous".into(), "packages/ui/extra".into()),
3670                (1, "included".into(), "app".into()),
3671                (1, "included".into(), "packages/ui/src".into()),
3672                (1, "excluded".into(), ".".into()),
3673                (1, "excluded".into(), "tests".into()),
3674            ]
3675        );
3676        // The roots discovery found, then each place: a directory by name,
3677        // and a file at the top by its own, never `.`.
3678        let hint =
3679            unclassified_source(&["app".into(), "packages/ui/src".into()], &entries).unwrap();
3680        assert_eq!(
3681            hint.roots,
3682            [
3683                "app",
3684                "packages/ui/src",
3685                "components",
3686                "packages/ui/extra",
3687                "proxy.ts"
3688            ]
3689        );
3690        assert_eq!(hint.directories[0].directory, "components");
3691        assert_eq!(hint.directories[0].files, 2);
3692        assert_eq!(unclassified_source(&[], &entries[3..6]), None);
3693    }
3694
3695    #[test]
3696    fn a_file_is_counted_under_its_first_folders() {
3697        assert_eq!(area_directory("app/api/cron/route.ts", 1), "app");
3698        assert_eq!(area_directory("app/api/cron/route.ts", 2), "app/api");
3699        assert_eq!(area_directory("app/page.tsx", 2), "app");
3700        assert_eq!(area_directory("proxy.ts", 2), ".");
3701    }
3702
3703    #[test]
3704    fn all_metric_keeps_statement_only_files_in_the_gap_set() {
3705        let gap = IndexedFileGap {
3706            view: CoverageViewId::All,
3707            file: "src/statement.js".into(),
3708            uncovered_lines: 0,
3709            uncovered_statements: 1,
3710            uncovered_functions: 0,
3711            missing_branches: 0,
3712            missing_mcdc_conditions: 0,
3713            measurement_limitations: 0,
3714            limitation_kinds: Vec::new(),
3715            covered_by_other_tests: crate::coverage_index::IndexedGapDimensions {
3716                lines: 0,
3717                statements: 0,
3718                functions: 0,
3719                branches: 0,
3720                mcdc_conditions: 0,
3721            },
3722            uncovered_everywhere: crate::coverage_index::IndexedGapDimensions {
3723                lines: 0,
3724                statements: 1,
3725                functions: 0,
3726                branches: 0,
3727                mcdc_conditions: 0,
3728            },
3729            totals: crate::coverage_index::IndexedGapDimensions {
3730                lines: 1,
3731                statements: 2,
3732                functions: 0,
3733                branches: 0,
3734                mcdc_conditions: 0,
3735            },
3736            covered: crate::coverage_index::IndexedGapDimensions {
3737                lines: 1,
3738                statements: 1,
3739                functions: 0,
3740                branches: 0,
3741                mcdc_conditions: 0,
3742            },
3743            score: 0,
3744        };
3745        assert!(has_gap_for_metric(&gap, MinimizeMetric::All));
3746        assert!(has_gap_for_metric(&gap, MinimizeMetric::Statements));
3747        assert!(!has_gap_for_metric(&gap, MinimizeMetric::Lines));
3748    }
3749
3750    fn result(id: &str, vector: McdcVector) -> RawTestResult {
3751        RawTestResult {
3752            test_id: Some(id.into()),
3753            scope: None,
3754            test: id.into(),
3755            test_file: Some("tests/permission.test.js".into()),
3756            title: None,
3757            retry: Some(0),
3758            status: Some("passed".into()),
3759            expected_status: None,
3760            flaky: false,
3761            provenance: TestProvenance {
3762                runner: "node:test".into(),
3763                kind: "unit".into(),
3764                project: None,
3765                source: "runner-default".into(),
3766            },
3767            role: "test".into(),
3768            attribution: crate::coverage_report::ATTRIBUTION_EXACT.into(),
3769            phases: Vec::new(),
3770            runtime: vec![RuntimeSnapshot {
3771                decisions: vec![crate::coverage_report::DecisionSnapshot {
3772                    meta: decision(),
3773                    vectors: vec![vector],
3774                }],
3775                hits: Vec::new(),
3776                events: Vec::new(),
3777                logicals: Vec::new(),
3778                phase_id: None,
3779            }],
3780            browser: Vec::new(),
3781            server: Vec::new(),
3782        }
3783    }
3784
3785    fn decision() -> DecisionMeta {
3786        DecisionMeta {
3787            id: "decision".into(),
3788            file: "src/permission.js".into(),
3789            line: 1,
3790            column: 1,
3791            source: "admin || owner".into(),
3792            conditions: vec!["admin".into(), "owner".into()],
3793            kind: "if".into(),
3794        }
3795    }
3796
3797    fn report(mut results: Vec<RawTestResult>) -> CoverageReport {
3798        analyze_coverage_results(&CoverageReportRequest {
3799            run_id: "run".into(),
3800            manifest: CoverageManifest {
3801                unmeasured: Vec::new(),
3802                decisions: vec![decision()],
3803                points: Vec::new(),
3804                branches: Vec::new(),
3805                limitations: Vec::new(),
3806                scope: None,
3807                assertion_sites: Vec::new(),
3808            },
3809            raw_results: std::mem::take(&mut results),
3810            generated_at: "time".into(),
3811            coverage_model: None,
3812            integrity: None,
3813            test_exit_code: ExitCodeInput::Present(Some(0)),
3814        })
3815        .unwrap()
3816    }
3817
3818    #[test]
3819    fn recomputes_mcdc_witnesses_and_removes_a_redundant_vector() {
3820        let report = report(vec![
3821            result(
3822                "admin",
3823                McdcVector {
3824                    values: vec![Some(true), None],
3825                    outcome: true,
3826                },
3827            ),
3828            result(
3829                "owner",
3830                McdcVector {
3831                    values: vec![Some(false), Some(true)],
3832                    outcome: true,
3833                },
3834            ),
3835            result(
3836                "both",
3837                McdcVector {
3838                    values: vec![Some(true), None],
3839                    outcome: true,
3840                },
3841            ),
3842            result(
3843                "neither",
3844                McdcVector {
3845                    values: vec![Some(false), Some(false)],
3846                    outcome: false,
3847                },
3848            ),
3849        ]);
3850        let minimized = minimum_test_set(&report.view, 100.0, MinimizeMetric::Mcdc, 5_000).unwrap();
3851        assert_eq!(minimized.selected.len(), 3);
3852        assert!(minimized.selected.contains(&"owner".into()));
3853        assert!(minimized.selected.contains(&"neither".into()));
3854        assert_eq!(minimized.summary.condition_coverage_pct, 100.0);
3855    }
3856
3857    #[test]
3858    fn a_test_that_belongs_to_no_test_is_not_minimized_away() {
3859        // The first guard catches this whenever the run-wide record holds
3860        // anything, which is nearly always -- so it is the rare run, where
3861        // those tests happened to reach nothing measured, that reaches this
3862        // one. Without it the smallest set would quietly drop a test whose
3863        // coverage is unknown rather than absent, and report the drop as a
3864        // saving.
3865        let mut parallel = result(
3866            "parallel",
3867            McdcVector {
3868                values: vec![Some(false), Some(false)],
3869                outcome: false,
3870            },
3871        );
3872        parallel.attribution = crate::coverage_report::ATTRIBUTION_RUN_WIDE.into();
3873        assert!(matches!(
3874            minimum_test_set(
3875                &report(vec![parallel]).view,
3876                100.0,
3877                MinimizeMetric::Mcdc,
3878                5_000,
3879            ),
3880            Err(QueryError::UnattributedEvidence)
3881        ));
3882    }
3883
3884    #[test]
3885    fn the_summary_counts_each_test_under_the_attribution_it_carries() {
3886        // These three numbers are what the `Attribution` line reads out, and
3887        // nothing -- here or in the integration scripts -- had ever checked
3888        // that a test lands in the bucket it was written with.
3889        let vector = || McdcVector {
3890            values: vec![Some(false), Some(false)],
3891            outcome: false,
3892        };
3893        let mut serial = result("serial", vector());
3894        serial.attribution = crate::coverage_report::ATTRIBUTION_EXACT.into();
3895        let mut parallel = result("parallel", vector());
3896        parallel.attribution = crate::coverage_report::ATTRIBUTION_RUN_WIDE.into();
3897        let mut ruby = result("ruby", vector());
3898        ruby.attribution = crate::coverage_report::ATTRIBUTION_PARTIAL.into();
3899        let mut also_parallel = result("also-parallel", vector());
3900        also_parallel.attribution = crate::coverage_report::ATTRIBUTION_RUN_WIDE.into();
3901        let report = report(vec![serial, parallel, ruby, also_parallel]);
3902
3903        let nonce = std::time::SystemTime::now()
3904            .duration_since(std::time::UNIX_EPOCH)
3905            .unwrap()
3906            .as_nanos();
3907        let root = std::env::temp_dir().join(format!(
3908            "supercov-attribution-counts-{}-{nonce}",
3909            std::process::id()
3910        ));
3911        std::fs::create_dir(&root).unwrap();
3912        let path = root.join("query-index.v1.bin");
3913        let identity = crate::query_index::QueryIndexIdentity {
3914            evidence_sha256: [1; 32],
3915            evidence_bytes: 100,
3916            analysis_sha256: [2; 32],
3917            producer_sha256: [3; 32],
3918            archive_schema_version: 2,
3919        };
3920        crate::query_index::write_query_index(
3921            &crate::coverage_index::coverage_index_sections(&report).unwrap(),
3922            &identity,
3923            &path,
3924        )
3925        .unwrap();
3926        let container = crate::query_index::QueryIndex::open(&path, &identity).unwrap();
3927        let index = crate::coverage_index::CoverageIndex::new(&container).unwrap();
3928
3929        let summary = coverage_summary_query(
3930            &index,
3931            CoverageSummaryQueryOptions {
3932                run: "run",
3933                view: CoverageViewId::All,
3934                kind: None,
3935                runner: None,
3936                valid: true,
3937                test_exit_code: Some(0),
3938                stale: false,
3939                stale_reasons: Vec::new(),
3940            },
3941        )
3942        .unwrap();
3943        assert_eq!(summary.test_attribution.exact, 1);
3944        assert_eq!(summary.test_attribution.run_wide, 2);
3945        assert_eq!(summary.test_attribution.partial, 1);
3946        assert_eq!(summary.test_attribution.total(), 4);
3947        std::fs::remove_dir_all(&root).ok();
3948    }
3949
3950    #[test]
3951    fn refuses_background_evidence() {
3952        let mut aggregate = result(
3953            "aggregate",
3954            McdcVector {
3955                values: vec![Some(false), Some(false)],
3956                outcome: false,
3957            },
3958        );
3959        aggregate.role = "background".into();
3960        assert!(matches!(
3961            minimum_test_set(
3962                &report(vec![aggregate]).view,
3963                100.0,
3964                MinimizeMetric::Mcdc,
3965                5_000,
3966            ),
3967            Err(QueryError::UnattributedEvidence)
3968        ));
3969    }
3970
3971    #[test]
3972    fn bounds_the_exact_search() {
3973        let report = report(vec![
3974            result(
3975                "admin",
3976                McdcVector {
3977                    values: vec![Some(true), None],
3978                    outcome: true,
3979                },
3980            ),
3981            result(
3982                "owner",
3983                McdcVector {
3984                    values: vec![Some(false), Some(true)],
3985                    outcome: true,
3986                },
3987            ),
3988            result(
3989                "neither",
3990                McdcVector {
3991                    values: vec![Some(false), Some(false)],
3992                    outcome: false,
3993                },
3994            ),
3995        ]);
3996        assert!(matches!(
3997            minimum_test_set(&report.view, 100.0, MinimizeMetric::Mcdc, 1),
3998            Err(QueryError::ComplexityLimit { .. })
3999        ));
4000    }
4001}