Skip to content

test: drop synthetic default class constructor ranges from coverage - #29693

Closed
robobun wants to merge 3 commits into
mainfrom
farm/b93d55f2/fix-29691-coverage-synthetic-ctor
Closed

robobun wants to merge 3 commits into
mainfrom
farm/b93d55f2/fix-29691-coverage-synthetic-ctor

Conversation

@robobun

@robobun robobun commented Apr 24, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #29691.
Fixes #7025.
Fixes #24908.

Repro

// dep.ts
export const Base = () => class {};

// subject.ts
import { Base } from "./dep";
export class Derived extends Base() {}

bun test --coverage reports subject.ts at 50% line coverage and 0%
function coverage. The lcov output marks the import line as uncovered
(DA:1,0) even though the module clearly loaded.

Also surfaces as 50% function coverage on any class without an explicit
constructor (#7025, #24908) because JSC's synthesized default constructor
gets counted as an uncovered function.

Cause

JSC synthesizes the default constructor for class Derived extends Base() {}
by linking a standalone builtin source: (function (...args) { super(...args); }).
CodeBlock::finishCreation then records an unexecuted range in the
FunctionHasExecutedCache under the owner's sourceID (subject.ts),
but the range's offsets ([1, 38)) live in the synthetic source,
not subject.ts. When coverage consumes those offsets as subject.ts byte
offsets, they happen to straddle bytes 1-37 — the import, a newline, and
the start of export class … — and flip both lines to 'uncovered'.

V8 doesn't emit anything similar, which is why Node's NODE_V8_COVERAGE
reports 100% on the same repro.

Fix

Two changes in src/bun.js/bindings/CodeCoverage.cpp and
src/sourcemap/CodeCoverage.zig:

  1. Drop synthetic ranges at the binding. Walk the VM's CodeBlocks
    whose owner matches the source we're reporting; for each of their
    function declarations and expressions, check whether the linked
    FunctionExecutable::sourceID() resolves to a different provider.
    That indicates UnlinkedFunctionExecutable::linkedSourceCode picked up
    BuiltinExecutables::defaultConstructorSourceCode instead of the
    parent source, which is the tell for a synthetic builtin default class
    constructor. Collect (unlinkedFunctionStart, unlinkedFunctionEnd)
    pairs and skip matching entries when draining functionHasExecutedCache.

  2. Preserve statement-level line hits for unexecuted functions. Snapshot
    lines_which_have_executed after statement blocks are processed. When a
    later function block wants to mark lines unexecuted, don't unset bits
    that statement processing already set — a never-called foo's
    export function foo() { line still ran as a statement even if the
    body didn't. This matches V8/istanbul behavior and incidentally fixed
    a pre-existing DA:9,0 in the existing lcov coverage reporter snapshot
    (function uncovered() declaration line is now DA:9,5).

Verification

@robobun

robobun commented Apr 24, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 3:35 AM PT - May 4th, 2026

Your commit f5309d0 is building: #51089

@github-actions

Copy link
Copy Markdown
Contributor

Found 3 issues this PR may fix:

  1. Coverage incorrectly reports implicit constructors as uncovered #24908 - Directly fixes implicit/synthetic constructors in derived classes being incorrectly reported as uncovered functions
  2. Missing function coverage reporting in class without explicit constructor #7025 - Directly fixes classes without explicit constructors showing 50% function coverage because the synthetic constructor is counted as uncovered
  3. bun test --coverage inaccurately reporting less than 100% coverage #9008 - Likely partially fixes unexplained sub-100% function coverage in class-heavy code where synthetic constructors contribute to inaccurate counts

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #24908
Fixes #7025
Fixes #9008

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9c1a86ec-fff6-4cbf-8417-fd727b485bab

📥 Commits

Reviewing files that changed from the base of the PR and between 1fa7f1b and 38247ef.

📒 Files selected for processing (1)
  • test/cli/test/coverage.test.ts

Walkthrough

Builds and filters function byte-range sets in the C++ coverage binding to exclude synthetic-only ranges, preserves statement-derived executed lines when processing function ranges in the Zig report generator, and adds an LCOV regression test for classes extending factory-call results without explicit constructors.

Changes

Cohort / File(s) Summary
C++ Coverage Filtering
src/bun.js/bindings/CodeCoverage.cpp
Traverse VM CodeBlocks to collect (start,end) byte-offset ranges from FunctionExecutables, classify ranges as same-source vs synthetic, omit ranges present only in the synthetic set when building BasicBlockRange, and set m_startOffset/m_endOffset from extracted values.
Zig Coverage Report Generation
src/sourcemap/CodeCoverage.zig
Clone lines_which_have_executed into a snapshot before function-range processing and only clear/unset lines_which_have_executed/line_hits for non-executed function ranges when the snapshot did not already mark the line; remove unconditional zeroing of line_hits for no-sourcemap branch.
Coverage Regression Tests & Sanitizer
test/cli/test/coverage.test.ts
Add LCOV regression test for class extending factory-call result without explicit constructor; add stderr sanitizer to strip ASAN/JSC signal-handler warnings; apply sanitizer to coverage snapshot tests and update inline coverage snapshot expectations.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately describes the main change: dropping synthetic default class constructor ranges from coverage reporting.
Description check ✅ Passed The description comprehensively covers the repro, cause, fix implementation details, and verification approach, fully addressing the required template sections.
Linked Issues check ✅ Passed The PR implements all objectives from linked issues #29691, #7025, #24908: detecting and dropping synthetic constructor ranges, preserving statement-level line hits, and ensuring accurate coverage for classes without explicit constructors.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing coverage reporting for synthetic constructors: C++ binding modifications, Zig sourcemap logic updates, test additions for the derived class repro, and ASAN warning filtering.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/bun.js/bindings/CodeCoverage.cpp`:
- Around line 49-80: The current filter incorrectly skips cached function ranges
by checking only numeric collisions against syntheticFunctionRanges, which can
drop real same-source functions that happen to share offsets; when iterating
vm.heap.forEachCodeBlock and collecting ranges (see syntheticFunctionRanges, the
collect lambda using unlinked->unlinkedFunctionStart()/End(), and the
functionRanges from vm.functionHasExecutedCache()->getFunctionRanges), build two
sets: synthetic ranges and same_source ranges (i.e., ranges produced from
executables whose sourceID == sourceID) and then, when iterating functionRanges,
only skip a range if it is in syntheticFunctionRanges and NOT in the same_source
set (skip only synthetic && !same_source) so real same-source cached ranges are
preserved.

In `@test/cli/test/coverage.test.ts`:
- Around line 95-98: The current assertion using
expect(subjectRecord).toContain("DA:2,") can match "DA:2,0" (uncovered); update
the assertion to require a non-zero hit count for line 2 by asserting the exact
non-zero value or using a pattern that excludes zero — e.g., change the check on
subjectRecord (the LCOV "DA" entry) to assert "DA:2,1" or use a regex/assertion
that ensures DA:2,<n> where n > 0 so the class declaration is confirmed
executed.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: a75343ad-404a-4233-83a2-63bcb42c7bda

📥 Commits

Reviewing files that changed from the base of the PR and between 259f16f and f37d513.

⛔ Files ignored due to path filters (1)
  • test/cli/test/__snapshots__/coverage.test.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (3)
  • src/bun.js/bindings/CodeCoverage.cpp
  • src/sourcemap/CodeCoverage.zig
  • test/cli/test/coverage.test.ts

Comment thread src/jsc/bindings/CodeCoverage.cpp Resolved
Comment thread test/cli/test/coverage.test.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@test/cli/test/coverage.test.ts`:
- Around line 69-99: Add a new, small regression test that specifically triggers
the synthetic && !same_source branch in CodeCoverage.cpp by creating a real
(non-synthetic) user function that deliberately shares the synthetic
constructor's raw (start,end) offsets so the same-source guard collision is
exercised; mirror the existing "derived class with no explicit constructor" test
pattern (test/cli/test/coverage.test.ts) but add a fixture file that defines a
user function with the same raw offsets as the synthetic constructor and assert
coverage records show both entries handled correctly (so the new branch is
executed and prevents the collision regression).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 27803008-9b31-48a6-a328-2393a6a3bd29

📥 Commits

Reviewing files that changed from the base of the PR and between f37d513 and 1fa7f1b.

📒 Files selected for processing (2)
  • src/bun.js/bindings/CodeCoverage.cpp
  • test/cli/test/coverage.test.ts

Comment on lines +69 to +99
test("derived class with no explicit constructor (issue #29691)", () => {
const dir = tempDirWithFiles("cov-29691", {
"dep.ts": `export const Base = () => class {};\n`,
"subject.ts": `import { Base } from "./dep";
export class Derived extends Base() {}
`,
"subject.test.ts": `import { expect, test } from "bun:test";
import { Derived } from "./subject";
test("loads the class", () => {
expect(Derived.name).toBe("Derived");
});
`,
});
const result = Bun.spawnSync([bunExe(), "test", "--coverage", "--coverage-reporter", "lcov"], {
cwd: dir,
env: bunEnv,
stdio: [null, null, "pipe"],
});
expect(result.exitCode).toBe(0);
expect(result.signalCode).toBeUndefined();

const lcov = readFileSync(path.join(dir, "coverage", "lcov.info"), "utf-8");

// subject.ts should not report the import on line 1 as uncovered (DA:1,0),
// and should not count the synthetic default constructor as a function.
const subjectRecord = lcov.split("end_of_record").find(r => r.includes("SF:subject.ts"))!;
expect(subjectRecord).toContain("FNF:1");
expect(subjectRecord).toContain("FNH:1");
expect(subjectRecord).toMatch(/DA:2,[1-9]\d*/); // class declaration line was evaluated (non-zero hits)
expect(subjectRecord).not.toContain("DA:1,0"); // import line is not bogusly marked unexecuted
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider adding a collision-specific regression for the new same-source guard.

This repro locks down the original synthetic-constructor bug, but it still doesn't exercise the new synthetic && !same_source branch in CodeCoverage.cpp. A tiny fixture where a real user function shares the synthetic constructor's raw (start, end) offsets would protect the collision fix directly.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/cli/test/coverage.test.ts` around lines 69 - 99, Add a new, small
regression test that specifically triggers the synthetic && !same_source branch
in CodeCoverage.cpp by creating a real (non-synthetic) user function that
deliberately shares the synthetic constructor's raw (start,end) offsets so the
same-source guard collision is exercised; mirror the existing "derived class
with no explicit constructor" test pattern (test/cli/test/coverage.test.ts) but
add a fixture file that defines a user function with the same raw offsets as the
synthetic constructor and assert coverage records show both entries handled
correctly (so the new branch is executed and prevents the collision regression).

robobun added 3 commits May 4, 2026 10:34
Fixes #29691.

JSC synthesizes a default class constructor for `class Foo {}` and
`class Foo extends Bar() {}` by linking a fresh SourceProvider whose body
is `(function () { })` or `(function (...args) { super(...args); })`.
`CodeBlock::finishCreation` then calls
`FunctionHasExecutedCache::insertUnexecutedRange(ownerSourceID, start, end)`
with offsets that live in the synthetic provider — not the owner's
source — so coverage saw a 37-byte range `[1, 38)` for the derived case
and marked whatever user code happened to sit at those offsets as an
uncovered 'function'. With a one-line file like:

  import { Base } from "./dep";
  export class Derived extends Base() {}

that meant `DA:1,0` for the import line, 50% line coverage, and 0%
function coverage.

Filter these out in the C++ binding: a function executable reached from
this source's code blocks whose `sourceID()` resolves to a different
provider is synthetic (see `UnlinkedFunctionExecutable::linkedSourceCode`),
so collect its `unlinkedFunctionStart`/`End` and skip matching entries
when reading `functionHasExecutedCache` ranges.

Also preserve statement-level line coverage when a function did not
execute: a never-called function's declaration line still ran as a
statement (`export function foo() {` executes even if `foo` is never
called), so don't unset that bit when its body range is marked
unexecuted. This matches V8/istanbul behavior and fixes a pre-existing
`DA:declLine,0` quirk the lcov snapshot test was pinning.
…te inline snapshot

- C++ filter: also collect `sameSourceFunctionRanges` so a real user
  function whose unlinkedFunctionStart/End numerically coincides with a
  synthetic default class constructor (e.g. a file opening with
  `!function(){return 1}();class X{}`) isn't dropped alongside the
  synthetic one. Skip only when a range is synthetic AND not also
  present in the same-source set.

- Test assertion: replace `toContain("DA:2,")` with a regex that
  requires a non-zero hit count, so a latent `DA:2,0` regression can't
  slip past.

- Inline snapshot: the `coveragePathIgnorePatterns - partial coverage
  without nan` test in coverage.test.ts hardcoded `include-me.ts |
  50.00 | 66.67`. The Zig statement-preservation change pushes its
  line coverage to 100% for the same reason `demo2.ts` line 9 went
  from DA:9,0 to DA:9,5 in the lcov snapshot — the module's
  top-level export-binding statements cover the `neverCalled`
  declaration line, which now survives the unexecuted-function sweep.
  Update the inline snapshot to match.
Debug/ASAN builds print `WARNING: ASAN interferes with JSC signal
handlers; useWasmFastMemory and useWasmFaultSignalHandler will be
disabled.` to stderr on every JS-executing subprocess (emitted via
`std::call_once` in Options.cpp — at most one line per process).
`normalizeBunSnapshot` doesn't scrub it, so the inline `toMatchInlineSnapshot`
calls in coverage.test.ts fail on the debug-ASAN CI lane against
snapshots captured from a release build. Filter lines starting with
`WARNING: ASAN interferes` out of `stderr` before normalizing — the
repo convention used in test/js/bun/resolve/, test/js/node/,
test/cli/install/ and elsewhere.
@Jarred-Sumner
Jarred-Sumner force-pushed the farm/b93d55f2/fix-29691-coverage-synthetic-ctor branch from 38247ef to f5309d0 Compare May 4, 2026 10:34
@robobun

robobun commented Jun 26, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: this PR predates the Rust rewrite and modifies source files that no longer exist on main (Zig sources removed, src/bun.js/ reorganized into src/jsc/). It cannot merge as-is.

If the underlying issue is still present, it will need a fresh fix against the current tree.

@robobun robobun closed this Jun 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

1 participant