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