Skip to main content

supercov_engine/
source_manifest.rs

1//! What a run's sources were: each captured file's bytes and declarations,
2//! the per-test execution record written when the run is published, and the
3//! change model that says which tests a later edit could have reached.
4//! `tests affected`, `runs source` and assertions coverage all read these.
5
6use crate::{
7    coverage_report::{
8        ArchiveReportRequest, CoverageReport, ExitCodeInput, analyze_coverage_archive,
9    },
10    evidence_archive::read_archive_selected,
11    lifecycle::atomic_write,
12    run_store::{RunMetadata, StoredRun},
13    source_units::{Code, Diff, named},
14};
15use serde::{Deserialize, Serialize};
16use serde_json::{Value, json};
17use sha2::{Digest, Sha256};
18use std::{
19    collections::{BTreeMap, BTreeSet},
20    fs,
21    path::Path,
22};
23pub type Files = BTreeMap<String, String>;
24pub fn digest(value: &impl Serialize) -> String {
25    format!(
26        "{:x}",
27        Sha256::digest(serde_json::to_vec(value).expect("serializable map"))
28    )
29}
30
31/// One-based lines and UTF-8 byte columns, for every language. Text is exact.
32pub fn local_path(file: &str) -> bool {
33    !file.is_empty()
34        && !file.contains(['\\', ':'])
35        && file.split('/').all(|p| !matches!(p, "" | "." | ".."))
36}
37pub fn line_starts(source: &str) -> Vec<usize> {
38    std::iter::once(0)
39        .chain(source.match_indices('\n').map(|(at, _)| at + 1))
40        .collect()
41}
42
43/// The text of 1-based `line`, exactly as `str::lines` would yield it: without
44/// its line ending, with a carriage return stripped only where a line feed
45/// follows it, and with no empty line after a final line feed.
46pub fn line_text<'s>(source: &'s str, starts: &[usize], line: usize) -> Option<&'s str> {
47    let start = *starts.get(line.checked_sub(1)?)?;
48    if start >= source.len() {
49        return None;
50    }
51    match starts.get(line) {
52        Some(next) => {
53            let text = &source[start..next - 1];
54            Some(text.strip_suffix('\r').unwrap_or(text))
55        }
56        None => Some(&source[start..]),
57    }
58}
59
60/// Source text held in memory for capture or a verified current-checkout query.
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
62#[serde(rename_all = "camelCase", deny_unknown_fields)]
63pub struct Inputs {
64    pub language: String,
65    pub files: Files,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(rename_all = "camelCase", deny_unknown_fields)]
70pub struct FileFingerprint {
71    pub sha256: String,
72    pub bytes: usize,
73    /// The parser's view of the file: what it declares, each declaration
74    /// digested with comments blanked. Absent for a file no parser reads and
75    /// in manifests written before this existed; such a file is compared by
76    /// its bytes, as every file once was.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub code: Option<Code>,
79}
80impl FileFingerprint {
81    pub fn of(source: &str) -> Self {
82        Self {
83            sha256: format!("{:x}", Sha256::digest(source.as_bytes())),
84            bytes: source.len(),
85            code: None,
86        }
87    }
88    /// Bytes and, where Supercov has a parser for the file, its declarations.
89    pub fn read(path: &str, source: &str) -> Self {
90        let mut fingerprint = Self::of(source);
91        fingerprint.code = crate::source_units::code(path, source);
92        fingerprint
93    }
94    pub fn same_bytes(&self, other: &Self) -> bool {
95        self.sha256 == other.sha256
96    }
97}
98pub type FileManifest = BTreeMap<String, FileFingerprint>;
99
100/// The run stores identities and hashes, never complete source files.
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
102#[serde(rename_all = "camelCase", deny_unknown_fields)]
103pub struct InputManifest {
104    pub schema_version: u32,
105    pub language: String,
106    pub files: FileManifest,
107}
108/// The manifest's schema: files, their bytes and their declarations.
109pub const MANIFEST_SCHEMA: u32 = 3;
110impl Inputs {
111    pub fn manifest(&self) -> InputManifest {
112        InputManifest {
113            schema_version: MANIFEST_SCHEMA,
114            language: self.language.clone(),
115            files: self
116                .files
117                .iter()
118                .map(|(p, s)| (p.clone(), FileFingerprint::read(p, s)))
119                .collect(),
120        }
121    }
122}
123impl InputManifest {
124    pub fn with_sources(&self, files: Files) -> Inputs {
125        Inputs {
126            language: self.language.clone(),
127            files,
128        }
129    }
130}
131
132#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
133#[serde(rename_all = "camelCase", deny_unknown_fields)]
134pub struct TestSelector {
135    pub file: String,
136    pub name: String,
137}
138
139/// What each test of a run executed, in the units of that run's manifest.
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141#[serde(rename_all = "camelCase", deny_unknown_fields)]
142pub struct Executions {
143    pub tests: Vec<Execution>,
144    /// Per file, the units that hold a probe of their own. A change confined
145    /// to these can reach a test only by being run.
146    pub probed: BTreeMap<String, Vec<usize>>,
147    /// Per file, the units the run actually reached -- every record's, the one
148    /// holding execution no test could be credited with included.
149    ///
150    /// This is the bound on a test whose own reach nothing recorded. It cannot
151    /// have run more than the run did, so a change outside this reached no
152    /// test at all and a change inside it might have reached any of them.
153    /// Without it the only sound answer for such a test would be "affected by
154    /// everything", which is true and useless.
155    #[serde(default)]
156    pub covered: BTreeMap<String, Vec<usize>>,
157}
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159#[serde(rename_all = "camelCase", deny_unknown_fields)]
160pub struct Execution {
161    pub test: TestSelector,
162    pub passed: bool,
163    /// Per file, the innermost unit of every probe this test fired.
164    pub files: BTreeMap<String, Vec<usize>>,
165    /// How completely `files` describes what this test ran: `exact`, `partial`
166    /// where it is a lower bound, or `run-wide` where nothing was recorded.
167    ///
168    /// Only under `exact` does an absence here mean the test did not run the
169    /// code. A Go test that called `t.Parallel()` records nothing of its own,
170    /// and a Ruby test records only the lines no earlier test had reached --
171    /// so reading either silence as proof is how a change to code a test
172    /// exercised comes back as "this test is unaffected".
173    #[serde(default = "exact_by_default")]
174    pub attribution: String,
175}
176
177/// Every execution recorded before attribution was a question was an exact
178/// one, so a record that does not say is one.
179fn exact_by_default() -> String {
180    crate::coverage_report::ATTRIBUTION_EXACT.to_owned()
181}
182/// How one captured file moved between two runs, judged once and read for
183/// every flow.
184pub enum FileChange<'a> {
185    Same,
186    /// Only comments changed: no program can tell.
187    CommentsOnly,
188    /// Not among the previous run's inputs.
189    Added,
190    Removed,
191    /// No parser reads the file on one side or the other; its bytes moved.
192    Bytes,
193    Code {
194        before: &'a Code,
195        after: &'a Code,
196        diff: Diff,
197        /// The change is confined to declaration bodies that only run: it
198        /// reaches a test only if the test ran one of them.
199        narrow: bool,
200    },
201}
202pub fn file_change<'a>(
203    before: Option<&'a FileFingerprint>,
204    after: Option<&'a FileFingerprint>,
205    probed: Option<&[usize]>,
206) -> Option<FileChange<'a>> {
207    let Some(before) = before else {
208        return after.map(|_| FileChange::Added);
209    };
210    let Some(after) = after else {
211        return Some(FileChange::Removed);
212    };
213    if before.same_bytes(after) {
214        return Some(FileChange::Same);
215    }
216    let (Some(old), Some(new)) = (&before.code, &after.code) else {
217        return Some(FileChange::Bytes);
218    };
219    if old.semantic == new.semantic {
220        return Some(FileChange::CommentsOnly);
221    }
222    let diff = old.diff(new);
223    let narrow = probed.is_some_and(|probed| diff.narrow(old, probed));
224    Some(FileChange::Code {
225        before: old,
226        after: new,
227        diff,
228        narrow,
229    })
230}
231/// Every unit that moved, by name: what changed, what arrived, what went.
232pub fn describe(before: &Code, after: &Code, diff: &Diff) -> String {
233    let mut parts = Vec::new();
234    if !diff.changed.is_empty() {
235        parts.push(named(diff.changed.iter().map(|i| &before.units[*i])));
236    }
237    if !diff.added.is_empty() {
238        parts.push(format!(
239            "added {}",
240            named(diff.added.iter().map(|i| &after.units[*i]))
241        ));
242    }
243    if !diff.removed.is_empty() {
244        parts.push(format!(
245            "removed {}",
246            named(diff.removed.iter().map(|i| &before.units[*i]))
247        ));
248    }
249    if parts.is_empty() {
250        "declarations".to_owned()
251    } else {
252        parts.join("; ")
253    }
254}
255
256/// The run's manifest, written beside the archive at publication so a query
257/// need not decompress the archive for one entry. Used only while the
258/// archive's digest is the one it records.
259const MANIFEST_CACHE_FILE: &str = "source-manifest.cache.json";
260/// What each test executed, written at publication; `tests affected` reads it.
261pub const EXECUTIONS_FILE: &str = "test-executions.json";
262/// The archive entry holding the run's source manifest.
263pub use crate::source_capture::ARCHIVE_PATH;
264
265#[derive(serde::Serialize, serde::Deserialize)]
266#[serde(rename_all = "camelCase", deny_unknown_fields)]
267struct ManifestCache {
268    evidence_digest: String,
269    manifest: InputManifest,
270    #[serde(default)]
271    statement_exclusions: Vec<Value>,
272}
273pub struct RunManifest {
274    pub manifest: InputManifest,
275    pub evidence_digest: String,
276    pub statement_exclusions: Vec<Value>,
277}
278pub struct RunInputs {
279    pub inputs: Inputs,
280    pub stored: RunManifest,
281}
282impl std::ops::Deref for RunInputs {
283    type Target = RunManifest;
284    fn deref(&self) -> &RunManifest {
285        &self.stored
286    }
287}
288/// The run's manifest with the current checkout's sources, which must be the
289/// run's own byte for byte.
290pub fn load_inputs(root: &Path, run: &StoredRun) -> Result<RunInputs, String> {
291    let stored = load_manifest(run)?;
292    let inputs = crate::source_capture::current_sources(root, &stored.manifest)?;
293    Ok(RunInputs { inputs, stored })
294}
295pub fn load_manifest(run: &StoredRun) -> Result<RunManifest, String> {
296    load_optional_manifest(run)?.ok_or_else(|| {
297        "This run has no source manifest. Run tests once with this version of Supercov".into()
298    })
299}
300/// An archive entry's name as its run wrote it. A merged run keeps each
301/// parent's entries under `shards/<n>/`, and a parent that was itself merged
302/// brings its own level along.
303fn unsharded(path: &str) -> &str {
304    let mut rest = path;
305    while let Some((shard, inner)) = rest
306        .strip_prefix("shards/")
307        .and_then(|after| after.split_once('/'))
308    {
309        if shard.is_empty() || !shard.bytes().all(|byte| byte.is_ascii_digit()) {
310            break;
311        }
312        rest = inner;
313    }
314    rest
315}
316/// The one value every entry of this name holds. The runs a merge accepts
317/// measured the same source, tests, dependencies and configuration, so each
318/// recorded the same manifest and the merged run has one; a merged run whose
319/// parents did not is not one run's code and is refused.
320fn the_one(
321    entries: &[crate::evidence_archive::EvidenceArchiveEntry],
322    named: impl Fn(&str) -> bool,
323) -> Result<Option<Value>, String> {
324    let mut found: Option<(&[u8], Value)> = None;
325    for entry in entries.iter().filter(|entry| named(&entry.path)) {
326        match &found {
327            Some((bytes, _)) if *bytes == entry.contents.as_slice() => {}
328            Some((_, value)) => {
329                let other: Value =
330                    serde_json::from_slice(&entry.contents).map_err(|e| e.to_string())?;
331                if other != *value {
332                    return Err("The runs merged into this one recorded different source manifests; use one of them instead".into());
333                }
334            }
335            None => {
336                found = Some((
337                    &entry.contents,
338                    serde_json::from_slice(&entry.contents).map_err(|e| e.to_string())?,
339                ));
340            }
341        }
342    }
343    Ok(found.map(|(_, value)| value))
344}
345fn load_optional_manifest(run: &StoredRun) -> Result<Option<RunManifest>, String> {
346    let merged = run.metadata.merged == Some(true);
347    let bytes = fs::read(&run.evidence_path).map_err(|e| e.to_string())?;
348    let evidence_digest = format!("{:x}", Sha256::digest(&bytes));
349    if let Some(cached) = fs::read(run.directory.join(MANIFEST_CACHE_FILE))
350        .ok()
351        .and_then(|bytes| serde_json::from_slice::<ManifestCache>(&bytes).ok())
352        .filter(|cached| cached.evidence_digest == evidence_digest)
353        .filter(|cached| validate_manifest(&cached.manifest).is_ok())
354    {
355        return Ok(Some(RunManifest {
356            manifest: cached.manifest,
357            evidence_digest,
358            statement_exclusions: cached.statement_exclusions,
359        }));
360    }
361    let named = |path: &str, name: &str| {
362        if merged {
363            unsharded(path) == name
364        } else {
365            path == name
366        }
367    };
368    let entries = read_archive_selected(&run.evidence_path, |path| {
369        named(path, ARCHIVE_PATH) || named(path, "statement-exclusions.json")
370    })
371    .map_err(|e| e.to_string())?;
372    let Some(value) = the_one(&entries, |path| named(path, ARCHIVE_PATH))? else {
373        return Ok(None);
374    };
375    if value["schemaVersion"].as_u64() != Some(u64::from(MANIFEST_SCHEMA)) {
376        return Err(
377            "Unsupported source manifest schema; rerun tests with this version of Supercov".into(),
378        );
379    }
380    let manifest = serde_json::from_value::<InputManifest>(value).map_err(|e| e.to_string())?;
381    validate_manifest(&manifest)?;
382    if fs::read(&run.evidence_path).map_err(|e| e.to_string())? != bytes {
383        return Err("Run archive changed during read".into());
384    }
385    Ok(Some(RunManifest {
386        manifest,
387        evidence_digest,
388        statement_exclusions: the_one(&entries, |path| named(path, "statement-exclusions.json"))?
389            .map(|value| serde_json::from_value(value).map_err(|e| e.to_string()))
390            .transpose()?
391            .unwrap_or_default(),
392    }))
393}
394fn validate_manifest(manifest: &InputManifest) -> Result<(), String> {
395    if manifest.files.iter().any(|(p, f)| {
396        !local_path(p) || f.sha256.len() != 64 || !f.sha256.bytes().all(|b| b.is_ascii_hexdigit())
397    }) {
398        return Err("Invalid source manifest".into());
399    }
400    Ok(())
401}
402
403/// The manifest a run archived, from the inputs the frontend archived it
404/// from and the digest publication took of the archive: what reading the
405/// archive back would give, without decompressing it to find one entry.
406pub(crate) fn archived_manifest(
407    manifest: InputManifest,
408    evidence_digest: String,
409) -> Result<RunManifest, String> {
410    validate_manifest(&manifest)?;
411    Ok(RunManifest {
412        manifest,
413        evidence_digest,
414        statement_exclusions: Vec::new(),
415    })
416}
417fn write_json(
418    root: &Path,
419    run: &StoredRun,
420    name: &str,
421    value: &impl serde::Serialize,
422) -> Result<(), String> {
423    let mut bytes = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?;
424    bytes.push(b'\n');
425    atomic_write(root, &run.directory.join(name), &bytes).map_err(|e| e.to_string())
426}
427/// Write the run's manifest cache and execution record into the unpublished
428/// run directory; the lifecycle publishes them with the run in one rename.
429///
430/// `analysed` is the run's coverage when the caller has already analysed its
431/// evidence. Merged runs and archives without a manifest have neither: a
432/// merged run is analysed by the first query that needs it, not by `merge`.
433pub(crate) fn prepare_publication_with(
434    root: &Path,
435    directory: &Path,
436    metadata: &RunMetadata,
437    analysed: Option<&CoverageReport>,
438    archived: Option<RunManifest>,
439) -> Result<(), String> {
440    if metadata.merged == Some(true) {
441        return Ok(());
442    }
443    let run = StoredRun {
444        id: metadata.id.clone(),
445        directory: directory.into(),
446        evidence_path: directory.join("evidence.raw.gz"),
447        metadata_path: directory.join("run.json"),
448        query_index_path: directory.join(crate::run_store::RUST_QUERY_INDEX_FILE),
449        metadata: metadata.clone(),
450    };
451    let input = match archived {
452        Some(input) => input,
453        None => match load_optional_manifest(&run)? {
454            Some(input) => input,
455            None => return Ok(()),
456        },
457    };
458    let current = crate::source_capture::current_sources(root, &input.manifest);
459    let owned;
460    let analysed = match analysed {
461        Some(report) => Some(report),
462        None => {
463            owned = coverage(&run).ok();
464            owned.as_ref()
465        }
466    };
467    // What each test ran, so a later edit can be told apart from code the test
468    // never reached. Evidence that will not analyse leaves the record out.
469    if let Some(executions) = analysed.and_then(|report| {
470        executions(
471            report,
472            &input.manifest,
473            current.as_ref().ok().map(|inputs| &inputs.files),
474        )
475    }) {
476        write_json(root, &run, EXECUTIONS_FILE, &executions)?;
477    }
478    // A cache: a run that cannot write it is read from its archive instead.
479    let _ = write_json(
480        root,
481        &run,
482        MANIFEST_CACHE_FILE,
483        &ManifestCache {
484            evidence_digest: input.evidence_digest.clone(),
485            manifest: input.manifest.clone(),
486            statement_exclusions: input.statement_exclusions.clone(),
487        },
488    );
489    Ok(())
490}
491/// Each test's execution, placed in the declarations of the run's own
492/// manifest: for every probe a test fired, the innermost unit holding it.
493/// Also which units hold a probe at all, per file, since only a change
494/// confined to such units can be said to have missed a test. Sources are
495/// needed to place JavaScript columns; without them there is no record.
496pub fn executions(
497    coverage: &CoverageReport,
498    manifest: &InputManifest,
499    sources: Option<&Files>,
500) -> Option<Executions> {
501    // Each point's file, by index into `files`, and unit. Hits are looked up
502    // millions of times on a large run, so the lookup hashes with Fx and a
503    // test's hits are grouped by file index before any name is copied.
504    let mut located: crate::interned::FastMap<&str, (usize, usize)> = Default::default();
505    let mut files: Vec<&str> = Vec::new();
506    let mut file_indexes: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
507    let mut probed: BTreeMap<String, BTreeSet<usize>> = BTreeMap::new();
508    for point in &coverage.view.points {
509        let meta = &point.meta;
510        let Some(code) = manifest
511            .files
512            .get(&meta.file)
513            .and_then(|fingerprint| fingerprint.code.as_ref())
514        else {
515            continue;
516        };
517        let column = if manifest.language == "javascript" {
518            let source = sources?.get(&meta.file)?;
519            let Some(column) = byte_column(source, meta.line, meta.column, &manifest.language)
520            else {
521                continue;
522            };
523            column
524        } else {
525            meta.column + 1
526        };
527        let unit = code.unit_at(meta.line, column);
528        let file = *file_indexes.entry(meta.file.as_str()).or_insert_with(|| {
529            files.push(meta.file.as_str());
530            files.len() - 1
531        });
532        located.insert(meta.id.as_str(), (file, unit));
533        if code.units[unit].is_code() {
534            probed.entry(meta.file.clone()).or_default().insert(unit);
535        }
536    }
537    // Everything the run reached, whoever reached it. Collected before the
538    // per-test loop because the record that holds what no test could be
539    // credited with has no test file, and the loop below skips it -- which is
540    // exactly the record a parallel suite's coverage lives in.
541    let mut covered_by_file = vec![Vec::new(); files.len()];
542    for test in &coverage.view.tests {
543        for hit in &test.hits {
544            if let Some((file, unit)) = located.get(hit.as_str()) {
545                covered_by_file[*file].push(*unit);
546            }
547        }
548    }
549    let covered = files
550        .iter()
551        .zip(covered_by_file)
552        .filter(|(_, units)| !units.is_empty())
553        .map(|(file, units)| {
554            (
555                (*file).to_owned(),
556                units.into_iter().collect::<BTreeSet<_>>(),
557            )
558        })
559        .collect::<BTreeMap<_, _>>();
560
561    let mut tests: BTreeMap<TestSelector, Execution> = BTreeMap::new();
562    for test in &coverage.view.tests {
563        let Some(file) = &test.file else {
564            continue;
565        };
566        let selector = TestSelector {
567            file: file.clone(),
568            name: test.name.clone(),
569        };
570        let record = tests.entry(selector.clone()).or_insert_with(|| Execution {
571            test: selector,
572            passed: false,
573            files: BTreeMap::new(),
574            attribution: crate::coverage_report::ATTRIBUTION_EXACT.to_owned(),
575        });
576        record.passed |= test.outcome == "passed";
577        // One name can be recorded more than once -- retries, a test declared
578        // in two files -- and a single incomplete appearance is enough to make
579        // the whole record's file list a lower bound.
580        if !crate::coverage_report::coverage_is_complete(&record.attribution) {
581            // already the weaker claim
582        } else if !crate::coverage_report::coverage_is_complete(&test.attribution) {
583            record.attribution = test.attribution.clone();
584        }
585        let mut reached = test
586            .hits
587            .iter()
588            .filter_map(|hit| located.get(hit.as_str()).copied())
589            .collect::<Vec<_>>();
590        reached.sort_unstable();
591        for group in reached.chunk_by(|left, right| left.0 == right.0) {
592            record
593                .files
594                .entry(files[group[0].0].to_owned())
595                .or_default()
596                .extend(group.iter().map(|(_, unit)| *unit));
597        }
598    }
599    let mut tests = tests.into_values().collect::<Vec<_>>();
600    for record in &mut tests {
601        for units in record.files.values_mut() {
602            units.sort_unstable();
603            units.dedup();
604        }
605    }
606    Some(Executions {
607        tests,
608        probed: probed
609            .into_iter()
610            .map(|(file, units)| (file, units.into_iter().collect()))
611            .collect(),
612        covered: covered
613            .into_iter()
614            .map(|(file, units)| (file, units.into_iter().collect()))
615            .collect(),
616    })
617}
618/// Which of a run's tests the current checkout's changes could have reached,
619/// from what each test executed and what has changed since, declaration by
620/// declaration. A test is affected by a change in code it ran, in its test
621/// file, or in a file it ran code in whose declarations changed shape; not by
622/// a change confined to code it never ran; not by comments or blank lines. A
623/// test that did not pass is listed as affected regardless: it has a result to
624/// establish. What this cannot see is a file the run never captured -- a file
625/// added since -- and the run's dependencies and configuration, which the
626/// working-tree check answers for.
627/// The files a run's tests are written in, where the run recorded what each
628/// of its tests ran.
629pub fn test_files(run: &StoredRun) -> Option<BTreeSet<String>> {
630    let executions: Executions =
631        serde_json::from_slice(&fs::read(run.directory.join(EXECUTIONS_FILE)).ok()?).ok()?;
632    Some(
633        executions
634            .tests
635            .into_iter()
636            .map(|record| record.test.file)
637            .collect(),
638    )
639}
640
641/// The files, of those a run was recorded with, that are not as they were.
642pub fn changed_files(recorded: &FileManifest, now: impl Fn(&str) -> Option<String>) -> Vec<String> {
643    recorded
644        .iter()
645        .filter(|(file, was)| now(file).as_deref() != Some(was.sha256.as_str()))
646        .map(|(file, _)| file.clone())
647        .collect()
648}
649
650/// `tests affected` of a merged run: each run it was merged from answers for
651/// its own tests, and a test in several of them is one test, affected where
652/// any of them says so -- as a test failed in either run is failed in the
653/// merge.
654fn affected_tests_of_merge(root: &Path, run: &StoredRun) -> Result<Value, String> {
655    let parents = run
656        .metadata
657        .parents
658        .as_deref()
659        .filter(|parents| !parents.is_empty())
660        .ok_or("This merged run does not say which runs it was merged from")?;
661    let inventory = crate::run_store::discover_runs(root).map_err(|error| error.to_string())?;
662    // Where a test is answered: affected outranks undetermined, which
663    // outranks unaffected.
664    const BUCKETS: [&str; 3] = ["affected", "undetermined", "unaffected"];
665    let mut tests = BTreeMap::<(String, String), (usize, Value)>::new();
666    let mut changed = BTreeMap::<String, Value>::new();
667    let mut meaning = Value::Null;
668    for parent in parents {
669        let Some(stored) = inventory.runs.iter().find(|stored| stored.id == *parent) else {
670            return Err(format!(
671                "Run {} was merged from {parent}, which is no longer stored, and a merge is answered from the runs it was merged from. Ask the others, or measure the suite again",
672                run.id
673            ));
674        };
675        let report = affected_tests(root, stored)?;
676        for (rank, bucket) in BUCKETS.iter().enumerate() {
677            for test in report[*bucket].as_array().into_iter().flatten() {
678                let key = (
679                    test["file"].as_str().unwrap_or_default().to_owned(),
680                    test["name"].as_str().unwrap_or_default().to_owned(),
681                );
682                match tests.get_mut(&key) {
683                    Some((held, _)) if *held < rank => {}
684                    Some((held, entry)) if *held == rank => {
685                        let mut reasons = entry["reasons"].as_array().cloned().unwrap_or_default();
686                        for reason in test["reasons"].as_array().into_iter().flatten() {
687                            if !reasons.contains(reason) {
688                                reasons.push(reason.clone());
689                            }
690                        }
691                        entry["reasons"] = Value::Array(reasons);
692                    }
693                    _ => {
694                        tests.insert(key, (rank, test.clone()));
695                    }
696                }
697            }
698        }
699        for file in report["changedFiles"].as_array().into_iter().flatten() {
700            if let Some(name) = file["file"].as_str() {
701                changed
702                    .entry(name.to_owned())
703                    .or_insert_with(|| file.clone());
704            }
705        }
706        if meaning.is_null() {
707            meaning = report["meaning"].clone();
708        }
709    }
710    let mut buckets = BUCKETS.map(|_| Vec::new());
711    for (rank, test) in tests.into_values() {
712        buckets[rank].push(test);
713    }
714    // Most likely to fail first, as within one run.
715    for bucket in &mut buckets[..2] {
716        bucket.sort_by_key(|entry| std::cmp::Reverse(entry["nameMatch"].as_u64().unwrap_or(0)));
717    }
718    let [affected, undetermined, unaffected] = buckets;
719    let total = affected.len() + undetermined.len() + unaffected.len();
720    Ok(json!({
721        "run": run.id,
722        "mergedFrom": parents,
723        "summary": {
724            "tests": total,
725            "affected": affected.len(),
726            "undetermined": undetermined.len(),
727            "unaffected": unaffected.len(),
728            "changedFiles": changed.len(),
729        },
730        "affected": affected,
731        "undetermined": undetermined,
732        "unaffected": unaffected,
733        "changedFiles": changed.into_values().collect::<Vec<_>>(),
734        "meaning": meaning,
735    }))
736}
737
738pub fn affected_tests(root: &Path, run: &StoredRun) -> Result<Value, String> {
739    // What each test ran is recorded when a run is published, beside the
740    // code it ran, and a merge records nothing: its parts hold the records,
741    // and a merge is answered from them when asked.
742    if run.metadata.merged == Some(true) {
743        return affected_tests_of_merge(root, run);
744    }
745    let stored = load_manifest(run)?;
746    let executions: Executions = fs::read(run.directory.join(EXECUTIONS_FILE))
747        .ok()
748        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
749        .ok_or(
750            "This run has no per-test execution record; rerun tests with this version of Supercov",
751        )?;
752    let executions = &executions;
753    let root = crate::workspace::canonicalize_simplified(root).map_err(|e| e.to_string())?;
754    let manifest = &stored.manifest;
755    let now = manifest
756        .files
757        .keys()
758        .filter_map(|file| {
759            let path = root.join(file);
760            let canonical = crate::workspace::canonicalize_simplified(&path).ok()?;
761            if !canonical.starts_with(&root) || !canonical.is_file() {
762                return None;
763            }
764            let text = fs::read_to_string(canonical).ok()?;
765            Some((file.clone(), FileFingerprint::read(file, &text)))
766        })
767        .collect::<FileManifest>();
768    let changes = manifest
769        .files
770        .keys()
771        .filter_map(|file| {
772            file_change(
773                manifest.files.get(file),
774                now.get(file),
775                executions.probed.get(file).map(Vec::as_slice),
776            )
777            .map(|change| (file.as_str(), change))
778        })
779        .collect::<BTreeMap<_, _>>();
780    let files = changes
781        .iter()
782        .filter_map(|(file, change)| {
783            let (kind, detail) = match change {
784                FileChange::Same | FileChange::Added => return None,
785                FileChange::CommentsOnly => ("formatting", None),
786                FileChange::Removed => ("removed", None),
787                FileChange::Bytes => ("changed", None),
788                FileChange::Code {
789                    before,
790                    after,
791                    diff,
792                    narrow,
793                } => (
794                    if *narrow { "bodies" } else { "declarations" },
795                    Some(describe(before, after, diff)),
796                ),
797            };
798            Some(json!({"file":file,"change":kind,"detail":detail}))
799        })
800        .collect::<Vec<_>>();
801    // What a test whose own reach is unknown could have reached.
802    //
803    // Nothing can narrow such a test below the run it ran in, and nothing
804    // needs to go wider: its reach is bounded above by what the run covered.
805    // So a change inside that bound could have reached it, and a change
806    // outside it -- code no test in the run ever ran, a file added since --
807    // could not have reached any test, this one included.
808    //
809    // That is a real narrowing rather than "always affected". It is also the
810    // only safe direction: reading an empty file list as "this change missed
811    // it" is what let a change to code every test exercised report `0 of 2
812    // tests affected` and exit 0, which an agent running only affected tests
813    // would act on by running nothing.
814    let beyond_the_run = changes
815        .iter()
816        .filter_map(|(file, change)| match change {
817            FileChange::Same | FileChange::CommentsOnly | FileChange::Added => None,
818            FileChange::Removed => Some(format!("{file} removed (the run covered code in it)")),
819            FileChange::Bytes => Some(format!("{file} changed (the run covered code in it)")),
820            FileChange::Code { before, diff, .. } => {
821                // Unit by unit rather than file by file: a function no test
822                // ran sits in the same file as the ones they did, so asking
823                // whether the file was covered would make every change to it
824                // reach every test.
825                let code = manifest.files.get(*file).and_then(|f| f.code.as_ref());
826                let reached = executions
827                    .covered
828                    .get(*file)
829                    .map(Vec::as_slice)
830                    .unwrap_or_default()
831                    .iter()
832                    .flat_map(|unit| match code {
833                        Some(code) if *unit < code.units.len() => {
834                            code.ancestors(*unit).collect::<Vec<_>>()
835                        }
836                        _ => vec![*unit],
837                    })
838                    .collect::<BTreeSet<_>>();
839                let hit = diff
840                    .changed
841                    .iter()
842                    .filter(|unit| reached.contains(unit))
843                    .filter_map(|unit| before.units.get(*unit))
844                    .collect::<Vec<_>>();
845                (!hit.is_empty())
846                    .then(|| format!("{file}: {} changed (the run covered it)", named(hit)))
847            }
848        })
849        .collect::<Vec<_>>();
850
851    // A JVM class's static initializer runs once per process and is credited
852    // to the first test to load the class, so a test that only reads a static
853    // field it set ran nothing recorded in that file. For a change to a
854    // class's declarations, a test whose own file names the class is affected
855    // too. (A module's top level in Python, Ruby, JavaScript or Go runs once
856    // as well, but replaying their histories missed no failing test there and
857    // the same rule grew dry-inflector's selection from 73% to 90% of its
858    // tests, so it is the JVM's alone.)
859    // Files tests load that nothing probes -- helpers, fixtures, support code
860    // beside the tests -- and that changed. No record says which test ran
861    // them, so a test is affected when its own file loads one: read from its
862    // imports where Supercov reads them, and otherwise by any change. Without
863    // this a helper every test called changing left every test unaffected.
864    let own_tests = executions
865        .tests
866        .iter()
867        .map(|record| record.test.file.clone())
868        .collect::<BTreeSet<_>>();
869    let known_tests = crate::run_store::discover_runs(&root)
870        .map(|inventory| {
871            inventory
872                .runs
873                .iter()
874                .filter_map(test_files)
875                .flatten()
876                .collect::<BTreeSet<_>>()
877        })
878        .unwrap_or_default()
879        .union(&own_tests)
880        .cloned()
881        .collect::<BTreeSet<_>>();
882    // What is measured, where the run's coverage manifest says: everything
883    // else first-party is a helper. Where it does not, only files beside the
884    // tests are; a measured file's top level changing is judged by what each
885    // test ran, above.
886    let measured = read_archive_selected(&run.evidence_path, |path| path == "manifest.json")
887        .ok()
888        .and_then(|entries| entries.into_iter().next())
889        .and_then(|entry| serde_json::from_slice::<Value>(&entry.contents).ok())
890        .and_then(|manifest| {
891            Some(
892                manifest["scope"]["entries"]
893                    .as_array()?
894                    .iter()
895                    .filter(|entry| entry["status"] == "included")
896                    .filter_map(|entry| entry["file"].as_str().map(str::to_owned))
897                    .collect::<BTreeSet<_>>(),
898            )
899        });
900    let helper = |file: &str| match &measured {
901        Some(measured) => !measured.contains(file),
902        None => crate::run_currency::beside_the_tests(file),
903    };
904    let helpers = changes
905        .iter()
906        .filter(|(file, change)| {
907            !matches!(
908                change,
909                FileChange::Same | FileChange::CommentsOnly | FileChange::Added
910            ) && !known_tests.contains(**file)
911                && helper(file)
912                && !crate::run_currency::configuration_file(file)
913                && !crate::run_currency::dependency_file(file)
914        })
915        // A change that only adds functions reaches no test written before.
916        .filter(|(file, change)| match change {
917            FileChange::Code { before, .. } => fs::read_to_string(root.join(file))
918                .ok()
919                .and_then(|text| crate::source_units::only_added(before, file, &text))
920                .is_none(),
921            _ => true,
922        })
923        .map(|(file, change)| {
924            let what = match change {
925                FileChange::Code {
926                    before,
927                    after,
928                    diff,
929                    ..
930                } => {
931                    format!("{file} changed: {}", describe(before, after, diff))
932                }
933                FileChange::Removed => format!("{file} removed"),
934                _ => format!("{file} changed"),
935            };
936            (*file, what)
937        })
938        .collect::<Vec<_>>();
939    let checkout =
940        (!helpers.is_empty()).then(|| crate::run_currency::Checkout::new(&root, &known_tests));
941    let ran = (!helpers.is_empty()).then(|| crate::run_currency::Ran::of(run));
942    let configurations = manifest
943        .files
944        .keys()
945        .filter(|file| crate::run_currency::configuration_file(file))
946        .cloned()
947        .collect::<Vec<_>>();
948    let mut loads_of = BTreeMap::<String, Option<crate::test_loads::Loads>>::new();
949    let named_by_tests = named_by_tests(&changes);
950    let mut test_sources = BTreeMap::<&str, Option<String>>::new();
951
952    let mut affected = Vec::new();
953    let mut undetermined = Vec::new();
954    let mut unaffected = Vec::new();
955    for record in &executions.tests {
956        let mut reasons = Vec::new();
957        // The changed declarations this test ran, where: what they held in
958        // the run (their own lines, nested declarations aside) and where
959        // they are now, so a caller can say which of their statements the
960        // test is known to check.
961        let mut changed_code = Vec::new();
962        if !record.passed {
963            reasons.push("did not pass in the run".to_owned());
964        }
965        match changes.get(record.test.file.as_str()) {
966            None | Some(FileChange::Same | FileChange::CommentsOnly | FileChange::Added) => {}
967            Some(FileChange::Removed) => reasons.push("test file removed".to_owned()),
968            Some(FileChange::Bytes) => reasons.push("test file changed".to_owned()),
969            Some(FileChange::Code {
970                before,
971                after,
972                diff,
973                ..
974            }) => reasons.push(format!(
975                "test file changed: {}",
976                describe(before, after, diff)
977            )),
978        }
979        for (file, units) in &record.files {
980            let code = manifest.files.get(file).and_then(|f| f.code.as_ref());
981            let ran = units
982                .iter()
983                .flat_map(|unit| match code {
984                    Some(code) if *unit < code.units.len() => {
985                        code.ancestors(*unit).collect::<Vec<_>>()
986                    }
987                    _ => vec![*unit],
988                })
989                .collect::<BTreeSet<_>>();
990            match changes.get(file.as_str()) {
991                None | Some(FileChange::Same | FileChange::CommentsOnly | FileChange::Added) => {}
992                Some(FileChange::Removed) => {
993                    reasons.push(format!("{file} removed (this test ran code in it)"));
994                }
995                Some(FileChange::Bytes) => {
996                    reasons.push(format!("{file} changed (this test ran code in it)"));
997                }
998                Some(FileChange::Code {
999                    before,
1000                    after,
1001                    diff,
1002                    narrow,
1003                }) => {
1004                    if *narrow {
1005                        let hit = diff
1006                            .changed
1007                            .iter()
1008                            .filter(|i| ran.contains(i))
1009                            .map(|i| &before.units[*i])
1010                            .collect::<Vec<_>>();
1011                        let now = after.by_path();
1012                        for index in diff.changed.iter().filter(|i| ran.contains(i)) {
1013                            let unit = &before.units[*index];
1014                            changed_code.push(json!({
1015                                "file": file,
1016                                "declaration": unit.path,
1017                                "own": own_lines(before, *index),
1018                                "now": now.get(unit.path.as_str()).map(|u| [u.line, u.end_line]),
1019                            }));
1020                        }
1021                        if !hit.is_empty() {
1022                            reasons
1023                                .push(format!("{file}: {} changed (this test ran it)", named(hit)));
1024                        }
1025                    } else {
1026                        reasons.push(format!(
1027                            "{file}: {} changed (this test ran code in this file)",
1028                            describe(before, after, diff)
1029                        ));
1030                    }
1031                }
1032            }
1033        }
1034        if let (Some(checkout), Some(ran)) = (&checkout, &ran) {
1035            let loads = loads_of.entry(record.test.file.clone()).or_insert_with(|| {
1036                checkout.loads(
1037                    &BTreeSet::from([record.test.file.clone()]),
1038                    ran.runners.as_ref(),
1039                    &configurations,
1040                )
1041            });
1042            for (file, what) in &helpers {
1043                let loaded = match loads {
1044                    Some(loads) if loads.open.is_none() => {
1045                        loads.files.contains(*file) || !checkout.places(file)
1046                    }
1047                    _ => true,
1048                };
1049                if loaded {
1050                    reasons.push(match loads {
1051                        Some(loads) if loads.open.is_none() && loads.files.contains(*file) => {
1052                            format!("{what} (this test's file loads it)")
1053                        }
1054                        _ => format!("{what} (a file tests may load)"),
1055                    });
1056                }
1057            }
1058        }
1059        for (file, names) in &named_by_tests {
1060            if record.files.contains_key(*file) || *file == record.test.file.as_str() {
1061                continue; // what it ran there already decided
1062            }
1063            let source = test_sources
1064                .entry(record.test.file.as_str())
1065                .or_insert_with(|| fs::read_to_string(root.join(&record.test.file)).ok());
1066            if let Some(name) = source
1067                .as_deref()
1068                .and_then(|text| names.iter().find(|name| names_word(text, name)))
1069            {
1070                reasons.push(format!(
1071                    "{file}: declarations changed, and the test file names {name} (code that runs once per process is credited to the first test to reach it)"
1072                ));
1073            }
1074        }
1075        if !crate::coverage_report::coverage_is_complete(&record.attribution) {
1076            // What its own record proves is the strong claim, and it keeps it:
1077            // a Ruby test credited with the changed line ran the changed line,
1078            // whatever else it also ran unrecorded.
1079            let proven = !reasons.is_empty();
1080            // The run's bound is what stands in for a record this test does
1081            // not have. Where it has one that already proves the change
1082            // reached it, saying so twice says nothing twice.
1083            if !proven {
1084                reasons.extend(beyond_the_run.iter().cloned());
1085                reasons.sort();
1086                reasons.dedup();
1087            }
1088            let entry = json!({
1089                "file": record.test.file,
1090                "name": record.test.name,
1091                "reasons": reasons,
1092                "attribution": record.attribution,
1093            });
1094            if proven {
1095                affected.push(entry);
1096            } else if reasons.is_empty() {
1097                unaffected.push(entry);
1098            } else {
1099                undetermined.push(entry);
1100            }
1101            continue;
1102        }
1103        let entry = json!({"file":record.test.file,"name":record.test.name,"reasons":reasons,"changedCode":changed_code});
1104        if reasons.is_empty() {
1105            unaffected.push(entry);
1106        } else {
1107            affected.push(entry);
1108        }
1109    }
1110    // Most likely to fail first: a test whose own file or name shares words
1111    // with a changed file (`test_receivebuffer.py` for `_receivebuffer.py`).
1112    // Replaying real commits in nine projects, this put a failing test in the
1113    // first three for 20 of 57 breaking commits where file order managed 13
1114    // (25 with assertion verdicts breaking its ties).
1115    let changed_words = changes
1116        .iter()
1117        .filter(|(_, change)| !matches!(change, FileChange::Same | FileChange::CommentsOnly))
1118        .flat_map(|(file, _)| words_of(file))
1119        .collect::<BTreeSet<_>>();
1120    for bucket in [&mut affected, &mut undetermined] {
1121        for entry in bucket.iter_mut() {
1122            entry["nameMatch"] = json!(name_match(entry, &changed_words));
1123        }
1124        bucket.sort_by_key(|entry| std::cmp::Reverse(entry["nameMatch"].as_u64().unwrap_or(0)));
1125    }
1126    Ok(json!({
1127        "run": run.id,
1128        "affected": affected,
1129        // Kept apart from `affected` because they are a different claim. A
1130        // test is affected when a change reached code it is recorded as having
1131        // run; it is undetermined when nothing recorded what it ran and the
1132        // change is inside what the run as a whole covered. Merging them would
1133        // report a precision the run does not have -- but both have to be run,
1134        // so both are in `--names`.
1135        "undetermined": undetermined,
1136        "unaffected": unaffected,
1137        "changedFiles": files,
1138        "summary": {
1139            "tests": executions.tests.len(),
1140            "affected": affected.len(),
1141            "undetermined": undetermined.len(),
1142            "unaffected": unaffected.len(),
1143            "changedFiles": files.len(),
1144        },
1145        "meaning": "Tests whose recorded execution a change since the run could have reached, and those whose execution nothing recorded: a test that ran alongside others has no coverage of its own, so it is undetermined whenever a change reaches anything the run covered. Run both. A file the run never captured, a dependency or a configuration change is not seen here; see workingTree."
1146    }))
1147}
1148/// For each changed JVM file whose declarations changed, the names a test
1149/// file may use to reach it: its top-level classes and its own name.
1150fn named_by_tests<'a>(
1151    changes: &BTreeMap<&'a str, FileChange<'_>>,
1152) -> BTreeMap<&'a str, BTreeSet<String>> {
1153    changes
1154        .iter()
1155        .filter(|(file, _)| {
1156            [".java", ".kt", ".kts", ".groovy", ".scala"]
1157                .iter()
1158                .any(|extension| file.ends_with(extension))
1159        })
1160        .filter_map(|(file, change)| match change {
1161            FileChange::Code {
1162                before,
1163                narrow: false,
1164                ..
1165            } => {
1166                let stem = file.rsplit('/').next()?.split('.').next()?.to_owned();
1167                let mut names = before
1168                    .units
1169                    .iter()
1170                    .filter(|unit| unit.parent.is_none_or(|p| before.units[p].path.is_empty()))
1171                    .filter_map(|unit| unit.path.rsplit('.').next().map(str::to_owned))
1172                    .filter(|name| name.len() > 2)
1173                    .collect::<BTreeSet<_>>();
1174                if stem.len() > 2
1175                    && !matches!(stem.as_str(), "mod" | "lib" | "main" | "index" | "__init__")
1176                {
1177                    names.insert(stem);
1178                }
1179                Some((*file, names))
1180            }
1181            _ => None,
1182        })
1183        .collect::<BTreeMap<_, _>>()
1184}
1185
1186/// The words a file's name is made of, test markers aside:
1187/// `tests/test_receive_buffer.py` -> `receive`, `buffer`;
1188/// `ReceiveBufferTest.java` -> `receive`, `buffer`.
1189fn words_of(path: &str) -> BTreeSet<String> {
1190    let stem = path.rsplit(['/', '\\']).next().unwrap_or(path);
1191    let stem = stem.split('.').next().unwrap_or(stem);
1192    split_words(stem)
1193        .into_iter()
1194        .filter(|w| !matches!(w.as_str(), "test" | "tests" | "spec" | "specs"))
1195        .collect()
1196}
1197
1198/// `receiveBuffer_v2` -> `receive`, `buffer`, `v2`: camel and snake case
1199/// split, lowercased, single letters dropped.
1200fn split_words(text: &str) -> Vec<String> {
1201    let mut words = Vec::new();
1202    let mut current = String::new();
1203    let mut previous_lower = false;
1204    for c in text.chars() {
1205        if !c.is_alphanumeric() {
1206            if !current.is_empty() {
1207                words.push(std::mem::take(&mut current));
1208            }
1209            previous_lower = false;
1210            continue;
1211        }
1212        if c.is_uppercase() && previous_lower && !current.is_empty() {
1213            words.push(std::mem::take(&mut current));
1214        }
1215        previous_lower = c.is_lowercase() || c.is_ascii_digit();
1216        current.extend(c.to_lowercase());
1217    }
1218    if !current.is_empty() {
1219        words.push(current);
1220    }
1221    words.into_iter().filter(|w| w.len() > 1).collect()
1222}
1223
1224/// How many of the changed files' words a test's file or name shares.
1225fn name_match(entry: &Value, changed: &BTreeSet<String>) -> usize {
1226    let file = entry["file"].as_str().unwrap_or("");
1227    let name = entry["name"].as_str().unwrap_or("");
1228    // The test's own name: after the last separator a runner puts between a
1229    // file or class and the test (`::`, `#`, `>`, `.`), parameters aside.
1230    let own = name
1231        .rsplit(['#', ':', '>', '.', '/'])
1232        .next()
1233        .unwrap_or(name)
1234        .split(['[', '('])
1235        .next()
1236        .unwrap_or("");
1237    let mut words = words_of(file);
1238    words.extend(split_words(own));
1239    words.intersection(changed).count()
1240}
1241
1242/// Whether `text` holds `word` as a whole identifier.
1243fn names_word(text: &str, word: &str) -> bool {
1244    text.match_indices(word).any(|(at, _)| {
1245        let before = text[..at].chars().last();
1246        let after = text[at + word.len()..].chars().next();
1247        let part = |c: Option<char>| c.is_some_and(|c| c.is_alphanumeric() || c == '_');
1248        !part(before) && !part(after)
1249    })
1250}
1251
1252/// A declaration's own lines: its span without the spans of the
1253/// declarations nested in it, as inclusive `[first, last]` ranges.
1254fn own_lines(code: &crate::source_units::Code, index: usize) -> Vec<[usize; 2]> {
1255    let unit = &code.units[index];
1256    let mut children = code
1257        .units
1258        .iter()
1259        .filter(|u| u.parent == Some(index))
1260        .map(|u| (u.line, u.end_line))
1261        .collect::<Vec<_>>();
1262    children.sort_unstable();
1263    let mut out = Vec::new();
1264    let mut next = unit.line;
1265    for (start, end) in children {
1266        if start > next {
1267            out.push([next, start - 1]);
1268        }
1269        next = next.max(end + 1);
1270    }
1271    if next <= unit.end_line {
1272        out.push([next, unit.end_line]);
1273    }
1274    out
1275}
1276
1277pub fn coverage(run: &StoredRun) -> Result<CoverageReport, String> {
1278    analyze_coverage_archive(&ArchiveReportRequest {
1279        archive_path: run.evidence_path.clone(),
1280        run_id: run.id.clone(),
1281        generated_at: run.metadata.started_at.clone(),
1282        integrity: None,
1283        test_exit_code: ExitCodeInput::Present(run.metadata.test_exit_code),
1284    })
1285    .map_err(|e| format!("{e:?}"))
1286}
1287fn byte_column(source: &str, line: usize, column: usize, language: &str) -> Option<usize> {
1288    byte_column_in(source, &line_starts(source), line, column, language)
1289}
1290
1291/// `byte_column`, given where each line starts, so that resolving a whole
1292/// file's statements looks each line up instead of walking the file to it.
1293fn byte_column_in(
1294    source: &str,
1295    starts: &[usize],
1296    line: usize,
1297    column: usize,
1298    language: &str,
1299) -> Option<usize> {
1300    if line == 0 {
1301        return None;
1302    }
1303    let line = line_text(source, starts, line)?;
1304    if language != "javascript" {
1305        // Native Rust, Python and Ruby manifests use zero-based byte columns.
1306        return column.checked_add(1);
1307    }
1308    if column == 0 {
1309        return None;
1310    }
1311    let mut units = 0;
1312    for (byte, ch) in line.char_indices() {
1313        if units == column - 1 {
1314            return Some(byte + 1);
1315        }
1316        units += ch.len_utf16();
1317    }
1318    (units == column - 1).then_some(line.len() + 1)
1319}
1320
1321#[cfg(test)]
1322mod tests {
1323    use super::*;
1324    use crate::evidence_archive::{read_archive, write_archive};
1325    use crate::run_store::discover_runs;
1326
1327    fn prepare_publication(
1328        root: &Path,
1329        directory: &Path,
1330        metadata: &RunMetadata,
1331        analysed: Option<&CoverageReport>,
1332    ) -> Result<(), String> {
1333        prepare_publication_with(root, directory, metadata, analysed, None)
1334    }
1335
1336    fn recorded(run: &StoredRun) -> Executions {
1337        serde_json::from_slice(&fs::read(run.directory.join(EXECUTIONS_FILE)).expect("a record"))
1338            .unwrap()
1339    }
1340
1341    #[test]
1342    fn a_merged_run_has_the_manifest_its_parents_share() {
1343        // `shards/<n>/` is where a merge puts each parent's entries; a parent
1344        // that was merged itself brings its own level.
1345        assert_eq!(unsharded("source-inputs.json"), "source-inputs.json");
1346        assert_eq!(
1347            unsharded("shards/0/source-inputs.json"),
1348            "source-inputs.json"
1349        );
1350        assert_eq!(
1351            unsharded("shards/12/shards/1/source-inputs.json"),
1352            "source-inputs.json"
1353        );
1354        assert_eq!(
1355            unsharded("shards/x/source-inputs.json"),
1356            "shards/x/source-inputs.json"
1357        );
1358        assert_eq!(
1359            unsharded("shards/source-inputs.json"),
1360            "shards/source-inputs.json"
1361        );
1362
1363        let entry = |path: &str, contents: &str| crate::evidence_archive::EvidenceArchiveEntry {
1364            path: path.into(),
1365            contents: contents.as_bytes().to_vec(),
1366        };
1367        let named = |path: &str| unsharded(path) == ARCHIVE_PATH;
1368        // The same manifest three times, once spelled differently, is one.
1369        let same = [
1370            entry("shards/0/source-inputs.json", r#"{"files":{"a.js":1}}"#),
1371            entry("shards/1/source-inputs.json", r#"{"files":{"a.js":1}}"#),
1372            entry("shards/2/source-inputs.json", r#"{ "files": {"a.js": 1} }"#),
1373            entry("shards/0/tests.jsonl", "not read"),
1374        ];
1375        assert_eq!(
1376            the_one(&same, named).unwrap(),
1377            Some(json!({"files": {"a.js": 1}}))
1378        );
1379        // Two different ones are refused: the merged run is not one run's code.
1380        let different = [
1381            entry("shards/0/source-inputs.json", r#"{"files":{"a.js":1}}"#),
1382            entry("shards/1/source-inputs.json", r#"{"files":{"a.js":2}}"#),
1383        ];
1384        assert!(
1385            the_one(&different, named)
1386                .unwrap_err()
1387                .contains("different source manifests")
1388        );
1389        assert_eq!(the_one(&[], named).unwrap(), None);
1390    }
1391
1392    /// `byte_column` as it was before it took line starts.
1393    fn reference_byte_column(
1394        source: &str,
1395        line: usize,
1396        column: usize,
1397        language: &str,
1398    ) -> Option<usize> {
1399        if line == 0 {
1400            return None;
1401        }
1402        let line = source.lines().nth(line - 1)?;
1403        if language != "javascript" {
1404            return column.checked_add(1);
1405        }
1406        if column == 0 {
1407            return None;
1408        }
1409        let mut units = 0;
1410        for (byte, ch) in line.char_indices() {
1411            if units == column - 1 {
1412                return Some(byte + 1);
1413            }
1414            units += ch.len_utf16();
1415        }
1416        (units == column - 1).then_some(line.len() + 1)
1417    }
1418
1419    #[test]
1420    fn a_column_from_line_starts_agrees_with_walking_the_file() {
1421        // JavaScript columns count UTF-16 units, so text whose widths differ --
1422        // accents, and an emoji that is two units -- is where they could part.
1423        for source in [
1424            "",
1425            "a",
1426            "a\n",
1427            "a\r\nb\r\n",
1428            "x\r",
1429            "héllo\nwörld\n",
1430            "😀x\ny😀z\n",
1431            "const a = 1;\n  b();\n",
1432        ] {
1433            let starts = line_starts(source);
1434            for language in ["javascript", "python"] {
1435                for line in 0..source.len() + 3 {
1436                    for column in 0..source.len() + 4 {
1437                        assert_eq!(
1438                            byte_column_in(source, &starts, line, column, language),
1439                            reference_byte_column(source, line, column, language),
1440                            "{language} {line}:{column} in {source:?}"
1441                        );
1442                    }
1443                }
1444            }
1445        }
1446    }
1447
1448    #[test]
1449    fn publication_records_what_each_test_ran_and_affected_tests_reads_it() {
1450        let root = std::env::temp_dir().join(format!("supercov-affected-{}", std::process::id()));
1451        let _ = fs::remove_dir_all(&root);
1452        fs::create_dir_all(root.join("src")).unwrap();
1453        fs::create_dir_all(root.join("tests")).unwrap();
1454        // The fixture's one point sits at line 1, column 0, so `work` has to
1455        // start the file: an `export` keyword there would belong to the top
1456        // level, not to the function.
1457        let app = "function work() {\n  return 1;\n}\nfunction idle() {\n  return 2;\n}\n";
1458        let test = "import assert from 'node:assert/strict';\nimport { LIMIT } from '../src/config.js';\nassert.equal(work(), 1);\n";
1459        let config = "export const LIMIT = 5;\nfunction check(n) {\n  return n < LIMIT;\n}\n";
1460        fs::write(root.join("src/app.js"), app).unwrap();
1461        fs::write(root.join("src/config.js"), config).unwrap();
1462        fs::write(root.join("tests/app.test.js"), test).unwrap();
1463        // The fixture run's one point sits at line 1, column 0 of src/app.js
1464        // with a zero-based byte column, which is how every non-JavaScript
1465        // frontend reports; the language is named for that.
1466        let inputs = crate::source_capture::capture(
1467            &root,
1468            "python",
1469            [
1470                "src/app.js".into(),
1471                "src/config.js".into(),
1472                "tests/app.test.js".into(),
1473            ],
1474        )
1475        .unwrap();
1476        let directory = crate::run_store::create_analyzable_test_run(&root, "first");
1477        let path = directory.join("evidence.raw.gz");
1478        let entries = crate::source_capture::append(read_archive(&path).unwrap(), &inputs).unwrap();
1479        let archive = write_archive(entries, &path).unwrap();
1480        let metadata_path = directory.join("run.json");
1481        let mut metadata: RunMetadata =
1482            serde_json::from_slice(&fs::read(&metadata_path).unwrap()).unwrap();
1483        metadata.raw_evidence.files = archive.files;
1484        metadata.raw_evidence.compressed_bytes = archive.compressed_bytes;
1485        metadata.raw_evidence.uncompressed_bytes = archive.uncompressed_bytes;
1486        fs::write(&metadata_path, serde_json::to_vec(&metadata).unwrap()).unwrap();
1487        prepare_publication(&root, &directory, &metadata, None).unwrap();
1488        let run = discover_runs(&root).unwrap().runs.remove(0);
1489        let stored = load_manifest(&run).unwrap();
1490        let executions = &recorded(&run);
1491        let code = stored.manifest.files["src/app.js"].code.as_ref().unwrap();
1492        let work = code.units.iter().position(|u| u.path == "work").unwrap();
1493        let idle = code.units.iter().position(|u| u.path == "idle").unwrap();
1494        assert_eq!(executions.tests.len(), 1);
1495        let record = &executions.tests[0];
1496        assert_eq!(record.test.file, "tests/app.test.js");
1497        assert_eq!(record.test.name, "test");
1498        assert!(record.passed);
1499        assert_eq!(record.files["src/app.js"], vec![work]);
1500        assert_eq!(
1501            executions.probed["src/app.js"],
1502            vec![work],
1503            "idle holds no probe in this run"
1504        );
1505        let _ = idle;
1506
1507        let names = |value: &Value, key: &str| {
1508            value[key]
1509                .as_array()
1510                .unwrap()
1511                .iter()
1512                .map(|t| t["name"].as_str().unwrap().to_owned())
1513                .collect::<Vec<_>>()
1514        };
1515        // Nothing changed.
1516        let report = affected_tests(&root, &run).unwrap();
1517        assert!(names(&report, "affected").is_empty(), "{report}");
1518        assert_eq!(names(&report, "unaffected"), ["test"]);
1519        assert_eq!(report["summary"]["changedFiles"], 0);
1520        // A comment: still nothing.
1521        fs::write(root.join("src/app.js"), format!("// about\n{app}")).unwrap();
1522        let report = affected_tests(&root, &run).unwrap();
1523        assert!(names(&report, "affected").is_empty(), "{report}");
1524        assert_eq!(report["changedFiles"][0]["change"], "formatting");
1525        // A body the test ran: affected, and it says which.
1526        fs::write(
1527            root.join("src/app.js"),
1528            app.replace("return 1;", "return 1 + 0;"),
1529        )
1530        .unwrap();
1531        let report = affected_tests(&root, &run).unwrap();
1532        assert_eq!(names(&report, "affected"), ["test"]);
1533        assert_eq!(
1534            report["affected"][0]["reasons"][0],
1535            "src/app.js: work (line 1) changed (this test ran it)"
1536        );
1537        // A body the test did not run, once idle has a probe of its own: not
1538        // affected. Here idle holds none, so the change is not one that can
1539        // be said to have missed the test, and it counts.
1540        fs::write(
1541            root.join("src/app.js"),
1542            app.replace("return 2;", "return 2 + 0;"),
1543        )
1544        .unwrap();
1545        let report = affected_tests(&root, &run).unwrap();
1546        assert_eq!(names(&report, "affected"), ["test"], "{report}");
1547        assert!(
1548            report["affected"][0]["reasons"][0]
1549                .as_str()
1550                .unwrap()
1551                .contains("this test ran code in this file"),
1552            "{report}"
1553        );
1554        // A declaration added: affected, the file's shape changed.
1555        fs::write(
1556            root.join("src/app.js"),
1557            format!("{app}function more() {{}}\n"),
1558        )
1559        .unwrap();
1560        let report = affected_tests(&root, &run).unwrap();
1561        assert_eq!(names(&report, "affected"), ["test"]);
1562        assert_eq!(report["changedFiles"][0]["change"], "declarations");
1563        // The test file itself.
1564        fs::write(root.join("src/app.js"), app).unwrap();
1565        fs::write(root.join("tests/app.test.js"), test.replace("1)", "2)")).unwrap();
1566        let report = affected_tests(&root, &run).unwrap();
1567        assert_eq!(names(&report, "affected"), ["test"]);
1568        assert!(
1569            report["affected"][0]["reasons"][0]
1570                .as_str()
1571                .unwrap()
1572                .starts_with("test file changed"),
1573            "{report}"
1574        );
1575        // Top-level code in a file the test names but never ran a statement
1576        // of: outside the JVM, not affected (a JVM class's static initializer
1577        // is the case the naming rule is for).
1578        fs::write(root.join("tests/app.test.js"), test).unwrap();
1579        fs::write(root.join("src/config.js"), config.replace("= 5", "= 6")).unwrap();
1580        let report = affected_tests(&root, &run).unwrap();
1581        assert!(names(&report, "affected").is_empty(), "{report}");
1582        fs::write(root.join("src/config.js"), config).unwrap();
1583        // A source file removed.
1584        fs::remove_file(root.join("src/app.js")).unwrap();
1585        let report = affected_tests(&root, &run).unwrap();
1586        assert_eq!(
1587            report["affected"][0]["reasons"][0],
1588            "src/app.js removed (this test ran code in it)"
1589        );
1590        fs::remove_dir_all(root).unwrap();
1591    }
1592
1593    /// h11's `test_receivebuffer.py` for `_receivebuffer.py`, commons-cli's
1594    /// `ConverterTests#testClassDoesNotInitialize` for `Converter.java`.
1595    #[test]
1596    fn a_test_named_like_the_changed_file_comes_first() {
1597        assert_eq!(
1598            words_of("h11/tests/test_receive_buffer.py"),
1599            BTreeSet::from(["receive".to_owned(), "buffer".to_owned()])
1600        );
1601        assert_eq!(
1602            words_of("src/test/java/org/apache/commons/cli/ConverterTests.java"),
1603            BTreeSet::from(["converter".to_owned()])
1604        );
1605        assert_eq!(
1606            split_words("parseHTTPVersion_v2"),
1607            ["parse", "httpversion", "v2"]
1608        );
1609        let changed = words_of("src/main/java/org/apache/commons/cli/Converter.java");
1610        let entry = |file: &str, name: &str| json!({"file": file, "name": name});
1611        assert_eq!(
1612            name_match(
1613                &entry(
1614                    "src/test/java/x/ConverterTests.java",
1615                    "x.ConverterTests#testClass()"
1616                ),
1617                &changed
1618            ),
1619            1
1620        );
1621        assert_eq!(
1622            name_match(
1623                &entry(
1624                    "src/test/java/x/OptionTests.java",
1625                    "x.OptionTests#testConverter()"
1626                ),
1627                &changed
1628            ),
1629            1,
1630            "the test's own name counts too"
1631        );
1632        assert_eq!(
1633            name_match(
1634                &entry(
1635                    "src/test/java/x/OptionTests.java",
1636                    "x.OptionTests#testBuilder()"
1637                ),
1638                &changed
1639            ),
1640            0
1641        );
1642    }
1643
1644    /// apache/commons-cli's `Converter.CLASS`: a static field set in a
1645    /// static initializer credited to whichever test loaded the class first.
1646    /// Its tests are reached by the class's name; a JavaScript module's top
1647    /// level is not.
1648    #[test]
1649    fn a_jvm_class_changed_in_its_declarations_is_reached_by_its_name() {
1650        let java = "package app;\nclass Converter {\n    static final Object CLASS = null;\n    static int size(int n) {\n        return n;\n    }\n}\n";
1651        let before = FileFingerprint::read("src/app/Converter.java", java);
1652        let after = FileFingerprint::read(
1653            "src/app/Converter.java",
1654            &java.replace("CLASS = null", "CLASS = new Object()"),
1655        );
1656        let js = "export const LIMIT = 5;\n";
1657        let js_before = FileFingerprint::read("src/config.js", js);
1658        let js_after = FileFingerprint::read("src/config.js", &js.replace('5', "6"));
1659        let changes = BTreeMap::from([
1660            (
1661                "src/app/Converter.java",
1662                file_change(Some(&before), Some(&after), Some(&[])).unwrap(),
1663            ),
1664            (
1665                "src/config.js",
1666                file_change(Some(&js_before), Some(&js_after), Some(&[])).unwrap(),
1667            ),
1668        ]);
1669        let named = named_by_tests(&changes);
1670        assert_eq!(
1671            named.get("src/app/Converter.java"),
1672            Some(&BTreeSet::from(["Converter".to_owned()]))
1673        );
1674        assert!(!named.contains_key("src/config.js"));
1675        assert!(names_word("assertEquals(Converter.CLASS, x)", "Converter"));
1676        assert!(!names_word("ConverterTests", "Converter"));
1677    }
1678
1679    #[test]
1680    fn a_test_that_ran_beside_others_is_undetermined_rather_than_unaffected() {
1681        // A parallel suite's coverage sits in the record nobody could claim,
1682        // and the tests beside it hold nothing of their own. Reading "this
1683        // test's record does not mention the changed file" as "this test is
1684        // unaffected" would answer `0 of 1 tests affected` for a change to the
1685        // only code the run executed -- and an agent running only the affected
1686        // tests would run nothing. The run's own bound is what stands in.
1687        let root = std::env::temp_dir().join(format!(
1688            "supercov-undetermined-{}-{}",
1689            std::process::id(),
1690            std::time::SystemTime::now()
1691                .duration_since(std::time::UNIX_EPOCH)
1692                .unwrap()
1693                .as_nanos()
1694        ));
1695        let _ = fs::remove_dir_all(&root);
1696        fs::create_dir_all(root.join("src")).unwrap();
1697        fs::create_dir_all(root.join("tests")).unwrap();
1698        let app = "function work() {\n  return 1;\n}\nfunction idle() {\n  return 2;\n}\n";
1699        let test = "import assert from 'node:assert/strict';\nimport { LIMIT } from '../src/config.js';\nassert.equal(work(), 1);\n";
1700        let config = "export const LIMIT = 5;\nfunction check(n) {\n  return n < LIMIT;\n}\n";
1701        fs::write(root.join("src/app.js"), app).unwrap();
1702        fs::write(root.join("src/config.js"), config).unwrap();
1703        fs::write(root.join("tests/app.test.js"), test).unwrap();
1704        let inputs = crate::source_capture::capture(
1705            &root,
1706            "python",
1707            ["src/app.js".into(), "tests/app.test.js".into()],
1708        )
1709        .unwrap();
1710        let directory = crate::run_store::create_run_wide_test_run(&root, "parallel");
1711        let path = directory.join("evidence.raw.gz");
1712        let entries = crate::source_capture::append(read_archive(&path).unwrap(), &inputs).unwrap();
1713        let archive = write_archive(entries, &path).unwrap();
1714        let metadata_path = directory.join("run.json");
1715        let mut metadata: RunMetadata =
1716            serde_json::from_slice(&fs::read(&metadata_path).unwrap()).unwrap();
1717        metadata.raw_evidence.files = archive.files;
1718        metadata.raw_evidence.compressed_bytes = archive.compressed_bytes;
1719        metadata.raw_evidence.uncompressed_bytes = archive.uncompressed_bytes;
1720        fs::write(&metadata_path, serde_json::to_vec(&metadata).unwrap()).unwrap();
1721        prepare_publication(&root, &directory, &metadata, None).unwrap();
1722        let run = discover_runs(&root).unwrap().runs.remove(0);
1723
1724        let executions = &recorded(&run);
1725        assert_eq!(executions.tests.len(), 1, "the named test, not the record");
1726        let record = &executions.tests[0];
1727        assert_eq!(
1728            record.attribution,
1729            crate::coverage_report::ATTRIBUTION_RUN_WIDE
1730        );
1731        assert!(
1732            record.files.is_empty(),
1733            "it is credited with nothing: {:?}",
1734            record.files
1735        );
1736        assert!(
1737            !executions.covered["src/app.js"].is_empty(),
1738            "and the run is credited with what it reached"
1739        );
1740
1741        let bucket = |value: &Value, key: &str| {
1742            value[key]
1743                .as_array()
1744                .unwrap()
1745                .iter()
1746                .map(|t| t["name"].as_str().unwrap().to_owned())
1747                .collect::<Vec<_>>()
1748        };
1749
1750        // Nothing changed: nothing to rerun, and the run's bound says nothing
1751        // either.
1752        let report = affected_tests(&root, &run).unwrap();
1753        assert_eq!(bucket(&report, "unaffected"), ["test"], "{report}");
1754        assert!(bucket(&report, "undetermined").is_empty(), "{report}");
1755
1756        // The one function the run executed changed. The test's own record
1757        // cannot say whether it reached it, and the run's can.
1758        fs::write(
1759            root.join("src/app.js"),
1760            app.replace("return 1;", "return 3;"),
1761        )
1762        .unwrap();
1763        let report = affected_tests(&root, &run).unwrap();
1764        assert!(
1765            bucket(&report, "affected").is_empty(),
1766            "nothing proves it ran the change: {report}"
1767        );
1768        assert_eq!(
1769            bucket(&report, "undetermined"),
1770            ["test"],
1771            "the run reached it, so this test might have: {report}"
1772        );
1773        assert_eq!(
1774            report["undetermined"][0]["attribution"],
1775            crate::coverage_report::ATTRIBUTION_RUN_WIDE,
1776            "{report}"
1777        );
1778        fs::remove_dir_all(root).unwrap();
1779    }
1780
1781    #[test]
1782    fn a_lower_bound_still_proves_what_it_recorded() {
1783        // Ruby's is the other incomplete attribution: the test is credited
1784        // with coverage, and that coverage is a floor rather than the whole of
1785        // what it ran. The floor is still evidence -- a test credited with the
1786        // changed line ran the changed line -- so it is affected outright,
1787        // with its own reason, rather than swept into the bucket for tests
1788        // nothing can say anything about.
1789        let root = std::env::temp_dir().join(format!(
1790            "supercov-partial-{}-{}",
1791            std::process::id(),
1792            std::time::SystemTime::now()
1793                .duration_since(std::time::UNIX_EPOCH)
1794                .unwrap()
1795                .as_nanos()
1796        ));
1797        let _ = fs::remove_dir_all(&root);
1798        fs::create_dir_all(root.join("src")).unwrap();
1799        fs::create_dir_all(root.join("tests")).unwrap();
1800        let app = "function work() {\n  return 1;\n}\nfunction idle() {\n  return 2;\n}\n";
1801        let test = "import assert from 'node:assert/strict';\nimport { LIMIT } from '../src/config.js';\nassert.equal(work(), 1);\n";
1802        let config = "export const LIMIT = 5;\nfunction check(n) {\n  return n < LIMIT;\n}\n";
1803        fs::write(root.join("src/app.js"), app).unwrap();
1804        fs::write(root.join("src/config.js"), config).unwrap();
1805        fs::write(root.join("tests/app.test.js"), test).unwrap();
1806        let inputs = crate::source_capture::capture(
1807            &root,
1808            "python",
1809            ["src/app.js".into(), "tests/app.test.js".into()],
1810        )
1811        .unwrap();
1812        let directory = crate::run_store::create_partial_test_run(&root, "partial");
1813        let path = directory.join("evidence.raw.gz");
1814        let entries = crate::source_capture::append(read_archive(&path).unwrap(), &inputs).unwrap();
1815        let archive = write_archive(entries, &path).unwrap();
1816        let metadata_path = directory.join("run.json");
1817        let mut metadata: RunMetadata =
1818            serde_json::from_slice(&fs::read(&metadata_path).unwrap()).unwrap();
1819        metadata.raw_evidence.files = archive.files;
1820        metadata.raw_evidence.compressed_bytes = archive.compressed_bytes;
1821        metadata.raw_evidence.uncompressed_bytes = archive.uncompressed_bytes;
1822        fs::write(&metadata_path, serde_json::to_vec(&metadata).unwrap()).unwrap();
1823        prepare_publication(&root, &directory, &metadata, None).unwrap();
1824        let run = discover_runs(&root).unwrap().runs.remove(0);
1825
1826        let executions = recorded(&run);
1827        let record = &executions.tests[0];
1828        assert_eq!(
1829            record.attribution,
1830            crate::coverage_report::ATTRIBUTION_PARTIAL
1831        );
1832        assert!(
1833            !record.files.is_empty(),
1834            "a lower bound is coverage it was credited with"
1835        );
1836
1837        let names = |value: &Value, key: &str| {
1838            value[key]
1839                .as_array()
1840                .unwrap()
1841                .iter()
1842                .map(|t| t["name"].as_str().unwrap().to_owned())
1843                .collect::<Vec<_>>()
1844        };
1845        fs::write(
1846            root.join("src/app.js"),
1847            app.replace("return 1;", "return 3;"),
1848        )
1849        .unwrap();
1850        let report = affected_tests(&root, &run).unwrap();
1851        assert_eq!(
1852            names(&report, "affected"),
1853            ["test"],
1854            "what its own record proves, it proves: {report}"
1855        );
1856        assert!(names(&report, "undetermined").is_empty(), "{report}");
1857        // And the reason is its own, not the run's stand-in.
1858        let reasons = report["affected"][0]["reasons"].as_array().unwrap();
1859        assert_eq!(reasons.len(), 1, "{report}");
1860        let reason = reasons[0].as_str().unwrap();
1861        assert!(
1862            reason.contains("this test ran it"),
1863            "the reason is its own: {report}"
1864        );
1865        assert!(
1866            !reason.contains("the run covered"),
1867            "and not the run's stand-in: {report}"
1868        );
1869        fs::remove_dir_all(root).unwrap();
1870    }
1871}