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, whose change since makes
642/// what it recorded a record of other tests. `now` gives a file's digest as
643/// it is; `ran` the files the run's own tests are in; `tests` every file
644/// known to hold tests.
645///
646/// A file of another test changing takes nothing from this run: that test
647/// was not in it. A file that is not known to be a test's is one a test may
648/// load, a helper or a fixture, and counts against every run.
649pub fn outdated_files(
650    recorded: &FileManifest,
651    now: impl Fn(&str) -> Option<String>,
652    ran: Option<&BTreeSet<String>>,
653    tests: &BTreeSet<String>,
654) -> Vec<String> {
655    recorded
656        .iter()
657        .filter(|(file, was)| now(file).as_deref() != Some(was.sha256.as_str()))
658        .filter(|(file, _)| !ran.is_some_and(|ran| !ran.contains(*file) && tests.contains(*file)))
659        .map(|(file, _)| file.clone())
660        .collect()
661}
662
663pub fn affected_tests(root: &Path, run: &StoredRun) -> Result<Value, String> {
664    // What each test ran is recorded when a run is published, beside the
665    // code it ran, and a merge records nothing: its parts hold the records.
666    if run.metadata.merged == Some(true) {
667        return Err(match run.metadata.parents.as_deref() {
668            Some(parents) if !parents.is_empty() => format!(
669                "A merged run keeps no record of what each test ran; ask the runs it was merged from: {}",
670                parents.join(", ")
671            ),
672            _ => "A merged run keeps no record of what each test ran; ask the runs it was merged from".into(),
673        });
674    }
675    let stored = load_manifest(run)?;
676    let executions: Executions = fs::read(run.directory.join(EXECUTIONS_FILE))
677        .ok()
678        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
679        .ok_or(
680            "This run has no per-test execution record; rerun tests with this version of Supercov",
681        )?;
682    let executions = &executions;
683    let root = crate::workspace::canonicalize_simplified(root).map_err(|e| e.to_string())?;
684    let manifest = &stored.manifest;
685    let now = manifest
686        .files
687        .keys()
688        .filter_map(|file| {
689            let path = root.join(file);
690            let canonical = crate::workspace::canonicalize_simplified(&path).ok()?;
691            if !canonical.starts_with(&root) || !canonical.is_file() {
692                return None;
693            }
694            let text = fs::read_to_string(canonical).ok()?;
695            Some((file.clone(), FileFingerprint::read(file, &text)))
696        })
697        .collect::<FileManifest>();
698    let changes = manifest
699        .files
700        .keys()
701        .filter_map(|file| {
702            file_change(
703                manifest.files.get(file),
704                now.get(file),
705                executions.probed.get(file).map(Vec::as_slice),
706            )
707            .map(|change| (file.as_str(), change))
708        })
709        .collect::<BTreeMap<_, _>>();
710    let files = changes
711        .iter()
712        .filter_map(|(file, change)| {
713            let (kind, detail) = match change {
714                FileChange::Same | FileChange::Added => return None,
715                FileChange::CommentsOnly => ("formatting", None),
716                FileChange::Removed => ("removed", None),
717                FileChange::Bytes => ("changed", None),
718                FileChange::Code {
719                    before,
720                    after,
721                    diff,
722                    narrow,
723                } => (
724                    if *narrow { "bodies" } else { "declarations" },
725                    Some(describe(before, after, diff)),
726                ),
727            };
728            Some(json!({"file":file,"change":kind,"detail":detail}))
729        })
730        .collect::<Vec<_>>();
731    // What a test whose own reach is unknown could have reached.
732    //
733    // Nothing can narrow such a test below the run it ran in, and nothing
734    // needs to go wider: its reach is bounded above by what the run covered.
735    // So a change inside that bound could have reached it, and a change
736    // outside it -- code no test in the run ever ran, a file added since --
737    // could not have reached any test, this one included.
738    //
739    // That is a real narrowing rather than "always affected". It is also the
740    // only safe direction: reading an empty file list as "this change missed
741    // it" is what let a change to code every test exercised report `0 of 2
742    // tests affected` and exit 0, which an agent running only affected tests
743    // would act on by running nothing.
744    let beyond_the_run = changes
745        .iter()
746        .filter_map(|(file, change)| match change {
747            FileChange::Same | FileChange::CommentsOnly | FileChange::Added => None,
748            FileChange::Removed => Some(format!("{file} removed (the run covered code in it)")),
749            FileChange::Bytes => Some(format!("{file} changed (the run covered code in it)")),
750            FileChange::Code { before, diff, .. } => {
751                // Unit by unit rather than file by file: a function no test
752                // ran sits in the same file as the ones they did, so asking
753                // whether the file was covered would make every change to it
754                // reach every test.
755                let code = manifest.files.get(*file).and_then(|f| f.code.as_ref());
756                let reached = executions
757                    .covered
758                    .get(*file)
759                    .map(Vec::as_slice)
760                    .unwrap_or_default()
761                    .iter()
762                    .flat_map(|unit| match code {
763                        Some(code) if *unit < code.units.len() => {
764                            code.ancestors(*unit).collect::<Vec<_>>()
765                        }
766                        _ => vec![*unit],
767                    })
768                    .collect::<BTreeSet<_>>();
769                let hit = diff
770                    .changed
771                    .iter()
772                    .filter(|unit| reached.contains(unit))
773                    .filter_map(|unit| before.units.get(*unit))
774                    .collect::<Vec<_>>();
775                (!hit.is_empty())
776                    .then(|| format!("{file}: {} changed (the run covered it)", named(hit)))
777            }
778        })
779        .collect::<Vec<_>>();
780
781    // A JVM class's static initializer runs once per process and is credited
782    // to the first test to load the class, so a test that only reads a static
783    // field it set ran nothing recorded in that file. For a change to a
784    // class's declarations, a test whose own file names the class is affected
785    // too. (A module's top level in Python, Ruby, JavaScript or Go runs once
786    // as well, but replaying their histories missed no failing test there and
787    // the same rule grew dry-inflector's selection from 73% to 90% of its
788    // tests, so it is the JVM's alone.)
789    let named_by_tests = named_by_tests(&changes);
790    let mut test_sources = BTreeMap::<&str, Option<String>>::new();
791
792    let mut affected = Vec::new();
793    let mut undetermined = Vec::new();
794    let mut unaffected = Vec::new();
795    for record in &executions.tests {
796        let mut reasons = Vec::new();
797        // The changed declarations this test ran, where: what they held in
798        // the run (their own lines, nested declarations aside) and where
799        // they are now, so a caller can say which of their statements the
800        // test is known to check.
801        let mut changed_code = Vec::new();
802        if !record.passed {
803            reasons.push("did not pass in the run".to_owned());
804        }
805        match changes.get(record.test.file.as_str()) {
806            None | Some(FileChange::Same | FileChange::CommentsOnly | FileChange::Added) => {}
807            Some(FileChange::Removed) => reasons.push("test file removed".to_owned()),
808            Some(FileChange::Bytes) => reasons.push("test file changed".to_owned()),
809            Some(FileChange::Code {
810                before,
811                after,
812                diff,
813                ..
814            }) => reasons.push(format!(
815                "test file changed: {}",
816                describe(before, after, diff)
817            )),
818        }
819        for (file, units) in &record.files {
820            let code = manifest.files.get(file).and_then(|f| f.code.as_ref());
821            let ran = units
822                .iter()
823                .flat_map(|unit| match code {
824                    Some(code) if *unit < code.units.len() => {
825                        code.ancestors(*unit).collect::<Vec<_>>()
826                    }
827                    _ => vec![*unit],
828                })
829                .collect::<BTreeSet<_>>();
830            match changes.get(file.as_str()) {
831                None | Some(FileChange::Same | FileChange::CommentsOnly | FileChange::Added) => {}
832                Some(FileChange::Removed) => {
833                    reasons.push(format!("{file} removed (this test ran code in it)"));
834                }
835                Some(FileChange::Bytes) => {
836                    reasons.push(format!("{file} changed (this test ran code in it)"));
837                }
838                Some(FileChange::Code {
839                    before,
840                    after,
841                    diff,
842                    narrow,
843                }) => {
844                    if *narrow {
845                        let hit = diff
846                            .changed
847                            .iter()
848                            .filter(|i| ran.contains(i))
849                            .map(|i| &before.units[*i])
850                            .collect::<Vec<_>>();
851                        let now = after.by_path();
852                        for index in diff.changed.iter().filter(|i| ran.contains(i)) {
853                            let unit = &before.units[*index];
854                            changed_code.push(json!({
855                                "file": file,
856                                "declaration": unit.path,
857                                "own": own_lines(before, *index),
858                                "now": now.get(unit.path.as_str()).map(|u| [u.line, u.end_line]),
859                            }));
860                        }
861                        if !hit.is_empty() {
862                            reasons
863                                .push(format!("{file}: {} changed (this test ran it)", named(hit)));
864                        }
865                    } else {
866                        reasons.push(format!(
867                            "{file}: {} changed (this test ran code in this file)",
868                            describe(before, after, diff)
869                        ));
870                    }
871                }
872            }
873        }
874        for (file, names) in &named_by_tests {
875            if record.files.contains_key(*file) || *file == record.test.file.as_str() {
876                continue; // what it ran there already decided
877            }
878            let source = test_sources
879                .entry(record.test.file.as_str())
880                .or_insert_with(|| fs::read_to_string(root.join(&record.test.file)).ok());
881            if let Some(name) = source
882                .as_deref()
883                .and_then(|text| names.iter().find(|name| names_word(text, name)))
884            {
885                reasons.push(format!(
886                    "{file}: declarations changed, and the test file names {name} (code that runs once per process is credited to the first test to reach it)"
887                ));
888            }
889        }
890        if !crate::coverage_report::coverage_is_complete(&record.attribution) {
891            // What its own record proves is the strong claim, and it keeps it:
892            // a Ruby test credited with the changed line ran the changed line,
893            // whatever else it also ran unrecorded.
894            let proven = !reasons.is_empty();
895            // The run's bound is what stands in for a record this test does
896            // not have. Where it has one that already proves the change
897            // reached it, saying so twice says nothing twice.
898            if !proven {
899                reasons.extend(beyond_the_run.iter().cloned());
900                reasons.sort();
901                reasons.dedup();
902            }
903            let entry = json!({
904                "file": record.test.file,
905                "name": record.test.name,
906                "reasons": reasons,
907                "attribution": record.attribution,
908            });
909            if proven {
910                affected.push(entry);
911            } else if reasons.is_empty() {
912                unaffected.push(entry);
913            } else {
914                undetermined.push(entry);
915            }
916            continue;
917        }
918        let entry = json!({"file":record.test.file,"name":record.test.name,"reasons":reasons,"changedCode":changed_code});
919        if reasons.is_empty() {
920            unaffected.push(entry);
921        } else {
922            affected.push(entry);
923        }
924    }
925    // Most likely to fail first: a test whose own file or name shares words
926    // with a changed file (`test_receivebuffer.py` for `_receivebuffer.py`).
927    // Replaying real commits in nine projects, this put a failing test in the
928    // first three for 20 of 57 breaking commits where file order managed 13
929    // (25 with assertion verdicts breaking its ties).
930    let changed_words = changes
931        .iter()
932        .filter(|(_, change)| !matches!(change, FileChange::Same | FileChange::CommentsOnly))
933        .flat_map(|(file, _)| words_of(file))
934        .collect::<BTreeSet<_>>();
935    for bucket in [&mut affected, &mut undetermined] {
936        for entry in bucket.iter_mut() {
937            entry["nameMatch"] = json!(name_match(entry, &changed_words));
938        }
939        bucket.sort_by_key(|entry| std::cmp::Reverse(entry["nameMatch"].as_u64().unwrap_or(0)));
940    }
941    Ok(json!({
942        "run": run.id,
943        "affected": affected,
944        // Kept apart from `affected` because they are a different claim. A
945        // test is affected when a change reached code it is recorded as having
946        // run; it is undetermined when nothing recorded what it ran and the
947        // change is inside what the run as a whole covered. Merging them would
948        // report a precision the run does not have -- but both have to be run,
949        // so both are in `--names`.
950        "undetermined": undetermined,
951        "unaffected": unaffected,
952        "changedFiles": files,
953        "summary": {
954            "tests": executions.tests.len(),
955            "affected": affected.len(),
956            "undetermined": undetermined.len(),
957            "unaffected": unaffected.len(),
958            "changedFiles": files.len(),
959        },
960        "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."
961    }))
962}
963/// For each changed JVM file whose declarations changed, the names a test
964/// file may use to reach it: its top-level classes and its own name.
965fn named_by_tests<'a>(
966    changes: &BTreeMap<&'a str, FileChange<'_>>,
967) -> BTreeMap<&'a str, BTreeSet<String>> {
968    changes
969        .iter()
970        .filter(|(file, _)| {
971            [".java", ".kt", ".kts", ".groovy", ".scala"]
972                .iter()
973                .any(|extension| file.ends_with(extension))
974        })
975        .filter_map(|(file, change)| match change {
976            FileChange::Code {
977                before,
978                narrow: false,
979                ..
980            } => {
981                let stem = file.rsplit('/').next()?.split('.').next()?.to_owned();
982                let mut names = before
983                    .units
984                    .iter()
985                    .filter(|unit| unit.parent.is_none_or(|p| before.units[p].path.is_empty()))
986                    .filter_map(|unit| unit.path.rsplit('.').next().map(str::to_owned))
987                    .filter(|name| name.len() > 2)
988                    .collect::<BTreeSet<_>>();
989                if stem.len() > 2
990                    && !matches!(stem.as_str(), "mod" | "lib" | "main" | "index" | "__init__")
991                {
992                    names.insert(stem);
993                }
994                Some((*file, names))
995            }
996            _ => None,
997        })
998        .collect::<BTreeMap<_, _>>()
999}
1000
1001/// The words a file's name is made of, test markers aside:
1002/// `tests/test_receive_buffer.py` -> `receive`, `buffer`;
1003/// `ReceiveBufferTest.java` -> `receive`, `buffer`.
1004fn words_of(path: &str) -> BTreeSet<String> {
1005    let stem = path.rsplit(['/', '\\']).next().unwrap_or(path);
1006    let stem = stem.split('.').next().unwrap_or(stem);
1007    split_words(stem)
1008        .into_iter()
1009        .filter(|w| !matches!(w.as_str(), "test" | "tests" | "spec" | "specs"))
1010        .collect()
1011}
1012
1013/// `receiveBuffer_v2` -> `receive`, `buffer`, `v2`: camel and snake case
1014/// split, lowercased, single letters dropped.
1015fn split_words(text: &str) -> Vec<String> {
1016    let mut words = Vec::new();
1017    let mut current = String::new();
1018    let mut previous_lower = false;
1019    for c in text.chars() {
1020        if !c.is_alphanumeric() {
1021            if !current.is_empty() {
1022                words.push(std::mem::take(&mut current));
1023            }
1024            previous_lower = false;
1025            continue;
1026        }
1027        if c.is_uppercase() && previous_lower && !current.is_empty() {
1028            words.push(std::mem::take(&mut current));
1029        }
1030        previous_lower = c.is_lowercase() || c.is_ascii_digit();
1031        current.extend(c.to_lowercase());
1032    }
1033    if !current.is_empty() {
1034        words.push(current);
1035    }
1036    words.into_iter().filter(|w| w.len() > 1).collect()
1037}
1038
1039/// How many of the changed files' words a test's file or name shares.
1040fn name_match(entry: &Value, changed: &BTreeSet<String>) -> usize {
1041    let file = entry["file"].as_str().unwrap_or("");
1042    let name = entry["name"].as_str().unwrap_or("");
1043    // The test's own name: after the last separator a runner puts between a
1044    // file or class and the test (`::`, `#`, `>`, `.`), parameters aside.
1045    let own = name
1046        .rsplit(['#', ':', '>', '.', '/'])
1047        .next()
1048        .unwrap_or(name)
1049        .split(['[', '('])
1050        .next()
1051        .unwrap_or("");
1052    let mut words = words_of(file);
1053    words.extend(split_words(own));
1054    words.intersection(changed).count()
1055}
1056
1057/// Whether `text` holds `word` as a whole identifier.
1058fn names_word(text: &str, word: &str) -> bool {
1059    text.match_indices(word).any(|(at, _)| {
1060        let before = text[..at].chars().last();
1061        let after = text[at + word.len()..].chars().next();
1062        let part = |c: Option<char>| c.is_some_and(|c| c.is_alphanumeric() || c == '_');
1063        !part(before) && !part(after)
1064    })
1065}
1066
1067/// A declaration's own lines: its span without the spans of the
1068/// declarations nested in it, as inclusive `[first, last]` ranges.
1069fn own_lines(code: &crate::source_units::Code, index: usize) -> Vec<[usize; 2]> {
1070    let unit = &code.units[index];
1071    let mut children = code
1072        .units
1073        .iter()
1074        .filter(|u| u.parent == Some(index))
1075        .map(|u| (u.line, u.end_line))
1076        .collect::<Vec<_>>();
1077    children.sort_unstable();
1078    let mut out = Vec::new();
1079    let mut next = unit.line;
1080    for (start, end) in children {
1081        if start > next {
1082            out.push([next, start - 1]);
1083        }
1084        next = next.max(end + 1);
1085    }
1086    if next <= unit.end_line {
1087        out.push([next, unit.end_line]);
1088    }
1089    out
1090}
1091
1092pub fn coverage(run: &StoredRun) -> Result<CoverageReport, String> {
1093    analyze_coverage_archive(&ArchiveReportRequest {
1094        archive_path: run.evidence_path.clone(),
1095        run_id: run.id.clone(),
1096        generated_at: run.metadata.started_at.clone(),
1097        integrity: None,
1098        test_exit_code: ExitCodeInput::Present(run.metadata.test_exit_code),
1099    })
1100    .map_err(|e| format!("{e:?}"))
1101}
1102fn byte_column(source: &str, line: usize, column: usize, language: &str) -> Option<usize> {
1103    byte_column_in(source, &line_starts(source), line, column, language)
1104}
1105
1106/// `byte_column`, given where each line starts, so that resolving a whole
1107/// file's statements looks each line up instead of walking the file to it.
1108fn byte_column_in(
1109    source: &str,
1110    starts: &[usize],
1111    line: usize,
1112    column: usize,
1113    language: &str,
1114) -> Option<usize> {
1115    if line == 0 {
1116        return None;
1117    }
1118    let line = line_text(source, starts, line)?;
1119    if language != "javascript" {
1120        // Native Rust, Python and Ruby manifests use zero-based byte columns.
1121        return column.checked_add(1);
1122    }
1123    if column == 0 {
1124        return None;
1125    }
1126    let mut units = 0;
1127    for (byte, ch) in line.char_indices() {
1128        if units == column - 1 {
1129            return Some(byte + 1);
1130        }
1131        units += ch.len_utf16();
1132    }
1133    (units == column - 1).then_some(line.len() + 1)
1134}
1135
1136#[cfg(test)]
1137mod tests {
1138    use super::*;
1139    use crate::evidence_archive::{read_archive, write_archive};
1140    use crate::run_store::discover_runs;
1141
1142    fn prepare_publication(
1143        root: &Path,
1144        directory: &Path,
1145        metadata: &RunMetadata,
1146        analysed: Option<&CoverageReport>,
1147    ) -> Result<(), String> {
1148        prepare_publication_with(root, directory, metadata, analysed, None)
1149    }
1150
1151    fn recorded(run: &StoredRun) -> Executions {
1152        serde_json::from_slice(&fs::read(run.directory.join(EXECUTIONS_FILE)).expect("a record"))
1153            .unwrap()
1154    }
1155
1156    #[test]
1157    fn a_merged_run_has_the_manifest_its_parents_share() {
1158        // `shards/<n>/` is where a merge puts each parent's entries; a parent
1159        // that was merged itself brings its own level.
1160        assert_eq!(unsharded("source-inputs.json"), "source-inputs.json");
1161        assert_eq!(
1162            unsharded("shards/0/source-inputs.json"),
1163            "source-inputs.json"
1164        );
1165        assert_eq!(
1166            unsharded("shards/12/shards/1/source-inputs.json"),
1167            "source-inputs.json"
1168        );
1169        assert_eq!(
1170            unsharded("shards/x/source-inputs.json"),
1171            "shards/x/source-inputs.json"
1172        );
1173        assert_eq!(
1174            unsharded("shards/source-inputs.json"),
1175            "shards/source-inputs.json"
1176        );
1177
1178        let entry = |path: &str, contents: &str| crate::evidence_archive::EvidenceArchiveEntry {
1179            path: path.into(),
1180            contents: contents.as_bytes().to_vec(),
1181        };
1182        let named = |path: &str| unsharded(path) == ARCHIVE_PATH;
1183        // The same manifest three times, once spelled differently, is one.
1184        let same = [
1185            entry("shards/0/source-inputs.json", r#"{"files":{"a.js":1}}"#),
1186            entry("shards/1/source-inputs.json", r#"{"files":{"a.js":1}}"#),
1187            entry("shards/2/source-inputs.json", r#"{ "files": {"a.js": 1} }"#),
1188            entry("shards/0/tests.jsonl", "not read"),
1189        ];
1190        assert_eq!(
1191            the_one(&same, named).unwrap(),
1192            Some(json!({"files": {"a.js": 1}}))
1193        );
1194        // Two different ones are refused: the merged run is not one run's code.
1195        let different = [
1196            entry("shards/0/source-inputs.json", r#"{"files":{"a.js":1}}"#),
1197            entry("shards/1/source-inputs.json", r#"{"files":{"a.js":2}}"#),
1198        ];
1199        assert!(
1200            the_one(&different, named)
1201                .unwrap_err()
1202                .contains("different source manifests")
1203        );
1204        assert_eq!(the_one(&[], named).unwrap(), None);
1205    }
1206
1207    /// `byte_column` as it was before it took line starts.
1208    fn reference_byte_column(
1209        source: &str,
1210        line: usize,
1211        column: usize,
1212        language: &str,
1213    ) -> Option<usize> {
1214        if line == 0 {
1215            return None;
1216        }
1217        let line = source.lines().nth(line - 1)?;
1218        if language != "javascript" {
1219            return column.checked_add(1);
1220        }
1221        if column == 0 {
1222            return None;
1223        }
1224        let mut units = 0;
1225        for (byte, ch) in line.char_indices() {
1226            if units == column - 1 {
1227                return Some(byte + 1);
1228            }
1229            units += ch.len_utf16();
1230        }
1231        (units == column - 1).then_some(line.len() + 1)
1232    }
1233
1234    #[test]
1235    fn a_column_from_line_starts_agrees_with_walking_the_file() {
1236        // JavaScript columns count UTF-16 units, so text whose widths differ --
1237        // accents, and an emoji that is two units -- is where they could part.
1238        for source in [
1239            "",
1240            "a",
1241            "a\n",
1242            "a\r\nb\r\n",
1243            "x\r",
1244            "héllo\nwörld\n",
1245            "😀x\ny😀z\n",
1246            "const a = 1;\n  b();\n",
1247        ] {
1248            let starts = line_starts(source);
1249            for language in ["javascript", "python"] {
1250                for line in 0..source.len() + 3 {
1251                    for column in 0..source.len() + 4 {
1252                        assert_eq!(
1253                            byte_column_in(source, &starts, line, column, language),
1254                            reference_byte_column(source, line, column, language),
1255                            "{language} {line}:{column} in {source:?}"
1256                        );
1257                    }
1258                }
1259            }
1260        }
1261    }
1262
1263    #[test]
1264    fn publication_records_what_each_test_ran_and_affected_tests_reads_it() {
1265        let root = std::env::temp_dir().join(format!("supercov-affected-{}", std::process::id()));
1266        let _ = fs::remove_dir_all(&root);
1267        fs::create_dir_all(root.join("src")).unwrap();
1268        fs::create_dir_all(root.join("tests")).unwrap();
1269        // The fixture's one point sits at line 1, column 0, so `work` has to
1270        // start the file: an `export` keyword there would belong to the top
1271        // level, not to the function.
1272        let app = "function work() {\n  return 1;\n}\nfunction idle() {\n  return 2;\n}\n";
1273        let test = "import assert from 'node:assert/strict';\nimport { LIMIT } from '../src/config.js';\nassert.equal(work(), 1);\n";
1274        let config = "export const LIMIT = 5;\nfunction check(n) {\n  return n < LIMIT;\n}\n";
1275        fs::write(root.join("src/app.js"), app).unwrap();
1276        fs::write(root.join("src/config.js"), config).unwrap();
1277        fs::write(root.join("tests/app.test.js"), test).unwrap();
1278        // The fixture run's one point sits at line 1, column 0 of src/app.js
1279        // with a zero-based byte column, which is how every non-JavaScript
1280        // frontend reports; the language is named for that.
1281        let inputs = crate::source_capture::capture(
1282            &root,
1283            "python",
1284            [
1285                "src/app.js".into(),
1286                "src/config.js".into(),
1287                "tests/app.test.js".into(),
1288            ],
1289        )
1290        .unwrap();
1291        let directory = crate::run_store::create_analyzable_test_run(&root, "first");
1292        let path = directory.join("evidence.raw.gz");
1293        let entries = crate::source_capture::append(read_archive(&path).unwrap(), &inputs).unwrap();
1294        let archive = write_archive(entries, &path).unwrap();
1295        let metadata_path = directory.join("run.json");
1296        let mut metadata: RunMetadata =
1297            serde_json::from_slice(&fs::read(&metadata_path).unwrap()).unwrap();
1298        metadata.raw_evidence.files = archive.files;
1299        metadata.raw_evidence.compressed_bytes = archive.compressed_bytes;
1300        metadata.raw_evidence.uncompressed_bytes = archive.uncompressed_bytes;
1301        fs::write(&metadata_path, serde_json::to_vec(&metadata).unwrap()).unwrap();
1302        prepare_publication(&root, &directory, &metadata, None).unwrap();
1303        let run = discover_runs(&root).unwrap().runs.remove(0);
1304        let stored = load_manifest(&run).unwrap();
1305        let executions = &recorded(&run);
1306        let code = stored.manifest.files["src/app.js"].code.as_ref().unwrap();
1307        let work = code.units.iter().position(|u| u.path == "work").unwrap();
1308        let idle = code.units.iter().position(|u| u.path == "idle").unwrap();
1309        assert_eq!(executions.tests.len(), 1);
1310        let record = &executions.tests[0];
1311        assert_eq!(record.test.file, "tests/app.test.js");
1312        assert_eq!(record.test.name, "test");
1313        assert!(record.passed);
1314        assert_eq!(record.files["src/app.js"], vec![work]);
1315        assert_eq!(
1316            executions.probed["src/app.js"],
1317            vec![work],
1318            "idle holds no probe in this run"
1319        );
1320        let _ = idle;
1321
1322        let names = |value: &Value, key: &str| {
1323            value[key]
1324                .as_array()
1325                .unwrap()
1326                .iter()
1327                .map(|t| t["name"].as_str().unwrap().to_owned())
1328                .collect::<Vec<_>>()
1329        };
1330        // Nothing changed.
1331        let report = affected_tests(&root, &run).unwrap();
1332        assert!(names(&report, "affected").is_empty(), "{report}");
1333        assert_eq!(names(&report, "unaffected"), ["test"]);
1334        assert_eq!(report["summary"]["changedFiles"], 0);
1335        // A comment: still nothing.
1336        fs::write(root.join("src/app.js"), format!("// about\n{app}")).unwrap();
1337        let report = affected_tests(&root, &run).unwrap();
1338        assert!(names(&report, "affected").is_empty(), "{report}");
1339        assert_eq!(report["changedFiles"][0]["change"], "formatting");
1340        // A body the test ran: affected, and it says which.
1341        fs::write(
1342            root.join("src/app.js"),
1343            app.replace("return 1;", "return 1 + 0;"),
1344        )
1345        .unwrap();
1346        let report = affected_tests(&root, &run).unwrap();
1347        assert_eq!(names(&report, "affected"), ["test"]);
1348        assert_eq!(
1349            report["affected"][0]["reasons"][0],
1350            "src/app.js: work (line 1) changed (this test ran it)"
1351        );
1352        // A body the test did not run, once idle has a probe of its own: not
1353        // affected. Here idle holds none, so the change is not one that can
1354        // be said to have missed the test, and it counts.
1355        fs::write(
1356            root.join("src/app.js"),
1357            app.replace("return 2;", "return 2 + 0;"),
1358        )
1359        .unwrap();
1360        let report = affected_tests(&root, &run).unwrap();
1361        assert_eq!(names(&report, "affected"), ["test"], "{report}");
1362        assert!(
1363            report["affected"][0]["reasons"][0]
1364                .as_str()
1365                .unwrap()
1366                .contains("this test ran code in this file"),
1367            "{report}"
1368        );
1369        // A declaration added: affected, the file's shape changed.
1370        fs::write(
1371            root.join("src/app.js"),
1372            format!("{app}function more() {{}}\n"),
1373        )
1374        .unwrap();
1375        let report = affected_tests(&root, &run).unwrap();
1376        assert_eq!(names(&report, "affected"), ["test"]);
1377        assert_eq!(report["changedFiles"][0]["change"], "declarations");
1378        // The test file itself.
1379        fs::write(root.join("src/app.js"), app).unwrap();
1380        fs::write(root.join("tests/app.test.js"), test.replace("1)", "2)")).unwrap();
1381        let report = affected_tests(&root, &run).unwrap();
1382        assert_eq!(names(&report, "affected"), ["test"]);
1383        assert!(
1384            report["affected"][0]["reasons"][0]
1385                .as_str()
1386                .unwrap()
1387                .starts_with("test file changed"),
1388            "{report}"
1389        );
1390        // Top-level code in a file the test names but never ran a statement
1391        // of: outside the JVM, not affected (a JVM class's static initializer
1392        // is the case the naming rule is for).
1393        fs::write(root.join("tests/app.test.js"), test).unwrap();
1394        fs::write(root.join("src/config.js"), config.replace("= 5", "= 6")).unwrap();
1395        let report = affected_tests(&root, &run).unwrap();
1396        assert!(names(&report, "affected").is_empty(), "{report}");
1397        fs::write(root.join("src/config.js"), config).unwrap();
1398        // A source file removed.
1399        fs::remove_file(root.join("src/app.js")).unwrap();
1400        let report = affected_tests(&root, &run).unwrap();
1401        assert_eq!(
1402            report["affected"][0]["reasons"][0],
1403            "src/app.js removed (this test ran code in it)"
1404        );
1405        fs::remove_dir_all(root).unwrap();
1406    }
1407
1408    /// h11's `test_receivebuffer.py` for `_receivebuffer.py`, commons-cli's
1409    /// `ConverterTests#testClassDoesNotInitialize` for `Converter.java`.
1410    #[test]
1411    fn a_test_named_like_the_changed_file_comes_first() {
1412        assert_eq!(
1413            words_of("h11/tests/test_receive_buffer.py"),
1414            BTreeSet::from(["receive".to_owned(), "buffer".to_owned()])
1415        );
1416        assert_eq!(
1417            words_of("src/test/java/org/apache/commons/cli/ConverterTests.java"),
1418            BTreeSet::from(["converter".to_owned()])
1419        );
1420        assert_eq!(
1421            split_words("parseHTTPVersion_v2"),
1422            ["parse", "httpversion", "v2"]
1423        );
1424        let changed = words_of("src/main/java/org/apache/commons/cli/Converter.java");
1425        let entry = |file: &str, name: &str| json!({"file": file, "name": name});
1426        assert_eq!(
1427            name_match(
1428                &entry(
1429                    "src/test/java/x/ConverterTests.java",
1430                    "x.ConverterTests#testClass()"
1431                ),
1432                &changed
1433            ),
1434            1
1435        );
1436        assert_eq!(
1437            name_match(
1438                &entry(
1439                    "src/test/java/x/OptionTests.java",
1440                    "x.OptionTests#testConverter()"
1441                ),
1442                &changed
1443            ),
1444            1,
1445            "the test's own name counts too"
1446        );
1447        assert_eq!(
1448            name_match(
1449                &entry(
1450                    "src/test/java/x/OptionTests.java",
1451                    "x.OptionTests#testBuilder()"
1452                ),
1453                &changed
1454            ),
1455            0
1456        );
1457    }
1458
1459    /// apache/commons-cli's `Converter.CLASS`: a static field set in a
1460    /// static initializer credited to whichever test loaded the class first.
1461    /// Its tests are reached by the class's name; a JavaScript module's top
1462    /// level is not.
1463    #[test]
1464    fn a_jvm_class_changed_in_its_declarations_is_reached_by_its_name() {
1465        let java = "package app;\nclass Converter {\n    static final Object CLASS = null;\n    static int size(int n) {\n        return n;\n    }\n}\n";
1466        let before = FileFingerprint::read("src/app/Converter.java", java);
1467        let after = FileFingerprint::read(
1468            "src/app/Converter.java",
1469            &java.replace("CLASS = null", "CLASS = new Object()"),
1470        );
1471        let js = "export const LIMIT = 5;\n";
1472        let js_before = FileFingerprint::read("src/config.js", js);
1473        let js_after = FileFingerprint::read("src/config.js", &js.replace('5', "6"));
1474        let changes = BTreeMap::from([
1475            (
1476                "src/app/Converter.java",
1477                file_change(Some(&before), Some(&after), Some(&[])).unwrap(),
1478            ),
1479            (
1480                "src/config.js",
1481                file_change(Some(&js_before), Some(&js_after), Some(&[])).unwrap(),
1482            ),
1483        ]);
1484        let named = named_by_tests(&changes);
1485        assert_eq!(
1486            named.get("src/app/Converter.java"),
1487            Some(&BTreeSet::from(["Converter".to_owned()]))
1488        );
1489        assert!(!named.contains_key("src/config.js"));
1490        assert!(names_word("assertEquals(Converter.CLASS, x)", "Converter"));
1491        assert!(!names_word("ConverterTests", "Converter"));
1492    }
1493
1494    #[test]
1495    fn a_test_that_ran_beside_others_is_undetermined_rather_than_unaffected() {
1496        // A parallel suite's coverage sits in the record nobody could claim,
1497        // and the tests beside it hold nothing of their own. Reading "this
1498        // test's record does not mention the changed file" as "this test is
1499        // unaffected" would answer `0 of 1 tests affected` for a change to the
1500        // only code the run executed -- and an agent running only the affected
1501        // tests would run nothing. The run's own bound is what stands in.
1502        let root = std::env::temp_dir().join(format!(
1503            "supercov-undetermined-{}-{}",
1504            std::process::id(),
1505            std::time::SystemTime::now()
1506                .duration_since(std::time::UNIX_EPOCH)
1507                .unwrap()
1508                .as_nanos()
1509        ));
1510        let _ = fs::remove_dir_all(&root);
1511        fs::create_dir_all(root.join("src")).unwrap();
1512        fs::create_dir_all(root.join("tests")).unwrap();
1513        let app = "function work() {\n  return 1;\n}\nfunction idle() {\n  return 2;\n}\n";
1514        let test = "import assert from 'node:assert/strict';\nimport { LIMIT } from '../src/config.js';\nassert.equal(work(), 1);\n";
1515        let config = "export const LIMIT = 5;\nfunction check(n) {\n  return n < LIMIT;\n}\n";
1516        fs::write(root.join("src/app.js"), app).unwrap();
1517        fs::write(root.join("src/config.js"), config).unwrap();
1518        fs::write(root.join("tests/app.test.js"), test).unwrap();
1519        let inputs = crate::source_capture::capture(
1520            &root,
1521            "python",
1522            ["src/app.js".into(), "tests/app.test.js".into()],
1523        )
1524        .unwrap();
1525        let directory = crate::run_store::create_run_wide_test_run(&root, "parallel");
1526        let path = directory.join("evidence.raw.gz");
1527        let entries = crate::source_capture::append(read_archive(&path).unwrap(), &inputs).unwrap();
1528        let archive = write_archive(entries, &path).unwrap();
1529        let metadata_path = directory.join("run.json");
1530        let mut metadata: RunMetadata =
1531            serde_json::from_slice(&fs::read(&metadata_path).unwrap()).unwrap();
1532        metadata.raw_evidence.files = archive.files;
1533        metadata.raw_evidence.compressed_bytes = archive.compressed_bytes;
1534        metadata.raw_evidence.uncompressed_bytes = archive.uncompressed_bytes;
1535        fs::write(&metadata_path, serde_json::to_vec(&metadata).unwrap()).unwrap();
1536        prepare_publication(&root, &directory, &metadata, None).unwrap();
1537        let run = discover_runs(&root).unwrap().runs.remove(0);
1538
1539        let executions = &recorded(&run);
1540        assert_eq!(executions.tests.len(), 1, "the named test, not the record");
1541        let record = &executions.tests[0];
1542        assert_eq!(
1543            record.attribution,
1544            crate::coverage_report::ATTRIBUTION_RUN_WIDE
1545        );
1546        assert!(
1547            record.files.is_empty(),
1548            "it is credited with nothing: {:?}",
1549            record.files
1550        );
1551        assert!(
1552            !executions.covered["src/app.js"].is_empty(),
1553            "and the run is credited with what it reached"
1554        );
1555
1556        let bucket = |value: &Value, key: &str| {
1557            value[key]
1558                .as_array()
1559                .unwrap()
1560                .iter()
1561                .map(|t| t["name"].as_str().unwrap().to_owned())
1562                .collect::<Vec<_>>()
1563        };
1564
1565        // Nothing changed: nothing to rerun, and the run's bound says nothing
1566        // either.
1567        let report = affected_tests(&root, &run).unwrap();
1568        assert_eq!(bucket(&report, "unaffected"), ["test"], "{report}");
1569        assert!(bucket(&report, "undetermined").is_empty(), "{report}");
1570
1571        // The one function the run executed changed. The test's own record
1572        // cannot say whether it reached it, and the run's can.
1573        fs::write(
1574            root.join("src/app.js"),
1575            app.replace("return 1;", "return 3;"),
1576        )
1577        .unwrap();
1578        let report = affected_tests(&root, &run).unwrap();
1579        assert!(
1580            bucket(&report, "affected").is_empty(),
1581            "nothing proves it ran the change: {report}"
1582        );
1583        assert_eq!(
1584            bucket(&report, "undetermined"),
1585            ["test"],
1586            "the run reached it, so this test might have: {report}"
1587        );
1588        assert_eq!(
1589            report["undetermined"][0]["attribution"],
1590            crate::coverage_report::ATTRIBUTION_RUN_WIDE,
1591            "{report}"
1592        );
1593        fs::remove_dir_all(root).unwrap();
1594    }
1595
1596    #[test]
1597    fn a_lower_bound_still_proves_what_it_recorded() {
1598        // Ruby's is the other incomplete attribution: the test is credited
1599        // with coverage, and that coverage is a floor rather than the whole of
1600        // what it ran. The floor is still evidence -- a test credited with the
1601        // changed line ran the changed line -- so it is affected outright,
1602        // with its own reason, rather than swept into the bucket for tests
1603        // nothing can say anything about.
1604        let root = std::env::temp_dir().join(format!(
1605            "supercov-partial-{}-{}",
1606            std::process::id(),
1607            std::time::SystemTime::now()
1608                .duration_since(std::time::UNIX_EPOCH)
1609                .unwrap()
1610                .as_nanos()
1611        ));
1612        let _ = fs::remove_dir_all(&root);
1613        fs::create_dir_all(root.join("src")).unwrap();
1614        fs::create_dir_all(root.join("tests")).unwrap();
1615        let app = "function work() {\n  return 1;\n}\nfunction idle() {\n  return 2;\n}\n";
1616        let test = "import assert from 'node:assert/strict';\nimport { LIMIT } from '../src/config.js';\nassert.equal(work(), 1);\n";
1617        let config = "export const LIMIT = 5;\nfunction check(n) {\n  return n < LIMIT;\n}\n";
1618        fs::write(root.join("src/app.js"), app).unwrap();
1619        fs::write(root.join("src/config.js"), config).unwrap();
1620        fs::write(root.join("tests/app.test.js"), test).unwrap();
1621        let inputs = crate::source_capture::capture(
1622            &root,
1623            "python",
1624            ["src/app.js".into(), "tests/app.test.js".into()],
1625        )
1626        .unwrap();
1627        let directory = crate::run_store::create_partial_test_run(&root, "partial");
1628        let path = directory.join("evidence.raw.gz");
1629        let entries = crate::source_capture::append(read_archive(&path).unwrap(), &inputs).unwrap();
1630        let archive = write_archive(entries, &path).unwrap();
1631        let metadata_path = directory.join("run.json");
1632        let mut metadata: RunMetadata =
1633            serde_json::from_slice(&fs::read(&metadata_path).unwrap()).unwrap();
1634        metadata.raw_evidence.files = archive.files;
1635        metadata.raw_evidence.compressed_bytes = archive.compressed_bytes;
1636        metadata.raw_evidence.uncompressed_bytes = archive.uncompressed_bytes;
1637        fs::write(&metadata_path, serde_json::to_vec(&metadata).unwrap()).unwrap();
1638        prepare_publication(&root, &directory, &metadata, None).unwrap();
1639        let run = discover_runs(&root).unwrap().runs.remove(0);
1640
1641        let executions = recorded(&run);
1642        let record = &executions.tests[0];
1643        assert_eq!(
1644            record.attribution,
1645            crate::coverage_report::ATTRIBUTION_PARTIAL
1646        );
1647        assert!(
1648            !record.files.is_empty(),
1649            "a lower bound is coverage it was credited with"
1650        );
1651
1652        let names = |value: &Value, key: &str| {
1653            value[key]
1654                .as_array()
1655                .unwrap()
1656                .iter()
1657                .map(|t| t["name"].as_str().unwrap().to_owned())
1658                .collect::<Vec<_>>()
1659        };
1660        fs::write(
1661            root.join("src/app.js"),
1662            app.replace("return 1;", "return 3;"),
1663        )
1664        .unwrap();
1665        let report = affected_tests(&root, &run).unwrap();
1666        assert_eq!(
1667            names(&report, "affected"),
1668            ["test"],
1669            "what its own record proves, it proves: {report}"
1670        );
1671        assert!(names(&report, "undetermined").is_empty(), "{report}");
1672        // And the reason is its own, not the run's stand-in.
1673        let reasons = report["affected"][0]["reasons"].as_array().unwrap();
1674        assert_eq!(reasons.len(), 1, "{report}");
1675        let reason = reasons[0].as_str().unwrap();
1676        assert!(
1677            reason.contains("this test ran it"),
1678            "the reason is its own: {report}"
1679        );
1680        assert!(
1681            !reason.contains("the run covered"),
1682            "and not the run's stand-in: {report}"
1683        );
1684        fs::remove_dir_all(root).unwrap();
1685    }
1686}