From c76c50c4f5d03ba0386c673ce3cc2063496661a3 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Wed, 2 Dec 2026 23:33:25 +0800 Subject: [PATCH 1/4] fix(cli): enforce the Test gap new-file Budget Closes #758 --- README.md | 1 + crates/cli/src/check.rs | 2 +- crates/cli/src/check/coverage.rs | 73 ++++++++++++++++++++---- crates/cli/src/check/errors.rs | 6 ++ crates/cli/src/commit_measurement.rs | 64 ++++++++++++++++++++- crates/cli/src/diff.rs | 21 ++++--- crates/cli/src/remedy.rs | 8 +++ crates/cli/tests/integration/test_gap.rs | 65 +++++++++++++++++++++ crates/report/HOW-TO.md | 1 + crates/report/src/diff/regressions.rs | 3 + crates/report/src/measurement.rs | 8 +++ crates/report/src/render.rs | 2 +- docs/guide/configuration.md | 4 +- docs/guide/test-gap.md | 8 ++- docs/reference.md | 12 +++- llms.txt | 2 +- 16 files changed, 252 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 101f3921..9b47796d 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ Five core Metrics are calibrated against stratified panels of current public rep Additional independent Metrics and structural checks run in the same pass: - **Test gap**: share of total Production Function mass not executed by tests, read from user-named LCOV or Cobertura XML Coverage reports without running your test suite, listing the heaviest untested functions first ([Test gap guide](./docs/guide/test-gap.md), [ADR 0017](./docs/adr/0017-test-gap-from-coverage-reports.md)). + Set `new_file_budgets.production.test_gap` to enforce the ratio on newly added Production files in `codeint diff`. - **Orphan files**: Production files unreachable from manifest-declared, program-start, and configured `entry_points`, classified as `unreferenced` or `test-only`. - **File size** (opt-in): the share of Production source lines beyond the File size limit set in `file_size.max_source_lines`, with one Oversized file Finding per file over the limit. - **Dependency hygiene**: three independent Metrics (`unused_dependencies`, `unlisted_dependencies`, and `dev_in_production_dependencies`) comparing `package.json`, `Cargo.toml`, `pyproject.toml`, `composer.json`, `pubspec.yaml`, and `go.mod` against imported external packages while excluding standard-library built-ins. diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index 4ec25cb2..0b4adc9a 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -21,7 +21,7 @@ use codeint_report::{ }; mod control_characters; -mod coverage; +pub(crate) mod coverage; mod errors; mod frameworks; mod lowering; diff --git a/crates/cli/src/check/coverage.rs b/crates/cli/src/check/coverage.rs index dfd5b32e..b89b7933 100644 --- a/crates/cli/src/check/coverage.rs +++ b/crates/cli/src/check/coverage.rs @@ -2,6 +2,7 @@ use std::collections::BTreeMap; use std::io::Read; use std::path::{Path, PathBuf}; +use codeint_git::{Snapshot, SnapshotFileLookup}; use codeint_metrics::{ CoverageApplyOutcome, CoverageParseError, MAX_COVERAGE_REPORT_BYTES, NamedCoverageReport, apply_coverage_reports, parse_coverage_report, @@ -60,20 +61,72 @@ pub(crate) fn load_coverage_reports( .iter() .map(|target| { let bytes = read_bounded_coverage_file(repository_root, &target.display, &target.full)?; - let report = parse_coverage_report(&bytes).map_err(|source| { - CheckError::InvalidCoverageReport { - path: target.display.clone(), - source, - } - })?; - Ok(NamedCoverageReport { - path: target.display.clone(), - report, - }) + parse_named_coverage_report(&target.display, &bytes) }) .collect() } +#[derive(Clone, Copy)] +pub(crate) enum NewFileCoverageSource<'a> { + WorkingTree(&'a Path), + Head(&'a Snapshot), +} + +impl NewFileCoverageSource<'_> { + pub(crate) fn load(self, paths: &[String]) -> Result, CheckError> { + match self { + Self::WorkingTree(root) => { + let paths = select_coverage_report_paths(root, root, paths, None); + load_coverage_reports(root, &paths) + } + Self::Head(snapshot) => paths + .iter() + .map(|path| load_head_coverage_report(snapshot, path)) + .collect(), + } + } +} + +fn load_head_coverage_report( + snapshot: &Snapshot, + path: &str, +) -> Result { + let missing = || CheckError::MissingHeadCoverageReport { + path: path.to_owned(), + }; + let normalized = Path::new(path) + .components() + .filter(|part| !matches!(part, std::path::Component::CurDir)) + .map(|part| part.as_os_str().to_string_lossy()) + .collect::>() + .join("/"); + let repo_path = RepoPath::new(normalized).map_err(|_| missing())?; + match snapshot.read_following_symlinks(&repo_path)? { + SnapshotFileLookup::File(bytes) => parse_named_coverage_report(path, &bytes), + SnapshotFileLookup::OutsideRepository => Err(CheckError::CoverageReportOutsideRepository { + path: path.to_owned(), + }), + SnapshotFileLookup::Missing + | SnapshotFileLookup::BrokenSymlink + | SnapshotFileLookup::NotAFile => Err(missing()), + } +} + +fn parse_named_coverage_report( + path: &str, + bytes: &[u8], +) -> Result { + let report = + parse_coverage_report(bytes).map_err(|source| CheckError::InvalidCoverageReport { + path: path.to_owned(), + source, + })?; + Ok(NamedCoverageReport { + path: path.to_owned(), + report, + }) +} + pub(crate) fn apply_loaded_coverage_reports( reports: &[NamedCoverageReport], languages: &mut [MeasuredLanguage], diff --git a/crates/cli/src/check/errors.rs b/crates/cli/src/check/errors.rs index 9ed5c58e..239671b3 100644 --- a/crates/cli/src/check/errors.rs +++ b/crates/cli/src/check/errors.rs @@ -73,6 +73,8 @@ pub(crate) enum CheckError { }, #[error("Coverage report {path:?} does not exist")] MissingCoverageReport { path: String }, + #[error("Coverage report {path:?} does not exist at the selected --head ref")] + MissingHeadCoverageReport { path: String }, #[error("Coverage report {path:?} is outside the Git repository")] CoverageReportOutsideRepository { path: String }, #[error("cannot read Coverage report {path:?}")] @@ -93,6 +95,10 @@ pub(crate) enum CheckError { "budgets.production.test_gap ({budget}) is set, but Test gap is absent; the Test gap Budget needs a Coverage report" )] TestGapBudgetWithoutCoverage { budget: f64 }, + #[error( + "new_file_budgets.production.test_gap is set, but no Coverage report applies to the languages of newly added Production files" + )] + NewFileTestGapBudgetWithoutCoverage, #[error("{config_file}: dialects.{} conflict: {conflict}", conflict.language)] DialectConflict { config_file: ConfigFileKind, diff --git a/crates/cli/src/commit_measurement.rs b/crates/cli/src/commit_measurement.rs index 81d98fbc..e21a1415 100644 --- a/crates/cli/src/commit_measurement.rs +++ b/crates/cli/src/commit_measurement.rs @@ -2,12 +2,13 @@ use std::collections::{BTreeMap, HashSet}; use codeint_config::Configuration; use codeint_git::{CommitId, Repository, ResultCache, Snapshot}; -use codeint_metrics::DependencyHygiene; -use codeint_model::{CodeModel, Metric, RepoPath}; +use codeint_metrics::{DependencyHygiene, TestGap, apply_coverage_reports}; +use codeint_model::{CodeModel, Metric, RepoPath, SourceSet}; use codeint_plugin_host::{PLUGIN_INTERFACE_VERSION, built_in_language_names}; use codeint_report::{CommitMeasurement, CommitMeasurementOptions}; use serde::Serialize; +use crate::check::coverage::NewFileCoverageSource; use crate::check::{ CheckError, LoadedPlugins, LoweringCache, MeasuredSnapshot, SelectedPackage, compute_dependency_hygiene, compute_orphan_files, compute_orphan_files_for_subset, @@ -179,6 +180,7 @@ pub(crate) fn measure_all_languages_with_new_files( configuration: &Configuration, package: Option<&str>, lowering_cache: Option<&LoweringCache>, + coverage_source: NewFileCoverageSource<'_>, ) -> Result< ( Option, @@ -196,6 +198,7 @@ pub(crate) fn measure_all_languages_with_new_files( plugins, configuration, selected.as_ref(), + coverage_source, )?; let measurement = measure_snapshot_to_commit(snapshot, plugins, configuration, selected.as_ref())?; @@ -219,6 +222,7 @@ fn measure_new_files_subset( plugins: &LoadedPlugins, configuration: &Configuration, selected: Option<&SelectedPackage>, + coverage_source: NewFileCoverageSource<'_>, ) -> Result, CheckError> { let orphan_files = compute_orphan_files_for_subset(snapshot, selected, new_files); let models: Vec = snapshot @@ -230,6 +234,23 @@ fn measure_new_files_subset( if models.is_empty() { return Ok(None); } + let test_gap = if configuration + .new_file_budgets + .production_test_gap() + .is_some() + && models.iter().flat_map(|model| &model.files).any(|file| { + file.model.source_set == SourceSet::Production && !file.model.functions.is_empty() + }) { + Some(measure_new_file_test_gap( + snapshot, + new_files, + selected, + coverage_source, + &configuration.coverage_reports, + )?) + } else { + None + }; let metric_plugins = plugins.metric_plugins(); let disabled_hazard_rules = configuration.hazards.disabled_rules_set(); let empty_hygiene = DependencyHygiene::default(); @@ -247,9 +268,48 @@ fn measure_new_files_subset( }, ) .map_err(|error| CheckError::metric_plugin(configuration.config_file(), error))?; + let measurement = match test_gap { + Some(ratio) => measurement.with_new_file_test_gap(ratio), + None => measurement, + }; Ok(Some(measurement)) } +fn measure_new_file_test_gap( + snapshot: &MeasuredSnapshot, + new_files: &HashSet, + selected: Option<&SelectedPackage>, + coverage_source: NewFileCoverageSource<'_>, + coverage_paths: &[String], +) -> Result { + let coverage = coverage_source.load(coverage_paths)?; + let mut models: Vec<_> = snapshot + .languages + .iter() + .map(|language| CodeModel { + files: language.model.files.clone(), + languages: language.model.languages.clone(), + ..CodeModel::default() + }) + .collect(); + apply_coverage_reports(&coverage, &mut models, &snapshot.file_line_counts)?; + for (model, measured) in models.iter_mut().zip(&snapshot.languages) { + model.files.retain(|file| { + file.model.source_set == SourceSet::Production + && new_files.contains(&file.path) + && selected + .is_none_or(|pkg| pkg.matches(measured.model.workspace.package_of(&file.path))) + }); + } + let covered = CodeModel::merge(models.into_iter().filter(|model| { + !model.files.is_empty() && model.languages.iter().any(|facts| facts.has_coverage) + })) + .into_source_sets(); + TestGap::measure(covered.get(SourceSet::Production)) + .map(|test_gap| test_gap.ratio()) + .ok_or(CheckError::NewFileTestGapBudgetWithoutCoverage) +} + fn filter_model_to_new_files( model: &CodeModel, new_files: &HashSet, diff --git a/crates/cli/src/diff.rs b/crates/cli/src/diff.rs index 84c1c994..a716a13b 100644 --- a/crates/cli/src/diff.rs +++ b/crates/cli/src/diff.rs @@ -8,6 +8,7 @@ use codeint_report::{ BaseCommit, CommitMeasurement, DiffReport, DiffReportOptions, Head, HeadCommit, }; +use crate::check::coverage::NewFileCoverageSource; use crate::check::{ CheckError, LoweringCache, PreparedOwnership, SelectedPackage, WorkspaceContext, WorkspaceRef, }; @@ -262,9 +263,7 @@ fn measure_head_with_snapshots( &base_snapshot, &head_snapshot, &rename_map, - request.package, - request.lowering_cache, - request.check_new_file_budgets, + &request, )? { return Ok(MeasuredHead { selected: measured.selected, @@ -313,24 +312,28 @@ fn measure_head_if_new_files( base_snapshot: &Snapshot, head_snapshot: &Snapshot, renames: &RenameMap, - package: Option<&str>, - lowering_cache: &LoweringCache, - enabled: bool, + request: &MeasureHeadRequest<'_>, ) -> Result, CheckError> { - if !enabled { + if !request.check_new_file_budgets { return Ok(None); } let new_files = newly_added_files(base_snapshot, head_snapshot, renames); if new_files.is_empty() { return Ok(None); } + let coverage_source = if request.head_commit.is_some() { + NewFileCoverageSource::Head(head_snapshot) + } else { + NewFileCoverageSource::WorkingTree(context.repository.root()) + }; let (selected, measurement, new_files) = measure_all_languages_with_new_files( head_snapshot, &new_files, context.plugins, context.configuration, - package, - Some(lowering_cache), + request.package, + Some(request.lowering_cache), + coverage_source, )?; Ok(Some(NewFilesHeadMeasurement { selected, diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 6036bfe0..287bacf8 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -262,6 +262,9 @@ fn coverage_check_remedy(error: &CheckError) -> Option<&'static str> { CheckError::MissingCoverageReport { .. } => { "Check that the Coverage report path exists and generate it with your test runner before running codeint check." } + CheckError::MissingHeadCoverageReport { .. } => { + "Commit the Coverage report at the configured path in the selected head ref." + } CheckError::CoverageReportOutsideRepository { .. } => { "Pass a Coverage report file inside the Git repository; codeint refuses paths and symbolic links outside the repository." } @@ -277,6 +280,9 @@ fn coverage_check_remedy(error: &CheckError) -> Option<&'static str> { CheckError::TestGapBudgetWithoutCoverage { .. } => { "Name at least one LCOV or Cobertura XML Coverage report in coverage_reports or pass --coverage-report , or remove budgets.production.test_gap." } + CheckError::NewFileTestGapBudgetWithoutCoverage => { + "Name an LCOV or Cobertura XML report for the measured head in coverage_reports, or remove new_file_budgets.production.test_gap." + } _ => return None, }) } @@ -297,11 +303,13 @@ fn check_plugin_remedy(error: &CheckError) -> Cow<'static, str> { CheckError::ExtensionConflict { .. } | CheckError::UnknownWorkspacePackage { .. } | CheckError::MissingCoverageReport { .. } + | CheckError::MissingHeadCoverageReport { .. } | CheckError::CoverageReportOutsideRepository { .. } | CheckError::UnreadableCoverageReport { .. } | CheckError::InvalidCoverageReport { .. } | CheckError::CoverageApply(_) | CheckError::TestGapBudgetWithoutCoverage { .. } + | CheckError::NewFileTestGapBudgetWithoutCoverage | CheckError::DialectConflict { .. } | CheckError::UnknownHazardRule { .. } | CheckError::StateFile(_) diff --git a/crates/cli/tests/integration/test_gap.rs b/crates/cli/tests/integration/test_gap.rs index efda600a..b09c23a2 100644 --- a/crates/cli/tests/integration/test_gap.rs +++ b/crates/cli/tests/integration/test_gap.rs @@ -660,6 +660,71 @@ fn test_gap_budget_passes_under_and_equal_fails_over_with_full_report_and_reject } } +#[test] +fn diff_enforces_test_gap_budget_on_new_production_files() { + let repo = init_git_repo(&[ + ( + "codeint.json", + r#"{ + "coverage_reports": ["coverage/ignored.info"], + "new_file_budgets": { "production": { "test_gap": 0 } } + }"#, + ), + (".gitignore", "/coverage/ignored.info\n"), + ("src/legacy.py", "def legacy():\n return 1\n"), + ]); + let root = repo.path(); + let diff = &["diff", "main", "--format", "json"]; + let report = "coverage/ignored.info"; + let legacy_only = "SF:src/legacy.py\nDA:2,1\nend_of_record\n"; + write_file(root, report, legacy_only); + write_file(root, "src/worker.py", "def run():\n return 2\n"); + + let (check, _) = check_json(root, &[], 0); + let findings = &prod_test_gap(&check)["findings"]; + assert_eq!(findings[0]["path"], "src/worker.py"); + assert_eq!(findings[0]["untested_share"], 1.0); + + let (failure, stderr) = run_json(root, diff, None, 1); + assert_eq!( + failure["over_new_file_budget"], + json!([{ "source_set": "production", "metric": "test_gap", "ratio": 1.0, + "budget": 0.0, "files": 1 }]) + ); + assert!( + stderr.contains("the new-file production test_gap ratio 1 is over its new-file Budget 0"), + "{stderr}" + ); + + crate::common::run_git(root, &["switch", "-c", "feature"]); + crate::common::commit_all(root, "add worker"); + let committed_diff = &["diff", "main", "--head", "feature", "--format", "json"]; + let missing = run_codeint(root, committed_diff, None); + assert_eq!(missing.status.code(), Some(2)); + let stderr = String::from_utf8_lossy(&missing.stderr); + assert!( + stderr.contains( + "Coverage report \"coverage/ignored.info\" does not exist at the selected --head ref" + ), + "{stderr}" + ); + + crate::common::run_git(root, &["add", "-f", report]); + crate::common::commit_all(root, "record head coverage"); + write_file(root, report, "SF:src/worker.py\nDA:2,1\nend_of_record\n"); + let (clean, _) = run_json(root, diff, None, 0); + assert!(clean.get("over_new_file_budget").is_none()); + let (committed, _) = run_json(root, committed_diff, None, 1); + assert_eq!( + committed["over_new_file_budget"], + failure["over_new_file_budget"] + ); + fs::remove_file(root.join(report)).expect("remove working-tree Coverage report"); + write_file(root, "src/legacy.py", "def legacy():\n return 3\n"); + let (no_new_files, _) = run_json(root, &["diff", "HEAD", "--format", "json"], None, 0); + assert!(no_new_files.get("over_new_file_budget").is_none()); +} + #[test] fn diff_trend_and_result_cache_handle_coverage_reports_and_emit_one_line_note_only_when_named() { let repo = init_git_repo(&[ diff --git a/crates/report/HOW-TO.md b/crates/report/HOW-TO.md index 6e56f3b7..68eb8ce8 100644 --- a/crates/report/HOW-TO.md +++ b/crates/report/HOW-TO.md @@ -59,6 +59,7 @@ let measurement = CommitMeasurement::of(model); - `CommitMeasurement::of` splits the `CodeModel` by Source set and records the ratios, numerators, and worst-first Findings for all four Metrics. - `CommitMeasurement` derives `Serialize` and `Deserialize`, so callers can cache it per commit in `codeint_git::ResultCache`. +- Apply `with_new_file_test_gap` only to the uncached subset measurement passed as `DiffReportOptions::new_files`. - Pass `CommitMeasurement` values into `DiffReport::compare` or `TrendReport::of`. ## Compare two snapshots with `DiffReport` diff --git a/crates/report/src/diff/regressions.rs b/crates/report/src/diff/regressions.rs index 22121a75..d5b39150 100644 --- a/crates/report/src/diff/regressions.rs +++ b/crates/report/src/diff/regressions.rs @@ -89,6 +89,9 @@ fn source_set_measurement_ratios(measurement: &SourceSetMeasurement) -> Vec<(&st if let Some(hazards) = &measurement.hazards { ratios.push((Metric::Hazards.key(), hazards.ratio)); } + if let Some(test_gap) = measurement.new_file_test_gap { + ratios.push((Metric::TestGap.key(), test_gap)); + } for (key, external) in &measurement.external_metrics { ratios.push((key.as_str(), external.measurement.ratio)); } diff --git a/crates/report/src/measurement.rs b/crates/report/src/measurement.rs index d0b14f97..57da3f1c 100644 --- a/crates/report/src/measurement.rs +++ b/crates/report/src/measurement.rs @@ -65,6 +65,8 @@ pub(crate) struct SourceSetMeasurement { pub(crate) file_size: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) hazards: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) new_file_test_gap: Option, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(crate) external_metrics: BTreeMap, } @@ -239,6 +241,11 @@ impl CommitMeasurement { self } + pub fn with_new_file_test_gap(mut self, ratio: f64) -> CommitMeasurement { + self.production.new_file_test_gap = Some(ratio); + self + } + pub(crate) fn manifest_warnings(&self) -> &[String] { &self.manifest_warnings } @@ -504,6 +511,7 @@ impl SourceSetMeasurement { .collect(); Ok(SourceSetMeasurement { files: model.files.len(), + new_file_test_gap: None, erosion: MetricMeasurement::from_items( measured.erosion.ratio(), measured.erosion.eroded_function_mass(), diff --git a/crates/report/src/render.rs b/crates/report/src/render.rs index a3141757..44a9fd94 100644 --- a/crates/report/src/render.rs +++ b/crates/report/src/render.rs @@ -23,7 +23,7 @@ pub(crate) const TEST_GAP_NO_LANGUAGE_COVERAGE_NOTE: &str = "Test gap is not measured because no named Coverage report covers this language."; pub(crate) const TEST_GAP_NO_REPO_COVERAGE_NOTE: &str = "Test gap is not measured because no named Coverage report covers any measured language."; -pub(crate) const TEST_GAP_DIFF_NOTE: &str = "Test gap is left out of codeint diff because a Coverage report exists only for the code under measurement."; +pub(crate) const TEST_GAP_DIFF_NOTE: &str = "Test gap is left out of the base and head comparison. The Production new-file Budget uses the head Coverage report."; pub(crate) const TEST_GAP_TREND_NOTE: &str = "Test gap is left out of codeint trend because a Coverage report exists only for the code under measurement."; #[derive(Debug, thiserror::Error)] diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 6a34778e..b939c38b 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -156,13 +156,15 @@ If your config file pins an official schema tag newer than the running binary, c - **`new_file_budgets`**: per-Source-set maximum ratios (`0` to `1`) enforced by `codeint diff` solely across newly added files (present on the head side and absent at the merge-base), so teams with legacy debt can keep new code clean. Stays silent when no new files were added. Accepts the same per-Source-set keys as `budgets` (`orphan_files` and `test_gap` under `production` only, plus external Metric keys) and rejects repository-wide Dependency hygiene keys or Production-only keys outside `production` with exit code `2`. + For `production.test_gap`, name the head coverage in `coverage_reports`. + A working-tree diff reads the reports from disk, and `--head ` reads them from the selected ref. - **`regression_limits`**: per-Metric or per-Source-set tolerances for `codeint diff`, plus an opt-in `per_file` check (`false` by default). Set `per_file: true` to compare file-level Metric numerators and Findings for every modified file so `codeint diff` fails whenever any individual modified file worsens, even if another file deleted a larger Finding. Keep `per_file: false` (the default) when you want moving an unchanged function between files to pass. `ratio_rise` defaults to `0.01`; `new_findings` accepts `any_new_finding`, `numerator_rise` (with `numerator_rise_with_new_findings` retained as a deprecated 0.x alias), or `never`. By default, `erosion`, `cognitive_complexity`, `duplication`, `verbosity`, and external Metrics use `numerator_rise` (failing whenever the numerator rises, rounded to 4 decimal places, while keeping the `0.01` `ratio_rise` buffer when the numerator is flat), whereas `import_cycles`, `boundaries`, `orphan_files`, `hazards`, `unused_dependencies`, `unlisted_dependencies`, and `dev_in_production_dependencies` fail on `any_new_finding` (plus numerator rise). Setting `orphan_files` under `regression_limits.test`, `regression_limits.generated`, or `regression_limits.vendored` stops the run with exit code `2`, because Orphan files applies to the Production Source set only. - Setting `test_gap` under `regression_limits` stops the run with exit code `2`, because `codeint diff` leaves Test gap out. + Setting `test_gap` under `regression_limits` stops the run with exit code `2`, because the base and head comparison omits Test gap. - **`dialects`**: map folders or file globs under `dialects.` (for example `dialects.sql`) to Dialect names exported by that Language plugin (`postgresql`, `mysql`, `sqlite`, or `duckdb` for SQL); unmatched files use the plugin's default Dialect (generic SQL for `sql`). See [SQL](./sql.md). - **`hazards`**: list Hazard line rule names under `hazards.disabled_rules` to turn them off across the repository. diff --git a/docs/guide/test-gap.md b/docs/guide/test-gap.md index dea59fe3..698ff41b 100644 --- a/docs/guide/test-gap.md +++ b/docs/guide/test-gap.md @@ -235,7 +235,13 @@ When `--coverage-report` is present on the command line, it replaces `coverage_r - **Missing Coverage report with a Budget**: If `budgets.production.test_gap` is set and Test gap is absent, codeint stops the run with exit code `2` and reports that the Budget needs a Coverage report. A CI job that lost its Coverage report never passes silently. - **Invalid Budget or Regression keys**: Setting `test_gap` under `budgets.test`, `budgets.generated`, or `budgets.vendored`, or anywhere under `regression_limits`, stops the run with exit code `2` and names the key. -- **`codeint diff` and `codeint trend`**: Neither command computes Test gap, because a Coverage report exists only for the code under measurement and not for the merge-base or past commits. +- **New-file Budget**: Set `new_file_budgets.production.test_gap` to enforce Test gap on newly added Production files in `codeint diff`. + Name the Coverage reports in `coverage_reports`. + With `--head `, commit the reports at the configured paths in that ref. + With a working-tree diff, keep the reports on disk. + A missing report at the selected head or a lack of applicable coverage stops the Budget check with exit code `2`. + See [New-file Budgets](../reference.md#new-file-budgets). +- **History**: The base and head comparison in `codeint diff` and all commits in `codeint trend` omit Test gap. When a Coverage report is named, both commands print one line stating that Test gap is left out. See [docs/reference.md#test-gap](../reference.md#test-gap) for every CLI flag, schema key, security bound, and report field. diff --git a/docs/reference.md b/docs/reference.md index edd94e05..dbabd735 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -430,7 +430,8 @@ Commits added to the base branch after your branch started are not part of the c Both sides use the configuration file of the working tree, so the comparison shows changes in the code, not in the configuration. Both sides follow the same file rules as `codeint check`. -`codeint diff` computes Test gap for neither side; when a Coverage report is named, it prints one line stating that Test gap is left out because a Coverage report exists only for the code under measurement. +`codeint diff` measures Test gap only for the Production [new-file Budget](#new-file-budgets). +When a Coverage report is named, the report explains that Test gap is left out of the base and head comparison. The report classifies each Finding by its `id`, surrounding-line context anchors, and detected file renames: new when only the head side has it, resolved when only the merge-base has it, and unchanged when both have it. By default (`--rename-threshold 50`), `codeint diff` detects exact and similar file renames in process (for both the working tree and `--head`), keeps pre-existing Findings in renamed files classified as unchanged and hidden by `.codeint/baseline.json`, excludes rename destinations from `new_file_budgets`, and remaps `per_file` base numerators across renames. @@ -1441,6 +1442,13 @@ codeint: the production erosion ratio 0.7986 is over its Budget 0.2 `new_file_budgets` sets stricter per-Source-set Budgets that `codeint diff` enforces solely across files present in the head snapshot and absent at the merge-base. When a change adds no new files, `new_file_budgets` stays silent and adds no failures. Repository-wide Dependency hygiene keys are not allowed under `new_file_budgets`, and `orphan_files` and `test_gap` are accepted under `new_file_budgets.production` only; setting them under another Source set stops the run with exit code 2. + +`new_file_budgets.production.test_gap` uses the named `coverage_reports` to measure Test gap across newly added Production files. +For a working-tree diff, codeint reads the reports from disk, including files Git ignores. +For `codeint diff --head `, codeint reads the reports at the configured paths from the selected head ref. +If the selected head ref lacks a named report, codeint exits with code 2 and names the missing path. +If new Production files need measurement and no report covers any of their languages, codeint exits with code 2. + When a Metric across the newly added files exceeds its new-file Budget, `codeint diff` writes the full report, lists each failure under `over_new_file_budget` (and under `runs[0].properties.newFileBudgetFailures` in SARIF), names it on standard error, and exits with code 1: ```json codeint.json @@ -1513,7 +1521,7 @@ codeint: file src/route.ts regressed in production erosion: eroded_function_mass When `per_file` is `true`, each modified file is checked against its own base file-level numerator (and new Findings when `new_findings` is `any_new_finding`), while Metrics configured with `new_findings: "never"` skip per-file checks. Unmodified files and modified files that improve or stay equal pass. Setting `orphan_files` under `regression_limits.test`, `regression_limits.generated`, or `regression_limits.vendored` stops the run with exit code 2 and names the key, because Orphan files applies to the Production Source set only (use `regression_limits.orphan_files` or `regression_limits.production.orphan_files`). -Setting `test_gap` under `regression_limits` (at the top level or under any Source set) stops the run with exit code 2 and names the key, because `codeint diff` leaves Test gap out. +Setting `test_gap` under `regression_limits` (at the top level or under any Source set) stops the run with exit code 2 and names the key, because the base and head comparison omits Test gap. An invalid limit stops the run with exit code 2 and names the key: diff --git a/llms.txt b/llms.txt index d9752ce6..1e752e63 100644 --- a/llms.txt +++ b/llms.txt @@ -10,7 +10,7 @@ - [Getting Started](docs/guide/getting-started.md): install codeint, initialize `codeint.jsonc`, and run `check`, `diff`, `ratchet update`, `baseline update`, `trend`, `doctor`, `plugin test`, `config`, `report`, `guard`, `trace`, `impact`, `churn`, `coupling`, and `update`. - [Configuration](docs/guide/configuration.md): configure `codeint.{json,jsonc,toml,yaml,yml}` or `.codeint/config.{json,jsonc,toml,yaml,yml}` default output `format`, Budgets, new-file Budgets, Regression limits (including opt-in `per_file` checks), Ratchet path, Source sets, architectural boundaries, near-clones, entry points, dependency hygiene, Coverage reports, SQL Dialects, Hazards disabled rules, and multi-language folders, plus `codeint config --resolved`. - [Import boundaries](docs/guide/import-boundaries.md): define architectural zones, `public_files` encapsulation, built-in `layered` and `hexagonal` presets, `allow_external` and `deny_external` third-party package glob rules, and pre-edit `codeint guard` checks. -- [Test gap](docs/guide/test-gap.md): measure untested Production Function mass from LCOV and Cobertura XML Coverage reports, set up each test tool, and enforce a Test gap Budget. +- [Test gap](docs/guide/test-gap.md): measure untested Production Function mass from LCOV and Cobertura XML Coverage reports, set up each test tool, and enforce a Test gap Budget in `check` or a new-file Budget in `diff`. - [Hazards](docs/guide/hazards.md): measure Hazard lines next to Software entropy with strict non-leakage, disable named rules, and enforce Budgets and Regression limits. - [Built-in Languages](docs/guide/languages.md): TypeScript/JavaScript/Vue/Svelte, Rust, PHP, Dart, Python, Go, SQL, and Shell rules, function names, cognitive complexity, manifests, and calibrated Reference ranges. - [Go Guide](docs/guide/go.md): Go terminology mapping, Source sets, Flagged line rules, multi-file Go package imports, entry points, and `go.mod` Dependency hygiene. From b67a0c4a6d91d02b86b5008f62a65cafc147356c Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Wed, 2 Dec 2026 23:48:33 +0800 Subject: [PATCH 2/4] fix(cli): close coverage gaps in diff Budget checks --- crates/cli/src/check/coverage.rs | 26 +++++-- crates/cli/src/commit_measurement.rs | 16 ++-- crates/cli/src/remedy.rs | 1 + crates/cli/tests/integration/test_gap.rs | 57 +++++++++++--- crates/git/HOW-TO.md | 2 + crates/git/src/lib.rs | 6 ++ crates/git/src/snapshot_lookup.rs | 99 ++++++++++++++++++------ crates/git/src/tests.rs | 15 ++++ crates/report/src/diff.rs | 15 +++- crates/report/src/diff/regressions.rs | 12 ++- crates/report/src/measurement.rs | 23 ++++-- crates/report/src/render.rs | 2 +- 12 files changed, 213 insertions(+), 61 deletions(-) diff --git a/crates/cli/src/check/coverage.rs b/crates/cli/src/check/coverage.rs index b89b7933..6f6175f0 100644 --- a/crates/cli/src/check/coverage.rs +++ b/crates/cli/src/check/coverage.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use std::io::Read; use std::path::{Path, PathBuf}; -use codeint_git::{Snapshot, SnapshotFileLookup}; +use codeint_git::{GitError, Snapshot, SnapshotFileLookup}; use codeint_metrics::{ CoverageApplyOutcome, CoverageParseError, MAX_COVERAGE_REPORT_BYTES, NamedCoverageReport, apply_coverage_reports, parse_coverage_report, @@ -101,14 +101,26 @@ fn load_head_coverage_report( .collect::>() .join("/"); let repo_path = RepoPath::new(normalized).map_err(|_| missing())?; - match snapshot.read_following_symlinks(&repo_path)? { - SnapshotFileLookup::File(bytes) => parse_named_coverage_report(path, &bytes), - SnapshotFileLookup::OutsideRepository => Err(CheckError::CoverageReportOutsideRepository { + match snapshot.read_following_symlinks_bounded(&repo_path, MAX_COVERAGE_REPORT_BYTES as u64) { + Err(GitError::FileTooLarge { size_bytes, .. }) => Err(CheckError::InvalidCoverageReport { path: path.to_owned(), + source: CoverageParseError::ReportTooLarge { + size_bytes: usize::try_from(size_bytes).unwrap_or(usize::MAX), + max_bytes: MAX_COVERAGE_REPORT_BYTES, + }, }), - SnapshotFileLookup::Missing - | SnapshotFileLookup::BrokenSymlink - | SnapshotFileLookup::NotAFile => Err(missing()), + Err(error) => Err(error.into()), + Ok(SnapshotFileLookup::File(bytes)) => parse_named_coverage_report(path, &bytes), + Ok(SnapshotFileLookup::OutsideRepository) => { + Err(CheckError::CoverageReportOutsideRepository { + path: path.to_owned(), + }) + } + Ok( + SnapshotFileLookup::Missing + | SnapshotFileLookup::BrokenSymlink + | SnapshotFileLookup::NotAFile, + ) => Err(missing()), } } diff --git a/crates/cli/src/commit_measurement.rs b/crates/cli/src/commit_measurement.rs index e21a1415..d75d7706 100644 --- a/crates/cli/src/commit_measurement.rs +++ b/crates/cli/src/commit_measurement.rs @@ -269,7 +269,9 @@ fn measure_new_files_subset( ) .map_err(|error| CheckError::metric_plugin(configuration.config_file(), error))?; let measurement = match test_gap { - Some(ratio) => measurement.with_new_file_test_gap(ratio), + Some((ratio, unmatched_paths)) => { + measurement.with_new_file_test_gap(ratio, unmatched_paths) + } None => measurement, }; Ok(Some(measurement)) @@ -281,7 +283,7 @@ fn measure_new_file_test_gap( selected: Option<&SelectedPackage>, coverage_source: NewFileCoverageSource<'_>, coverage_paths: &[String], -) -> Result { +) -> Result<(f64, Vec), CheckError> { let coverage = coverage_source.load(coverage_paths)?; let mut models: Vec<_> = snapshot .languages @@ -292,7 +294,7 @@ fn measure_new_file_test_gap( ..CodeModel::default() }) .collect(); - apply_coverage_reports(&coverage, &mut models, &snapshot.file_line_counts)?; + let outcome = apply_coverage_reports(&coverage, &mut models, &snapshot.file_line_counts)?; for (model, measured) in models.iter_mut().zip(&snapshot.languages) { model.files.retain(|file| { file.model.source_set == SourceSet::Production @@ -302,11 +304,15 @@ fn measure_new_file_test_gap( }); } let covered = CodeModel::merge(models.into_iter().filter(|model| { - !model.files.is_empty() && model.languages.iter().any(|facts| facts.has_coverage) + model + .files + .iter() + .any(|file| !file.model.functions.is_empty()) + && model.languages.iter().any(|facts| facts.has_coverage) })) .into_source_sets(); TestGap::measure(covered.get(SourceSet::Production)) - .map(|test_gap| test_gap.ratio()) + .map(|test_gap| (test_gap.ratio(), outcome.unmatched_paths)) .ok_or(CheckError::NewFileTestGapBudgetWithoutCoverage) } diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 287bacf8..87d45f5e 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -501,6 +501,7 @@ pub(crate) fn git_remedy(error: &GitError) -> &'static str { GitError::Read { .. } => { "Check that you have permission to read the file, then run codeint again." } + GitError::FileTooLarge { .. } => "Reduce the file size to the stated limit.", GitError::UnknownRef { .. } => { "Pass a branch, tag, or commit that exists in this repository; fetch it first when it lives on a remote: git fetch origin main" } diff --git a/crates/cli/tests/integration/test_gap.rs b/crates/cli/tests/integration/test_gap.rs index b09c23a2..f9413dae 100644 --- a/crates/cli/tests/integration/test_gap.rs +++ b/crates/cli/tests/integration/test_gap.rs @@ -660,22 +660,21 @@ fn test_gap_budget_passes_under_and_equal_fails_over_with_full_report_and_reject } } +const NEW_FILE_TEST_GAP_CONFIG: &str = r#"{ + "coverage_reports": ["coverage/lcov.info"], + "new_file_budgets": { "production": { "test_gap": 0 } } +}"#; + #[test] fn diff_enforces_test_gap_budget_on_new_production_files() { let repo = init_git_repo(&[ - ( - "codeint.json", - r#"{ - "coverage_reports": ["coverage/ignored.info"], - "new_file_budgets": { "production": { "test_gap": 0 } } - }"#, - ), - (".gitignore", "/coverage/ignored.info\n"), + ("codeint.json", NEW_FILE_TEST_GAP_CONFIG), + (".gitignore", "/coverage/lcov.info\n"), ("src/legacy.py", "def legacy():\n return 1\n"), ]); let root = repo.path(); let diff = &["diff", "main", "--format", "json"]; - let report = "coverage/ignored.info"; + let report = "coverage/lcov.info"; let legacy_only = "SF:src/legacy.py\nDA:2,1\nend_of_record\n"; write_file(root, report, legacy_only); write_file(root, "src/worker.py", "def run():\n return 2\n"); @@ -704,16 +703,26 @@ fn diff_enforces_test_gap_budget_on_new_production_files() { let stderr = String::from_utf8_lossy(&missing.stderr); assert!( stderr.contains( - "Coverage report \"coverage/ignored.info\" does not exist at the selected --head ref" + "Coverage report \"coverage/lcov.info\" does not exist at the selected --head ref" ), "{stderr}" ); crate::common::run_git(root, &["add", "-f", report]); crate::common::commit_all(root, "record head coverage"); - write_file(root, report, "SF:src/worker.py\nDA:2,1\nend_of_record\n"); + write_file( + root, + report, + "SF:src/worker.py\nDA:2,1\nend_of_record\nSF:missing.py\nDA:1,0\nend_of_record\n", + ); let (clean, _) = run_json(root, diff, None, 0); assert!(clean.get("over_new_file_budget").is_none()); + assert!( + clean["test_gap_note"] + .as_str() + .expect("Test gap note") + .contains("Coverage report path matched no repository file unambiguously: missing.py.") + ); let (committed, _) = run_json(root, committed_diff, None, 1); assert_eq!( committed["over_new_file_budget"], @@ -725,6 +734,32 @@ fn diff_enforces_test_gap_budget_on_new_production_files() { assert!(no_new_files.get("over_new_file_budget").is_none()); } +#[test] +fn diff_test_gap_requires_coverage_for_a_language_with_new_production_functions() { + let repo = init_git_repo(&[ + ("codeint.json", NEW_FILE_TEST_GAP_CONFIG), + ("src/legacy.ts", "export const legacy = 1;\n"), + ( + "coverage/lcov.info", + "SF:src/legacy.ts\nDA:1,1\nend_of_record\n", + ), + ]); + let root = repo.path(); + let diff = &["diff", "main", "--format", "json"]; + write_file(root, "src/constants.ts", "export const value = 2;\n"); + let (without_functions, _) = run_json(root, diff, None, 0); + assert!(without_functions.get("over_new_file_budget").is_none()); + + write_file(root, "src/worker.py", "def run():\n return 2\n"); + let missing = run_codeint(root, diff, None); + let stderr = String::from_utf8_lossy(&missing.stderr); + assert_eq!(missing.status.code(), Some(2), "{stderr}"); + assert!( + stderr.contains("new_file_budgets.production.test_gap"), + "{stderr}" + ); +} + #[test] fn diff_trend_and_result_cache_handle_coverage_reports_and_emit_one_line_note_only_when_named() { let repo = init_git_repo(&[ diff --git a/crates/git/HOW-TO.md b/crates/git/HOW-TO.md index 4b128b2f..88c09790 100644 --- a/crates/git/HOW-TO.md +++ b/crates/git/HOW-TO.md @@ -52,6 +52,8 @@ let bytes = local.read(path)?; - A commit `Snapshot` follows the same rules as the working tree: regular and executable files are files, symbolic links are left out, and submodules are listed. - Measure both `Snapshot` values with the same code; the caller never knows which kind it holds. - Use `Snapshot::read_following_symlinks` or `Repository::read_working_tree_file_following_symlinks` when reading a specific repository-contained state or configuration file (such as `.codeint/ratchet.json`) across commits or the working tree; both run the same component-by-component symlink walker within repository containment (`SnapshotFileLookup::{Missing, File, OutsideRepository, BrokenSymlink, NotAFile}`) while leaving `Snapshot::files()` limited to regular files. +- Use `Snapshot::read_following_symlinks_bounded` when the caller has a byte limit. + A committed blob over the limit returns `GitError::FileTooLarge` before its contents are read. - `CommitId` displays as the full hexadecimal object id; use it to name the commit in a report or a cache key. ## Read the merge-base of two refs diff --git a/crates/git/src/lib.rs b/crates/git/src/lib.rs index 2100ede7..4e9e9a85 100644 --- a/crates/git/src/lib.rs +++ b/crates/git/src/lib.rs @@ -97,6 +97,12 @@ pub enum GitError { #[source] source: gix::Error, }, + #[error("{path} is {size_bytes} bytes, exceeding the {max_bytes}-byte limit")] + FileTooLarge { + path: RepoPath, + size_bytes: u64, + max_bytes: u64, + }, } const HEAD: &str = "HEAD"; diff --git a/crates/git/src/snapshot_lookup.rs b/crates/git/src/snapshot_lookup.rs index ca212685..64743cc3 100644 --- a/crates/git/src/snapshot_lookup.rs +++ b/crates/git/src/snapshot_lookup.rs @@ -1,4 +1,5 @@ use std::collections::VecDeque; +use std::io::Read; use std::path::{Path, PathBuf}; use codeint_model::RepoPath; @@ -23,17 +24,35 @@ impl Repository { path: &RepoPath, ) -> Result { let index = self.repository.index_or_empty().map_err(GitError::Walk)?; - read_working_tree_file(&self.root, &index, path) + read_working_tree_file(&self.root, &index, path, None) } } impl Snapshot { pub fn read_following_symlinks(&self, path: &RepoPath) -> Result { + self.read_path_following_symlinks(path, None) + } + + pub fn read_following_symlinks_bounded( + &self, + path: &RepoPath, + max_bytes: u64, + ) -> Result { + self.read_path_following_symlinks(path, Some(max_bytes)) + } + + fn read_path_following_symlinks( + &self, + path: &RepoPath, + max_bytes: Option, + ) -> Result { match &self.contents { - Contents::WorkingTree { root, index, .. } => read_working_tree_file(root, index, path), + Contents::WorkingTree { root, index, .. } => { + read_working_tree_file(root, index, path, max_bytes) + } Contents::Commit { repository, commit, .. - } => read_commit_file(&repository.to_thread_local(), *commit, path), + } => read_commit_file(&repository.to_thread_local(), *commit, path, max_bytes), } } } @@ -62,6 +81,25 @@ struct CommitTree<'a> { commit: CommitId, root_tree: &'a gix::Tree<'a>, requested_path: &'a RepoPath, + max_bytes: Option, +} + +impl CommitTree<'_> { + fn read_blob(&self, oid: gix::ObjectId) -> Result, GitError> { + let read_error = |source| GitError::ReadBlob { + path: self.requested_path.clone(), + commit: self.commit, + source, + }; + if let Some(max_bytes) = self.max_bytes { + let header = self.repository.find_header(oid).map_err(read_error)?; + enforce_size_limit(self.requested_path, header.size(), max_bytes)?; + } + self.repository + .find_blob(oid) + .map(|mut blob| blob.take_data()) + .map_err(read_error) + } } impl PathTree for CommitTree<'_> { @@ -77,12 +115,7 @@ impl PathTree for CommitTree<'_> { }; let mode = entry.mode(); if mode.is_link() { - let bytes = read_commit_blob( - self.repository, - entry.object_id(), - self.requested_path, - self.commit, - )?; + let bytes = self.read_blob(entry.object_id())?; return Ok(TreeNode::Symlink( std::str::from_utf8(&bytes).ok().map(str::to_owned), )); @@ -97,7 +130,7 @@ impl PathTree for CommitTree<'_> { } fn read_file(&self, oid: gix::ObjectId) -> Result { - let bytes = read_commit_blob(self.repository, oid, self.requested_path, self.commit)?; + let bytes = self.read_blob(oid)?; Ok(SnapshotFileLookup::File(bytes)) } } @@ -107,6 +140,7 @@ struct WorkingTreeFs<'a> { canonical_root: PathBuf, index: &'a gix::worktree::Index, requested_path: &'a RepoPath, + max_bytes: Option, } impl WorkingTreeFs<'_> { @@ -152,8 +186,24 @@ impl PathTree for WorkingTreeFs<'_> { if !canonical.starts_with(&self.canonical_root) { return Ok(SnapshotFileLookup::OutsideRepository); } - let bytes = - std::fs::read(&canonical).map_err(|source| read_error(self.requested_path, source))?; + let map_read_error = |source| read_error(self.requested_path, source); + let bytes = match self.max_bytes { + Some(max_bytes) => { + let file = std::fs::File::open(canonical).map_err(map_read_error)?; + enforce_size_limit( + self.requested_path, + file.metadata().map_err(map_read_error)?.len(), + max_bytes, + )?; + let mut bytes = Vec::new(); + file.take(max_bytes.saturating_add(1)) + .read_to_end(&mut bytes) + .map_err(map_read_error)?; + enforce_size_limit(self.requested_path, bytes.len() as u64, max_bytes)?; + bytes + } + None => std::fs::read(canonical).map_err(map_read_error)?, + }; Ok(SnapshotFileLookup::File(bytes)) } } @@ -353,6 +403,7 @@ fn read_commit_file( repository: &gix::Repository, commit: CommitId, path: &RepoPath, + max_bytes: Option, ) -> Result { let root_tree = repository .find_commit(commit.0) @@ -363,6 +414,7 @@ fn read_commit_file( commit, root_tree: &root_tree, requested_path: path, + max_bytes, }; PathWalker::new(&tree, path).walk() } @@ -371,6 +423,7 @@ fn read_working_tree_file( root: &Path, index: &gix::worktree::Index, path: &RepoPath, + max_bytes: Option, ) -> Result { let canonical_root = canonicalize_path(root, path)?; let tree = WorkingTreeFs { @@ -378,6 +431,7 @@ fn read_working_tree_file( canonical_root, index, requested_path: path, + max_bytes, }; PathWalker::new(&tree, path).walk() } @@ -397,20 +451,15 @@ fn lookup_tree_entry<'repo>( .map_err(|source| GitError::CommitTree { commit, source }) } -fn read_commit_blob( - repository: &gix::Repository, - oid: gix::ObjectId, - path: &RepoPath, - commit: CommitId, -) -> Result, GitError> { - repository - .find_blob(oid) - .map(|mut blob| blob.take_data()) - .map_err(|source| GitError::ReadBlob { +fn enforce_size_limit(path: &RepoPath, size_bytes: u64, max_bytes: u64) -> Result<(), GitError> { + if size_bytes > max_bytes { + return Err(GitError::FileTooLarge { path: path.clone(), - commit, - source, - }) + size_bytes, + max_bytes, + }); + } + Ok(()) } fn is_absolute_target(target: &str) -> bool { diff --git a/crates/git/src/tests.rs b/crates/git/src/tests.rs index 4ebeaa8a..0746684f 100644 --- a/crates/git/src/tests.rs +++ b/crates/git/src/tests.rs @@ -910,6 +910,21 @@ fn commit_snapshot_resolves_symlinks_with_repository_containment_and_keeps_files .contains(&repo_path(".codeint/ratchet.json")) ); assert!(snapshot.files().contains(&repo_path(".codeint/real.json"))); + let real_path = repo_path(".codeint/real.json"); + assert!(matches!( + snapshot.read_following_symlinks_bounded(&real_path, 7), + Err(crate::GitError::FileTooLarge { + size_bytes: 8, + max_bytes: 7, + .. + }) + )); + assert_eq!( + snapshot + .read_following_symlinks_bounded(&real_path, 8) + .expect("file at the byte limit"), + SnapshotFileLookup::File(b"{\"ok\":1}".to_vec()) + ); assert_eq!( snapshot diff --git a/crates/report/src/diff.rs b/crates/report/src/diff.rs index 1054e768..ca656342 100644 --- a/crates/report/src/diff.rs +++ b/crates/report/src/diff.rs @@ -85,6 +85,17 @@ impl DiffReport { if let Some(deps) = &dependencies { over_budget_failures.extend(deps.over_budget(options.budgets)); } + let coverage_unmatched_note = options + .new_files + .as_ref() + .and_then(|measurement| measurement.new_file_test_gap.as_ref()) + .and_then(|gap| crate::format_unmatched_coverage_note(&gap.unmatched_coverage_paths)); + let test_gap_note = options + .include_test_gap_note + .then(|| match coverage_unmatched_note { + Some(note) => format!("{TEST_GAP_DIFF_NOTE}\n{note}"), + None => TEST_GAP_DIFF_NOTE.to_owned(), + }); let over_new_file_budget_failures = options.new_file_budgets.map_or_else(Vec::new, |budgets| { regressions::over_new_file_budget(options.new_files, budgets) @@ -111,9 +122,7 @@ impl DiffReport { over_ratchet: Vec::new(), regressions: regression_failures, source_sets, - test_gap_note: options - .include_test_gap_note - .then(|| TEST_GAP_DIFF_NOTE.to_owned()), + test_gap_note, ratchet_note: None, manifest_warnings, dependencies, diff --git a/crates/report/src/diff/regressions.rs b/crates/report/src/diff/regressions.rs index d5b39150..b9ff07e9 100644 --- a/crates/report/src/diff/regressions.rs +++ b/crates/report/src/diff/regressions.rs @@ -41,12 +41,19 @@ pub(super) fn over_new_file_budget( if budgets.is_empty() { return Vec::new(); } + let test_gap = measurement.new_file_test_gap.as_ref().map(|gap| gap.ratio); let mut failures = Vec::new(); for (source_set, set_measurement) in measurement.into_source_sets() { if set_measurement.files == 0 { continue; } - for (metric, ratio) in source_set_measurement_ratios(&set_measurement) { + let mut ratios = source_set_measurement_ratios(&set_measurement); + if source_set == SourceSet::Production + && let Some(ratio) = test_gap + { + ratios.push((Metric::TestGap.key(), ratio)); + } + for (metric, ratio) in ratios { let rounded = Decimal::rounded(ratio); if let Some(budget) = budgets.budget_for_key(source_set, metric) && !budget.admits(rounded.0) @@ -89,9 +96,6 @@ fn source_set_measurement_ratios(measurement: &SourceSetMeasurement) -> Vec<(&st if let Some(hazards) = &measurement.hazards { ratios.push((Metric::Hazards.key(), hazards.ratio)); } - if let Some(test_gap) = measurement.new_file_test_gap { - ratios.push((Metric::TestGap.key(), test_gap)); - } for (key, external) in &measurement.external_metrics { ratios.push((key.as_str(), external.measurement.ratio)); } diff --git a/crates/report/src/measurement.rs b/crates/report/src/measurement.rs index 57da3f1c..beee4e72 100644 --- a/crates/report/src/measurement.rs +++ b/crates/report/src/measurement.rs @@ -33,6 +33,14 @@ pub struct CommitMeasurement { dependencies: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] manifest_warnings: Vec, + #[serde(skip)] + pub(crate) new_file_test_gap: Option, +} + +#[derive(Debug)] +pub(crate) struct NewFileTestGap { + pub(crate) ratio: f64, + pub(crate) unmatched_coverage_paths: Vec, } #[derive(Debug, Default, Serialize, Deserialize)] @@ -65,8 +73,6 @@ pub(crate) struct SourceSetMeasurement { pub(crate) file_size: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) hazards: Option>, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub(crate) new_file_test_gap: Option, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(crate) external_metrics: BTreeMap, } @@ -241,8 +247,15 @@ impl CommitMeasurement { self } - pub fn with_new_file_test_gap(mut self, ratio: f64) -> CommitMeasurement { - self.production.new_file_test_gap = Some(ratio); + pub fn with_new_file_test_gap( + mut self, + ratio: f64, + unmatched_coverage_paths: Vec, + ) -> CommitMeasurement { + self.new_file_test_gap = Some(NewFileTestGap { + ratio, + unmatched_coverage_paths, + }); self } @@ -329,6 +342,7 @@ impl CommitMeasurement { vendored: measure(SourceSet::Vendored, None)?, dependencies, manifest_warnings: Vec::new(), + new_file_test_gap: None, }) } @@ -511,7 +525,6 @@ impl SourceSetMeasurement { .collect(); Ok(SourceSetMeasurement { files: model.files.len(), - new_file_test_gap: None, erosion: MetricMeasurement::from_items( measured.erosion.ratio(), measured.erosion.eroded_function_mass(), diff --git a/crates/report/src/render.rs b/crates/report/src/render.rs index 44a9fd94..78ef0c2a 100644 --- a/crates/report/src/render.rs +++ b/crates/report/src/render.rs @@ -23,7 +23,7 @@ pub(crate) const TEST_GAP_NO_LANGUAGE_COVERAGE_NOTE: &str = "Test gap is not measured because no named Coverage report covers this language."; pub(crate) const TEST_GAP_NO_REPO_COVERAGE_NOTE: &str = "Test gap is not measured because no named Coverage report covers any measured language."; -pub(crate) const TEST_GAP_DIFF_NOTE: &str = "Test gap is left out of the base and head comparison. The Production new-file Budget uses the head Coverage report."; +pub(crate) const TEST_GAP_DIFF_NOTE: &str = "Test gap is left out of the base and head comparison. The Production new-file Budget can use the head Coverage report."; pub(crate) const TEST_GAP_TREND_NOTE: &str = "Test gap is left out of codeint trend because a Coverage report exists only for the code under measurement."; #[derive(Debug, thiserror::Error)] From 6da4c66233c2e5bbb836481abc700ca3ba4d9ba7 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Wed, 2 Dec 2026 23:52:40 +0800 Subject: [PATCH 3/4] fix(git): scope bounded coverage reads to commits --- crates/cli/src/check/coverage.rs | 17 ++++++---- crates/cli/src/diff.rs | 7 ++-- crates/git/HOW-TO.md | 2 +- crates/git/src/snapshot_lookup.rs | 51 +++++++----------------------- crates/git/src/tests.rs | 5 ++- docs/verification/features/diff.md | 17 ++++++++++ 6 files changed, 45 insertions(+), 54 deletions(-) diff --git a/crates/cli/src/check/coverage.rs b/crates/cli/src/check/coverage.rs index 6f6175f0..7b93fe29 100644 --- a/crates/cli/src/check/coverage.rs +++ b/crates/cli/src/check/coverage.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use std::io::Read; use std::path::{Path, PathBuf}; -use codeint_git::{GitError, Snapshot, SnapshotFileLookup}; +use codeint_git::{CommitId, GitError, Repository, SnapshotFileLookup}; use codeint_metrics::{ CoverageApplyOutcome, CoverageParseError, MAX_COVERAGE_REPORT_BYTES, NamedCoverageReport, apply_coverage_reports, parse_coverage_report, @@ -69,7 +69,7 @@ pub(crate) fn load_coverage_reports( #[derive(Clone, Copy)] pub(crate) enum NewFileCoverageSource<'a> { WorkingTree(&'a Path), - Head(&'a Snapshot), + Head(&'a Repository, CommitId), } impl NewFileCoverageSource<'_> { @@ -79,16 +79,17 @@ impl NewFileCoverageSource<'_> { let paths = select_coverage_report_paths(root, root, paths, None); load_coverage_reports(root, &paths) } - Self::Head(snapshot) => paths + Self::Head(repository, commit) => paths .iter() - .map(|path| load_head_coverage_report(snapshot, path)) + .map(|path| load_head_coverage_report(repository, commit, path)) .collect(), } } } fn load_head_coverage_report( - snapshot: &Snapshot, + repository: &Repository, + commit: CommitId, path: &str, ) -> Result { let missing = || CheckError::MissingHeadCoverageReport { @@ -101,7 +102,11 @@ fn load_head_coverage_report( .collect::>() .join("/"); let repo_path = RepoPath::new(normalized).map_err(|_| missing())?; - match snapshot.read_following_symlinks_bounded(&repo_path, MAX_COVERAGE_REPORT_BYTES as u64) { + match repository.read_commit_file_following_symlinks_bounded( + commit, + &repo_path, + MAX_COVERAGE_REPORT_BYTES as u64, + ) { Err(GitError::FileTooLarge { size_bytes, .. }) => Err(CheckError::InvalidCoverageReport { path: path.to_owned(), source: CoverageParseError::ReportTooLarge { diff --git a/crates/cli/src/diff.rs b/crates/cli/src/diff.rs index a716a13b..6a9e7627 100644 --- a/crates/cli/src/diff.rs +++ b/crates/cli/src/diff.rs @@ -321,10 +321,9 @@ fn measure_head_if_new_files( if new_files.is_empty() { return Ok(None); } - let coverage_source = if request.head_commit.is_some() { - NewFileCoverageSource::Head(head_snapshot) - } else { - NewFileCoverageSource::WorkingTree(context.repository.root()) + let coverage_source = match request.head_commit { + Some(commit) => NewFileCoverageSource::Head(context.repository, commit), + None => NewFileCoverageSource::WorkingTree(context.repository.root()), }; let (selected, measurement, new_files) = measure_all_languages_with_new_files( head_snapshot, diff --git a/crates/git/HOW-TO.md b/crates/git/HOW-TO.md index 88c09790..1bd8e751 100644 --- a/crates/git/HOW-TO.md +++ b/crates/git/HOW-TO.md @@ -52,7 +52,7 @@ let bytes = local.read(path)?; - A commit `Snapshot` follows the same rules as the working tree: regular and executable files are files, symbolic links are left out, and submodules are listed. - Measure both `Snapshot` values with the same code; the caller never knows which kind it holds. - Use `Snapshot::read_following_symlinks` or `Repository::read_working_tree_file_following_symlinks` when reading a specific repository-contained state or configuration file (such as `.codeint/ratchet.json`) across commits or the working tree; both run the same component-by-component symlink walker within repository containment (`SnapshotFileLookup::{Missing, File, OutsideRepository, BrokenSymlink, NotAFile}`) while leaving `Snapshot::files()` limited to regular files. -- Use `Snapshot::read_following_symlinks_bounded` when the caller has a byte limit. +- Use `Repository::read_commit_file_following_symlinks_bounded` when the caller has a byte limit for a committed file. A committed blob over the limit returns `GitError::FileTooLarge` before its contents are read. - `CommitId` displays as the full hexadecimal object id; use it to name the commit in a report or a cache key. diff --git a/crates/git/src/snapshot_lookup.rs b/crates/git/src/snapshot_lookup.rs index 64743cc3..d3ec45ba 100644 --- a/crates/git/src/snapshot_lookup.rs +++ b/crates/git/src/snapshot_lookup.rs @@ -1,5 +1,4 @@ use std::collections::VecDeque; -use std::io::Read; use std::path::{Path, PathBuf}; use codeint_model::RepoPath; @@ -24,35 +23,26 @@ impl Repository { path: &RepoPath, ) -> Result { let index = self.repository.index_or_empty().map_err(GitError::Walk)?; - read_working_tree_file(&self.root, &index, path, None) - } -} - -impl Snapshot { - pub fn read_following_symlinks(&self, path: &RepoPath) -> Result { - self.read_path_following_symlinks(path, None) + read_working_tree_file(&self.root, &index, path) } - pub fn read_following_symlinks_bounded( + pub fn read_commit_file_following_symlinks_bounded( &self, + commit: CommitId, path: &RepoPath, max_bytes: u64, ) -> Result { - self.read_path_following_symlinks(path, Some(max_bytes)) + read_commit_file(&self.repository, commit, path, Some(max_bytes)) } +} - fn read_path_following_symlinks( - &self, - path: &RepoPath, - max_bytes: Option, - ) -> Result { +impl Snapshot { + pub fn read_following_symlinks(&self, path: &RepoPath) -> Result { match &self.contents { - Contents::WorkingTree { root, index, .. } => { - read_working_tree_file(root, index, path, max_bytes) - } + Contents::WorkingTree { root, index, .. } => read_working_tree_file(root, index, path), Contents::Commit { repository, commit, .. - } => read_commit_file(&repository.to_thread_local(), *commit, path, max_bytes), + } => read_commit_file(&repository.to_thread_local(), *commit, path, None), } } } @@ -140,7 +130,6 @@ struct WorkingTreeFs<'a> { canonical_root: PathBuf, index: &'a gix::worktree::Index, requested_path: &'a RepoPath, - max_bytes: Option, } impl WorkingTreeFs<'_> { @@ -186,24 +175,8 @@ impl PathTree for WorkingTreeFs<'_> { if !canonical.starts_with(&self.canonical_root) { return Ok(SnapshotFileLookup::OutsideRepository); } - let map_read_error = |source| read_error(self.requested_path, source); - let bytes = match self.max_bytes { - Some(max_bytes) => { - let file = std::fs::File::open(canonical).map_err(map_read_error)?; - enforce_size_limit( - self.requested_path, - file.metadata().map_err(map_read_error)?.len(), - max_bytes, - )?; - let mut bytes = Vec::new(); - file.take(max_bytes.saturating_add(1)) - .read_to_end(&mut bytes) - .map_err(map_read_error)?; - enforce_size_limit(self.requested_path, bytes.len() as u64, max_bytes)?; - bytes - } - None => std::fs::read(canonical).map_err(map_read_error)?, - }; + let bytes = + std::fs::read(&canonical).map_err(|source| read_error(self.requested_path, source))?; Ok(SnapshotFileLookup::File(bytes)) } } @@ -423,7 +396,6 @@ fn read_working_tree_file( root: &Path, index: &gix::worktree::Index, path: &RepoPath, - max_bytes: Option, ) -> Result { let canonical_root = canonicalize_path(root, path)?; let tree = WorkingTreeFs { @@ -431,7 +403,6 @@ fn read_working_tree_file( canonical_root, index, requested_path: path, - max_bytes, }; PathWalker::new(&tree, path).walk() } diff --git a/crates/git/src/tests.rs b/crates/git/src/tests.rs index 0746684f..d8c70d2c 100644 --- a/crates/git/src/tests.rs +++ b/crates/git/src/tests.rs @@ -912,7 +912,7 @@ fn commit_snapshot_resolves_symlinks_with_repository_containment_and_keeps_files assert!(snapshot.files().contains(&repo_path(".codeint/real.json"))); let real_path = repo_path(".codeint/real.json"); assert!(matches!( - snapshot.read_following_symlinks_bounded(&real_path, 7), + repo.read_commit_file_following_symlinks_bounded(CommitId(commit_id), &real_path, 7), Err(crate::GitError::FileTooLarge { size_bytes: 8, max_bytes: 7, @@ -920,8 +920,7 @@ fn commit_snapshot_resolves_symlinks_with_repository_containment_and_keeps_files }) )); assert_eq!( - snapshot - .read_following_symlinks_bounded(&real_path, 8) + repo.read_commit_file_following_symlinks_bounded(CommitId(commit_id), &real_path, 8) .expect("file at the byte limit"), SnapshotFileLookup::File(b"{\"ok\":1}".to_vec()) ); diff --git a/docs/verification/features/diff.md b/docs/verification/features/diff.md index 6829e3a6..1b93417b 100644 --- a/docs/verification/features/diff.md +++ b/docs/verification/features/diff.md @@ -34,6 +34,23 @@ docs/verification/verify.sh doctor "$RUN_DIR" | `bad_ref` | Unknown base ref `no-such-branch` | `2` | Standard error reports the unknown ref | | `unborn_head` | Empty repository with unborn `HEAD` | `2` | Standard error reports the missing ref | +## Test gap new-file Budget + +The CLI integration tests cover the following states in temporary Git repositories: + +| State | Expected exit | Expected visible result | +| ----- | ------------- | ----------------------- | +| Add an uncovered Production Function with a zero Test gap Budget | `1` | JSON lists a `production.test_gap` new-file Budget failure with ratio `1` | +| Give the new Function full coverage in the working-tree report | `0` | JSON shows no new-file Budget failure | +| Compare a head ref whose committed report shows the Function is uncovered | `1` | JSON shows ratio `1` even when the local report shows full coverage | +| Compare a head ref that lacks the configured report | `2` | Standard error names the missing path | +| Edit only existing files | `0` | JSON shows no new-file Budget failure | +| Add a Production Function in a language with no applicable report | `2` | Standard error names `new_file_budgets.production.test_gap` | + +```sh +cargo test --locked -p codeint --test integration test_gap::diff_ +``` + ## Drive and Assert ```sh From 07640295226934bb286ca0a0d5c6b257d08d592a Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Thu, 3 Dec 2026 00:02:52 +0800 Subject: [PATCH 4/4] fix(cli): keep Test gap Budget examples and error handling valid --- crates/cli/src/remedy.rs | 5 ++--- docs/reference.md | 1 + 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 87d45f5e..d3822502 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -498,10 +498,9 @@ pub(crate) fn git_remedy(error: &GitError) -> &'static str { GitError::NonUtf8Path { .. } | GitError::InvalidPath(_) => { "Rename the file so that its path is valid UTF-8 with no backslash, then run codeint again." } - GitError::Read { .. } => { - "Check that you have permission to read the file, then run codeint again." + GitError::Read { .. } | GitError::FileTooLarge { .. } => { + "Check that the file is readable and within any stated size limit, then run codeint again." } - GitError::FileTooLarge { .. } => "Reduce the file size to the stated limit.", GitError::UnknownRef { .. } => { "Pass a branch, tag, or commit that exists in this repository; fetch it first when it lives on a remote: git fetch origin main" } diff --git a/docs/reference.md b/docs/reference.md index dbabd735..14a4927c 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1453,6 +1453,7 @@ When a Metric across the newly added files exceeds its new-file Budget, `codeint ```json codeint.json { + "coverage_reports": ["coverage/lcov.info"], "new_file_budgets": { "production": { "erosion": 0,