Repository navigation
fix(coverage): spawn console entry points as the gate does, or decline - #102
Conversation
A change that breaks the suite read SAFE on any editable-installed project whose testCmd is a console script. No PYTHONPATH required, and `pip install -e .` plus `pytest` is the default shape of a Python project, so this was reachable by default rather than by misuse. The gate runs `sh -c "pytest -q"`, where sys.path[0] is the bin directory, so an editable install resolves imports to the ORIGINAL tree. The coverage runner rewrote that to `coverage run -m pytest -q`, and `-m` puts CWD first, so it imported the SHADOW tree. The gate passed against unmodified code while coverage measured the changed code as covered, and fusing two true statements about two trees produced SAFE. The shadow-bypass guard could not help: the changed file WAS in measuredFiles, because coverage genuinely measured it, in a run whose result nobody used. The guard was defeated by the divergence itself. A console entry point is now resolved on PATH and run positionally, so sys.path[0] is the bin directory in both spawns and neither run can import a copy the other did not. That repairs the guard's precondition rather than adding a mechanism: coverage now measures the tree the gate ran, the shadow file is absent from measuredFiles, and the guard fires as designed. Resolution requires a Python shebang, so a Windows .exe launcher falls back to the module form that shipped before and nothing that works today stops working. The import-affecting decline from the previous issue survives to keep that fallback sound. Editable-install projects using a console script move from SAFE to UNPROVEN. Those verdicts were unsound in both directions, because the gate never ran the code under verification; the documented PYTHONPATH remedy restores a measured SAFE. Closes #98
Review found the first attempt introduced a NEW false SAFE and left the original one live on most real setups. Both are closed here. The resolver did not model the shell. It accepted a non-executable file the shell would skip, and it scanned PAST the shell's first match to find a Python script further down, so coverage could run a different program than the gate ran. Because a resolved entry point bypasses the earlier import-affecting decline, that made resolver fidelity load-bearing for a verdict. It now stops at the first executable match, as a shell does, and declines if that match is not a Python script. The fallback to module form is gone. Falling back to the shape that caused the false SAFE kept it alive wherever resolution failed, and resolution fails on the setups people actually use: pyenv and asdf install shell shims, nix wraps programs the same way, Windows console scripts are native launchers, and a deep venv shebang exceeded the read window. An unresolvable entry point is now declined outright. The shadow-bypass floor carries a reason. This branch routes a whole population onto it, and a bare "could not be determined" left them with no idea that prefixing the test command would give them a real verdict. The resolver is required rather than optional, so no call site can omit it and silently select a spawn shape the gate would not have used, and the governing rule now states when equivalence may be CONSTRUCTED rather than only recognised. Tests: the resolver gets direct tests it never had, covering the exec bit, PATH order, shims, deep shebangs and native binaries; each was proven to fail against the previous resolver. The regression test gains a control proving the edit breaks the suite and an assertion that the gate ran green, without which it passed with its own setup deleted. The environment restore moves to afterEach, because an in-body finally does not run when a test times out and the value leaked into later tests.
📝 WalkthroughWalkthroughCoverage now resolves Python console scripts through ChangesCoverage equivalence and verification diagnostics
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant VerifyDiff
participant CoverageReporter
participant EntryPointResolver
participant PythonCoverage
VerifyDiff->>CoverageReporter: classify test command
CoverageReporter->>EntryPointResolver: resolve console script using PATH
EntryPointResolver-->>CoverageReporter: executable Python script or null
CoverageReporter->>PythonCoverage: run positional coverage command
PythonCoverage-->>VerifyDiff: measured files or unknown coverage
VerifyDiff-->>VerifyDiff: report diagnostic for unmeasured files
Possibly related issues
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (5)
tests/integration/coverage-reporter.test.ts (2)
449-519: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the temporary directory after the test.
Line 457 creates
rootwithfs.mkdtempand never removes it. Each run leaves executable fixture files in the system temp directory. Add cleanup in atry/finallyor anafterEach.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/integration/coverage-reporter.test.ts` around lines 449 - 519, Add guaranteed cleanup for the temporary root created in the test using fs.mkdtemp: wrap the fixture setup and assertions in a try/finally and remove root recursively in the finally block, preserving all existing test behavior.
486-488: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winProve the directory case keeps searching rather than declining.
A directory match uses
continueinresolveConsoleScript, while a non-Python match usesreturn null. This assertion cannot tell the two behaviours apart, becausebholds noadir. Add a Python script namedadirinb, then assert the resolver returns that file.♻️ Proposed test addition
// A directory named like the entry point is not a match. await fs.mkdir(path.join(a, 'adir')); - expect(resolveConsoleScript('adir', { PATH: PATHV })).toBeNull(); + await fs.writeFile(path.join(b, 'adir'), '#!/usr/bin/env python3\nprint(6)\n', { + mode: 0o755, + }); + // Skipped, not declined: the shell keeps searching past a directory. + expect(resolveConsoleScript('adir', { PATH: PATHV })).toBe(path.join(b, 'adir'));🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/integration/coverage-reporter.test.ts` around lines 486 - 488, Extend the directory-case test around resolveConsoleScript by creating a Python script named adir in the later PATH entry b, then assert the resolver returns that script’s path. Keep the existing directory in a so the test verifies directory matches continue searching rather than returning null.src/analyze/coverage/python-line-coverage.ts (2)
359-371: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReport why the command was declined.
toCoverageRunArgsnow returnsnullfor a new and common case: a console entry point that does not resolve to a Python script. pyenv, asdf, and nix shims hit this path. The reported reason stayscannot wrap test command for coverage: <cmd>, which does not tell the user that the entry point could not be resolved or thatpython3 -m pytestavoids the problem.The linked issue asks for an explanatory reason for any new degradation. Return a discriminated decline reason from
toCoverageRunArgs, or add the remediation hint to this message.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/analyze/coverage/python-line-coverage.ts` around lines 359 - 371, Update the toCoverageRunArgs failure handling so the measurementFailureReason identifies that the console entry point could not be resolved for coverage, rather than only stating that wrapping failed. Include the actionable remediation hint to use “python3 -m pytest”, or propagate a discriminated decline reason from toCoverageRunArgs into this result.
285-293: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winMatch the interpreter, not the whole shebang line.
/python/itests the complete shebang line. A wrapper whose interpreter path containspythonbut ends in another interpreter, for example#!/opt/python3.11/bin/bashor a nix wrapper under a...python...store path, is accepted as a Python script.coverage runthen receives a shell script, writes no data file, and the run degrades to unknown instead of declining here.Restrict the test to the interpreter token, and handle
envexplicitly.♻️ Proposed refactor
- // Only a Python script can be handed to `coverage run` positionally. - // A shim (`#!/usr/bin/env bash`, pyenv and asdf install these), a - // native launcher (Windows `.exe`), or a shebang we cannot read is not - // one, and the caller declines rather than substituting module form. - if (first.startsWith('#!') && /python/i.test(first)) return candidate; + // Only a Python script can be handed to `coverage run` positionally. + // A shim (`#!/usr/bin/env bash`, pyenv and asdf install these), a + // native launcher (Windows `.exe`), or a shebang we cannot read is not + // one, and the caller declines rather than substituting module form. + // Test the INTERPRETER basename, not the whole line: a wrapper whose + // path merely contains `python` is not a Python script. + if (first.startsWith('#!')) { + const words = first.slice(2).trim().split(/\s+/).filter(Boolean); + // `#!/usr/bin/env python3` names the interpreter in the argument. + const interp = path.posix.basename(words[0] ?? '') === 'env' ? words[1] : words[0]; + if (/^python[0-9.]*$/i.test(path.posix.basename(interp ?? ''))) return candidate; + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/analyze/coverage/python-line-coverage.ts` around lines 285 - 293, The regex pattern /python/i.test(first) checks the entire shebang line, which incorrectly matches paths containing "python" as a directory component (like #!/opt/python3.11/bin/bash). Extract and validate only the interpreter token from the shebang: parse the first token after the #! prefix, handle the special case where that token is "env" by extracting the next token as the actual interpreter, and then test only that interpreter name against the python pattern. This ensures wrapper scripts or nix paths with "python" in their directory names are not mistakenly accepted as Python scripts.src/verify/verify-diff.ts (1)
135-147: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMove the Python-specific remediation text behind the Python coverage adapter, and cap the file list.
Two points on the new message:
The text names
PYTHONPATH,sys.path, and thesrclayout. The coding guidelines require the verification and analysis engines to stay language-agnostic and keep language-specific logic inside language adapters.assessCoverageis already Python-coupled, so this is not a new coupling, but the change adds language-specific prose to the engine. Expose the remediation string from the Python coverage module and consume it here.
namesjoins every unmeasured path with no bound. A wide diff produces a very longunknownReasonin the serializedVerdictReport. Truncate after a fixed count and report the remainder as a count.As per coding guidelines: "Keep language-specific logic inside language adapters; verification and analysis engines must remain language-agnostic."♻️ Proposed change for the unbounded list
- const names = unmeasured.map((r) => r.path).join(', '); + const paths = unmeasured.map((r) => r.path); + const shown = paths.slice(0, 5); + const names = + paths.length > shown.length + ? `${shown.join(', ')} (+${paths.length - shown.length} more)` + : shown.join(', ');🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/verify/verify-diff.ts` around lines 135 - 147, Update the unmeasured-file handling in assessCoverage to obtain the Python-specific remediation text from the Python coverage adapter instead of embedding PYTHONPATH, sys.path, or src-layout wording in the language-agnostic engine. Also cap the displayed unmeasured paths at a fixed count and append the number of omitted files to unknownReason when additional paths remain.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/analyze/coverage/python-line-coverage.ts`:
- Around line 359-371: Update the toCoverageRunArgs failure handling so the
measurementFailureReason identifies that the console entry point could not be
resolved for coverage, rather than only stating that wrapping failed. Include
the actionable remediation hint to use “python3 -m pytest”, or propagate a
discriminated decline reason from toCoverageRunArgs into this result.
- Around line 285-293: The regex pattern /python/i.test(first) checks the entire
shebang line, which incorrectly matches paths containing "python" as a directory
component (like #!/opt/python3.11/bin/bash). Extract and validate only the
interpreter token from the shebang: parse the first token after the #! prefix,
handle the special case where that token is "env" by extracting the next token
as the actual interpreter, and then test only that interpreter name against the
python pattern. This ensures wrapper scripts or nix paths with "python" in their
directory names are not mistakenly accepted as Python scripts.
In `@src/verify/verify-diff.ts`:
- Around line 135-147: Update the unmeasured-file handling in assessCoverage to
obtain the Python-specific remediation text from the Python coverage adapter
instead of embedding PYTHONPATH, sys.path, or src-layout wording in the
language-agnostic engine. Also cap the displayed unmeasured paths at a fixed
count and append the number of omitted files to unknownReason when additional
paths remain.
In `@tests/integration/coverage-reporter.test.ts`:
- Around line 449-519: Add guaranteed cleanup for the temporary root created in
the test using fs.mkdtemp: wrap the fixture setup and assertions in a
try/finally and remove root recursively in the finally block, preserving all
existing test behavior.
- Around line 486-488: Extend the directory-case test around
resolveConsoleScript by creating a Python script named adir in the later PATH
entry b, then assert the resolver returns that script’s path. Keep the existing
directory in a so the test verifies directory matches continue searching rather
than returning null.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: fb67e5e6-69f4-4daa-868f-937c55973b0a
📒 Files selected for processing (4)
src/analyze/coverage/python-line-coverage.tssrc/verify/verify-diff.tstests/integration/coverage-reporter.test.tstests/integration/verify-diff.test.ts
Windows CI went red on all three Node versions, and it was right to. Seven pre-existing tests drove a bare `pytest -q` while asserting things about coverage MEASUREMENT rather than command classification. Console entry points cannot be resolved on Windows, so they now decline and measure nothing. They use module form instead, which is equivalent by recognition on every platform. The regression guard covered both command forms in one loop. That is no longer one property: module form always measures, and console-script form measures only where the construction is possible. Split, with the POSIX half naming issue #100. The exec-bit case cannot be expressed on Windows, where chmod is a no-op and every readable file reports executable. Moved to its own POSIX-only test rather than weakened. Two reason assertions demanded the PYTHONPATH remedy wording from a path whose degradation mechanism is platform-dependent: POSIX resolves and the guard fires, Windows declines. They now assert that the floor explains itself at all, and the remedy wording is pinned on the src-layout case, which is module form and so behaves identically everywhere.
The default was a bare `pytest -q`, a console entry point. Since those are now resolved or declined rather than rewritten, the default could not be measured on a platform where resolution is impossible, and the legacy analyze path that relies on it lost coverage on Windows. Module form is what `detect.ts` auto-detects, what every documented example teaches, and equivalent by recognition in both spawn shapes on every platform. It should always have been the default.
Closes #98.
What
Makes the coverage run spawn a console entry point the way the tests gate does, and declines when it cannot.
Why
A change that breaks the test suite read
SAFE.The gate runs
sh -c "pytest -q", wheresys.path[0]is the bin directory, so an editable install resolves imports to the ORIGINAL tree. The coverage runner rewrote that tocoverage run -m pytest -q, and-mprepends CWD, so it imported the SHADOW tree. The gate passed against unmodified code while coverage measured the changed line as covered, and fusing two true statements about two different trees produced:The shadow-bypass guard could not help. The changed file was in
measuredFiles, because coverage genuinely measured it, in a run whose result nobody used. The guard was defeated by the divergence itself.Measured,
sys.path[0]for all three spawn shapes:A console entry point is now resolved on PATH and run positionally, so both spawns import the same copy. That repairs the shadow-bypass guard's precondition rather than adding a mechanism: coverage measures the tree the gate ran, the shadow file is absent from
measuredFiles, and the guard fires as designed.Before and after
Real venv, genuine
pip install -e .:Review caught two things in the first attempt. Both are fixed here.
It introduced a new false SAFE. The resolver did not model the shell: it accepted a non-executable file the shell would skip, and scanned past the shell's first match to find a Python script further down. Because a resolved entry point bypasses #95's decline, resolver fidelity became load-bearing for a verdict. Demonstrated:
Now it stops at the first executable match, as a shell does, and declines if that match is not a Python script.
The fallback kept the original bug alive almost everywhere. Falling back to module form when resolution failed was described as safe because #95's import-affecting decline would catch it. That is false, and #98 is the proof: an editable install has no import-affecting variable. Resolution fails on the setups people actually use, and each was reproduced reading
SAFEon a breaking change:#!/usr/bin/env bashshims#!/bin/shexec-wrapper when the interpreter path is long.exelaunchersSo the residual was never "Windows". There is now no fallback: an unresolvable entry point declines.
The governing rule, amended
The module header now says how equivalence may be established, because this PR does something #95's rule did not anticipate: it constructs equivalence rather than only recognising it.
The third clause is the one this PR learned the hard way.
Silent declines were the bug, so the floor explains itself
This PR routes a whole population onto the shadow-bypass floor, which returned
unknownCoverage()with no reason. It now names the cause and the remedy, because the entire product argument for the behaviour change is thatPYTHONPATH=.restores a soundSAFE, and nothing in the output pointed there.An earlier revision of this branch deleted a
unknownReasonassertion when the degradation moved from a decline to the guard. That was a disclosure regression dressed as a test update; the assertion is restored and strengthened.Behaviour change, stated deliberately
Projects passing a console-script
testCmdon a setup where the entry point cannot be resolved now getUNPROVENinstead ofSAFE.Those
SAFEs were unsound in both directions: onmain, the breaking edit and a good edit both readSAFEwith identical text, so the verdict carried no information. This removes a non-measurement, not a measurement.Scope is narrower than #98's description implied, and I corrected that on the issue:
src/verify/runners/detect.ts:47auto-detects Python aspython3 -m pytest -q, which is module form, equivalent on both sides, and untouched. Every documented example teaches that form. The affected population is callers who explicitly pass a bare console script.Evidence
Run on
186c169:Locked contracts untouched.
VerdictReportstructurally unchanged, noreportVersionbump.Red-first, by mutation
Diffing against
maincannot prove the classifier tests red, because the signature changed. Each guard was verified by mutating this branch:The end-to-end test is genuinely red on
mainwithexpected 'SAFE' not to be 'SAFE'.resolveConsoleScripthad no direct tests and now has them: exec bit, PATH order, shell shims, directories, relative and empty PATH elements, CRLF shebangs, long shebangs, native binaries.The regression test gained a control proving the edit breaks the suite, plus
gates.tests.passed. Without those it passed with its ownPYTHONPATHsetup deleted, because an unimportable package makes the baseline red andUNPROVENarrives for an unrelated reason.The environment restore moved to
afterEach. An in-bodyfinallydoes not run when a test times out, and the leaked value was measured reaching later tests in the same file.Windows: CI caught two more, both real
Windows went red on all three Node versions after the first push, and it was right to.
Seven pre-existing tests drove a bare
pytest -qwhile asserting things about coverage measurement rather than command classification. Console entry points cannot resolve on Windows, so they declined and measured nothing. They now use module form, equivalent by recognition everywhere.The default
testCmdwas itself a bare console script.reportCoveragedefaulted to'pytest -q', so the legacy analyze path, which passes notestCmd, lost coverage on Windows. It now defaults topython3 -m pytest -q: whatdetect.tsauto-detects, what every documented example teaches, and equivalent by recognition on every platform. It should always have been that.Two assertions also demanded the
PYTHONPATHremedy wording from a path whose degradation mechanism is platform-dependent (POSIX resolves and the guard fires; Windows declines). They now assert the floor explains itself at all, and the remedy wording is pinned on the src-layout case, which is module form and behaves identically everywhere. The exec-bit case moved to a POSIX-only test, sincechmodis a no-op on Windows.Windows is now green, so #98's "verified on Windows" criterion is discharged for correctness. The capability limitation stands and is filed as #100: console-script
testCmdon Windows always declines toUNPROVEN. That is strictly safer than the falseSAFEit replaces.One honest observation
One non-reproducing failure. During this work the pre-existing
a flaky test that heals on retrytest failed once withexpected 'UNSAFE' not to be 'UNSAFE', under heavy parallel load. It has passed five consecutive runs since (three full-file, two isolated) and I could not reproduce it. That test deliberately simulates a flake using marker files in the shared temp dir. I am recording it rather than calling it noise.Follow-ups, filed
pythonBin, not its shebang interpreter, which can produce an accurate verdict with a confidently wrong reasonUNPROVENfloor and deserves its own issue, red-first proof and flake analysis