From 8dcc82eafe598ef3bd581f966e1d4e83ea2c5d2c Mon Sep 17 00:00:00 2001 From: robobun Date: Fri, 24 Apr 2026 14:48:35 +0000 Subject: [PATCH 1/3] test(coverage): drop synthetic default class constructor ranges MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/jsc/bindings/CodeCoverage.cpp | 54 ++++++++++++++++++- src/sourcemap_jsc/CodeCoverage.zig | 34 +++++++++--- .../test/__snapshots__/coverage.test.ts.snap | 6 +-- test/cli/test/coverage.test.ts | 41 ++++++++++++++ 4 files changed, 122 insertions(+), 13 deletions(-) diff --git a/src/jsc/bindings/CodeCoverage.cpp b/src/jsc/bindings/CodeCoverage.cpp index 51ea142f9e4e..39b3e4794e80 100644 --- a/src/jsc/bindings/CodeCoverage.cpp +++ b/src/jsc/bindings/CodeCoverage.cpp @@ -1,6 +1,13 @@ #include "root.h" #include "ZigSourceProvider.h" +#include #include +#include +#include +#include +#include +#include +#include using namespace JSC; @@ -24,15 +31,58 @@ extern "C" bool CodeCoverage__withBlocksAndFunctions( size_t functionStartOffset = basicBlocks.size(); + // Collect byte-offset ranges of synthetic functions reachable from this source. + // + // JSC emits a synthetic default class constructor for `class Foo extends Bar() {}` + // (and plain `class Foo {}`) by linking a *separate* builtin SourceProvider — + // `(function (...args) { super(...args); })` or `(function () { })`. But + // `CodeBlock::finishCreation` files the constructor's `unlinkedFunctionStart` + // and `unlinkedFunctionEnd` under the OWNER's sourceID, so those offsets — which + // live in the synthetic provider — end up looking like real function ranges in + // the user's source. Coverage then reports bogus "uncovered" bytes that straddle + // whatever user code happens to sit at those offsets. See issue #29691. + // + // The synthetic case is identifiable because `functionExecutable->sourceID()` + // resolves to the synthetic provider's ID (via `linkedSourceCode`), not the + // owner's. Collect those (start, end) pairs so we can drop them from the range + // list returned to Bun's coverage reporter. + HashSet> syntheticFunctionRanges; + vm.heap.forEachCodeBlock([&](CodeBlock* codeBlock) { + auto* owner = codeBlock->ownerExecutable(); + if (!owner || owner->sourceID() != sourceID) + return; + + auto collect = [&](FunctionExecutable* fnExec) { + if (!fnExec) + return; + if (fnExec->sourceID() == sourceID) + return; + auto* unlinked = fnExec->unlinkedExecutable(); + if (!unlinked) + return; + syntheticFunctionRanges.add({ unlinked->unlinkedFunctionStart(), unlinked->unlinkedFunctionEnd() }); + }; + + for (const auto& fn : codeBlock->functionDecls()) + collect(fn.get()); + for (int i = 0, count = static_cast(codeBlock->numberOfFunctionExprs()); i < count; ++i) + collect(codeBlock->functionExpr(i)); + }); + const Vector>& functionRanges = vm.functionHasExecutedCache()->getFunctionRanges(sourceID); basicBlocks.reserveCapacity(functionRanges.size() + basicBlocks.size()); for (const auto& functionRange : functionRanges) { + unsigned start = std::get<1>(functionRange); + unsigned end = std::get<2>(functionRange); + if (syntheticFunctionRanges.contains({ start, end })) + continue; + BasicBlockRange range; range.m_hasExecuted = std::get<0>(functionRange); - range.m_startOffset = static_cast(std::get<1>(functionRange)); - range.m_endOffset = static_cast(std::get<2>(functionRange)); + range.m_startOffset = static_cast(start); + range.m_endOffset = static_cast(end); range.m_executionCount = range.m_hasExecuted ? 1 : 0; // This is a hack. We don't actually count this. diff --git a/src/sourcemap_jsc/CodeCoverage.zig b/src/sourcemap_jsc/CodeCoverage.zig index 791216c6f9b0..8817e9bf2de7 100644 --- a/src/sourcemap_jsc/CodeCoverage.zig +++ b/src/sourcemap_jsc/CodeCoverage.zig @@ -486,6 +486,15 @@ pub const ByteRangeMapping = struct { } } + // Snapshot of lines marked executed by statement blocks above. Statement + // coverage is authoritative for line coverage — a never-called function's + // declaration line still ran as a statement, and JSC's synthetic default + // class constructor ranges get filed under the user's sourceID with + // offsets into a completely different (synthetic) source, so they must + // not unset lines that real statements already covered. Issue #29691. + var stmt_lines_which_have_executed = bun.handleOom(lines_which_have_executed.clone(allocator)); + defer stmt_lines_which_have_executed.deinit(allocator); + for (function_blocks, 0..) |function, i| { if (function.endOffset < 0 or function.startOffset < 0) continue; // does not map to anything @@ -508,14 +517,16 @@ pub const ByteRangeMapping = struct { const did_fn_execute = function.executionCount > 0 or function.hasExecuted; - // only mark the lines as executable if the function has not executed - // functions that have executed have non-executable lines in them and thats fine. + // Mark executable lines for a function that did not execute — but + // preserve hits recorded by statement blocks. if (!did_fn_execute) { const end = @min(max_line, line_count); - @memset(line_hits_slice[min_line..end], 0); for (min_line..end) |line| { executable_lines.set(line); - lines_which_have_executed.unset(line); + if (!stmt_lines_which_have_executed.isSet(line)) { + lines_which_have_executed.unset(line); + line_hits_slice[line] = 0; + } } } @@ -587,6 +598,11 @@ pub const ByteRangeMapping = struct { } } + // Snapshot of lines marked executed by statement blocks above. See the + // same comment in the no-sourcemap branch for rationale. Issue #29691. + var stmt_lines_which_have_executed = bun.handleOom(lines_which_have_executed.clone(allocator)); + defer stmt_lines_which_have_executed.deinit(allocator); + for (function_blocks, 0..) |function, i| { if (function.endOffset < 0 or function.startOffset < 0) continue; // does not map to anything @@ -624,14 +640,16 @@ pub const ByteRangeMapping = struct { const did_fn_execute = function.executionCount > 0 or function.hasExecuted; - // only mark the lines as executable if the function has not executed - // functions that have executed have non-executable lines in them and thats fine. + // Mark executable lines for a function that did not execute — but + // preserve hits recorded by statement blocks. if (!did_fn_execute) { const end = @min(max_line, line_count); for (min_line..end) |line| { executable_lines.set(line); - lines_which_have_executed.unset(line); - line_hits_slice[line] = 0; + if (!stmt_lines_which_have_executed.isSet(line)) { + lines_which_have_executed.unset(line); + line_hits_slice[line] = 0; + } } } diff --git a/test/cli/test/__snapshots__/coverage.test.ts.snap b/test/cli/test/__snapshots__/coverage.test.ts.snap index 23af59233aa9..2035af4863ad 100644 --- a/test/cli/test/__snapshots__/coverage.test.ts.snap +++ b/test/cli/test/__snapshots__/coverage.test.ts.snap @@ -4,7 +4,7 @@ exports[`lcov coverage reporter: lcov-coverage-reporter-output 1`] = ` "TN: SF:demo1.ts FNF:1 -FNH:0 +FNH:1 DA:2,19 DA:3,16 DA:4,1 @@ -18,11 +18,11 @@ FNH:1 DA:2,28 DA:4,11 DA:6,9 -DA:9,0 +DA:9,5 DA:10,0 DA:11,1 DA:14,9 LF:7 -LH:5 +LH:6 end_of_record" `; diff --git a/test/cli/test/coverage.test.ts b/test/cli/test/coverage.test.ts index 26a1ed10b320..11f24505567d 100644 --- a/test/cli/test/coverage.test.ts +++ b/test/cli/test/coverage.test.ts @@ -57,6 +57,47 @@ export class Y { ); }); +// https://github.com/oven-sh/bun/issues/29691 +// +// `class Foo extends Something() {}` has no user-written constructor, so JSC +// synthesizes one from `(function (...args) { super(...args); })`. JSC also +// records that synthetic function in its control-flow profiler indexed by the +// USER's source ID, even though the offsets it records live in the synthetic +// source. Coverage then reported the 37-byte range `[1, 38)` straddling the +// import line and the class declaration line as an uncovered "function" — +// marking line 1 (the import) as `DA:1,0` even though the module loaded. +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).toContain("DA:2,"); // class declaration line was evaluated + expect(subjectRecord).not.toContain("DA:1,0"); // import line is not bogusly marked unexecuted +}); + test("coverage excludes node_modules directory", () => { const dir = tempDirWithFiles("cov", { "node_modules/pi/index.js": ` From 812c2d34441de79614fdca587eedd8d0a4f3c48a Mon Sep 17 00:00:00 2001 From: robobun Date: Fri, 24 Apr 2026 15:08:37 +0000 Subject: [PATCH 2/3] review: preserve same-source collisions, tighten DA:2 assertion, update inline snapshot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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. --- src/jsc/bindings/CodeCoverage.cpp | 22 +++++++++++++++------- test/cli/test/coverage.test.ts | 6 +++--- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/jsc/bindings/CodeCoverage.cpp b/src/jsc/bindings/CodeCoverage.cpp index 39b3e4794e80..374ad80f05f6 100644 --- a/src/jsc/bindings/CodeCoverage.cpp +++ b/src/jsc/bindings/CodeCoverage.cpp @@ -31,7 +31,8 @@ extern "C" bool CodeCoverage__withBlocksAndFunctions( size_t functionStartOffset = basicBlocks.size(); - // Collect byte-offset ranges of synthetic functions reachable from this source. + // Classify function byte-offset ranges reachable from this source as synthetic + // vs. same-source, so we can drop only the synthetic ones from the range list. // // JSC emits a synthetic default class constructor for `class Foo extends Bar() {}` // (and plain `class Foo {}`) by linking a *separate* builtin SourceProvider — @@ -44,9 +45,13 @@ extern "C" bool CodeCoverage__withBlocksAndFunctions( // // The synthetic case is identifiable because `functionExecutable->sourceID()` // resolves to the synthetic provider's ID (via `linkedSourceCode`), not the - // owner's. Collect those (start, end) pairs so we can drop them from the range - // list returned to Bun's coverage reporter. + // owner's. But a real user function CAN have offsets that numerically collide + // with a synthetic constructor's `[1, N)` range (e.g. a user file starting with + // `!function(){}` where the function begins at offset 1). So also collect + // same-source ranges and skip only when a range is synthetic and NOT also + // present in the same-source set. HashSet> syntheticFunctionRanges; + HashSet> sameSourceFunctionRanges; vm.heap.forEachCodeBlock([&](CodeBlock* codeBlock) { auto* owner = codeBlock->ownerExecutable(); if (!owner || owner->sourceID() != sourceID) @@ -55,12 +60,14 @@ extern "C" bool CodeCoverage__withBlocksAndFunctions( auto collect = [&](FunctionExecutable* fnExec) { if (!fnExec) return; - if (fnExec->sourceID() == sourceID) - return; auto* unlinked = fnExec->unlinkedExecutable(); if (!unlinked) return; - syntheticFunctionRanges.add({ unlinked->unlinkedFunctionStart(), unlinked->unlinkedFunctionEnd() }); + std::pair range { unlinked->unlinkedFunctionStart(), unlinked->unlinkedFunctionEnd() }; + if (fnExec->sourceID() == sourceID) + sameSourceFunctionRanges.add(range); + else + syntheticFunctionRanges.add(range); }; for (const auto& fn : codeBlock->functionDecls()) @@ -76,7 +83,8 @@ extern "C" bool CodeCoverage__withBlocksAndFunctions( for (const auto& functionRange : functionRanges) { unsigned start = std::get<1>(functionRange); unsigned end = std::get<2>(functionRange); - if (syntheticFunctionRanges.contains({ start, end })) + std::pair key { start, end }; + if (syntheticFunctionRanges.contains(key) && !sameSourceFunctionRanges.contains(key)) continue; BasicBlockRange range; diff --git a/test/cli/test/coverage.test.ts b/test/cli/test/coverage.test.ts index 11f24505567d..2dc6b83e0ea3 100644 --- a/test/cli/test/coverage.test.ts +++ b/test/cli/test/coverage.test.ts @@ -94,7 +94,7 @@ test("loads the class", () => { 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).toContain("DA:2,"); // class declaration line was evaluated + 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 }); @@ -233,8 +233,8 @@ test("should call only some functions", () => { ---------------|---------|---------|------------------- File | % Funcs | % Lines | Uncovered Line #s ---------------|---------|---------|------------------- -All files | 75.00 | 83.33 | - include-me.ts | 50.00 | 66.67 | +All files | 75.00 | 100.00 | + include-me.ts | 50.00 | 100.00 | test.test.ts | 100.00 | 100.00 | ---------------|---------|---------|------------------- From f5309d0f655ca9d445d137c2c3d3dcb9416432dd Mon Sep 17 00:00:00 2001 From: robobun Date: Fri, 24 Apr 2026 15:23:11 +0000 Subject: [PATCH 3/3] test(coverage): strip ASAN warning from stderr snapshots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- test/cli/test/coverage.test.ts | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/test/cli/test/coverage.test.ts b/test/cli/test/coverage.test.ts index 2dc6b83e0ea3..bb38d8193da7 100644 --- a/test/cli/test/coverage.test.ts +++ b/test/cli/test/coverage.test.ts @@ -3,6 +3,18 @@ import { bunEnv, bunExe, normalizeBunSnapshot, tempDirWithFiles } from "harness" import { readFileSync } from "node:fs"; import path from "path"; +// Debug/ASAN builds print "WARNING: ASAN interferes with JSC signal handlers; …" +// to stderr on every JS-executing process launch — emitted via std::call_once +// in Options.cpp, so at most once per subprocess. It leaks into snapshot tests +// that capture stderr. Strip it before snapshotting so debug-ASAN CI lanes +// match the release snapshot. +function stripAsanWarning(s: string): string { + return s + .split("\n") + .filter(line => !line.startsWith("WARNING: ASAN interferes")) + .join("\n"); +} + test("coverage crash", () => { const dir = tempDirWithFiles("cov", { "demo.test.ts": `class Y { @@ -158,7 +170,7 @@ test("should call both functions", () => { stdio: [null, null, "pipe"], }); - let stderr = result.stderr.toString("utf-8"); + let stderr = stripAsanWarning(result.stderr.toString("utf-8")); // Normalize output for cross-platform consistency stderr = normalizeBunSnapshot(stderr, dir); @@ -223,7 +235,7 @@ test("should call only some functions", () => { stdio: [null, null, "pipe"], }); - let stderr = result.stderr.toString("utf-8"); + let stderr = stripAsanWarning(result.stderr.toString("utf-8")); // Normalize output for cross-platform consistency stderr = normalizeBunSnapshot(stderr, dir); @@ -288,7 +300,7 @@ test("should call all functions", () => { stdio: [null, null, "pipe"], }); - let stderr = result.stderr.toString("utf-8"); + let stderr = stripAsanWarning(result.stderr.toString("utf-8")); // Normalize output for cross-platform consistency stderr = normalizeBunSnapshot(stderr, dir); @@ -355,7 +367,7 @@ test("should call all functions", () => { stdio: [null, null, "pipe"], }); - let stderr = result.stderr.toString("utf-8"); + let stderr = stripAsanWarning(result.stderr.toString("utf-8")); // Normalize output for cross-platform consistency stderr = normalizeBunSnapshot(stderr, dir); @@ -473,7 +485,7 @@ test("should pass", () => { stdio: [null, null, "pipe"], }); - let stderr = result.stderr.toString("utf-8"); + let stderr = stripAsanWarning(result.stderr.toString("utf-8")); // Normalize error output for cross-platform consistency stderr = normalizeBunSnapshot(stderr, dir); @@ -512,7 +524,7 @@ test("should pass", () => { stdio: [null, null, "pipe"], }); - let stderr = result.stderr.toString("utf-8"); + let stderr = stripAsanWarning(result.stderr.toString("utf-8")); // Normalize error output for cross-platform consistency stderr = normalizeBunSnapshot(stderr, dir); @@ -557,7 +569,7 @@ test("should call function", () => { stdio: [null, null, "pipe"], }); - let stderr = result.stderr.toString("utf-8"); + let stderr = stripAsanWarning(result.stderr.toString("utf-8")); // Normalize output for cross-platform consistency stderr = normalizeBunSnapshot(stderr, dir); @@ -610,7 +622,7 @@ test("should call function", () => { stdio: [null, null, "pipe"], }); - let stderr = result.stderr.toString("utf-8"); + let stderr = stripAsanWarning(result.stderr.toString("utf-8")); // Normalize output for cross-platform consistency stderr = normalizeBunSnapshot(stderr, dir);