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