Keep source-bundle comparison totals honest under the row cap (R3.12) (#1778) (#1778)

A source-to-bundle comparison with more scripts than max_rows reported the examined window's counts as if they covered the whole tree, and its count of bundle units without a source was the capped row count. It now says how many scripts were examined beside the total, counts every unclaimed unit while still listing at most max_rows, and marks a capped result with a rows_capped limitation and partial coverage.
This commit is contained in:
Alex Joaquim Pereira authored and GitHub committed 2026-11-12 19:46:46 +07:00
1 parent 290c2fde44
commit 664ce030d1
6 files changed
+122 -12

No files matched your search

+23 -8
View File
@@ -335,6 +335,10 @@ struct UncertainSource<'a> {
/// An incomplete source-map inventory (truncated, an unread external section, or a map that
/// couldn't be read) cannot establish that an otherwise unmatched source is absent. Such sources
/// are reported separately in `uncertain_sources`; positive matches remain available.
///
/// At most `max_rows` source scripts are examined and at most `max_rows` rows of each list are
/// kept: `summary.scripts_examined` and `rows_capped` say when the counts cover only that window,
/// while bundle units without an observed source are counted in full.
pub fn diff_source_and_bundle(src: &SourceGraph, app: &AppGraph, max_rows: usize) -> Value {
let mut units: Vec<Unit<'_>> = Vec::new();
for m in app.modules.iter().filter(|m| m.kind == "script") {
@@ -384,7 +388,10 @@ pub fn diff_source_and_bundle(src: &SourceGraph, app: &AppGraph, max_rows: usize
let mut uncertain = Vec::new();
let mut claimed: BTreeSet<usize> = BTreeSet::new();
let mut by_quality: BTreeMap<&str, usize> = BTreeMap::new();
let source_scripts = src.files.iter().filter(|f| is_script(&f.path)).count();
let mut scripts_examined = 0usize;
for f in src.files.iter().filter(|f| is_script(&f.path)).take(max_rows) {
scripts_examined += 1;
let norm = norm_path(&f.path);
let fs: BTreeSet<&str> = f.strings.iter().map(String::as_str).filter(|s| s.len() >= 4).collect();
let ff: BTreeSet<&str> = f.functions.iter().map(String::as_str).collect();
@@ -456,20 +463,28 @@ pub fn diff_source_and_bundle(src: &SourceGraph, app: &AppGraph, max_rows: usize
},
}
}
let unclaimed: Vec<Value> = units
.iter()
.enumerate()
.filter(|(i, u)| !claimed.contains(i) && !u.id.contains("node_modules"))
.map(|(_, u)| json!({"unit": u.id, "file": u.file, "kind": u.kind}))
.take(max_rows)
.collect();
// A unit without a source is counted in full even when only some rows are listed: the list is
// for reading, the count is evidence.
let mut bundle_units_without_source = 0usize;
let mut unclaimed: Vec<Value> = Vec::new();
for (i, u) in units.iter().enumerate() {
if claimed.contains(&i) || u.id.contains("node_modules") {
continue;
}
bundle_units_without_source += 1;
if unclaimed.len() < max_rows {
unclaimed.push(json!({"unit": u.id, "file": u.file, "kind": u.kind}));
}
}
let rows_capped = scripts_examined < source_scripts || bundle_units_without_source > unclaimed.len();
json!({
"source_graph_id": src.source_graph_id,
"graph_id": app.graph_id,
"source_map_inventory_truncated": source_map_inventory_truncated,
"source_map_external_sections": source_map_external,
"source_map_unreadable": source_map_unreadable,
"summary": {"source_scripts": src.files.iter().filter(|f| is_script(&f.path)).count(), "bundle_units": units.len(), "matched": matches.len(), "unmatched_sources": unmatched.len(), "uncertain_sources": uncertain.len(), "bundle_units_without_source": unclaimed.len(), "by_quality": by_quality},
"rows_capped": rows_capped,
"summary": {"source_scripts": source_scripts, "scripts_examined": scripts_examined, "bundle_units": units.len(), "matched": matches.len(), "unmatched_sources": unmatched.len(), "uncertain_sources": uncertain.len(), "bundle_units_without_source": bundle_units_without_source, "by_quality": by_quality},
"matches": matches,
"unmatched_sources": unmatched,
"uncertain_sources": uncertain,
@@ -0,0 +1,50 @@
//! A source-to-bundle comparison that examines only `max_rows` scripts says how many it examined,
//! and the unclaimed-unit count stays complete even when only some rows are listed.
use craft_anything_analysis::js_app::{AppFile, AppGraph, AppInput, AppOptions, analyze_application};
use craft_anything_analysis::js_source::{SourceGraph, build_source_graph, diff_source_and_bundle};
use serde_json::json;
fn app_graph(files: &[(&str, &str)]) -> AppGraph {
let files: Vec<AppFile> = files.iter().map(|(path, src)| AppFile { path: (*path).into(), bytes: src.as_bytes().to_vec() }).collect();
let listing = files.iter().map(|f| (f.path.clone(), f.bytes.len() as u64)).collect();
analyze_application(&AppInput { files, listing, ..Default::default() }, &AppOptions::default(), &|| false).unwrap()
}
fn source_graph(paths: &[&str]) -> SourceGraph {
let files: Vec<_> = paths.iter().map(|path| ((*path).to_string(), Vec::new())).collect();
build_source_graph("reference", &files, 0, false, &Default::default(), &|| false).unwrap()
}
/// A capped comparison examines only the first script but reports that beside the total, and the
/// unclaimed-unit count stays complete even though only one row is listed.
#[test]
fn examined_scripts_and_unclaimed_units_are_counted_in_full() {
let graph = app_graph(&[("a.js", "const a = 1;\n"), ("b.js", "const b = 2;\n"), ("c.js", "const c = 3;\n")]);
let src = source_graph(&["a.js", "b.js"]);
let diff = diff_source_and_bundle(&src, &graph, 1);
let summary = &diff["summary"];
assert_eq!(summary["scripts_examined"], json!(1), "{diff}");
assert_eq!(summary["source_scripts"], json!(2), "{diff}");
assert_eq!(summary["matched"], json!(1), "{diff}");
assert_eq!(summary["unmatched_sources"], json!(0), "{diff}");
assert_eq!(summary["uncertain_sources"], json!(0), "{diff}");
assert_eq!(diff["rows_capped"], json!(true), "{diff}");
// b.js and c.js are unclaimed: the count is complete even though only one row is listed.
assert_eq!(summary["bundle_units_without_source"], json!(2), "{diff}");
assert_eq!(diff["bundle_units_without_source"].as_array().map(Vec::len), Some(1), "{diff}");
}
/// With room for every script, the comparison examines all of them and does not claim a cap.
#[test]
fn an_uncapped_comparison_reports_every_script() {
let graph = app_graph(&[("a.js", "const a = 1;\n"), ("b.js", "const b = 2;\n")]);
let src = source_graph(&["a.js", "b.js"]);
let diff = diff_source_and_bundle(&src, &graph, 10);
let summary = &diff["summary"];
assert_eq!(summary["scripts_examined"], json!(2), "{diff}");
assert_eq!(summary["source_scripts"], json!(2), "{diff}");
assert_eq!(summary["matched"], json!(2), "{diff}");
assert_eq!(summary["bundle_units_without_source"], json!(0), "{diff}");
assert_eq!(diff["rows_capped"], json!(false), "{diff}");
}
+38 -4
View File
@@ -488,7 +488,7 @@ fn default_rows() -> usize {
}
/// Compare a reference source tree with a shipped bundle, carrying a source map's unread external
/// sections into the evidence as uncertainty rather than absent sources.
/// sections and the row cap into the evidence as uncertainty rather than absent sources.
fn compare_source_to_bundle_tool(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError> {
let p: SourceBundleParams = parse_params(params)?;
let (src, sid) = if let Some(path) = is_path_input(&p.source) {
@@ -508,12 +508,14 @@ fn compare_source_to_bundle_tool(ctx: &mut Ctx<'_>, params: Value) -> Result<Too
(g, Some(ev.id))
};
let (app, aid) = load_graph(ctx, &p.application)?;
let d = diff_source_and_bundle(&src, &app, p.max_rows.clamp(1, 100_000));
let max_rows = p.max_rows.clamp(1, 100_000);
let d = diff_source_and_bundle(&src, &app, max_rows);
let s = &d["summary"];
let summary = format!(
"{} of {} source script(s) matched shipped code; {} unmatched; {} uncertain; {} bundle unit(s) with no observed source match.",
s["matched"], s["source_scripts"], s["unmatched_sources"], s["uncertain_sources"], s["bundle_units_without_source"]
"{} of {} source script(s) examined; {} matched; {} unmatched; {} uncertain; {} bundle unit(s) with no observed source match.",
s["scripts_examined"], s["source_scripts"], s["matched"], s["unmatched_sources"], s["uncertain_sources"], s["bundle_units_without_source"]
);
let rows_capped = d["rows_capped"].as_bool().unwrap_or(false);
let inventory_truncated = d["source_map_inventory_truncated"].as_bool().unwrap_or(false);
let map_external = d["source_map_external_sections"].as_bool().unwrap_or(false);
let map_unreadable = d["source_map_unreadable"].as_bool().unwrap_or(false);
@@ -554,6 +556,16 @@ fn compare_source_to_bundle_tool(ctx: &mut Ctx<'_>, params: Value) -> Result<Too
))
.coverage(Coverage { status: CoverageStatus::Partial, ..Default::default() });
}
if rows_capped {
b = b
.limitation(Limitation::new(
"rows_capped",
format!(
"At most {max_rows} source scripts are compared and at most {max_rows} rows are listed; the match counts cover the examined scripts, and bundle units without an observed source are counted in full."
),
))
.coverage(Coverage { status: CoverageStatus::Partial, ..Default::default() });
}
Ok(ToolOutput::evidence(with_links(b, [sid, aid]).build()?))
}
@@ -892,6 +904,28 @@ mod tests {
assert_eq!(c["confidence"], "inferred");
}
/// A comparison that examines one of two scripts says so, marks the rows capped, and carries
/// partial coverage with the limitation.
#[test]
fn source_comparison_discloses_capped_rows_and_examined_scripts() {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("reference");
fx::write_files(&src, &[("src/a.js", "const a = 1;\n".to_string()), ("src/b.js", "const b = 2;\n".to_string())]).unwrap();
let dist = dir.path().join("dist");
fx::write_files(&dist, &[("main.js", "const main = 3;\n".to_string())]).unwrap();
let e = Engine::new(crate::testing::session());
let comparison = call(&e, "js_source_bundle_compare", json!({"source": src, "application": dist, "max_rows": 1})).unwrap();
assert_eq!(comparison["result"]["summary"]["scripts_examined"], 1, "{}", comparison["result"]);
assert_eq!(comparison["result"]["summary"]["source_scripts"], 2);
assert_eq!(comparison["result"]["summary"]["bundle_units_without_source"], 1);
assert_eq!(comparison["result"]["rows_capped"], true);
let limitations = comparison["limitations"].as_array().unwrap();
assert!(limitations.iter().any(|l| l["code"] == "rows_capped"), "{limitations:?}");
assert_eq!(comparison["coverage"]["status"], "partial");
let summary = comparison["summary"].as_str().unwrap();
assert!(summary.contains("1 of 2 source script(s) examined"), "{summary}");
}
#[test]
fn source_comparison_discloses_an_unreadable_map() {
let dir = tempfile::tempdir().unwrap();
+5
View File
@@ -2595,6 +2595,11 @@ Owner: open · Status: in progress
lists without limit.
— claimed: AlexJoaquimPereira, branch bugfix/r3.12-js-fallback-list-bounds
- [x] A source-to-bundle comparison with more scripts than `max_rows` now says how many it examined
(`scripts_examined`), keeps the unclaimed-unit total complete, marks `rows_capped`, and adds a
partial-coverage limitation, so a capped window's counts are never read as totals.
— claimed: AlexJoaquimPereira, branch bugfix/r3.12-source-bundle-compare-totals
### R3.13 Web inspection correctness
Owner: open · Status: in progress
+1
View File
@@ -83,6 +83,7 @@ coverage and secrets passed. The companion CLI was built with locked dependencie
| External source-map sections | An index-map section that points at an external map (`url`) adds no sources here. The parser counts those unread sections, an application graph records them with a `source_map_external_sections` limitation, and a source comparison reports otherwise unmatched sources as uncertain (`source_map_external_sections`) with partial coverage, not as missing; an inline-only map is unchanged, and a sources-only read counts them too. | Format, analysis and engine regressions cover an inline section beside an external one, nested index maps, an inline-only map, the sources-only read, many external sections not spending the source budget, and the comparison's limitation and partial coverage. |
| Unreadable source maps | A map that is malformed, has a data URL that can't be decoded, or is listed but wasn't loaded is marked `unreadable` with a `source_map_unreadable` limitation; a source comparison then reports otherwise unmatched sources as uncertain (`source_map_unreadable`) with partial coverage, not as missing. A map refused only for its mappings or section offsets keeps its `sources` list with a `source_map_mappings_unreadable` limitation, so its sources match and the ones it doesn't name stay missing; mappings that, as far as they decode, name a source past the end of the list, or a section with neither a map nor a URL, or both, still make the map unreadable. A stand-alone `.map` file beside an analysed script (no comment pointing at it) is read like a referenced one, after them, sharing the inventory budget; other `.map` files (game levels, CSS maps, maps beside a page, maps whose script wasn't loaded) stay listed and unread, without affecting the comparison. A map listed as `./path` and loaded as `path` is one map. Graphs saved before the field load as readable. A map too big to be listed in single-file mode still reads as absent. | Analysis regressions cover a malformed map, an unloaded map, a bad data URL and an unloaded stand-alone map, a stand-alone map beside its script whose sources now match, other `.map` files left alone, a `./`-listed map read once, and older saved graphs; another covers bad mappings, unordered sections and bad mappings in a section (it fails on the former analyzer), and a format regression covers `parse_sources`; an engine regression checks the comparison's limitation and partial coverage. |
| Source-map source inventories | Expanded paths are checked before allocation against shared entry and UTF-8 byte limits, keeping complete identities in source order. Defaults retain at most 1,000,000 paths and 64 MiB across indexed sections. Application graphs keep the existing 5,000-path limit per map and share the total budget across maps; omitted paths set `sources_truncated` and a limitation. Source-to-bundle comparisons preserve positive matches and report other sources as `uncertain_sources` with the `source_map_inventory_truncated` reason, separate from confirmed unmatched sources. Tool evidence reports the uncertainty and partial coverage. | Format, analysis and public-tool regressions cover repeated large roots, relative and absolute-looking sources, exact and zero limits, UTF-8 bytes, null and empty names, nested sections, application-wide budgets, older saved graphs, complete inventories, retained matches and row limits. The default-byte and omitted-source diff regressions fail on unchanged production code. |
| Source-bundle comparison row cap | A source-to-bundle comparison examines at most `max_rows` source scripts but reports `scripts_examined` beside the total, counts every bundle unit without an observed source (not just the listed rows), and sets `rows_capped` when either the script window or the row list is cut. The tool adds a `rows_capped` limitation and partial coverage. | Analysis regressions cover a capped window (1 of 2 scripts, two unclaimed units, one listed row) and an uncapped comparison; an engine regression checks the tool's limitation, partial coverage and summary. |
| Source map URL roots | A relative source keeps the empty authority of webpack:/// and file:/// roots. | Generated-position lookups and source lists with scheme roots, an HTTPS directory and a relative directory. |
| Source map root prefixes | A nonempty sourceRoot prefixes every source before URL interpretation, including leading slashes and URL-shaped sources. Empty, absent and null roots preserve the original source identity for compatibility with generated maps. Lookups and recovered source inventories use the same path. | Five regression groups cover root/source combinations, empty/absent/null roots, source indexes and content, and independent roots in indexed maps. Three groups fail against the former prefix logic; relative-root and empty-root compatibility controls pass. |
| Inline maps with URL fragments | Ignore a data URL's fragment during decoding, preserve percent-encoded number signs in the data, and accept case-insensitive data and base64 markers. | Regression cases added: Raw and encoded fragments, mixed-case markers, queries and non-data schemes. |
+5
View File
@@ -602,6 +602,11 @@ the buffer before a real dependency appeared. Discover wrapper bindings first an
recognised dependencies against their limit. Keep the buffer bounded, and test unrelated calls,
forward declarations and more actual dependencies than the limit permits.
**A capped window's counts read as totals.** A source-to-bundle comparison stopped examining after
`max_rows` scripts but put its matched/unmatched counts beside the total script count, and reported
the truncated unclaimed rows as the number of unclaimed units. Report how many were examined, count
totals separately from listed rows, and mark the cap in the result and the tool's limitation.
**A list cap stopped at one parsing path.** The syntax-tree pass bounded `endpoints` and `exposed`,
but the lexer fallback, used for huge, deeply nested or unparsable sources, pushed to both without
a limit, so the path chosen for hostile input was the one that could grow. Apply the same cap to