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