1use 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
273#[serde(rename_all = "camelCase")]
274pub struct TestAttributionCounts {
275 pub exact: usize,
277 pub partial: usize,
279 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 #[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 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 #[serde(skip_serializing_if = "Option::is_none")]
354 pub unclassified_source: Option<UnclassifiedSource>,
355}
356
357#[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#[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
385fn 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
411pub 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 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 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 #[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 #[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 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 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 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 #[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 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 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 "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 #[serde(skip_serializing_if = "Option::is_none")]
2232 pub inputs: Option<CoverageDiffInputs>,
2233}
2234
2235#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
2239#[serde(rename_all = "camelCase")]
2240pub struct CoverageDiffInputs {
2241 pub source_changed: bool,
2243 pub tests_changed: bool,
2244}
2245
2246#[derive(Debug, Clone, Copy)]
2247pub struct CoverageDiffQueryOptions<'a> {
2248 pub older_run: &'a str,
2249 pub newer_run: &'a str,
2250 pub view: CoverageViewId,
2251 pub kind: Option<&'a str>,
2252 pub runner: Option<&'a str>,
2253 pub offset: usize,
2254 pub limit: usize,
2255}
2256
2257struct DiffSnapshot {
2258 summary: CoverageSummary,
2259 lines: BTreeSet<String>,
2260 branches: HashMap<String, String>,
2261 mcdc: HashMap<String, String>,
2262}
2263
2264fn diff_snapshot(
2265 index: &CoverageIndex<'_>,
2266 view: CoverageViewId,
2267) -> Result<DiffSnapshot, QueryError> {
2268 let summary = index.summary(view)?;
2269 let lines = index
2270 .lines(view)?
2271 .into_iter()
2272 .filter(|line| line.covered)
2273 .map(|line| format!("{}:{}", line.file, line.line))
2274 .collect();
2275 let branches = index
2276 .hit_metadata(view)?
2277 .into_iter()
2278 .filter(|metadata| metadata.obligation == "branch" && !metadata.tests.is_empty())
2279 .map(|metadata| {
2280 let parent = metadata
2281 .parent_id
2282 .ok_or(QueryError::InvalidRecordSelection)?;
2283 Ok((
2284 format!("{parent}:{}", metadata.id),
2285 format!(
2286 "{}:{} {}",
2287 metadata.file,
2288 metadata.line,
2289 metadata.alternative.unwrap_or_default()
2290 ),
2291 ))
2292 })
2293 .collect::<Result<HashMap<_, _>, QueryError>>()?;
2294 let mcdc = index
2295 .decision_details(view)?
2296 .into_iter()
2297 .flat_map(|decision| {
2298 decision
2299 .conditions
2300 .into_iter()
2301 .filter(|condition| condition.covered)
2302 .map(move |condition| {
2303 (
2304 format!("{}:c{}", decision.meta.id, condition.index),
2305 format!(
2306 "{}:{} C{} {}",
2307 decision.meta.file,
2308 decision.meta.line,
2309 condition.index + 1,
2310 condition.source
2311 ),
2312 )
2313 })
2314 })
2315 .collect();
2316 Ok(DiffSnapshot {
2317 summary,
2318 lines,
2319 branches,
2320 mcdc,
2321 })
2322}
2323
2324fn js_string_cmp(left: &str, right: &str) -> std::cmp::Ordering {
2325 left.encode_utf16().cmp(right.encode_utf16())
2326}
2327
2328fn rounded_delta(newer: f64, older: f64) -> f64 {
2329 ((newer - older) * 100.0).round() / 100.0
2330}
2331
2332pub fn coverage_diff_query(
2333 older: &CoverageIndex<'_>,
2334 newer: &CoverageIndex<'_>,
2335 options: CoverageDiffQueryOptions<'_>,
2336) -> Result<(CoverageDiffData, AgentPagination), QueryError> {
2337 if options.limit == 0 {
2338 return Err(QueryError::InvalidPagination);
2339 }
2340 let older = diff_snapshot(older, options.view)?;
2341 let newer = diff_snapshot(newer, options.view)?;
2342 let mut gained_lines = newer
2343 .lines
2344 .difference(&older.lines)
2345 .cloned()
2346 .collect::<Vec<_>>();
2347 let mut lost_lines = older
2348 .lines
2349 .difference(&newer.lines)
2350 .cloned()
2351 .collect::<Vec<_>>();
2352 let mut gained_branches = newer
2353 .branches
2354 .iter()
2355 .filter(|(id, _)| !older.branches.contains_key(*id))
2356 .map(|(_, label)| label.clone())
2357 .collect::<Vec<_>>();
2358 let mut lost_branches = older
2359 .branches
2360 .iter()
2361 .filter(|(id, _)| !newer.branches.contains_key(*id))
2362 .map(|(_, label)| label.clone())
2363 .collect::<Vec<_>>();
2364 let mut gained_mcdc = newer
2365 .mcdc
2366 .iter()
2367 .filter(|(id, _)| !older.mcdc.contains_key(*id))
2368 .map(|(_, label)| label.clone())
2369 .collect::<Vec<_>>();
2370 let mut lost_mcdc = older
2371 .mcdc
2372 .iter()
2373 .filter(|(id, _)| !newer.mcdc.contains_key(*id))
2374 .map(|(_, label)| label.clone())
2375 .collect::<Vec<_>>();
2376 for values in [
2377 &mut gained_lines,
2378 &mut lost_lines,
2379 &mut gained_branches,
2380 &mut lost_branches,
2381 &mut gained_mcdc,
2382 &mut lost_mcdc,
2383 ] {
2384 values.sort_by(|left, right| js_string_cmp(left, right));
2385 }
2386 let total = [
2387 gained_lines.len(),
2388 gained_branches.len(),
2389 gained_mcdc.len(),
2390 lost_lines.len(),
2391 lost_branches.len(),
2392 lost_mcdc.len(),
2393 ]
2394 .into_iter()
2395 .max()
2396 .unwrap_or(0);
2397 let page = |values: &[String]| {
2398 values
2399 .iter()
2400 .skip(options.offset)
2401 .take(options.limit)
2402 .cloned()
2403 .collect::<Vec<_>>()
2404 };
2405 let gained = CoverageDiffSide {
2406 line_count: gained_lines.len(),
2407 branch_count: gained_branches.len(),
2408 mcdc_count: gained_mcdc.len(),
2409 lines: page(&gained_lines),
2410 branches: page(&gained_branches),
2411 mcdc: page(&gained_mcdc),
2412 };
2413 let lost = CoverageDiffSide {
2414 line_count: lost_lines.len(),
2415 branch_count: lost_branches.len(),
2416 mcdc_count: lost_mcdc.len(),
2417 lines: page(&lost_lines),
2418 branches: page(&lost_branches),
2419 mcdc: page(&lost_mcdc),
2420 };
2421 let returned = [
2422 gained.lines.len(),
2423 gained.branches.len(),
2424 gained.mcdc.len(),
2425 lost.lines.len(),
2426 lost.branches.len(),
2427 lost.mcdc.len(),
2428 ]
2429 .into_iter()
2430 .max()
2431 .unwrap_or(0);
2432 Ok((
2433 CoverageDiffData {
2434 filters: query_filters(options.view, options.kind, options.runner),
2435 older: options.older_run.into(),
2436 newer: options.newer_run.into(),
2437 delta: CoverageDiffDelta {
2438 lines: rounded_delta(
2439 newer.summary.lines.percentage,
2440 older.summary.lines.percentage,
2441 ),
2442 branches: rounded_delta(
2443 newer.summary.branches.percentage,
2444 older.summary.branches.percentage,
2445 ),
2446 mcdc: rounded_delta(
2447 newer.summary.condition_coverage_pct,
2448 older.summary.condition_coverage_pct,
2449 ),
2450 },
2451 gained,
2452 lost,
2453 inputs: None,
2454 },
2455 pagination(options.offset, options.limit, returned, total),
2456 ))
2457}
2458
2459pub fn coverage_scope_query(
2460 index: &CoverageIndex<'_>,
2461 options: CoverageScopeQueryOptions<'_>,
2462) -> Result<(CoverageScopeData, AgentPagination), QueryError> {
2463 if options.limit == 0 {
2464 return Err(QueryError::InvalidPagination);
2465 }
2466 let projection = index.projection(options.view, options.kind, options.runner)?;
2467 let scope = projection
2468 .source_scope
2469 .ok_or(QueryError::ScopeUnavailable)?;
2470 let mut entries = index.scope_entries(options.view)?;
2471 entries.sort_by(|left, right| {
2472 scope_status_rank(&left.status)
2473 .cmp(&scope_status_rank(&right.status))
2474 .then_with(|| left.file.cmp(&right.file))
2475 });
2476 let groups = scope_groups(&entries);
2477 let unclassified = unclassified_source(&scope.roots, &entries);
2478 let total = entries.len();
2479 let selected = entries
2480 .into_iter()
2481 .skip(options.offset)
2482 .take(options.limit)
2483 .collect::<Vec<_>>();
2484 let returned = selected.len();
2485 Ok((
2486 CoverageScopeData {
2487 run: options.run.into(),
2488 filters: CoverageQueryFilters {
2489 outcome: match options.view {
2490 CoverageViewId::All => "all",
2491 CoverageViewId::Passed => "passed",
2492 CoverageViewId::Failed => "failed",
2493 }
2494 .into(),
2495 kind: options.kind.map(str::to_owned),
2496 runner: options.runner.map(str::to_owned),
2497 },
2498 kind: scope.kind,
2499 language: scope.language,
2500 model: scope.model,
2501 mode: scope.mode,
2502 roots: scope.roots,
2503 unit: scope.unit,
2504 measurement_complete: scope.measurement_complete,
2505 counts: ScopeCounts {
2506 included: scope.included,
2507 excluded: scope.excluded,
2508 ambiguous: scope.ambiguous,
2509 },
2510 measurement: projection.measurement,
2511 groups,
2512 unclassified_source: unclassified,
2513 entries: selected,
2514 },
2515 pagination(options.offset, options.limit, returned, total),
2516 ))
2517}
2518
2519pub fn coverage_summary_query(
2520 index: &CoverageIndex<'_>,
2521 options: CoverageSummaryQueryOptions<'_>,
2522) -> Result<CoverageSummaryData, QueryError> {
2523 let projection = index.projection(options.view, options.kind, options.runner)?;
2524 let mut test_kind_sources = BTreeMap::new();
2525 for test in index.test_summaries(options.view)?.iter().filter(|t| {
2526 t.role == "test"
2527 && options.kind.is_none_or(|k| t.provenance.kind == k)
2528 && options.runner.is_none_or(|r| t.provenance.runner == r)
2529 }) {
2530 *test_kind_sources
2531 .entry(test.provenance.source.clone())
2532 .or_insert(0) += 1;
2533 }
2534 let mut diagnostics = Vec::new();
2535 let mut transport_blockers = 0usize;
2536 if projection.empty_evidence_tests > 0 {
2537 diagnostics.push(CoverageDiagnostic {
2538 code: "TEST_EVIDENCE_MISSING".into(),
2539 severity: "warning".into(),
2540 message: format!(
2541 "{} 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: {}",
2542 projection.empty_evidence_tests,
2543 projection.first_empty_evidence_test.as_deref().unwrap_or("unknown")
2544 ),
2545 });
2546 }
2547 if let Some(transport) = &projection.transport {
2548 if transport.corrupt_records > 0 {
2549 transport_blockers += 1;
2550 diagnostics.push(CoverageDiagnostic {
2551 code: "CORRUPT_EVIDENCE_RECORDS".into(),
2552 severity: "error".into(),
2553 message: format!(
2554 "{} malformed evidence record(s) in {} file(s) were excluded; coverage is incomplete.",
2555 transport.corrupt_records, transport.corrupt_files
2556 ),
2557 });
2558 }
2559 if transport.remote_launches > 0
2560 && transport.scoped_server_records == 0
2561 && transport.background_server_records == 0
2562 && projection.attribution.server_explicit == 0
2563 && projection.attribution.server_fallback == 0
2564 {
2565 transport_blockers += 1;
2566 diagnostics.push(CoverageDiagnostic {
2567 code: "REMOTE_SERVER_EVIDENCE_MISSING".into(),
2568 severity: "error".into(),
2569 message: "Remote launches were supervised, but neither scoped nor background server evidence returned. Supercov refuses to describe this measurement as complete.".into(),
2570 });
2571 }
2572 }
2573 let coverage_by_kind = index.dimensions(options.view, CoverageDimension::Kind)?;
2574 let coverage_by_runner = index.dimensions(options.view, CoverageDimension::Runner)?;
2575 let coverage_by_tests = if options.kind.is_none() && options.runner.is_none() {
2576 index
2577 .dimensions(options.view, CoverageDimension::Tests)?
2578 .into_iter()
2579 .next()
2580 .filter(|tests| tests.tests + tests.setups > 0)
2581 .map(|tests| tests.summary)
2582 } else {
2583 None
2584 };
2585 let other_e2e_kinds = coverage_by_kind
2586 .iter()
2587 .filter(|dimension| dimension.tests > 0)
2588 .filter_map(|dimension| dimension.kind.clone())
2589 .filter(|kind| kind != "e2e")
2590 .collect::<Vec<_>>();
2591 let e2e_observed = coverage_by_kind
2592 .iter()
2593 .any(|dimension| dimension.tests > 0 && dimension.kind.as_deref() == Some("e2e"));
2594 let e2e_gap_context = if options.kind.is_none()
2595 && options.runner.is_none()
2596 && e2e_observed
2597 && !other_e2e_kinds.is_empty()
2598 {
2599 let mut covered_elsewhere = IndexedGapDimensions {
2600 lines: 0,
2601 statements: 0,
2602 functions: 0,
2603 branches: 0,
2604 mcdc_conditions: 0,
2605 };
2606 let mut uncovered_everywhere = covered_elsewhere.clone();
2607 for gap in index.file_gaps(options.view, Some("e2e"), None)? {
2608 covered_elsewhere.lines += gap.covered_by_other_tests.lines;
2609 covered_elsewhere.statements += gap.covered_by_other_tests.statements;
2610 covered_elsewhere.functions += gap.covered_by_other_tests.functions;
2611 covered_elsewhere.branches += gap.covered_by_other_tests.branches;
2612 covered_elsewhere.mcdc_conditions += gap.covered_by_other_tests.mcdc_conditions;
2613 uncovered_everywhere.lines += gap.uncovered_everywhere.lines;
2614 uncovered_everywhere.statements += gap.uncovered_everywhere.statements;
2615 uncovered_everywhere.functions += gap.uncovered_everywhere.functions;
2616 uncovered_everywhere.branches += gap.uncovered_everywhere.branches;
2617 uncovered_everywhere.mcdc_conditions += gap.uncovered_everywhere.mcdc_conditions;
2618 }
2619 Some(CoverageKindGapContext {
2620 kind: "e2e".into(),
2621 other_kinds: other_e2e_kinds,
2622 covered_elsewhere,
2623 uncovered_everywhere,
2624 })
2625 } else {
2626 None
2627 };
2628 let filters = CoverageQueryFilters {
2629 outcome: match options.view {
2630 CoverageViewId::All => "all",
2631 CoverageViewId::Passed => "passed",
2632 CoverageViewId::Failed => "failed",
2633 }
2634 .into(),
2635 kind: options.kind.map(str::to_owned),
2636 runner: options.runner.map(str::to_owned),
2637 };
2638 let mut measurement = projection.measurement.clone();
2639 if transport_blockers > 0 {
2640 measurement.complete = false;
2641 measurement.limitations = measurement.limitations.saturating_add(transport_blockers);
2642 measurement.blocking = measurement.blocking.saturating_add(transport_blockers);
2643 }
2644 let structurally_complete = projection.summary.coverage_complete && measurement.complete;
2645 let complete = options.view == CoverageViewId::Passed
2646 && options.valid
2647 && !options.stale
2648 && structurally_complete;
2649 Ok(CoverageSummaryData {
2650 test_kind_sources,
2651 assertion_coverage: None,
2652 run: options.run.into(),
2653 command: Vec::new(),
2654 hints: Vec::new(),
2655 workspace: None,
2656 filters,
2657 model: index.model()?,
2658 generated_at: projection.generated_at,
2659 valid: options.valid,
2660 test_exit_code: options.test_exit_code,
2661 stale: options.stale,
2662 stale_reasons: options.stale_reasons,
2663 structurally_complete,
2664 complete,
2665 coverage: projection.summary,
2666 measurement,
2667 coverage_by_kind,
2668 coverage_by_tests,
2669 e2e_gap_context,
2670 coverage_by_runner,
2671 attribution: projection.attribution,
2672 test_attribution: {
2673 let mut counts = TestAttributionCounts::default();
2674 for test in index
2675 .test_summaries(options.view)?
2676 .iter()
2677 .filter(|test| test.role == "test")
2678 {
2679 match test.attribution.as_str() {
2680 crate::coverage_report::ATTRIBUTION_RUN_WIDE => counts.run_wide += 1,
2681 crate::coverage_report::ATTRIBUTION_PARTIAL => counts.partial += 1,
2682 _ => counts.exact += 1,
2683 }
2684 }
2685 counts
2686 },
2687 transport: projection.transport,
2688 diagnostics,
2689 confidence: (options.kind.is_none() && options.runner.is_none())
2690 .then_some(projection.confidence),
2691 files_with_gaps: projection.files_with_gaps,
2692 files_with_coverage_gaps: projection.files_with_coverage_gaps,
2693 files_with_measurement_limitations: projection.measurement.files,
2694 tests: projection.tests,
2695 setups: projection.setups,
2696 test_outcomes: projection.test_outcomes,
2697 unclassified_source: match &projection.source_scope {
2698 Some(scope) if scope.ambiguous > 0 => {
2699 unclassified_source(&scope.roots, &index.scope_entries(options.view)?)
2700 }
2701 _ => None,
2702 },
2703 source_scope: projection.source_scope,
2704 })
2705}
2706
2707#[derive(Debug, Clone, PartialEq)]
2708pub enum CoverageDimensionQueryData {
2709 Kinds(CoverageKindsData),
2710 Runners(CoverageRunnersData),
2711}
2712
2713#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2716#[serde(rename_all = "camelCase")]
2717pub struct CoverageArea {
2718 pub directory: String,
2719 pub files: usize,
2720 pub totals: IndexedGapDimensions,
2721 pub covered: IndexedGapDimensions,
2722 pub by_kind: Vec<CoverageAreaKind>,
2723 #[serde(skip_serializing_if = "Option::is_none")]
2727 pub covered_by_tests: Option<IndexedGapDimensions>,
2728}
2729
2730#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2731#[serde(rename_all = "camelCase")]
2732pub struct CoverageAreaKind {
2733 pub kind: String,
2734 pub covered: IndexedGapDimensions,
2735}
2736
2737#[derive(Debug, Clone, PartialEq, Serialize)]
2738#[serde(rename_all = "camelCase")]
2739pub struct CoverageAreasData {
2740 pub run: String,
2741 pub filters: CoverageQueryFilters,
2742 pub metric: MinimizeMetric,
2743 pub depth: usize,
2744 pub kinds: Vec<String>,
2747 pub areas: Vec<CoverageArea>,
2748}
2749
2750#[derive(Debug, Clone, Copy)]
2751pub struct CoverageAreasQueryOptions<'a> {
2752 pub run: &'a str,
2753 pub view: CoverageViewId,
2754 pub metric: MinimizeMetric,
2755 pub kind: Option<&'a str>,
2756 pub runner: Option<&'a str>,
2757 pub depth: usize,
2758 pub offset: usize,
2759 pub limit: usize,
2760}
2761
2762fn area_directory(file: &str, depth: usize) -> String {
2765 let mut folders = file.split('/').collect::<Vec<_>>();
2766 folders.pop();
2767 if folders.is_empty() {
2768 ".".into()
2769 } else {
2770 folders[..folders.len().min(depth)].join("/")
2771 }
2772}
2773
2774fn add_dimensions(sum: &mut IndexedGapDimensions, value: &IndexedGapDimensions) {
2775 sum.lines += value.lines;
2776 sum.statements += value.statements;
2777 sum.functions += value.functions;
2778 sum.branches += value.branches;
2779 sum.mcdc_conditions += value.mcdc_conditions;
2780}
2781
2782const NO_DIMENSIONS: IndexedGapDimensions = IndexedGapDimensions {
2783 lines: 0,
2784 statements: 0,
2785 functions: 0,
2786 branches: 0,
2787 mcdc_conditions: 0,
2788};
2789
2790pub fn dimension_for_metric(dimensions: &IndexedGapDimensions, metric: MinimizeMetric) -> usize {
2792 match metric {
2793 MinimizeMetric::All | MinimizeMetric::Lines => dimensions.lines,
2794 MinimizeMetric::Statements => dimensions.statements,
2795 MinimizeMetric::Functions => dimensions.functions,
2796 MinimizeMetric::Branches => dimensions.branches,
2797 MinimizeMetric::Mcdc => dimensions.mcdc_conditions,
2798 }
2799}
2800
2801pub fn coverage_areas_query(
2805 index: &CoverageIndex<'_>,
2806 options: CoverageAreasQueryOptions<'_>,
2807) -> Result<(CoverageAreasData, AgentPagination), QueryError> {
2808 if options.limit == 0 || options.depth == 0 {
2809 return Err(QueryError::InvalidPagination);
2810 }
2811 let files = index.file_gaps(options.view, options.kind, options.runner)?;
2812 if (options.kind.is_some() || options.runner.is_some()) && files.is_empty() {
2813 return Err(QueryError::TestFilterEmpty {
2814 kind: options.kind.map(str::to_owned),
2815 runner: options.runner.map(str::to_owned),
2816 });
2817 }
2818 let kinds = if options.kind.is_none() && options.runner.is_none() {
2819 index
2820 .dimensions(options.view, CoverageDimension::Kind)?
2821 .into_iter()
2822 .filter(|kind| kind.tests > 0 && kind.attributed > 0)
2823 .filter_map(|kind| kind.kind)
2824 .collect::<Vec<_>>()
2825 } else {
2826 Vec::new()
2827 };
2828 let mut areas = BTreeMap::<String, CoverageArea>::new();
2829 for file in &files {
2830 let directory = area_directory(&file.file, options.depth);
2831 let area = areas
2832 .entry(directory.clone())
2833 .or_insert_with(|| CoverageArea {
2834 directory,
2835 files: 0,
2836 totals: NO_DIMENSIONS,
2837 covered: NO_DIMENSIONS,
2838 by_kind: kinds
2839 .iter()
2840 .map(|kind| CoverageAreaKind {
2841 kind: kind.clone(),
2842 covered: NO_DIMENSIONS,
2843 })
2844 .collect(),
2845 covered_by_tests: None,
2846 });
2847 area.files += 1;
2848 add_dimensions(&mut area.totals, &file.totals);
2849 add_dimensions(&mut area.covered, &file.covered);
2850 }
2851 for (position, kind) in kinds.iter().enumerate() {
2852 for file in index.file_gaps(options.view, Some(kind), None)? {
2853 if let Some(area) = areas.get_mut(&area_directory(&file.file, options.depth)) {
2854 add_dimensions(&mut area.by_kind[position].covered, &file.covered);
2855 }
2856 }
2857 }
2858 if !kinds.is_empty() {
2859 let tested = index.file_gaps(options.view, Some(crate::coverage_index::ALL_TESTS), None)?;
2860 if !tested.is_empty() {
2861 for area in areas.values_mut() {
2862 area.covered_by_tests = Some(NO_DIMENSIONS);
2863 }
2864 for file in tested {
2865 if let Some(sum) = areas
2866 .get_mut(&area_directory(&file.file, options.depth))
2867 .and_then(|area| area.covered_by_tests.as_mut())
2868 {
2869 add_dimensions(sum, &file.covered);
2870 }
2871 }
2872 }
2873 }
2874 let mut areas = areas.into_values().collect::<Vec<_>>();
2875 areas.sort_by(|left, right| {
2876 dimension_for_metric(&right.totals, options.metric)
2877 .cmp(&dimension_for_metric(&left.totals, options.metric))
2878 .then_with(|| left.directory.cmp(&right.directory))
2879 });
2880 let total = areas.len();
2881 let page = areas
2882 .into_iter()
2883 .skip(options.offset)
2884 .take(options.limit)
2885 .collect::<Vec<_>>();
2886 let returned = page.len();
2887 Ok((
2888 CoverageAreasData {
2889 run: options.run.into(),
2890 filters: CoverageQueryFilters {
2891 outcome: match options.view {
2892 CoverageViewId::All => "all",
2893 CoverageViewId::Passed => "passed",
2894 CoverageViewId::Failed => "failed",
2895 }
2896 .into(),
2897 kind: options.kind.map(str::to_owned),
2898 runner: options.runner.map(str::to_owned),
2899 },
2900 metric: options.metric,
2901 depth: options.depth,
2902 kinds,
2903 areas: page,
2904 },
2905 pagination(options.offset, options.limit, returned, total),
2906 ))
2907}
2908
2909#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
2911#[serde(rename_all = "camelCase")]
2912pub struct TestWithoutEvidence {
2913 pub id: String,
2914 pub name: String,
2915 #[serde(skip_serializing_if = "Option::is_none")]
2916 pub file: Option<String>,
2917 pub kind: String,
2918 pub runner: String,
2919 pub outcome: String,
2920 pub assertions: usize,
2921}
2922
2923#[derive(Debug, Clone, PartialEq, Serialize)]
2924#[serde(rename_all = "camelCase")]
2925pub struct TestsWithoutEvidenceData {
2926 pub run: String,
2927 pub filters: CoverageQueryFilters,
2928 pub tests: Vec<TestWithoutEvidence>,
2929}
2930
2931#[derive(Debug, Clone, Copy)]
2932pub struct TestsWithoutEvidenceOptions<'a> {
2933 pub run: &'a str,
2934 pub view: CoverageViewId,
2935 pub kind: Option<&'a str>,
2936 pub runner: Option<&'a str>,
2937 pub offset: usize,
2938 pub limit: usize,
2939}
2940
2941pub fn tests_without_evidence_query(
2945 index: &CoverageIndex<'_>,
2946 options: TestsWithoutEvidenceOptions<'_>,
2947) -> Result<(TestsWithoutEvidenceData, AgentPagination), QueryError> {
2948 if options.limit == 0 {
2949 return Err(QueryError::InvalidPagination);
2950 }
2951 let mut assertions = BTreeMap::<String, usize>::new();
2952 for phase in index.phase_summaries(options.view)? {
2953 *assertions.entry(phase.test).or_insert(0) += 1;
2954 }
2955 let mut tests = index
2956 .test_details(options.view)?
2957 .into_iter()
2958 .filter(|test| {
2959 test.summary.role == "test"
2960 && test.lines.is_empty()
2961 && test.hits.is_empty()
2962 && test.decisions.is_empty()
2963 && options
2964 .kind
2965 .is_none_or(|kind| test.summary.provenance.kind == kind)
2966 && options
2967 .runner
2968 .is_none_or(|runner| test.summary.provenance.runner == runner)
2969 })
2970 .filter_map(|test| {
2971 let assertions = *assertions.get(&test.summary.id)?;
2972 Some(TestWithoutEvidence {
2973 id: test.summary.id,
2974 name: test.summary.name,
2975 file: test.summary.file,
2976 kind: test.summary.provenance.kind,
2977 runner: test.summary.provenance.runner,
2978 outcome: test.summary.outcome,
2979 assertions,
2980 })
2981 })
2982 .collect::<Vec<_>>();
2983 tests.sort_by(|left, right| {
2984 (&left.file, &left.name, &left.id).cmp(&(&right.file, &right.name, &right.id))
2985 });
2986 let total = tests.len();
2987 let page = tests
2988 .into_iter()
2989 .skip(options.offset)
2990 .take(options.limit)
2991 .collect::<Vec<_>>();
2992 let returned = page.len();
2993 Ok((
2994 TestsWithoutEvidenceData {
2995 run: options.run.into(),
2996 filters: CoverageQueryFilters {
2997 outcome: match options.view {
2998 CoverageViewId::All => "all",
2999 CoverageViewId::Passed => "passed",
3000 CoverageViewId::Failed => "failed",
3001 }
3002 .into(),
3003 kind: options.kind.map(str::to_owned),
3004 runner: options.runner.map(str::to_owned),
3005 },
3006 tests: page,
3007 },
3008 pagination(options.offset, options.limit, returned, total),
3009 ))
3010}
3011
3012#[derive(Debug, Clone, PartialEq)]
3013pub enum CoverageFileQueryData {
3014 Files(CoverageFilesData),
3015 Gaps(CoverageGapsData),
3016}
3017
3018#[derive(Debug, Clone, PartialEq)]
3019pub struct CoverageFileQueryResult {
3020 pub data: CoverageFileQueryData,
3021 pub pagination: AgentPagination,
3022}
3023
3024#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3025#[serde(rename_all = "lowercase")]
3026pub enum DecisionSort {
3027 Location,
3028 Missing,
3029}
3030
3031#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
3032#[serde(rename_all = "camelCase")]
3033pub struct DecisionGapTotals {
3034 pub decisions: usize,
3035 pub decisions_with_missing_conditions: usize,
3036 pub conditions: usize,
3037 pub missing_conditions: usize,
3038}
3039
3040#[derive(Debug, Clone, PartialEq, Serialize)]
3041#[serde(rename_all = "camelCase")]
3042pub struct CoverageFileDecisionsData {
3043 pub run: String,
3044 pub filters: CoverageQueryFilters,
3045 pub file: String,
3046 pub group: String,
3047 pub sort: DecisionSort,
3048 pub totals: DecisionGapTotals,
3049 pub decisions: Vec<IndexedDecisionGap>,
3050}
3051
3052#[derive(Debug, Clone, Copy)]
3053pub struct CoverageFileDecisionsOptions<'a> {
3054 pub run: &'a str,
3055 pub view: CoverageViewId,
3056 pub kind: Option<&'a str>,
3057 pub runner: Option<&'a str>,
3058 pub file: &'a str,
3059 pub sort: DecisionSort,
3060 pub offset: usize,
3061 pub limit: usize,
3062}
3063
3064#[derive(Debug, Clone)]
3065pub struct CoverageDimensionQueryOptions<'a> {
3066 pub run: &'a str,
3067 pub view: CoverageViewId,
3068 pub dimension: CoverageDimension,
3069 pub filters: CoverageQueryFilters,
3070 pub offset: usize,
3071 pub limit: usize,
3072}
3073
3074pub fn coverage_dimension_query(
3075 index: &CoverageIndex<'_>,
3076 options: CoverageDimensionQueryOptions<'_>,
3077) -> Result<(CoverageDimensionQueryData, AgentPagination), QueryError> {
3078 let CoverageDimensionQueryOptions {
3079 run,
3080 view,
3081 dimension,
3082 filters,
3083 offset,
3084 limit,
3085 } = options;
3086 if limit == 0 {
3087 return Err(QueryError::InvalidPagination);
3088 }
3089 let values = index.dimensions(view, dimension)?;
3090 let total = values.len();
3091 let selected = values
3092 .into_iter()
3093 .skip(offset)
3094 .take(limit)
3095 .collect::<Vec<_>>();
3096 let returned = selected.len();
3097 let data = match dimension {
3098 CoverageDimension::Kind | CoverageDimension::Tests => {
3100 CoverageDimensionQueryData::Kinds(CoverageKindsData {
3101 run: run.into(),
3102 filters,
3103 kinds: selected,
3104 })
3105 }
3106 CoverageDimension::Runner => CoverageDimensionQueryData::Runners(CoverageRunnersData {
3107 run: run.into(),
3108 filters,
3109 runners: selected,
3110 }),
3111 };
3112 Ok((data, pagination(offset, limit, returned, total)))
3113}
3114
3115#[derive(Debug, Clone, Copy)]
3116pub struct CoverageFileQueryOptions<'a> {
3117 pub run: &'a str,
3118 pub view: CoverageViewId,
3119 pub metric: MinimizeMetric,
3120 pub gaps_only: bool,
3121 pub kind: Option<&'a str>,
3122 pub runner: Option<&'a str>,
3123 pub offset: usize,
3124 pub limit: usize,
3125}
3126
3127fn gap_metric_value(gap: &IndexedFileGap, metric: MinimizeMetric) -> usize {
3128 match metric {
3129 MinimizeMetric::All => gap.score,
3130 MinimizeMetric::Lines => gap.uncovered_lines,
3131 MinimizeMetric::Statements => gap.uncovered_statements,
3132 MinimizeMetric::Functions => gap.uncovered_functions,
3133 MinimizeMetric::Branches => gap.missing_branches,
3134 MinimizeMetric::Mcdc => gap.missing_mcdc_conditions,
3135 }
3136}
3137
3138fn has_gap_for_metric(gap: &IndexedFileGap, metric: MinimizeMetric) -> bool {
3139 match metric {
3140 MinimizeMetric::All => {
3141 gap.uncovered_lines > 0
3142 || gap.uncovered_statements > 0
3143 || gap.uncovered_functions > 0
3144 || gap.missing_branches > 0
3145 || gap.missing_mcdc_conditions > 0
3146 }
3147 _ => gap_metric_value(gap, metric) > 0,
3148 }
3149}
3150
3151pub fn coverage_file_decisions_query(
3152 index: &CoverageIndex<'_>,
3153 options: CoverageFileDecisionsOptions<'_>,
3154) -> Result<(CoverageFileDecisionsData, AgentPagination), QueryError> {
3155 if options.limit == 0 {
3156 return Err(QueryError::InvalidPagination);
3157 }
3158 let all = index.decision_gaps(options.view, options.kind, options.runner, options.file)?;
3159 if (options.kind.is_some() || options.runner.is_some()) && all.is_empty() {
3160 if index
3163 .file_gaps(options.view, options.kind, options.runner)?
3164 .is_empty()
3165 {
3166 return Err(QueryError::TestFilterEmpty {
3167 kind: options.kind.map(str::to_owned),
3168 runner: options.runner.map(str::to_owned),
3169 });
3170 }
3171 }
3172 let totals = DecisionGapTotals {
3173 decisions: all.len(),
3174 decisions_with_missing_conditions: all
3175 .iter()
3176 .filter(|decision| decision.missing_conditions > 0)
3177 .count(),
3178 conditions: all.iter().map(|decision| decision.conditions).sum(),
3179 missing_conditions: all.iter().map(|decision| decision.missing_conditions).sum(),
3180 };
3181 let mut missing = all
3182 .into_iter()
3183 .filter(|decision| decision.missing_conditions > 0)
3184 .collect::<Vec<_>>();
3185 missing.sort_by(|left, right| match options.sort {
3186 DecisionSort::Missing => right
3187 .missing_conditions
3188 .cmp(&left.missing_conditions)
3189 .then_with(|| left.line.cmp(&right.line))
3190 .then_with(|| left.column.cmp(&right.column)),
3191 DecisionSort::Location => left
3192 .line
3193 .cmp(&right.line)
3194 .then_with(|| left.column.cmp(&right.column))
3195 .then_with(|| left.id.cmp(&right.id)),
3196 });
3197 let total = missing.len();
3198 let rows = missing
3199 .into_iter()
3200 .skip(options.offset)
3201 .take(options.limit)
3202 .collect::<Vec<_>>();
3203 let returned = rows.len();
3204 let filters = CoverageQueryFilters {
3205 outcome: match options.view {
3206 CoverageViewId::All => "all",
3207 CoverageViewId::Passed => "passed",
3208 CoverageViewId::Failed => "failed",
3209 }
3210 .into(),
3211 kind: options.kind.map(str::to_owned),
3212 runner: options.runner.map(str::to_owned),
3213 };
3214 Ok((
3215 CoverageFileDecisionsData {
3216 run: options.run.into(),
3217 filters,
3218 file: options.file.into(),
3219 group: "decision".into(),
3220 sort: options.sort,
3221 totals,
3222 decisions: rows,
3223 },
3224 pagination(options.offset, options.limit, returned, total),
3225 ))
3226}
3227
3228pub fn coverage_file_query(
3229 index: &CoverageIndex<'_>,
3230 options: CoverageFileQueryOptions<'_>,
3231) -> Result<CoverageFileQueryResult, QueryError> {
3232 let CoverageFileQueryOptions {
3233 run,
3234 view,
3235 metric,
3236 gaps_only,
3237 kind,
3238 runner,
3239 offset,
3240 limit,
3241 } = options;
3242 if limit == 0 {
3243 return Err(QueryError::InvalidPagination);
3244 }
3245 let mut files = index.file_gaps(view, kind, runner)?;
3246 if (kind.is_some() || runner.is_some()) && files.is_empty() {
3247 return Err(QueryError::TestFilterEmpty {
3248 kind: kind.map(str::to_owned),
3249 runner: runner.map(str::to_owned),
3250 });
3251 }
3252 if gaps_only {
3253 files.retain(|gap| has_gap_for_metric(gap, metric) || gap.measurement_limitations > 0);
3254 }
3255 files.sort_by(|left, right| {
3256 gap_metric_value(right, metric)
3257 .cmp(&gap_metric_value(left, metric))
3258 .then_with(|| {
3259 right
3260 .measurement_limitations
3261 .cmp(&left.measurement_limitations)
3262 })
3263 .then_with(|| left.file.cmp(&right.file))
3264 });
3265 let total = files.len();
3266 let page = files
3267 .into_iter()
3268 .skip(offset)
3269 .take(limit)
3270 .collect::<Vec<_>>();
3271 let page_info = pagination(offset, limit, page.len(), total);
3272 let filters = CoverageQueryFilters {
3273 outcome: match view {
3274 CoverageViewId::All => "all",
3275 CoverageViewId::Passed => "passed",
3276 CoverageViewId::Failed => "failed",
3277 }
3278 .into(),
3279 kind: kind.map(str::to_owned),
3280 runner: runner.map(str::to_owned),
3281 };
3282 let data = if gaps_only {
3283 CoverageFileQueryData::Gaps(CoverageGapsData {
3284 run: run.into(),
3285 filters,
3286 metric,
3287 gaps: page,
3288 })
3289 } else {
3290 CoverageFileQueryData::Files(CoverageFilesData {
3291 run: run.into(),
3292 filters,
3293 metric,
3294 files: page,
3295 })
3296 };
3297 Ok(CoverageFileQueryResult {
3298 data,
3299 pagination: page_info,
3300 })
3301}
3302
3303#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3304enum ObligationMetric {
3305 Lines,
3306 Statements,
3307 Functions,
3308 Branches,
3309 Mcdc,
3310}
3311
3312impl ObligationMetric {
3313 fn selected(self, metric: MinimizeMetric) -> bool {
3314 metric == MinimizeMetric::All
3315 || matches!(
3316 (self, metric),
3317 (Self::Lines, MinimizeMetric::Lines)
3318 | (Self::Statements, MinimizeMetric::Statements)
3319 | (Self::Functions, MinimizeMetric::Functions)
3320 | (Self::Branches, MinimizeMetric::Branches)
3321 | (Self::Mcdc, MinimizeMetric::Mcdc)
3322 )
3323 }
3324
3325 fn public(self) -> MinimizeMetric {
3326 match self {
3327 Self::Lines => MinimizeMetric::Lines,
3328 Self::Statements => MinimizeMetric::Statements,
3329 Self::Functions => MinimizeMetric::Functions,
3330 Self::Branches => MinimizeMetric::Branches,
3331 Self::Mcdc => MinimizeMetric::Mcdc,
3332 }
3333 }
3334}
3335
3336#[derive(Clone)]
3337struct Obligation {
3338 id: String,
3339 metric: ObligationMetric,
3340 options: Vec<Vec<String>>,
3342}
3343
3344struct ObligationModel {
3345 obligations: Vec<Obligation>,
3346 setup_by_file: BTreeMap<String, Vec<String>>,
3347 tests_by_file: BTreeMap<String, Vec<String>>,
3348 background: Vec<String>,
3349}
3350
3351impl ObligationModel {
3352 fn expand(&self, selected: &BTreeSet<String>) -> BTreeSet<String> {
3353 let mut expanded = selected.clone();
3354 expanded.extend(self.background.iter().cloned());
3355 for (file, setup_ids) in &self.setup_by_file {
3356 if self
3357 .tests_by_file
3358 .get(file)
3359 .is_some_and(|tests| tests.iter().any(|id| selected.contains(id)))
3360 {
3361 expanded.extend(setup_ids.iter().cloned());
3362 }
3363 }
3364 expanded
3365 }
3366}
3367
3368fn deduplicate_options(options: impl IntoIterator<Item = Vec<String>>) -> Vec<Vec<String>> {
3369 let mut unique = BTreeMap::<String, Vec<String>>::new();
3370 for mut option in options {
3371 option.sort();
3372 option.dedup();
3373 let key = option.join("\0");
3374 unique.entry(key).or_insert(option);
3375 }
3376 unique.into_values().collect()
3377}
3378
3379fn evidence_choices(
3380 ids: &[Id],
3381 tests: &HashMap<&str, &crate::coverage_report::TestCoverageResult>,
3382 candidates: &BTreeSet<String>,
3383 tests_by_file: &BTreeMap<String, Vec<String>>,
3384) -> Vec<Vec<String>> {
3385 let mut choices = Vec::new();
3386 for id in ids {
3387 let Some(test) = tests.get(id.as_str()) else {
3388 continue;
3389 };
3390 if test.role == "background" {
3391 choices.push(Vec::new());
3392 } else if test.role == "setup" {
3393 if let Some(file) = &test.file {
3394 choices.extend(
3395 tests_by_file
3396 .get(file)
3397 .into_iter()
3398 .flatten()
3399 .map(|candidate| vec![candidate.clone()]),
3400 );
3401 }
3402 } else if candidates.contains(id.as_str()) {
3403 choices.push(vec![id.to_string()]);
3404 }
3405 }
3406 deduplicate_options(choices)
3407}
3408
3409fn build_obligations(view: &CoverageView, candidates: &BTreeSet<String>) -> ObligationModel {
3410 let tests = view
3411 .tests
3412 .iter()
3413 .map(|test| (test.id.as_str(), test))
3414 .collect::<HashMap<_, _>>();
3415 let mut tests_by_file = BTreeMap::<String, Vec<String>>::new();
3416 let mut setup_by_file = BTreeMap::<String, Vec<String>>::new();
3417 let mut background = Vec::new();
3418 for test in &view.tests {
3419 match test.role.as_str() {
3420 "test" if candidates.contains(&test.id) => {
3421 if let Some(file) = &test.file {
3422 tests_by_file
3423 .entry(file.clone())
3424 .or_default()
3425 .push(test.id.clone());
3426 }
3427 }
3428 "setup" => {
3429 if let Some(file) = &test.file {
3430 setup_by_file
3431 .entry(file.clone())
3432 .or_default()
3433 .push(test.id.clone());
3434 }
3435 }
3436 "background" => background.push(test.id.clone()),
3437 _ => {}
3438 }
3439 }
3440 let choices = |ids: &[Id]| evidence_choices(ids, &tests, candidates, &tests_by_file);
3441 let mut obligations = Vec::new();
3442 let mut unique_lines = BTreeMap::new();
3443 for line in &view.lines {
3444 unique_lines.insert((line.file.as_str(), line.line), line);
3445 }
3446 for ((file, line), result) in unique_lines {
3447 obligations.push(Obligation {
3448 id: format!("line:{file}:{line}"),
3449 metric: ObligationMetric::Lines,
3450 options: choices(&result.tests),
3451 });
3452 }
3453 for point in &view.points {
3454 let (kind, metric) = match point.meta.kind {
3455 crate::coverage_analysis::PointKind::Statement => {
3456 ("statement", ObligationMetric::Statements)
3457 }
3458 crate::coverage_analysis::PointKind::Function => {
3459 ("function", ObligationMetric::Functions)
3460 }
3461 };
3462 obligations.push(Obligation {
3463 id: format!("{kind}:{}", point.meta.id),
3464 metric,
3465 options: choices(&point.tests),
3466 });
3467 }
3468 for branch in &view.branches {
3469 for alternative in &branch.alternatives {
3470 obligations.push(Obligation {
3471 id: format!("branch:{}:{}", branch.meta.id, alternative.id),
3472 metric: ObligationMetric::Branches,
3473 options: choices(&alternative.tests),
3474 });
3475 }
3476 }
3477 for decision in &view.decisions {
3478 for condition in 0..decision.meta.conditions.len() {
3479 let mut options = Vec::new();
3480 for left in 0..decision.vector_observations.len() {
3481 for right in (left + 1)..decision.vector_observations.len() {
3482 let first = &decision.vector_observations[left];
3483 let second = &decision.vector_observations[right];
3484 if !is_independence_pair(&first.vector, &second.vector, condition) {
3485 continue;
3486 }
3487 for first_choice in choices(&first.tests) {
3488 for second_choice in choices(&second.tests) {
3489 let mut combined = first_choice.clone();
3490 combined.extend(second_choice);
3491 options.push(combined);
3492 }
3493 }
3494 }
3495 }
3496 obligations.push(Obligation {
3497 id: format!("mcdc:{}:{condition}", decision.meta.id),
3498 metric: ObligationMetric::Mcdc,
3499 options: deduplicate_options(options),
3500 });
3501 }
3502 }
3503 ObligationModel {
3504 obligations,
3505 setup_by_file,
3506 tests_by_file,
3507 background,
3508 }
3509}
3510
3511fn percentage(metric: ObligationMetric, summary: &CoverageSummary) -> f64 {
3512 match metric {
3513 ObligationMetric::Lines => summary.lines.percentage,
3514 ObligationMetric::Statements => summary.statements.percentage,
3515 ObligationMetric::Functions => summary.functions.percentage,
3516 ObligationMetric::Branches => summary.branches.percentage,
3517 ObligationMetric::Mcdc => summary.condition_coverage_pct,
3518 }
3519}
3520
3521fn obligation_satisfied(obligation: &Obligation, selected: &BTreeSet<String>) -> bool {
3522 obligation
3523 .options
3524 .iter()
3525 .any(|option| option.iter().all(|test| selected.contains(test)))
3526}
3527
3528struct Search<'a> {
3529 obligations: &'a [Obligation],
3530 skip_limits: BTreeMap<ObligationMetric, usize>,
3531 best: BTreeSet<String>,
3532 explored_states: usize,
3533 max_states: usize,
3534 seen: BTreeSet<String>,
3535 candidate_tests: usize,
3536 target: f64,
3537 metric: MinimizeMetric,
3538}
3539
3540impl Search<'_> {
3541 fn visit(
3542 &mut self,
3543 selected: BTreeSet<String>,
3544 skipped: BTreeSet<String>,
3545 skipped_by_metric: BTreeMap<ObligationMetric, usize>,
3546 ) -> Result<(), QueryError> {
3547 self.explored_states += 1;
3548 if self.explored_states > self.max_states {
3549 return Err(QueryError::ComplexityLimit {
3550 candidate_tests: self.candidate_tests,
3551 obligations: self.obligations.len(),
3552 explored_states: self.explored_states,
3553 max_states: self.max_states,
3554 target: self.target,
3555 metric: self.metric,
3556 });
3557 }
3558 if selected.len() >= self.best.len() {
3559 return Ok(());
3560 }
3561 let state_key = format!(
3562 "{}|{}",
3563 selected.iter().cloned().collect::<Vec<_>>().join(","),
3564 skipped.iter().cloned().collect::<Vec<_>>().join(",")
3565 );
3566 if !self.seen.insert(state_key) {
3567 return Ok(());
3568 }
3569 let mut unmet = self
3570 .obligations
3571 .iter()
3572 .filter(|obligation| {
3573 !skipped.contains(&obligation.id) && !obligation_satisfied(obligation, &selected)
3574 })
3575 .collect::<Vec<_>>();
3576 if unmet.is_empty() {
3577 self.best = selected;
3578 return Ok(());
3579 }
3580 unmet.sort_by(|left, right| {
3581 let feasible = |obligation: &Obligation| {
3582 obligation
3583 .options
3584 .iter()
3585 .filter(|option| option.iter().any(|test| !selected.contains(test)))
3586 .count()
3587 };
3588 feasible(left)
3589 .cmp(&feasible(right))
3590 .then_with(|| left.id.cmp(&right.id))
3591 });
3592 let obligation = unmet[0];
3593 let mut additions = deduplicate_options(obligation.options.iter().filter_map(|option| {
3594 let addition = option
3595 .iter()
3596 .filter(|test| !selected.contains(*test))
3597 .cloned()
3598 .collect::<Vec<_>>();
3599 (!addition.is_empty()).then_some(addition)
3600 }));
3601 additions.sort_by(|left, right| {
3602 left.len()
3603 .cmp(&right.len())
3604 .then_with(|| left.join("\0").cmp(&right.join("\0")))
3605 });
3606 for addition in additions {
3607 if selected.len() + addition.len() >= self.best.len() {
3608 continue;
3609 }
3610 let mut next = selected.clone();
3611 next.extend(addition);
3612 self.visit(next, skipped.clone(), skipped_by_metric.clone())?;
3613 }
3614 let skipped_count = skipped_by_metric
3615 .get(&obligation.metric)
3616 .copied()
3617 .unwrap_or(0);
3618 if skipped_count
3619 < self
3620 .skip_limits
3621 .get(&obligation.metric)
3622 .copied()
3623 .unwrap_or(0)
3624 {
3625 let mut next_skipped = skipped;
3626 next_skipped.insert(obligation.id.clone());
3627 let mut next_counts = skipped_by_metric;
3628 next_counts.insert(obligation.metric, skipped_count + 1);
3629 self.visit(selected, next_skipped, next_counts)?;
3630 }
3631 Ok(())
3632 }
3633}
3634
3635pub fn minimum_test_set(
3636 view: &CoverageView,
3637 target: f64,
3638 metric: MinimizeMetric,
3639 max_states: usize,
3640) -> Result<MinimumTestSetResult, QueryError> {
3641 use crate::coverage_report::coverage_is_complete;
3642 if !target.is_finite() || !(0.0..=100.0).contains(&target) {
3643 return Err(QueryError::InvalidTarget(target));
3644 }
3645 if view.tests.iter().any(|test| {
3646 test.role == "background" && (!test.hits.is_empty() || !test.decisions.is_empty())
3647 }) {
3648 return Err(QueryError::UnattributedEvidence);
3649 }
3650 if view
3657 .tests
3658 .iter()
3659 .any(|test| test.role == "test" && !coverage_is_complete(&test.attribution))
3660 {
3661 return Err(QueryError::UnattributedEvidence);
3662 }
3663 let candidate_tests = view
3664 .tests
3665 .iter()
3666 .filter(|test| test.role == "test")
3667 .map(|test| test.id.clone())
3668 .collect::<BTreeSet<_>>();
3669 let model = build_obligations(view, &candidate_tests);
3670 let obligations = model
3671 .obligations
3672 .iter()
3673 .filter(|obligation| obligation.metric.selected(metric))
3674 .cloned()
3675 .collect::<Vec<_>>();
3676 let mut totals = BTreeMap::<ObligationMetric, usize>::new();
3677 for obligation in &obligations {
3678 *totals.entry(obligation.metric).or_default() += 1;
3679 }
3680 let metrics = [
3681 ObligationMetric::Lines,
3682 ObligationMetric::Statements,
3683 ObligationMetric::Functions,
3684 ObligationMetric::Branches,
3685 ObligationMetric::Mcdc,
3686 ]
3687 .into_iter()
3688 .filter(|candidate| candidate.selected(metric))
3689 .collect::<Vec<_>>();
3690 let skip_limits = metrics
3691 .iter()
3692 .map(|selected_metric| {
3693 let total = totals.get(selected_metric).copied().unwrap_or(0);
3694 let required = ((total as f64 * target) / 100.0).ceil() as usize;
3695 (*selected_metric, total.saturating_sub(required))
3696 })
3697 .collect::<BTreeMap<_, _>>();
3698 let full_expanded = model.expand(&candidate_tests);
3699 let full_summary = coverage_summary_for_tests(view, &full_expanded)?;
3700 for selected_metric in &metrics {
3701 let reachable = percentage(*selected_metric, &full_summary);
3702 if reachable + 1e-9 < target {
3703 return Err(QueryError::TargetUnreachable {
3704 metric: selected_metric.public(),
3705 target,
3706 reachable,
3707 });
3708 }
3709 }
3710 let mut search = Search {
3711 obligations: &obligations,
3712 skip_limits,
3713 best: candidate_tests.clone(),
3714 explored_states: 0,
3715 max_states,
3716 seen: BTreeSet::new(),
3717 candidate_tests: candidate_tests.len(),
3718 target,
3719 metric,
3720 };
3721 search.visit(BTreeSet::new(), BTreeSet::new(), BTreeMap::new())?;
3722 let expanded = model.expand(&search.best);
3723 let summary = coverage_summary_for_tests(view, &expanded)?;
3724 Ok(MinimumTestSetResult {
3725 optimal: true,
3726 target,
3727 metric,
3728 selected: search.best.into_iter().collect(),
3729 expanded: expanded.into_iter().collect(),
3730 summary,
3731 explored_states: search.explored_states,
3732 })
3733}
3734
3735#[cfg(test)]
3736mod tests {
3737 use crate::{
3738 coverage_analysis::McdcVector,
3739 coverage_report::{
3740 CoverageManifest, CoverageReport, CoverageReportRequest, DecisionMeta, ExitCodeInput,
3741 RawTestResult, RuntimeSnapshot, TestProvenance, analyze_coverage_results,
3742 },
3743 };
3744
3745 use super::*;
3746
3747 fn scope_entry(
3748 file: &str,
3749 status: &str,
3750 reason: &str,
3751 package: Option<&str>,
3752 ) -> IndexedScopeEntry {
3753 IndexedScopeEntry {
3754 file: file.into(),
3755 status: status.into(),
3756 reason: reason.into(),
3757 package_root: package.map(str::to_owned),
3758 measurement_limitations: 0,
3759 limitation_kinds: Vec::new(),
3760 }
3761 }
3762
3763 #[test]
3764 fn a_scope_is_grouped_by_place_and_names_the_roots_that_settle_it() {
3765 let unclassified = "unclassified first-party source";
3766 let entries = [
3767 scope_entry("components/a.tsx", "ambiguous", unclassified, None),
3768 scope_entry("components/ui/b.tsx", "ambiguous", unclassified, None),
3769 scope_entry("proxy.ts", "ambiguous", unclassified, None),
3770 scope_entry(
3771 "app/page.tsx",
3772 "included",
3773 "discovered package source root",
3774 None,
3775 ),
3776 scope_entry(
3777 "tests/a.test.ts",
3778 "excluded",
3779 "test or fixture source",
3780 None,
3781 ),
3782 scope_entry(
3783 "next.config.ts",
3784 "excluded",
3785 "build/test/tool configuration",
3786 None,
3787 ),
3788 scope_entry(
3789 "packages/ui/extra/c.ts",
3790 "ambiguous",
3791 unclassified,
3792 Some("packages/ui"),
3793 ),
3794 scope_entry(
3795 "packages/ui/src/d.ts",
3796 "included",
3797 "discovered package source root",
3798 Some("packages/ui"),
3799 ),
3800 ];
3801 let groups = scope_groups(&entries)
3802 .into_iter()
3803 .map(|group| (group.files, group.status, group.directory))
3804 .collect::<Vec<_>>();
3805 assert_eq!(
3806 groups,
3807 [
3808 (2, "ambiguous".to_owned(), "components".to_owned()),
3809 (1, "ambiguous".into(), ".".into()),
3810 (1, "ambiguous".into(), "packages/ui/extra".into()),
3811 (1, "included".into(), "app".into()),
3812 (1, "included".into(), "packages/ui/src".into()),
3813 (1, "excluded".into(), ".".into()),
3814 (1, "excluded".into(), "tests".into()),
3815 ]
3816 );
3817 let hint =
3820 unclassified_source(&["app".into(), "packages/ui/src".into()], &entries).unwrap();
3821 assert_eq!(
3822 hint.roots,
3823 [
3824 "app",
3825 "packages/ui/src",
3826 "components",
3827 "packages/ui/extra",
3828 "proxy.ts"
3829 ]
3830 );
3831 assert_eq!(hint.directories[0].directory, "components");
3832 assert_eq!(hint.directories[0].files, 2);
3833 assert_eq!(unclassified_source(&[], &entries[3..6]), None);
3834 }
3835
3836 #[test]
3837 fn a_file_is_counted_under_its_first_folders() {
3838 assert_eq!(area_directory("app/api/cron/route.ts", 1), "app");
3839 assert_eq!(area_directory("app/api/cron/route.ts", 2), "app/api");
3840 assert_eq!(area_directory("app/page.tsx", 2), "app");
3841 assert_eq!(area_directory("proxy.ts", 2), ".");
3842 }
3843
3844 #[test]
3845 fn all_metric_keeps_statement_only_files_in_the_gap_set() {
3846 let gap = IndexedFileGap {
3847 view: CoverageViewId::All,
3848 file: "src/statement.js".into(),
3849 uncovered_lines: 0,
3850 uncovered_statements: 1,
3851 uncovered_functions: 0,
3852 missing_branches: 0,
3853 missing_mcdc_conditions: 0,
3854 measurement_limitations: 0,
3855 limitation_kinds: Vec::new(),
3856 covered_by_other_tests: crate::coverage_index::IndexedGapDimensions {
3857 lines: 0,
3858 statements: 0,
3859 functions: 0,
3860 branches: 0,
3861 mcdc_conditions: 0,
3862 },
3863 uncovered_everywhere: crate::coverage_index::IndexedGapDimensions {
3864 lines: 0,
3865 statements: 1,
3866 functions: 0,
3867 branches: 0,
3868 mcdc_conditions: 0,
3869 },
3870 totals: crate::coverage_index::IndexedGapDimensions {
3871 lines: 1,
3872 statements: 2,
3873 functions: 0,
3874 branches: 0,
3875 mcdc_conditions: 0,
3876 },
3877 covered: crate::coverage_index::IndexedGapDimensions {
3878 lines: 1,
3879 statements: 1,
3880 functions: 0,
3881 branches: 0,
3882 mcdc_conditions: 0,
3883 },
3884 score: 0,
3885 };
3886 assert!(has_gap_for_metric(&gap, MinimizeMetric::All));
3887 assert!(has_gap_for_metric(&gap, MinimizeMetric::Statements));
3888 assert!(!has_gap_for_metric(&gap, MinimizeMetric::Lines));
3889 }
3890
3891 fn result(id: &str, vector: McdcVector) -> RawTestResult {
3892 RawTestResult {
3893 test_id: Some(id.into()),
3894 scope: None,
3895 test: id.into(),
3896 test_file: Some("tests/permission.test.js".into()),
3897 title: None,
3898 retry: Some(0),
3899 status: Some("passed".into()),
3900 expected_status: None,
3901 flaky: false,
3902 provenance: TestProvenance {
3903 runner: "node:test".into(),
3904 kind: "unit".into(),
3905 project: None,
3906 source: "runner-default".into(),
3907 },
3908 role: "test".into(),
3909 attribution: crate::coverage_report::ATTRIBUTION_EXACT.into(),
3910 phases: Vec::new(),
3911 runtime: vec![RuntimeSnapshot {
3912 decisions: vec![crate::coverage_report::DecisionSnapshot {
3913 meta: decision(),
3914 vectors: vec![vector],
3915 }],
3916 hits: Vec::new(),
3917 events: Vec::new(),
3918 logicals: Vec::new(),
3919 phase_id: None,
3920 }],
3921 browser: Vec::new(),
3922 server: Vec::new(),
3923 }
3924 }
3925
3926 fn decision() -> DecisionMeta {
3927 DecisionMeta {
3928 id: "decision".into(),
3929 file: "src/permission.js".into(),
3930 line: 1,
3931 column: 1,
3932 source: "admin || owner".into(),
3933 conditions: vec!["admin".into(), "owner".into()],
3934 kind: "if".into(),
3935 }
3936 }
3937
3938 fn report(mut results: Vec<RawTestResult>) -> CoverageReport {
3939 analyze_coverage_results(&CoverageReportRequest {
3940 run_id: "run".into(),
3941 manifest: CoverageManifest {
3942 unmeasured: Vec::new(),
3943 decisions: vec![decision()],
3944 points: Vec::new(),
3945 branches: Vec::new(),
3946 limitations: Vec::new(),
3947 scope: None,
3948 assertion_sites: Vec::new(),
3949 },
3950 raw_results: std::mem::take(&mut results),
3951 generated_at: "time".into(),
3952 coverage_model: None,
3953 integrity: None,
3954 test_exit_code: ExitCodeInput::Present(Some(0)),
3955 })
3956 .unwrap()
3957 }
3958
3959 #[test]
3960 fn recomputes_mcdc_witnesses_and_removes_a_redundant_vector() {
3961 let report = report(vec![
3962 result(
3963 "admin",
3964 McdcVector {
3965 values: vec![Some(true), None],
3966 outcome: true,
3967 },
3968 ),
3969 result(
3970 "owner",
3971 McdcVector {
3972 values: vec![Some(false), Some(true)],
3973 outcome: true,
3974 },
3975 ),
3976 result(
3977 "both",
3978 McdcVector {
3979 values: vec![Some(true), None],
3980 outcome: true,
3981 },
3982 ),
3983 result(
3984 "neither",
3985 McdcVector {
3986 values: vec![Some(false), Some(false)],
3987 outcome: false,
3988 },
3989 ),
3990 ]);
3991 let minimized = minimum_test_set(&report.view, 100.0, MinimizeMetric::Mcdc, 5_000).unwrap();
3992 assert_eq!(minimized.selected.len(), 3);
3993 assert!(minimized.selected.contains(&"owner".into()));
3994 assert!(minimized.selected.contains(&"neither".into()));
3995 assert_eq!(minimized.summary.condition_coverage_pct, 100.0);
3996 }
3997
3998 #[test]
3999 fn a_test_that_belongs_to_no_test_is_not_minimized_away() {
4000 let mut parallel = result(
4007 "parallel",
4008 McdcVector {
4009 values: vec![Some(false), Some(false)],
4010 outcome: false,
4011 },
4012 );
4013 parallel.attribution = crate::coverage_report::ATTRIBUTION_RUN_WIDE.into();
4014 assert!(matches!(
4015 minimum_test_set(
4016 &report(vec![parallel]).view,
4017 100.0,
4018 MinimizeMetric::Mcdc,
4019 5_000,
4020 ),
4021 Err(QueryError::UnattributedEvidence)
4022 ));
4023 }
4024
4025 #[test]
4026 fn the_summary_counts_each_test_under_the_attribution_it_carries() {
4027 let vector = || McdcVector {
4031 values: vec![Some(false), Some(false)],
4032 outcome: false,
4033 };
4034 let mut serial = result("serial", vector());
4035 serial.attribution = crate::coverage_report::ATTRIBUTION_EXACT.into();
4036 let mut parallel = result("parallel", vector());
4037 parallel.attribution = crate::coverage_report::ATTRIBUTION_RUN_WIDE.into();
4038 let mut ruby = result("ruby", vector());
4039 ruby.attribution = crate::coverage_report::ATTRIBUTION_PARTIAL.into();
4040 let mut also_parallel = result("also-parallel", vector());
4041 also_parallel.attribution = crate::coverage_report::ATTRIBUTION_RUN_WIDE.into();
4042 let report = report(vec![serial, parallel, ruby, also_parallel]);
4043
4044 let nonce = std::time::SystemTime::now()
4045 .duration_since(std::time::UNIX_EPOCH)
4046 .unwrap()
4047 .as_nanos();
4048 let root = std::env::temp_dir().join(format!(
4049 "supercov-attribution-counts-{}-{nonce}",
4050 std::process::id()
4051 ));
4052 std::fs::create_dir(&root).unwrap();
4053 let path = root.join("query-index.v1.bin");
4054 let identity = crate::query_index::QueryIndexIdentity {
4055 evidence_sha256: [1; 32],
4056 evidence_bytes: 100,
4057 analysis_sha256: [2; 32],
4058 producer_sha256: [3; 32],
4059 archive_schema_version: 2,
4060 };
4061 crate::query_index::write_query_index(
4062 &crate::coverage_index::coverage_index_sections(&report).unwrap(),
4063 &identity,
4064 &path,
4065 )
4066 .unwrap();
4067 let container = crate::query_index::QueryIndex::open(&path, &identity).unwrap();
4068 let index = crate::coverage_index::CoverageIndex::new(&container).unwrap();
4069
4070 let summary = coverage_summary_query(
4071 &index,
4072 CoverageSummaryQueryOptions {
4073 run: "run",
4074 view: CoverageViewId::All,
4075 kind: None,
4076 runner: None,
4077 valid: true,
4078 test_exit_code: Some(0),
4079 stale: false,
4080 stale_reasons: Vec::new(),
4081 },
4082 )
4083 .unwrap();
4084 assert_eq!(summary.test_attribution.exact, 1);
4085 assert_eq!(summary.test_attribution.run_wide, 2);
4086 assert_eq!(summary.test_attribution.partial, 1);
4087 assert_eq!(summary.test_attribution.total(), 4);
4088 std::fs::remove_dir_all(&root).ok();
4089 }
4090
4091 #[test]
4092 fn refuses_background_evidence() {
4093 let mut aggregate = result(
4094 "aggregate",
4095 McdcVector {
4096 values: vec![Some(false), Some(false)],
4097 outcome: false,
4098 },
4099 );
4100 aggregate.role = "background".into();
4101 assert!(matches!(
4102 minimum_test_set(
4103 &report(vec![aggregate]).view,
4104 100.0,
4105 MinimizeMetric::Mcdc,
4106 5_000,
4107 ),
4108 Err(QueryError::UnattributedEvidence)
4109 ));
4110 }
4111
4112 #[test]
4113 fn bounds_the_exact_search() {
4114 let report = report(vec![
4115 result(
4116 "admin",
4117 McdcVector {
4118 values: vec![Some(true), None],
4119 outcome: true,
4120 },
4121 ),
4122 result(
4123 "owner",
4124 McdcVector {
4125 values: vec![Some(false), Some(true)],
4126 outcome: true,
4127 },
4128 ),
4129 result(
4130 "neither",
4131 McdcVector {
4132 values: vec![Some(false), Some(false)],
4133 outcome: false,
4134 },
4135 ),
4136 ]);
4137 assert!(matches!(
4138 minimum_test_set(&report.view, 100.0, MinimizeMetric::Mcdc, 1),
4139 Err(QueryError::ComplexityLimit { .. })
4140 ));
4141 }
4142}