Skip to main content

supercov_engine/
source_manifest.rs

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