forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Conversation
github-actions
Bot
force-pushed
the
deps/update-elysia
branch
from
March 1, 2026 04:44
ce6f10a to
a498903
Compare
@github-actions
github-actions
Bot
changed the title
(削除) deps: update elysia to 1.4.25 (削除ここまで)
(追記) deps: update elysia to 1.4.26 (追記ここまで)
Mar 1, 2026
github-actions
Bot
force-pushed
the
deps/update-elysia
branch
from
March 8, 2026 04:37
a498903 to
86d897c
Compare
@github-actions
github-actions
Bot
changed the title
(削除) deps: update elysia to 1.4.26 (削除ここまで)
(追記) deps: update elysia to 1.4.27 (追記ここまで)
Mar 8, 2026
github-actions
Bot
force-pushed
the
deps/update-elysia
branch
from
March 22, 2026 04:42
86d897c to
783cbaa
Compare
@github-actions
github-actions
Bot
changed the title
(削除) deps: update elysia to 1.4.27 (削除ここまで)
(追記) deps: update elysia to 1.4.28 (追記ここまで)
Mar 22, 2026
igorls
pushed a commit
that referenced
this pull request
Apr 9, 2026
Fixes a segfault when reading `.fd` on the result of `Bun.listen({ tls:
{ ... } })`.
`Listener.getFD` was calling `uws_listener.socket(true).fd()` for TLS
listeners. For `is_ssl=true`, the uSockets wrapper
`us_internal_ssl_socket_get_native_handle` returns `s->ssl`, and `fd()`
then calls `SSL_get_fd()` on it. But a listen socket has no SSL object —
SSL is per-connection — so `s->ssl` is uninitialized memory (ASAN poison
`0xbebebe...`) and the call segfaults.
Listen sockets always have a plain poll fd regardless of TLS, so get it
via the non-SSL path.
```
#3 SSL_get_rfd (ssl=0xbebebe0000000018)
#4 SSL_get_fd (ssl=0xbebebe0000000018)
#5 deps.uws.socket.NewSocketHandler(true).fd () at src/deps/uws/socket.zig:283
bun.js.api.bun.socket.Listener.getFD at src/bun.js/api/bun/socket/Listener.zig:532
```
Repro (also triggered when `console.log()` introspects the listener):
```js
const s = Bun.listen({
hostname: "localhost", port: 0,
socket: { data(){}, open(){}, close(){} },
tls: { passphrase: "abc" },
});
console.log(s.fd);
```
Found by Fuzzilli.
---------
Co-authored-by: robobun <robobun@users.noreply.github.com>
igorls
pushed a commit
that referenced
this pull request
Apr 25, 2026
) ## Problem Fuzzilli hit a flaky SIGSEGV (fingerprint `2519cad1804eace1`) from: ```js const v13 = Bun.jest().vi; try { v13.mock("function f2() {\n const v6 = new ArrayBuffer();\n ...\n}"); } catch (e) {} Bun.gc(true); ``` `JSMock__jsModuleMock` calls `Bun__resolveSyncWithSource` on the specifier before validating the callback, which sends the garbage string through the resolver. The resolver's auto-install gate at `loadNodeModules` only checks `esm_ != null`; `ESModule.Package.parse` accepts anything that doesn't start with `.` or contain `\` / `%`, so the whole function source is treated as a package name. `enqueueDependencyToRoot` then calls `PackageManager.sleepUntil`, which re-enters `EventLoop.tick()` from inside a call that is itself running inside an event-loop tick: ``` #0 ConcurrentTask.PackedNextPtr.atomicLoadPtr #1 UnboundedQueue(ConcurrentTask).popBatch #3 event_loop.tickConcurrentWithCount #7 AnyEventLoop.tick #8 PackageManager.sleepUntil #9 PackageManager.enqueueDependencyToRoot oven-sh#10 Resolver.resolveAndAutoInstall oven-sh#16 Bun__resolveSyncWithSource oven-sh#17 JSMock__jsModuleMock ``` The same path is reachable from `Bun.resolveSync`, `import()`, and `require.resolve` with any user-provided string. ## Fix Gate the auto-install branch on `strings.isNPMPackageName(esm_.?.name)`. That validator already exists and is used by `bun link`, `bun pm view`, and the bundler; it rejects newlines, spaces, braces, and anything else that could never be a registry package. Specifiers failing the check fall straight through to `.not_found` — the same result the registry fetch would eventually produce — without initializing the package manager or ticking the event loop. This is a resolver-level fix, so it covers every entry point (not just `mock.module`). It also avoids spurious network requests for garbage specifiers; on this container a single resolve of a multi-line specifier dropped from ~275ms to ~16ms. ## Tests - `test/js/bun/resolve/resolve-autoinstall-invalid-name.test.ts` stands up a local registry and verifies zero manifest requests for a set of invalid names with `--install=force`, plus a positive control that a valid name still hits the registry. - `test/js/bun/test/mock/mock-module-non-string.test.ts` gains a case for `mock.module` with newline / whitespace / bracket specifiers (with and without a callback). - Existing `test/cli/run/run-autoinstall.test.ts` (11 tests) and `test/js/bun/test/mock/mock-module.test.ts` all pass. Related: oven-sh#28945, oven-sh#28956, oven-sh#28500, oven-sh#28511. Fingerprint: `2519cad1804eace1`
igorls
pushed a commit
that referenced
this pull request
Apr 25, 2026
...yToRoot (oven-sh#29483) Fuzzilli found a use-after-poison in the runtime auto-install path. `enqueueDependencyToRoot` passed `&lockfile.buffers.dependencies.items[dep_id]` into `enqueueDependencyWithMainAndSuccessFn`. When the manifest for the requested package is already cached (on disk or in memory) but the extracted tarball is not, control reaches `getOrPutResolvedPackageWithFindResult`, which calls `Lockfile.Package.fromNPM`. That grows `buffers.dependencies` via `ensureUnusedCapacity` to make room for the package's own dependencies, reallocating the backing storage. The subsequent `.extract` branch then read `dependency.behavior.isRequired()` from the freed buffer. ``` #0 getOrPutResolvedPackageWithFindResult PackageManagerEnqueue.zig:1520 dependency.behavior.isRequired() #1 getOrPutResolvedPackage PackageManagerEnqueue.zig:1778 #2 enqueueDependencyWithMainAndSuccessFn PackageManagerEnqueue.zig:523 #3 enqueueDependencyToRoot PackageManagerEnqueue.zig:321 #4 Resolver.enqueueDependencyToResolve resolver.zig:2356 ... oven-sh#14 Bun__resolveSync oven-sh#15 functionImportMeta__resolveSyncPrivate (runtime require() path) ``` Two changes: - `enqueueDependencyToRoot` now copies the `Dependency` to the stack before taking its address, matching every other caller of `enqueueDependencyWithMainAndSuccessFn` (`processDependencyListItem`, `processPeerDependencyList`, etc.). - The one read that ran after `fromNPM` now uses the `behavior` parameter that was already passed by value, instead of re-dereferencing `dependency`. Repro (debug/ASAN only): auto-install a package with a warm on-disk manifest but no extracted tarball — `fromNPM` appending even a single dependency forces a realloc of the one-entry buffer. The new test warms the cache, removes the extracted tarballs, and runs `require()` via `-e` so it goes through `Bun__resolveSync` → `enqueueDependencyToRoot`.
igorls
pushed a commit
that referenced
this pull request
Apr 25, 2026
`ResolveMessage.create` stored the `referrer` path via `Fs.Path.init`
without cloning. Every caller passes a temporary buffer — the `toUTF8()`
of a `bun.String` that is `deinit()`'d on return — so reading
`.referrer` after the creating frame unwound was a use-after-free.
Found by Fuzzilli as a flaky `use-after-poison` via `vi.mock()` →
`Bun__resolveSyncWithSource` → `resolveMaybeNeedsTrailingSlash`, but it
reproduces deterministically under ASAN with any non-ASCII source path:
```js
let err;
try {
Bun.resolveSync("./does-not-exist", "/tmp/café-🎉/file.js");
} catch (e) { err = e; }
Bun.gc(true);
err.referrer; // use-after-poison
```
```
==3080==ERROR: AddressSanitizer: use-after-poison on address 0x77cca9db0000 ...
READ of size 44 at 0x77cca9db0000 thread T0
#0 in __asan_memcpy
#1 in Zig::toStringCopy(ZigString) helpers.h:217
#2 in ZigString__toValueGC bindings.cpp:3402
#3 in ZigString.toJS ZigString.zig:57
#4 in ResolveMessage.getReferrer ResolveMessage.zig:221
```
In release builds the first 8 bytes of the returned referrer are
overwritten by mimalloc's free-list pointer instead of crashing.
Clone the referrer in `create()` and free it in `finalize()`. Also
`deinit()` the `toUTF8()` temporaries in `processFetchLog` now that
`create()` copies.
Co-authored-by: robobun <robobun@users.noreply.github.com>
igorls
pushed a commit
that referenced
this pull request
May 6, 2026
...double-free in deinit (oven-sh#29988) ## Repro Dev server with a directory watch that has two pending resolution-failure dependencies (`./sub/a` at index 0, `./sub/b` at index 1). Create `sub/a.ts` so dep 0 resolves; because it is not the tail slot, `freeDependencyIndex(0)` pushes index 0 onto `dependencies_free_list`. Shut the server down. ``` ==ERROR: AddressSanitizer: negative-size-param: (size=-6148914691236517206) #1 mem.Allocator.free #2 bake.DevServer.deinit /workspace/bun/src/bake/DevServer.zig:686 #3 bun.js.api.server.NewServer(.http,.debug).deinitIfWeCan Address 0xaaaaaaaaaaaaaaaa is a wild pointer ``` ## Cause `DirectoryWatchStore.freeDependencyIndex` frees `dep.specifier` and (in debug) sets the whole slot to `undefined`, then pushes the index onto `dependencies_free_list`. The slot stays in `dependencies.items`. `DevServer.deinit` iterates every `dependencies.items` slot and calls `alloc.free(watcher.specifier)` without consulting the free list, so free-list slots are freed a second time. In debug builds the `undefined` (0xAA...) slice trips ASAN's negative-size check; in release it is a straight double-free. `memoryCost` has the same blind iteration and would read `.len` from freed memory. ## Fix After freeing, write an empty slice back into `specifier` so the slot is safe to revisit: `alloc.free(&.{})` is a no-op and `.len == 0`. ## Verification New test `deinit with a free-list slot in DirectoryWatchStore.dependencies` in `test/bake/dev/bundle.test.ts` arranges the free-list slot and lets the harness's graceful-exit call `deinit`. - `git stash -- src/ && bun bd test ... -t 'deinit with a free-list slot'` → 3/3 **fail** (ASAN abort at DevServer.zig:686) - with fix → 3/3 **pass** - adjacent `removing 'use client' from a component with a pending resolution failure` test still passes --------- Co-authored-by: robobun <robobun@users.noreply.github.com>
igorls
pushed a commit
that referenced
this pull request
May 6, 2026
...ion getters (oven-sh#30078) ## Problem `server.upgrade(req, opts)` reads `Sec-WebSocket-Key` / `Sec-WebSocket-Protocol` / `Sec-WebSocket-Extensions` from `request.getFetchHeaders()` via `FetchHeaders.fastGet`, which returns a `ZigString` that **borrows** directly from the header map entry's `StringImpl` (`bindings.cpp` `WebCore__FetchHeaders__fastGet_` → `Zig::toZigString(StringView)`, no ref taken). It then invokes the `opts.data` / `opts.headers` getters — arbitrary user JS — and only afterwards passes those borrowed slices to `resp.upgrade()`. A getter that mutates `req.headers` (e.g. `req.headers.set('sec-websocket-key', ...)`) drops the sole ref on the original `StringImpl` (`HTTPHeaderMap::set` does a `RefPtr` assignment), freeing it. `resp.upgrade()` then reads freed memory for the key/protocol/extensions. ```js Bun.serve({ fetch(req, server) { req.headers; // materialize FetchHeaders server.upgrade(req, { get data() { req.headers.set('sec-websocket-key', 'x'); // frees the borrowed StringImpl return undefined; }, }); }, websocket: { message() {} }, }); ``` The re-entrancy guard after the getters only checks `isAbortedOrEnded() / didUpgradeWebSocket()`, not header mutation. The `opts.headers` path was already defensively cloning with `toSliceClone` (because `fastRemove` there frees the backing); the `request.headers` path was missed. ## Fix Clone `sec_websocket_key` / `protocol` / `extensions` into owned `ZigString.Slice` storage immediately after reading them from `request.getFetchHeaders()`, so the bytes stay valid across the option getters and `resp.upgrade()`. The `opts.headers` override path reuses the same owned slots (freeing the previous clone first). ## Verification New test in `test/js/bun/websocket/websocket-server-upgrade-reentrant.test.ts` spawns a subprocess with `Malloc=1` (routes bmalloc → system heap so ASAN observes `StringImpl` frees) and has an `opts.data` getter overwrite all three `Sec-WebSocket-*` headers. **Before** (src/ stashed, `bun bd test`): ``` ==ERROR: AddressSanitizer: heap-use-after-free #3 uWS::HttpResponse<false>::upgrade ... HttpResponse.h:269 #6 server.zig:1076 (resp.upgrade call) (fail) server.upgrade() clones Sec-WebSocket-* from request.headers before running option getters ``` **After**: all three tests in the file pass. Also fails on `USE_SYSTEM_BUN=1` (release, no ASAN) — with `Malloc=1` the system allocator reuses the freed slot and the WebSocket client rejects the handshake (bad `Sec-WebSocket-Accept` / mismatched protocol). Co-authored-by: robobun <robobun@users.noreply.github.com>
igorls
pushed a commit
that referenced
this pull request
May 6, 2026
...es (oven-sh#30077) ## What When a chunked (or HTTP/3) request body exceeds `maxRequestBodySize`, `onBufferedBodyChunk` writes the 413 directly on the raw uWS response: ```zig resp.writeStatus("413 Payload Too Large"); resp.endWithoutBody(comptime !http3); ``` `internalEnd` → `markDone()` nulls `onAborted`, so when the socket closes no abort ever fires to detach `ctx.resp` or release the base ref. `this.resp` is left pointing at a completed response whose socket is about to be freed by `us_internal_free_closed_sockets`. If the fetch handler returned a pending Promise: - **resolve**: `handleResolve` → `isAbortedOrEnded()` is false (`this.resp != null`) → `render()` → `runCorkedWithType` corks the freed socket → **heap-use-after-free** (ASAN trace below). - **reject**: `handleReject` reads `resp.hasResponded()` off freed memory, sees `true`, skips the error handler, and returns without ever releasing the base ref → **RequestContext leaks** (`server.pendingRequests` never returns to 0). ## Fix Route through `this.endWithoutBody()` (the `RequestContext` wrapper) instead of the raw `resp.endWithoutBody()`. That path does `detachResponse()` (nulls `this.resp`, clears `onData`/`onAborted`/`onTimeout`) and `deref()` (releases the base ref), matching every other end path in this file. The body promise is rejected with the specific `"Request body exceeded maxRequestBodySize"` error *before* `endWithoutBody()` so `endRequestStreaming()` doesn't overwrite it with a generic `ConnectionClosed`. `has_written_status` is set so any later `renderMissing`/`renderMetadata` knows the status line is already committed. ## Repro ``` ==ERROR: AddressSanitizer: heap-use-after-free #0 us_socket_group socket.c:77 #1 uWS::AsyncSocket<false>::getLoopData() AsyncSocket.h:69 #2 uWS::AsyncSocket<false>::isCorked() AsyncSocket.h:141 #3 uWS::HttpResponse<false>::cork(...) HttpResponse.h:647 #4 uws_res_cork libuwsockets.cpp:1740 #5 ...runCorkedWithType Response.zig:299 #6 ...doRenderBlob RequestContext.zig:1942 ... oven-sh#11 ...handleResolve RequestContext.zig:220 oven-sh#12 ...onResolve RequestContext.zig:154 freed by: #1 us_poll_free epoll_kqueue.c:73 #2 us_internal_free_closed_sockets loop.c:305 ``` ## Test `test/js/bun/http/serve-pending-promise-abort-leak.test.ts` — new case sends a raw `Transfer-Encoding: chunked` POST exceeding `maxRequestBodySize` with a handler that holds its resolve/reject, waits for the socket to be reclaimed, then settles the Promise. Asserts `pendingRequests` returns to 0 for both paths, the body was rejected with the right message, and a follow-up request still works. Without the fix: ASAN heap-use-after-free on the resolve path; on release builds the reject path shows `pendingAfterReject: 1` (leak). Co-authored-by: robobun <robobun@users.noreply.github.com>
igorls
pushed a commit
that referenced
this pull request
May 6, 2026
...to prevent UAF (oven-sh#30057) ## What `UDPSocket.sendMany()` and `UDPSocket.send()` both captured raw pointers into the payload's ArrayBuffer backing store (or borrowed `WTFStringImpl` storage for Latin-1 strings) and then hit JSC safepoints before handing those pointers to `bsd_sendmmsg`: - **`sendMany`**: subsequent loop iterations call `iter.next()` (slow path → `JSObject.getIndex`), `coerceToInt32` on the port, and `toBunString` on the address - **`send`**: `parseAddr` calls `coerceToInt32` on the port and `toBunString` on the address after the payload is captured Any of these can run user JS that detaches an earlier payload's ArrayBuffer via `.transfer(newLen)` (which synchronously frees the old backing store) or drops the last reference to a JSString, leaving the captured pointer dangling. ## Repro ```js const buf = new ArrayBuffer(4096); const payload = new Uint8Array(buf); const evilPort = { valueOf() { buf.transfer(0); // synchronously frees the 4096-byte backing store return server.port; }, }; client.sendMany([payload, evilPort, "127.0.0.1"]); // or client.send(payload, evilPort, "127.0.0.1") // bsd_sendmmsg reads 4096 bytes from the freed region ``` Under ASAN (with `Malloc=1` so bmalloc routes through the system heap): ``` ==...==ERROR: AddressSanitizer: heap-use-after-free on address ... at pc ... READ of size 4096 at ... thread T0 #0 ... in read_iovec(...) #2 ... in sendmmsg #3 ... in bsd_sendmmsg packages/bun-usockets/src/bsd.c:123 freed by thread T0 here: ... oven-sh#14 ... in JSC::arrayBufferCopyAndDetach(...) JSArrayBufferPrototype.cpp:365 ... oven-sh#30 ... in JSC::JSValue::toInt32(...) ← parseAddr's coerceToInt32 ``` ## Fix - **`sendMany`**: root every payload JSValue in a `MarkedArgumentBuffer` for the duration of the call and split the loop into two phases. Phase 1 collects/validates payload JSValues and runs all user-JS re-entrance (`iter.next`, `parseAddr`). Phase 2 borrows byte slices from the rooted JSValues once no more user JS sits between capture and `socket.send`. GC cannot collect a rooted payload; an ArrayBuffer that was detached during phase 1 reports a zero-length slice instead of a dangling pointer. No payload bytes are copied. - **`send`**: reorder so `parseAddr` runs before the payload pointer is captured. `payload_arg` stays rooted in the callframe, and nothing between capture and `socket.send` hits a JSC safepoint — so no copy is needed. ## Verification - **Without fix:** `bun bd test test/js/bun/udp/udp_socket.test.ts -t 'detaching an ArrayBuffer'` → ASAN heap-use-after-free in `read_iovec` → `bsd_sendmmsg` for both `send` and `sendMany`, tests fail - **With fix:** both tests pass; received bytes match the original payload - Full `test/js/bun/udp/` suite (207 tests) passes - `zig:check-all` passes on all targets --------- Co-authored-by: robobun <robobun@users.noreply.github.com> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
igorls
pushed a commit
that referenced
this pull request
May 6, 2026
## Problem
`MarkedArrayBuffer.destroy()` did two things:
```zig
allocator.free(content.buffer.slice()); // free the bytes
allocator.destroy(this); // free *this
```
Every constructor that is actually used (`fromString`, `fromBytes`,
`fromJS`, `fromTypedArray`, `fromArrayBuffer`) returns
`MarkedArrayBuffer` **by value**, so `this` is never an individually
heap-allocated struct — it's a stack local, an embedded field, or an
ArrayList slot. The `allocator.destroy(this)` call passes that interior
pointer to mimalloc.
In the readdir Buffer error-cleanup path (`readdirWithEntries` /
`readdirInner`), entries are appended by value via
`Buffer.fromString()`:
- `allocator.destroy(&entries.items[0])` frees `entries.items.ptr`
- the next loop iteration reads `this.*` from poisoned memory
- `entries.deinit()` frees the same pointer again
## Repro
```js
const fs = require('fs');
// dir contains regular files + a self-referential symlink 'loop -> loop'
fs.readdirSync(dir, { encoding: 'buffer', recursive: true });
```
The recursive walk collects Buffer entries for the root, then fails with
`ELOOP` opening the symlink (not in the swallowed `NOENT/NOTDIR/PERM`
set), and enters the cleanup loop. Under ASAN:
```
==3593==ERROR: AddressSanitizer: use-after-poison on address 0x737ec6e50040
READ of size 64 at 0x737ec6e50040 thread T0
#1 MarkedArrayBuffer.destroy array_buffer.zig:591
#2 NodeFS.readdirInner node_fs.zig:5013
#3 NodeFS.readdir node_fs.zig:4518
```
## Fix
- Drop `allocator.destroy(this)` from `MarkedArrayBuffer.destroy()`. The
struct is passed/stored by value; callers own its storage.
- Remove the unused `MarkedArrayBuffer.init()` (the only function that
heap-allocated the struct, zero callers) so there's no pairing that
would leak.
- The readdir call sites keep calling `.destroy()`, which still checks
`this.allocator` before freeing bytes — JS-owned buffers remain
untouched.
Also fixed the adjacent `Dirent` arm of the recursive-sync error
cleanup: `result.name.deref()` → `result.deref()` so `Dirent.path` is
released too (matching the non-recursive and async cleanup sites).
## Verification
New test in `test/js/node/fs/fs.test.ts` creates a temp dir with files +
a self-referential symlink, spawns a subprocess that calls
`readdirSync({encoding:'buffer', recursive:true})`, and asserts it
throws `ELOOP` and exits 0.
```
# without fix
(fail) readdirSync({encoding: 'buffer', recursive: true}) frees entries safely ...
{ exitCode: 134, stdout: "" } # SIGABRT from ASAN
# with fix
(pass) readdirSync({encoding: 'buffer', recursive: true}) frees entries safely ... [1.5s]
{ exitCode: 0, stdout: "ELOOP" }
```
`zig:check-all` passes on all targets.
---------
Co-authored-by: robobun <robobun@users.noreply.github.com>
igorls
pushed a commit
that referenced
this pull request
May 6, 2026
...en-sh#30196) ## What does this PR do? Fixes a use-after-free in `HTMLRewriter.transform()` that caused flaky SIGSEGV crashes found by fuzzing. When transforming a string or ArrayBuffer, the body is buffered synchronously and fed to lol-html via `write()` followed by `end()`. If a document/element handler returns a rejected promise for the final `lastInTextNode` chunk (emitted from `end()`), the `end() catch` branch in `BufferOutputSink.runOutputSink` would call `response.finalize()` directly on the output `Response`. That `Response` is already owned by its JS wrapper cell (created earlier in `init()` via `sink.response.toJS()`), so destroying it in-place left the wrapper's `m_ctx` pointing at freed memory. When GC later swept the wrapper, its destructor invoked `Response.finalize()` again on that freed pointer: ``` AddressSanitizer: use-after-poison #0 bun.js.bindings.JSRef.JSRef.deinit src/bun.js/bindings/JSRef.zig:188 #1 bun.js.bindings.JSRef.JSRef.finalize src/bun.js/bindings/JSRef.zig:200 #2 bun.js.webcore.Response.finalize src/bun.js/webcore/Response.zig:474 #3 ResponseClass__finalize codegen/ZigGeneratedClasses.zig:17250 #4 WebCore::JSResponse::~JSResponse() codegen/ZigGeneratedClasses.cpp:54979 ``` The `write()` error path (just above it) already handled this correctly by returning the error and letting the JS wrapper own the Response lifetime. This PR makes the `end()` error path do the same — drop the manual `response.finalize()` and `sink.response = undefined`. ## How did you verify your code works? Minimal repro that reliably triggers the ASAN error before the fix and passes cleanly after: ```js const rewriter = new HTMLRewriter(); rewriter.onDocument({ text(chunk) { if (chunk.lastInTextNode) { return Promise.reject(new Error("boom")); } }, }); try { rewriter.transform(new Uint8Array([97, 98, 99]).buffer); } catch (e) {} Bun.gc(true); ``` Added regression tests in `test/js/workerd/html-rewriter.test.js` covering both ArrayBuffer and string inputs. All existing HTMLRewriter tests pass. --------- Co-authored-by: robobun <robobun@users.noreply.github.com>
igorls
pushed a commit
that referenced
this pull request
May 6, 2026
...0174) ## What `RequestContext` stored `response_ptr: ?*Response` and, for plain `Blob`/`InternalBlob`/`WTFStringImpl` bodies, left the Response JSValue unprotected. `renderBytes()` → `tryEnd()` can hit backpressure and register an `onWritable` callback, unwinding with `response_ptr` still set. Nothing rooted the Response (`RequestContext` is a pool struct, not GC-visited), so GC could finalize it. If the client then aborted while the request body was still `.Locked`, `onAbort()` dereferenced a freed `*Response` — heap-use-after-free under ASAN at `RequestContext.zig:692`. ## Repro ``` POST → handler returns new Response(8MB string) sync → tryEnd() backpressure (client paused) → onWritable registered, return → Bun.gc(true) → Response collected, response_ptr dangles → client.destroy() → onAbort → deref response_ptr → UAF ``` ASAN trace (unpatched): ``` ==ERROR: AddressSanitizer: use-after-poison #0 bun.js.bindings.JSRef.JSRef.tryGet #1 bun.js.webcore.Response.getBodyReadableStream #2 RequestContext.onAbort src/bun.js/api/server/RequestContext.zig:693 #3 uWS::HttpContext<false>::onClose ``` ## Fix Give `Response` a `weak_ptr_data` field (mirroring `Request.WeakRef`) and replace `response_ptr: ?*Response` with `response_weakref: Response.WeakRef` via `bun.ptr.WeakPtr`. `Response.destroy()` now defers freeing the allocation until outstanding weak refs drop; `WeakRef.get()` returns null once the contents are gone. `onAbort` / `handleResolveStream` / `handleRejectStream` call `.get()` and simply skip the readable-stream cleanup when it's null — a no-op for in-memory bodies anyway, since the body was already extracted via `useAsAnyBlobAllowNonUTF8String()` before backpressure. File-backed and `.Locked` bodies continue to `protect()` `response_jsvalue` as before; those paths need the Response's status/headers alive across the async hop for `renderMetadata()`. The hot path (small in-memory responses) no longer needs `protect()`/`unprotect()`. The two redundant `ctx.response_ptr = response` assignments right before `ctx.render(response)` are dropped — `render()` already sets the weak ref. ## Verification `test/js/bun/http/serve-response-gc-backpressure-abort.test.ts` (ASAN/debug-only): POST with incomplete chunked body so `request_body` stays `.Locked`, handler returns a large string Response, client pauses so `tryEnd()` stalls, `Bun.gc(true)` loop, then client closes. - **without fix**: `AddressSanitizer: use-after-poison` in `onAbort` → `Response.getBodyReadableStream` - **with fix**: passes, `abortCount === iterations`, `pendingRequests === 0` --------- Co-authored-by: robobun <robobun@users.noreply.github.com>
igorls
pushed a commit
that referenced
this pull request
May 6, 2026
...worker panic, never retry (oven-sh#30216) ## What `bun test --isolate` / `--parallel` crashes when a test file loads a native addon whose deferred napi finalizers outlive the file. The `--parallel` coordinator then silently retries the file once, which masks the panic and lets the run exit 0. Fixes oven-sh#30205, oven-sh#30191. Supersedes oven-sh#30214 (same NapiEnv fix, but without the coordinator change, the `cleanup_hooks` retarget, or a test that actually reproduces on unpatched `main`). ## Reproduction ```sh git clone https://github.com/workglow-dev/libs && cd libs bun i && bun run build:packages bun test --timeout=30000 --parallel=4 packages/test/src/test/{util,task}/*.test.ts ``` On `main` (d484fd6), 3–4 workers crash per run with either ``` ASSERTION FAILED: isMarked(cell) JavaScriptCore/heap/Heap.cpp:1232 : void JSC::Heap::addToRememberedSet(const JSCell *) ``` or (when the slot is already being reallocated) ``` ASSERTION FAILED: m_cellState == CellState::DefinitelyWhite JavaScriptCore/JSCellInlines.h:69 : JSC::JSCell::JSCell(VM &, Structure *) ``` and in release builds the segfaults at `0x68` / `0xD0` reported in oven-sh#30205. ## Root cause Frame-pointer walk from the assertion: ``` #3 Bun::NapiHandleScope::open(Zig::GlobalObject*, bool) #4 NapiHandleScope__open #6 napi.Finalizer.run #7 napi.NapiFinalizerTask.runOnJSThread oven-sh#10 event_loop.tick oven-sh#11 event_loop.waitForPromise oven-sh#13 VirtualMachine.loadEntryPointForTestRunner ← next test file ``` `NapiEnv::m_globalObject` is a raw `Zig::GlobalObject*`. For non-experimental addons (`nm_version != NAPI_VERSION_EXPERIMENTAL`, which is ~every real-world addon — sharp, better-sqlite3, etc.), `napi_wrap`/`napi_create_external` finalizers are **deferred** to the event loop as `NapiFinalizerTask` rather than run inside GC sweep. Objects rooted on the old global (module graph, `globalThis.*`) only become collectable when `Zig__GlobalObject__createForTestIsolation` runs `gcUnprotect(oldGlobal)`. The `DeferGC` from oven-sh#29573 ends at that function's `}`, so the next GC runs there, collects those objects, and enqueues their finalizers. Those tasks then run on the very next `eventLoop().tick()` — inside `loadEntryPointForTestRunner`'s `waitForPromise` for file N+1. `Finalizer.run` opens a `NapiHandleScope` via `env->globalObject()`, which reads `NapiHandleScopeImplStructure()` off the dead cell and writes `m_currentNapiHandleScopeImpl` on it → write barrier on an unmarked cell. The `--parallel` coordinator's `reapWorker` then re-queued the file once (`retries[idx] < 1`) into a fresh worker with no stale `NapiEnv`, which passed — so the run reported 0 fail despite multiple Bun panics in the log. ## Fix **NapiEnv retarget** (`ZigGlobalObject.cpp`, `napi.h`): `Zig__GlobalObject__createForTestIsolation` now calls `newGlobal->adoptNapiEnvsForTestIsolation(oldGlobal)` before `gcUnprotect`. Each `NapiEnv::m_globalObject` is repointed at the new global and the `Ref<NapiEnv>`s are moved over, so late finalizers open handle scopes on a live global and the envs stay owned after the old global is swept. `VirtualMachine.swapGlobalForTestIsolation` also repoints `rare_data.cleanup_hooks[*].globalThis` so `CleanupHook.eql()` stays accurate. **No retry, abort on panic** (`Coordinator.zig`): removed the per-file retry. A worker that dies mid-file is counted as one failure. If it died by a fatal signal (SIGILL/SIGTRAP/SIGABRT/SIGBUS/SIGFPE/SIGSEGV/SIGSYS — Bun's own `@trap()`, a JSC/WTF assertion, or native-addon crash), the whole run aborts with `error: a test worker process crashed with <SIG> while running <file>`. `process.exit()` / SIGKILL are still just a per-file failure and the run continues. ## Verification - `test/regression/issue/30205.test.ts` — 4 tests. Adds a tiny non-experimental addon (`isolate_finalizer_addon.c`) and a fixture pattern (`Bun.gc(true)` + module-scope `await 0` + objects rooted on `globalThis`) that crashes **8/8** on unpatched `main` and passes 8/8 with this change. - `workglow-dev/libs` full 201-file unit suite: ×ばつ clean `--parallel=4` runs (was 3–4 crashes/run). - Gate: `git stash -- src/ && bun bd test test/regression/issue/30205.test.ts` → 3/4 fail; with fix → 4/4 pass. - `test/cli/test/isolation.test.ts`, `test/regression/issue/29519.test.ts` → pass (one pre-existing unrelated timeout in isolation.test.ts, same as oven-sh#29573). - `test/cli/test/parallel.test.ts` → all tests I touched pass; the 3 timing-sensitive scale-up/work-steal tests that fail in this container fail identically on unmodified `main`. --------- Co-authored-by: robobun <robobun@users.noreply.github.com> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
igorls
pushed a commit
that referenced
this pull request
May 31, 2026
...ven-sh#31219) ### What does this PR do? Fixes a fuzzer-reported SIGSEGV (fingerprint `a8d2694be898a53f`) in the `Bun.jest()` / `expect` statics area. The reported reproducer exercises `Bun.jest().expect`, `expect.extend()`, and `new` on an expect static: ```js const v2 = Bun.jest().expect; try { v2.extend(); } catch (e) {} const t6 = v2.arrayContaining; new t6(); Bun.gc(true); ``` **Root cause (primary fix):** matchers registered through `expect.extend()` are wrapped in `JSWrappingFunction`. `JSWrappingFunction::create` passed `nullptr` as the native constructor to `VM::getHostFunction`. JSC only treats `callHostFunctionAsConstructor` as "not constructible", so the wrapper was considered constructible with a null native constructor — `new expect.someCustomMatcher()` jumps straight to address 0: ``` Thread 1 received signal SIGSEGV, Segmentation fault. #0 0x0000000000000000 in ?? () #3 llint_op_construct () ``` Deterministic repro (crashes on current main, raw SIGSEGV with no output — matching the fuzzer's crash signature): ```js const e = Bun.jest().expect; e.extend({ myMatcher() { return { pass: true, message: () => "" }; } }); new e.myMatcher(); ``` The fix passes `callHostFunctionAsConstructor` so `new` on a wrapped matcher throws `TypeError: function is not a constructor` like other native functions. **Secondary hardening (same area):** if `Bun__Jest__createTestModuleObject` ever fails it returns an empty `JSValue`, and the `m_lazyTestModuleObject` initializer called `toObject()` on it — a null-cell dereference. The initializer now falls back to a plain object, `Bun__Jest__testModuleObject` surfaces the pending exception, `Bun.jest()` maps it to a thrown JS error, and the `xdescribe` arm of `create_test_module` propagates its error instead of returning an empty value as success. ### How did you verify your code works? - `new (expect.extend-registered matcher)()` segfaults on the baked build and throws a `TypeError` with this change. - Regression test added to `test/js/bun/test/bun-test.test.ts`: it spawns a subprocess that registers a custom matcher, constructs it (plus the original fuzzer shape: `extend()` with no args, `new expect.arrayContaining`), runs `Bun.gc(true)`, and asserts a clean exit. The test fails on the baked build (`USE_SYSTEM_BUN=1`) with the subprocess dying from SIGSEGV, and passes with this change. - `bun bd test` on `bun-test.test.ts`, `expect-extend.test.js`, `jest-extended.test.js`, `expect-extend-asymmetric-match-throw.test.ts`, `expect-extend-preload.test.ts`, `describe.test.ts`, `jest-each.test.ts`, `expect-symbol-toPrimitive-crash.test.ts` — all pass.
igorls
pushed a commit
that referenced
this pull request
May 31, 2026
...s longer than the comparand (oven-sh#31264) ### What does this PR do? Fixes an ASAN `global-buffer-overflow` found by fuzzing the CSS parser: ``` asan:global-buffer-overflow:strncasecmp|eql_case_insensitive_ascii|eql_case_insensitive_ascii|bun_core::string::immutable::eql_case_insensitive_ascii_ignore_length ``` **Repro** ```sh BUN_FEATURE_FLAG_INTERNAL_FOR_TESTING=1 bun -e 'require("bun:internal-for-testing").cssInternals.minifyTest(":nth-child(Nn", "")' ``` ``` ==ERROR: AddressSanitizer: global-buffer-overflow READ of size 2 ... #0 strncasecmp #1 bun_core::strings_impl::eql_case_insensitive_ascii src/bun_core/lib.rs #2 bun_core::string::immutable::eql_case_insensitive_ascii_ignore_length src/bun_core/string/immutable.rs #3 bun_css::css_parser::nth::parse_nth src/css/css_parser.rs #4 bun_css::selectors::parser::parse_nth_pseudo_class src/css/selectors/parser.rs ``` **Cause** `strings_impl::eql_case_insensitive_ascii(a, b, check_len)` defers to `strncasecmp(a, b, a.len())`, which reads up to `a.len()` bytes from *both* buffers. The Zig original (`strings.eqlCaseInsensitiveASCII`) compared against NUL-terminated comptime literals, so `strncasecmp` stopped at the sentinel and reported a mismatch whenever `a` was longer than `b`. Rust byte-string literals carry no terminator, so the An+B parser's ident branch (`parse_nth`), which compares an arbitrary user ident against the keywords `"even" / "odd" / "n" / "-n" / "n-" / "-n-"` with the ignore-length variant, reads past the end of the keyword literal as soon as the ident is longer than the keyword and shares its prefix (`Nn` vs `n`, `n-3` vs `n`, ...). Besides the OOB read, the comparison result depended on whatever byte happens to follow the literal in rodata. **Fix** Reject `b.len() < a.len()` up front in `eql_case_insensitive_ascii` before calling `strncasecmp` — the same result the NUL sentinel produced in Zig, so observable behavior is unchanged for every in-bounds input (all other callers of the ignore-length variant already pass equal-length slices). `strncasecmp` now only ever reads within both slices. **Verification** - `bun bd test test/js/bun/css/nth-anplusb-ident.test.ts` without the fix (src/ stashed): aborts with the ASAN global-buffer-overflow above. - With the fix: passes. The new test covers valid `n-<digits>` idents that are longer than the `n`/`n-` keywords (`:nth-child(n-3)`, `:nth-child(N-3)`, `:nth-last-child(n- 42)`), keyword case-insensitivity (`:nth-child(N)`), an invalid ident (`:nth-child(NN)` → parse error), and the exact fuzzer-minimized input run in a subprocess. - `bun bd test test/js/bun/css/css.test.ts`: 1032 pass, 0 fail (no behavior change for the existing suite). - A second fuzz report hits the same overflow through `Bun.build` with a CSS entrypoint containing `:nth-child(Nn`; that path goes through the same `parse_nth` comparison and is covered by this fix (`Bun.build` now reports a parse error instead of aborting). - The `build-rust` CI failures on this PR (unused label / unnecessary `unsafe` warnings in `src/spawn`, `src/install`, `src/crash_handler`, `src/runtime/ffi`, `src/runtime/dns_jsc`) are present on current `main` commits that don't include this change and come from files this PR doesn't touch.
github-actions
Bot
force-pushed
the
deps/update-elysia
branch
from
June 21, 2026 05:44
783cbaa to
094fc3a
Compare
@github-actions
github-actions
Bot
changed the title
(削除) deps: update elysia to 1.4.28 (削除ここまで)
(追記) deps: update elysia to 1.4.29 (追記ここまで)
Jun 21, 2026
igorls
pushed a commit
that referenced
this pull request
Aug 21, 2026
oven-sh#35255) `test/js/bun/http/serve-protocols.test.ts` has been going red on main (build 78445 darwin-x64 hard, 78462 debian-11-aarch64 hard, plus 78300/78419 with retries), always as ``` error: HTTP3StreamReset fetching "https://127.0.0.1:<port>/echo" ✗ Bun.serve over http/3 > POST echo 1000000 bytes [20169.37ms] ``` Reproduced on Linux by looping the file: the h3 subset alone fails about 17 of 100 runs. ## Cause The ten concurrent h3 tests share one lsquic client engine and one unconnected UDP socket. `bsd_create_udp_socket()` sets `IP_RECVERR` on every UDP socket (for `node:dgram`'s error surfacing, oven-sh#28827), including QUIC's. When a finished test `proc.kill()`s its server, the client session is still in the engine and keeps scheduling retransmits / `NEW_CONNECTION_ID` to an unbound port. With `IP_RECVERR` on, the resulting ICMP port-unreachable is queued on the shared socket and the next `sendmmsg` returns `-1 ECONNREFUSED`, even though that call is sending a datagram to a live peer. `us_quic_packets_out` reports that as a short return, lsquic clears `ENPUB_CAN_SEND` for the whole engine and only its one-second `resume_sending_at` failsafe re-enables it. With several dead sessions generating ICMPs, every failsafe retry fails the same way and the live 1MB upload never advances; the 20s in CI is two idle-timeout rounds through `retry_or_fail`. While tracing that I also found an unsigned underflow in lsquic's `send_batch` requeue loop: when the first unsent spec in a batch coalesces multiple packets (`pack_off[0] == 0`, `iovlen > 1`), `end = &batch->packets[off - 1]` indexes with `UINT_MAX` and only the last packet of the coalesced group is returned to the connection. The earlier ones are the INIT ACK and the HSK CRYPTO carrying the client Finished, so the peer can never complete the handshake. This is the same hang reached from a different direction (real EAGAIN backpressure instead of stale ICMP). ## Fix - `IP_RECVERR` is now opt-in via `LIBUS_UDP_LINUX_RECVERR`, set by `us_create_udp_socket` when a `recv_error_cb` is provided. `node:dgram` always passes one and keeps the option; QUIC passes `NULL` and no longer gets it. This matches libuv's `UV_UDP_LINUX_RECVERR` gating that `bsd.c` already cited. - `us_quic_packets_out()` retries once on a non-`EAGAIN`/`ENOBUFS` send failure before reporting a short return, so a stale `sk_err` that does surface cannot pause the engine. Both the `sendmmsg` and per-packet paths now go through `US_FAULT_CHECK(US_FAULT_SENDMSG, ...)` so the short-return path is reachable from tests. - `patches/lsquic/requeue-unsent-coalesced.patch` rewrites the requeue loop's bounds as `[off, off+count)` so every packet in an unsent coalesced datagram is returned to the connection. The same underflow is present in upstream lsquic master; I will open a PR there separately. - `serve-protocols.test.ts` now stops each fixture server gracefully on stdin close (`server.stop(true)`), matching `serve-http3.test.ts`, so the pooled client session sees `CONNECTION_CLOSE` instead of leaving the engine retransmitting to unbound ports. - `test/js/web/fetch/fetch-http3-syscall-fault.test.ts` injects `EAGAIN` on the coalesced handshake datagram (the `pack_off[0]==0`, `iovlen>1` spec the lsquic patch fixes), a one-shot `ECONNREFUSED` that the retry-once branch consumes, and a burst of `EAGAIN` that the `on_drain` path recovers from. ## Verification Release build, looped: | | before | after | | --- | --- | --- | | `serve-protocols -t "http/3"` | 17/100 fail | 2/100 fail | | `serve-protocols` (full) | 7/100 fail | 4/200 fail | Debug+ASAN: `serve-protocols`, `serve-http3` (46), `fetch-http3-client` (52), `fetch-http3-adversarial` (29), `fetch-http3-syscall-fault` (3) and `dgram.test.ts` all pass, 211 tests total. The residual ~1-2% is a separate pre-existing bug (the client's 36-byte HSK CRYPTO is buffered but never flushed when `drain_send_body` writes the whole 1MB body synchronously from `on_stream_open`); I've handed that off as its own issue. With CI's retry it is well under the flake threshold. ### Gate note The fault-injection hook that makes the new test deterministic lives in `packages/bun-usockets/src/quic.c`, so `git stash -- src/ packages/` removes it along with the fix and the fault never fires. The lsquic piece lives in `patches/` and `scripts/`, which the stash does not touch. That means a single stashed run passes (no fault, no stall) and a single unstashed run passes (fault fires, fix handles it), and the gate cannot distinguish them mechanically. The 300-iteration probe above is the evidence; the fault-injection tests pin the behavior going forward. <details> <summary>lsquic debug trace of the stall</summary> ``` engine: packets out returned 0 (out of 1) [C919...] event: unsent packet oven-sh#15 ACK_FREQUENCY, size 36 [C919...] sendctl: packet oven-sh#15 has been delayed engine: send_packets_out: sent 0 packets ... <- no "can send again"; nothing for 1s engine: failsafe activated: resume sending packets again after timeout engine: packets out returned 0 (out of 10) <- fails again, live conn's oven-sh#207 included ``` and for the underflow, a batch with `pack_off[0]=0`, `iovlen[0]=3`: ``` engine: packets out returned 0 (out of 2) event: unsent packet #3 ACK PADDING, size 1059 event: unsent packet #4 ACK CRYPTO, size 87 event: unsent packet #5 NEW_CONNECTION_ID, size 54 event: unsent packet #6 STREAM, size 114 sendctl: packet #6 has been delayed sendctl: packet #5 has been delayed ... <- #3 and #4 never requeued [WARN] sendctl: send history gap 2 - 5 ``` </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 1 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/web/fetch/fetch-http3-syscall-fault.test.ts <!-- robobun:evidence:end --> --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
igorls
pushed a commit
that referenced
this pull request
Aug 21, 2026
...ed (oven-sh#36247) ## What `test/js/bun/http/bun-serve-html.test.ts` segfaults on `windows-aarch64` after oven-sh#36175 landed (builds 84162, 84194; one earlier sighting in 83933): ``` panic(main thread): Segmentation fault at address 0x48 Features: ... dev_server(14) ... ``` Symbolicated in oven-sh#36214 as `AsyncFSTask<Access>::run_from_js_thread` with `self = null`, i.e. a zeroed `ConcurrentTask` was dispatched. ## Cause `DevServer.watcher_atomics.events[*].concurrent_task` is the intrusive MPSC node the watcher thread links into `EventLoop.concurrent_tasks` when it submits a hot-reload event. It was an inline field of `DevServer`, so `server.stop()` → `drop(Box<DevServer>)` freed it while it was still linked. The next `tick_concurrent` then read `.next`/`.task`/`.auto_delete` from freed memory. ASAN on Linux confirms: ``` heap-use-after-free: ConcurrentTask::get_next (unbounded_queue.rs) ← BatchIterator::next ← EventLoop::tick_concurrent_with_count freed by: Box<DevServer>::drop ← NewServer::deinit_if_we_can ← NewServer::stop ← dispose_from_js (using server) ``` On release builds the freed block reads back as zeros, so the copied `Task` is `{tag: 0, ptr: null}`; tag 0 is `task_tag::Access`, whose `run_from_js_thread` loads `self.result` at offset `0x48`. The bug is latent and platform-agnostic. oven-sh#36175 exposed it because the CI runner now spawns the napi addon prebuild in the background while serial tests run; that writes under the watched project root, so the `jsx-runtime` DevServers in this test file now reliably receive a hot-reload event between the last `await fetch` and `using server` disposal. ## Fix `watcher_atomics` is now a `NonNull<WatcherAtomics>` owned via `bun_core::heap::into_raw`, so the allocation can outlive `DevServer` and every queued pointer keeps allocation-root provenance. `watcher_acquire_event`, `watcher_release_and_submit_event` and `recycle_event_from_dev_server` take `*mut Self` and derive the returned `*mut HotReloadEvent` (and the linked `concurrent_task` node) from that root pointer via raw place projections rather than from a `&mut WatcherAtomics` reborrow. `Drop for DevServer` reads `next_event` after `Watcher::shutdown` has serialised out the watcher thread (which guarantees it is stable): - `DONE`: nothing is queued; clear and `heap::destroy` as before. - otherwise: a `concurrent_task` is still linked (or its `Task` is already in the drain FIFO). Null `owner` on every event and leave the allocation alive. `HotReloadEvent::run` checks `owner.is_null()` first; when set it reclaims the allocation via the new `atomics` backref and returns without touching the dead `DevServer`. The `# Safety` contracts on `run` and the `BakeHotReloadEvent` dispatch arm are updated to describe the null-owner case. ## Test `test/js/bun/http/bun-serve-html-hot-reload-drop.test.ts` creates a development server, bundles once so `app.js` is watched, synchronously rewrites `app.js`, spins briefly without yielding so the watcher thread can enqueue, disposes the server, then yields. Ten iterations. In a separate file because the React-bundling cases in `bun-serve-html.test.ts` already exceed the default per-test timeout under a debug+ASAN build on `main`. <details><summary>fail-before (debug+ASAN, src/ at main)</summary> ``` ==25521==ERROR: AddressSanitizer: heap-use-after-free on address 0x79315e4743e8 READ of size 8 at 0x79315e4743e8 thread T0 #2 <ConcurrentTask as Node>::get_next unbounded_queue.rs:82 #3 BatchIterator<ConcurrentTask>::next unbounded_queue.rs:135 #4 EventLoop::tick_concurrent_with_count event_loop.rs:507 0x79315e4743e8 is located 488 bytes inside of 16512-byte region freed by thread T0 here: #9 Box<DevServer>::drop oven-sh#12 NewServer<false,true>::deinit_if_we_can mod.rs:1770 oven-sh#13 NewServer<false,true>::stop mod.rs:1665 oven-sh#14 NewServer<false,true>::dispose_from_js server_body.rs:2584 ``` </details> Passes with the fix in ~2.4s under debug+ASAN (also on a local `windows-aarch64` debug build, where the original `bun-serve-html.test.ts` is now 19/19); `test/bake/deinitialization.test.ts` still green. Supersedes the producer half of oven-sh#36214 (which adds a sentinel for the same zeroed-task symptom). <!-- robobun:evidence:begin --> --- **[review]** gate passed · iteration 4 · 6 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 1 failed, 2 skipped $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/bun/http/bun-serve-html.test.ts test/js/bun/http/bun-serve-html-hot-reload-drop.test.ts bun test v1.4.0 (5f6622f) test/js/bun/http/bun-serve-html.test.ts: waitForServer /tmp/html-css-js_ObkyZk { "/": "/tmp/html-css-js_ObkyZk/index.html", "/dashboard": "/tmp/html-css-js_ObkyZk/dashboard.html", } [0.12ms] bundle index.html 1.09 KB [0.05ms] bundle dashboard.html 1.27 KB (pass) serve html [630.67ms] waitForServer /tmp/bun-serve-html-txt_5C6B7a { "/": "/tmp/bun-serve-html-txt_5C6B7a/index.html", } [0.15ms] bundle index.html 0.40 KB HASH efbnbska (pass) serve plugins > basic plugin [556.20ms] waitForServer /tmp/html-css-js-failing-plugin_OPRhwb { "/": "/tmp/html-css-js-failing-plugin_OPRhwb/index.html", } error: Plugin failed intentionally at /tmp/html-css-js-failing-plugin_OPRhwb/styles.css:0 error: Plugin failed intentionally at /tmp/html-css-js-failing-plugin_OPRhwb/styles.css:0 (pass) serve plugins > serve html with failing plugin [491.35ms] waitForServer /tmp/html-css-js-empty-plugins_biqnN6 { "/": "/tmp/htm ... (truncated) release without fix: all passed bun test v1.4.0-canary.1 (96ff7ec) test/js/bun/http/bun-serve-html.test.ts: waitForServer /tmp/html-css-js_ZmgkBG { "/": "/tmp/html-css-js_ZmgkBG/index.html", "/dashboard": "/tmp/html-css-js_ZmgkBG/dashboard.html", } [0.00ms] bundle index.html 1.09 KB [0.00ms] bundle dashboard.html 1.27 KB (pass) serve html [25.17ms] waitForServer /tmp/bun-serve-html-txt_uWNogT { "/": "/tmp/bun-serve-html-txt_uWNogT/index.html", } [0.00ms] bundle index.html 0.40 KB HASH efbnbska (pass) serve plugins > basic plugin [17.25ms] waitForServer /tmp/html-css-js-failing-plugin_Kd1a8p { "/": "/tmp/html-css-js-failing-plugin_Kd1a8p/index.html", } error: Plugin failed intentionally at /tmp/html-css-js-failing-plugin_Kd1a8p/styles.css:0 error: Plugin failed intentionally at /tmp/html-css-js-failing-plugin_Kd1a8p/styles.css:0 (pass) serve plugins > serve html with failing plugin [16.33ms] waitForServer /tmp/html-css-js-empty-plugins_Ecz7qJ { "/": "/tmp/html-css-js-empty-plugins_Ecz7qJ/index.html", } [0.00ms] bundle index.html 0.71 KB (pass) serve plugins > empty plugin array [13.23ms] Waiting for server waitForServer /tmp/html-css-js-concurrent-plugins_l7wQg5 { "/": "/tmp/ ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: 2 skipped $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/bun/http/bun-serve-html.test.ts test/js/bun/http/bun-serve-html-hot-reload-drop.test.ts bun test v1.4.0 (5f6622f) test/js/bun/http/bun-serve-html.test.ts: waitForServer /tmp/html-css-js_CpXhx4 { "/": "/tmp/html-css-js_CpXhx4/index.html", "/dashboard": "/tmp/html-css-js_CpXhx4/dashboard.html", } [0.09ms] bundle index.html 1.09 KB [0.05ms] bundle dashboard.html 1.27 KB (pass) serve html [588.64ms] waitForServer /tmp/bun-serve-html-txt_rjZL4e { "/": "/tmp/bun-serve-html-txt_rjZL4e/index.html", } [0.15ms] bundle index.html 0.40 KB HASH efbnbska (pass) serve plugins > basic plugin [552.11ms] waitForServer /tmp/html-css-js-failing-plugin_D8NJ2O { "/": "/tmp/html-css-js-failing-plugin_D8NJ2O/index.html", } error: Plugin failed intentionally at /tmp/html-css-js-failing-plugin_D8NJ2O/styles.css:0 error: Plugin failed intentionally at /tmp/html-css-js-failing-plugin_D8NJ2O/styles.css:0 (pass) serve plugins > serve html with failing plugin [505.55ms] waitForServer /tmp/html-css-js-empty-plugins_vK0DVI { "/": "/tmp/htm ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 673ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/7] gen bake.{client,server,error}.js -> bake.client.js, bake.server.js, bake.error.js [2/7] gen generated_host_exports.rs generated_host_exports.rs: 94 exports (host=3, lazy=10, generic=81, rust=0); 240 extern-C blocks audited [2/7] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu) nightly-2026年07月20日-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026年07月19日) �[1m�[92m Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) �[1m�[92m Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno) �[1m�[92m Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr) �[1m�[92m Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys) �[1m�[92m Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety) �[1m�[92m Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys) �[1m�[92m Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys) �[1m�[92m Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd) �[1m�[92m Compiling�[0m ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/runtime/bake/DevServer.rs | 63 +++- src/runtime/bake/dev_server/lifecycle.rs | 12 +- src/runtime/bake/dev_server/mod.rs | 401 +++++++++++---------- src/runtime/dispatch.rs | 10 +- .../http/bun-serve-html-hot-reload-drop.test.ts | 82 +++++ test/js/bun/http/bun-serve-html.test.ts | 10 +- 6 files changed, 374 insertions(+), 204 deletions(-) ``` </details> **gate history** · 3 passed · 2 rejected · iteration 4 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/runtime/bake/DevServer.rs 10 13 0 src/runtime/bake/dev_server/lifecycle.rs 5 9 0 src/runtime/bake/dev_server/mod.rs 13 12 0 src/runtime/dispatch.rs 3 2 0 test/js/bun/http/bun-serve-html-hot-reload-drop.test.ts 1 5 0 test/js/bun/http/bun-serve-html.test.ts 6 9 0 ``` </details> <!-- robobun:evidence:end --> --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
igorls
pushed a commit
that referenced
this pull request
Aug 21, 2026
...e cache (oven-sh#37034) ### Problem On the `13 x64-asan` lane, a test that exercises non-ISO Temporal calendars from a test callback can abort after a fully green run with a LeakSanitizer report. Seen in build 89504 on oven-sh#37024, whose `test/js/bun/bun-object/deep-equals-temporal.test.ts` uses `[u-ca=hebrew]`: ``` Direct leak of 624 byte(s) in 1 object(s) allocated from: #1 icu_75::HebrewCalendar::clone() const #2 icu_75::Calendar::createInstance(icu_75::TimeZone*, icu_75::Locale const&, UErrorCode&) #3 ucal_open_75 #4 JSC::TemporalCore::buildCalendarTemplate(WTF::AbstractLocker const&, unsigned int) #5 JSC::TemporalCore::withCalendar<JSC::TemporalCore::calendarYear(...)::$_0>(...) ``` The CI annotation titles this `direct leak of 624b in {closure#0} (src/jsc/JSValue.rs:1664:22)` because that is the first in-repo frame (the test-runner's `JSValue::call`); everything below it is WebKit/ICU. ### Cause `TemporalCore::withCalendar` (`vendor/WebKit/.../temporal/core/CalendarICUBridge.cpp`) keeps up to 8 open `UCalendar` templates in a process-lifetime `LazyNeverDestroyed` `TinyLRUCache`, one per calendar ID (non-ISO arithmetic, plus pure-ISO `PlainDateTime.prototype.with`, which reaches the same path unguarded); LRU eviction `ucal_close`s them, so the set is bounded. The `CalendarCacheEntry` that owns each `UCalendar` is `WTF_MAKE_TZONE_ALLOCATED` (bmalloc), which LSan does not scan, so the libc-allocated `UCalendar` (and the ICU `TimeZone` inside it) is reported as a direct leak even though it is reachable. Whether a given run aborts depends on whether some stale stack or register value still points at the ICU object when LSan scans at exit, hence the intermittence. This is the calendar twin of the already-suppressed `TemporalCore::withTimeZone` entry (same cache design, same TZone-allocated owner). ### Fix - Add a `leak:TemporalCore::buildCalendarTemplate` suppression to `test/leaksan.supp`, mirroring the `withTimeZone` entry. The pattern anchors on the template builder rather than `withCalendar` itself so that a future real leak inside one of the many op lambdas `withCalendar` runs would still be reported; every cached-template allocation carries the builder frame. (`withTimeZone` has no such builder frame, its `ucal_open` is inline, so that entry keeps its existing pattern.) - Drop the `test/no-validate-leaksan.txt` escape hatch oven-sh#37024 added for `deep-equals-temporal.test.ts`, re-enabling leak validation for it; that file exercises the suppressed path on the asan lane. ### Verification On a debug ASAN build, running `bun test test/js/bun/bun-object/deep-equals-temporal.test.ts` under the CI leak-validation env (`BUN_DESTRUCT_VM_ON_EXIT=1`, `detect_leaks=1:abort_on_error=1`, repo suppression file): - with the new entry: clean exit, 5/5 runs - without it: LSan abort with the calendar-template stacks above, 3/3 runs A standalone probe exercising 8 non-ISO calendars plus pure-ISO `PlainDateTime.with` from a timer callback shows the same split (10/10 aborts without, 10/10 clean with; `print_suppressions=1` attributes exactly the ICU template allocations to the new entry). Top-level module code cannot reproduce this: its allocation stacks carry `JSC::JSModuleLoader::evaluateNonVirtual`, which the suppression file already covers wholesale. An ASAN-gated test pinning the entry was part of an earlier revision and was dropped per review; the re-enabled `deep-equals-temporal.test.ts` covers the path in CI instead. The Expect-wrapper shutdown leak mentioned in the dropped no-validate comment is a separate issue tracked in oven-sh#32180: that is `bun test`'s own finalizer-owned memory, while this cache deliberately survives VM teardown, so oven-sh#32180 would not prevent this report. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 1 · docs-only change; test-proof not applicable <!-- robobun:evidence:end --> --------- Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
igorls
pushed a commit
that referenced
this pull request
Aug 21, 2026
...-comparison (oven-sh#37168) ### Problem `Bun__deepEquals` has heap-use-after-free when a getter on a nested object mutates one of the objects being compared. All entry points are affected: `Bun.deepEquals`, `expect().toEqual` / `toStrictEqual`, `assert.deepStrictEqual` / `deepEqual`, and `util.isDeepStrictEqual`. ```js // Malloc=1 <bun-asan> repro.mjs const p1 = {}, p2 = {}; for (let i = 0; i < 8; i++) { p1['k'+i] = i; p2['k'+i] = i; } let f = 0; p1.a = { get x() { if (!f++) for (let i = 0; i < 2000; i++) p1['n'+i] = i; return 1; } }; p2.a = { get x() { return 1; } }; p1.z = 1; p2.z = 1; Bun.deepEquals(p1, p2, true); ``` ASAN (with `Malloc=1` so JSC's bmalloc routes through the system allocator): ``` heap-use-after-free READ of size 8 #0 CompactPropertyTableEntry::key() Structure.h #1 PropertyTable::forEachProperty #2 Structure::forEachProperty #3 Bun__deepEquals<...> bindings.cpp freed by: PropertyTable::destroyIndexVector <- PropertyTable::rehash <- PropertyTable::add <- Structure::addNewPropertyTransition <- JSObject::putDirectInternal ``` ### Cause The object fast path walks the structure's `PropertyTable` with `Structure::forEachProperty` and recurses into `Bun__deepEquals` from inside the lambda. Comparing a nested value can run a user getter; if that getter adds (or deletes) properties on the parent object, JSC takes the shared table off the old structure and rehashes it, freeing the index vector the outer walk is iterating. Every remaining sibling property is then read from freed memory and its stale offset fed to `getDirect()`. In release builds this shows up as a SEGV at a forged address or a wrong verdict. ### Fix Collect the (left, right) value pairs into a `MarkedArgumentBuffer` under `forEachProperty` with no side effects, then run `sameValue` and the recursive comparisons after the walk finishes. This is the same shape as `Object.assign`'s fast path (snapshot under `forEachProperty`, side-effectful work after). The buffer keeps the snapshotted values visible to GC, so allocation churn in a getter cannot collect them either. The reverse `o2` walk already did only direct structure reads and now also completes before any user code can run. Verdicts are unchanged for non-mutating comparisons (existing suites pass); a comparison whose getter mutates the object now deterministically compares the snapshot, which matches Node's behavior for the repro above (`true`). ### Verification - New test in `test/js/bun/bun-object/deep-equals.test.ts` (renamed from `deep-equals.spec.ts` to match the test naming convention): spawns an ASAN child with `Malloc=1` (bmalloc routed through the system allocator so ASAN can see the freed table) covering same-structure, mixed-structure, delete, right-side mutation, and GC-churn variants across all entry points. Fails before the fix (ASAN heap-use-after-free abort), passes after. - `test/js/bun/bun-object/`, `test/js/node/assert/deep-equal.test.ts`, `assert-typedarray-deepequal.test.ts`: 542 pass. - `test/js/bun/test/expect.test.js`: 415 pass. - `test/js/node/test/parallel/test-assert-deep-with-error.js`: 2 pass. ### Scope The same pattern exists in `JSC__JSValue__forEachPropertyImpl` in this file (the `Bun.inspect` / `console.log` property walk), where the formatter callback can run a nested value's `inspect.custom` mid-walk. Verified with ASAN to hit the same free/read pair. That is a pre-existing bug in the console/inspect subsystem and is intentionally excluded here; a follow-up fix for that site is in progress. The other `forEachProperty` sites (CommonJS export enumeration, HTTP header writing, the ordered/non-indexed iteration variants) run no user code inside the walk. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 3 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/bun/bun-object/deep-equals.test.ts <!-- robobun:evidence:end -->
igorls
pushed a commit
that referenced
this pull request
Aug 21, 2026
...id-format (oven-sh#37169) ### Problem `Bun.inspect` and `console.log` have a heap-use-after-free when formatting a value runs user code that mutates the object being formatted. The default-enabled `Symbol.for("nodejs.util.inspect.custom")` hook on a nested value is enough to trigger it: ```js // Malloc=1 <bun-asan> repro.mjs const p = {}; for (let i = 0; i < 8; i++) p['k'+i] = i; let f = 0; p.a = { [Symbol.for('nodejs.util.inspect.custom')]() { if (!f++) for (let i = 0; i < 256; i++) p['n'+i] = i; return 'a'; } }; p.z = 1; console.log(Bun.inspect(p).length); ``` ASAN (with `Malloc=1` so JSC's bmalloc routes through the system allocator): ``` heap-use-after-free READ of size 8 #0 CompactPropertyTableEntry::key() Structure.h #1 PropertyTable::forEachProperty #2 Structure::forEachProperty #3 JSC__JSValue__forEachPropertyImpl bindings.cpp freed by: PropertyTable::destroyIndexVector <- PropertyTable::rehash <- PropertyTable::add <- Structure::addNewPropertyTransition <- JSObject::putDirectInternal ``` ### Cause The fast path of `JSC__JSValue__forEachPropertyImpl` walks the structure's `PropertyTable` with `Structure::forEachProperty` and invokes the formatter callback from inside the walk. The callback recursively formats the property value, which can run user code: a nested value's `inspect.custom`, or a getter on a built-in subclass (for example an overridden `Map.prototype.size`). If that code adds or deletes properties on the parent object, JSC rehashes the shared table, freeing the index vector the outer walk is iterating, and every remaining entry is read from freed memory. The fast-path guard only inspects the parent's structure, and a parent with plain data properties passes it; the hostile hook lives on a nested value. Same bug class as the deepEquals fix in oven-sh#37168, which deliberately excluded this site. ### Fix Collect the entries (key, attributes, direct value) under `forEachProperty` with no side effects, then resolve remaining values and invoke the callback on the snapshot after the walk finishes. The values go in a `MarkedArgumentBuffer` so GC in a callback cannot collect them; keys are retained as `Identifier`s. The snapshot is per structure walk, so the prototype-chain restart loop still re-reads each prototype's live structure. Properties added to the object while it is being formatted are no longer printed: the walk now reflects the object as it was when formatting started. That matches Node, which collects the key list before formatting values. The other `forEachProperty` sites are unaffected: the non-indexed and ordered variants never take this fast path, and the remaining callers run no user code in the callback. ### Verification - New test in `test/js/bun/util/inspect.test.js` (ASAN-only, child spawned with `Malloc=1`) covering: `inspect.custom` adding properties via `Bun.inspect` and `console.log`, deleting properties, a `Map` subclass `size` getter, the prototype fast-walk of an own-property-less object, and GC churn inside the hook with object-valued siblings formatted afterwards. Fails before the fix (ASAN abort, empty stdout), passes after. - `test/js/bun/util/inspect.test.js`: 74 pass. `test/js/bun/console/`: 85 pass, 1 skip. - `inspect-error.test.js` minified-file snapshots and `inspect-error-leak.test.js` fail identically with and without this diff locally (pre-existing, unrelated to property enumeration).
igorls
pushed a commit
that referenced
this pull request
Aug 21, 2026
...ven-sh#37273) ### Problem `H2FrameParser::handle_received_stream_id` creates a `Stream` box, inserts it into the stream map, and then invokes the JS `streamStart` callback directly via `callback.call` without arming the `DispatchGuard`, while still holding the raw `*mut Stream`. Every other JS dispatch site in the parser arms the guard, because `rewrite_read` frees streams queued in `pending_engine_stream_closes` only at dispatch depth 0. JS reached from inside that callback (the `Http2Stream` constructor calls `this.on("pause", ...)`, so a patched `EventEmitter.prototype.on` runs there; the handler also calls back into native `rstStream` for refused streams) can close the just-created stream, queueing its deferred free, and then re-enter `parser.read()` at depth 0. The drain frees the box, and the callback return path writes the stream context through the dangling pointer: ``` ==ERROR: AddressSanitizer: heap-use-after-free ... #1 <bun_runtime::api::h2_frame_parser_body::Stream>::set_context src/runtime/api/bun/h2_frame_parser.rs:2110 #2 <...H2FrameParser>::handle_received_stream_id src/runtime/api/bun/h2_frame_parser.rs:5372 #3 <...H2FrameParser>::get_next_stream src/runtime/api/bun/h2_frame_parser.rs:8335 freed by: oven-sh#12 <...H2FrameParser>::rewrite_read::{closure#3} src/runtime/api/bun/h2_frame_parser.rs:5804 ``` The callers that keep dereferencing the returned pointer (`request()`, `get_next_stream`, the engine HEADERS path) were exposed to the same freed box. ### Fix Arm `enter_dispatch` across the callback, matching the invariant documented on `enter_dispatch` (every section that holds a `Stream` pointer while user JS can run must arm the guard). With the guard armed, the deferred-close drain cannot run while the callback executes, so the pointer stays valid for `set_context` and for the callers. Also skip the context install when the callback closed the stream: `free_resources` already dropped its `sctx` root, and re-inserting one afterwards would pin the dead JS stream object until the session dies. This is the guard-arming fix for the pre-existing issue flagged during review of oven-sh#37272 (that PR only removes dead code around it). ### Verification New test in `test/js/node/http2/node-http2-streams-rehash.test.ts` (the file covering this class of reentrancy bugs) reproduces the exact sequence: close the new stream and re-enter `read()` from inside the `streamStart` callback. Without the fix it fails on every build tier: heap-use-after-free under the ASAN debug build, and on release builds `getStreamContext(2)` throws "Invalid stream id" because the drain already freed the entry inside the callback. With the fix the entry survives the callback with no context installed (covering the skip-install branch), and a follow-up depth-0 `read()` asserts the deferred close then actually drains. Existing http2 suites (`node-http2.test.js`, `h2-conformance.test.ts`, the staged h2 tests, node's server-push parallel tests) pass with the change. <!-- robobun:evidence:begin --> --- **[review]** gate passed · iteration 1 · 2 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 1 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" "test/js/node/http2/node-http2-streams-rehash.test.ts" bun test v1.4.0 (8f79562) test/js/node/http2/node-http2-streams-rehash.test.ts: (pass) session.request() from a stream 'timeout' listener during forEachStream does not UAF on hashmap rehash [3284.09ms] (pass) http2 client request() does not hold *Stream across user-controlled options getters [6184.76ms] 198 | env: bunEnv, 199 | stdout: "pipe", 200 | stderr: "pipe", 201 | }); 202 | const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); 203 | expect({ stdout: stdout.trim(), exitCode, stderr }).toMatchObject({ stdout: "OK", exitCode: 0 }); ^ error: expect(received).toMatchObject(expected) { - "exitCode": 0, - "stdout": "OK", + "exitCode": 1, + "stderr": + "================================================================= + ==101685==ERROR: AddressSanitizer: heap-use-after-free on address 0x79be9bb005c0 at pc 0x00000e7ec22e bp ... (truncated) release without fix: all passed bun test v1.4.0-canary.1 (7725ac8) test/js/node/http2/node-http2-streams-rehash.test.ts: (pass) session.request() from a stream 'timeout' listener during forEachStream does not UAF on hashmap rehash [163.99ms] (pass) http2 client request() does not hold *Stream across user-controlled options getters [78.42ms] (pass) closing the new stream and re-entering read() inside the streamStart callback does not UAF [31.29ms] (pass) http2 client write callback that opens new streams during flushQueue does not UAF [49.40ms] (pass) DeferredTaskQueue::run tolerates an on_auto_flush callback that unregisters itself and returns true [46.51ms] 5 pass 0 fail 5 expect() calls Ran 5 tests across 1 file. [513.00ms] __F:0:S:0 ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: all passed $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" "test/js/node/http2/node-http2-streams-rehash.test.ts" bun test v1.4.0 (8f79562) test/js/node/http2/node-http2-streams-rehash.test.ts: (pass) session.request() from a stream 'timeout' listener during forEachStream does not UAF on hashmap rehash [3278.34ms] (pass) http2 client request() does not hold *Stream across user-controlled options getters [6171.66ms] (pass) closing the new stream and re-entering read() inside the streamStart callback does not UAF [1906.06ms] (pass) http2 client write callback that opens new streams during flushQueue does not UAF [2819.28ms] (pass) DeferredTaskQueue::run tolerates an on_auto_flush callback that unregisters itself and returns true [2618.43ms] 5 pass 0 fail 5 expect() calls Ran 5 tests across 1 file. [19.19s] __F:0:S:0 release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 689ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/6] gen generated_host_exports.rs generated_host_exports.rs: 93 exports (host=3, lazy=10, generic=80, rust=0); 239 extern-C blocks audited [1/6] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu) nightly-2026年07月20日-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026年07月19日) �[1m�[92m Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) �[1m�[92m Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno) �[1m�[92m Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr) �[1m�[92m Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys) �[1m�[92m Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety) �[1m�[92m Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys) �[1m�[92m Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys) �[1m�[92m Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd) �[1m�[92m Compiling�[0m bun_picohttp v0.0.0 (/workspace/bun/src/picohttp) �[1m�[92m Compiling�[0m bun_brotli v ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/runtime/api/bun/h2_frame_parser.rs | 19 +++- .../node/http2/node-http2-streams-rehash.test.ts | 100 +++++++++++++++++++++ 2 files changed, 115 insertions(+), 4 deletions(-) ``` </details> **gate history** · 2 passed · 0 rejected · iteration 1 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/runtime/api/bun/h2_frame_parser.rs 10 4 0 test/js/node/http2/node-http2-streams-rehash.test.ts 2 3 0 ``` </details> <!-- robobun:evidence:end --> --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
igorls
pushed a commit
that referenced
this pull request
Aug 21, 2026
...n-sh#37813) ### Problem - An HTML route served without the DevServer (`development: false` or `{ hmr: false }`) bundles on its first request. If the only client disconnects and `server.stop(true)` is called while a `[serve.static]` plugin still has that build parked, `stop()` settles, the next GC frees the server, and the build then finishes against the freed server. - Debug build: `AddressSanitizer: heap-use-after-free` in `html_bundle::Route::on_complete` (parked in `onLoad`) or `Route::on_plugins_resolved` (parked in the plugin's `setup()`). A release build reads the freed `NewServer` with no report. - Cause: while a route is building, nothing counts as keeping the server alive. The clients waiting on the build only count as connections, so once they drop the server's idle check sees no pending work. - The other route kinds already count their asynchronous work in the server's pending-request counter; the HTML build was the one piece of in-flight work that did not. ### Fix - Entering the building state now takes one pending request on the server; both ways out of it (build finished, plugin load rejected) answer the waiting clients and then release it. - This holds the server for exactly the window in which the route will call back into it. The release runs the server's idle pass, so a server stopped mid-build is freed right after the build lands. - Visible change: `server.pendingRequests` is 1 while an HTML route bundles and `await server.stop()` waits for the bundle, as it already does for a `fetch` handler still running. A build cancelled by VM teardown is not covered; at exit it leaves the same state an in-flight `fetch` handler does. - Verification: a new test parks the route in the build, in the plugin load, and in a plugin load that rejects. Unfixed debug build: all three report 0 pending requests and an early-settled `stop()`, and the first two die with the ASAN reports above. Fixed: all three pass, as do the existing HTML-serve tests that do not need the DevServer. ### Background - HTML routes: `Bun.serve({ routes: { "/": html } })` with an imported `.html` file. Without the DevServer the route bundles the page once, on the first request, registers the outputs as static routes, and holds requests that arrive during the build. - `[serve.static]` plugins: a bunfig entry naming bundler plugins for these routes, loaded on the first request. Both the plugin load and the bundle finish on later event-loop turns and complete by calling back into the server through a raw pointer stored on the route. - Pending requests: the server's count of in-flight work, exposed as `server.pendingRequests`. `stop()` settles and the server can be torn down only when the count is zero; static and file routes already raise it when a response goes asynchronous. - Server lifetime: stopping a server does not free it. Once nothing is pending, the JS wrapper becomes collectable and the native server is freed on a later GC, so a stale pointer to it only fails after a GC. <details> <summary>Original description</summary> ### Repro HTML route served without the DevServer (`development: false` or `{ hmr: false }`), with a `[serve.static]` plugin whose `onLoad` parks on a promise. Request the route, drop the client, `server.stop(true)`, drop the server, `Bun.gc(true)` plus a couple of event-loop turns, then let `onLoad` resolve. Debug (ASAN) build: ``` ==1165==ERROR: AddressSanitizer: heap-use-after-free on address 0x73defa800738 ... READ of size 8 at 0x73defa800738 thread T0 #0 in <bun_runtime::server::NewServer<false, false>>::global_this src/runtime/server/mod.rs:451 #1 in <bun_runtime::server::AnyServer>::global_this src/runtime/server/mod.rs:3847 #2 in <bun_runtime::server::html_bundle::Route>::on_complete src/runtime/server/HTMLBundle.rs #3 in JSBundleCompletionTask::on_complete src/runtime/api/js_bundle_completion_task.rs:642 freed by thread T0 here: ... oven-sh#11 in <bun_runtime::server::NewServer<false, false>>::deinit src/runtime/server/mod.rs:2122 oven-sh#12 in NewServer::schedule_deinit::{closure#1} src/runtime/server/mod.rs:1957 ``` Parking in the plugin's `setup()` instead (so the route is still waiting for the plugin load when the server goes away) gives the same report one step earlier: ``` READ of size 1 ... in <bun_runtime::server::html_bundle::Route>::on_plugins_resolved src/runtime/server/HTMLBundle.rs #1 in <bun_runtime::server::server_body::ServePlugins>::handle_on_resolve src/runtime/server/server_body.rs:1150 #2 in bun_runtime::server::server_body::on_resolve_impl ``` On a release build the same sequence reads a freed `NewServer` (its config, then `append_static_route` / `reload_static_routes` on it) without a report. ### Cause `html_bundle::Route` keeps a raw `server` back-pointer and bundles on its first request. Both the plugin load and the build finish on later event-loop turns and call back into the server through that pointer (`on_plugins_resolved` reads the config, `on_complete` registers the output files as static routes and reloads the route table). While the route is in `State::Building`, nothing holds the server on its behalf: `on_plugins_resolved` only refs the route itself, and the clients waiting in `pending_responses` only count as connections, which they can drop at any time. So once the last client disconnects and the server is stopped, `deinit_if_we_can` sees no pending requests, settles `stop()`, downgrades the wrapper, and the next GC frees the `NewServer` with the build still in flight. `StaticRoute` / `FileRoute` / `DirectoryRoute` already handle their asynchronous work with the server's `pending_requests` counter (`on_pending_request` when a response goes async, `on_static_request_complete` when it finishes); the route's build is the same kind of in-flight work and was the one thing not counted. ### Fix `schedule_bundle` calls `server.on_pending_request()` whenever the route enters `State::Building` (plugins ready, or plugins still loading), and the two ways out of that state (`on_complete`, `on_plugins_rejected`) go through a new `finish_building`, which answers the pending responses and then calls `on_request_complete()`. That keeps the server allocated for exactly the window in which the route will call back into it, and `on_request_complete` runs the idle pass, so a server that was stopped while building is downgraded and freed right after the build lands (the `stop()` promise now settles then as well, matching what happens for a `fetch` handler that is still running when `stop()` is called). With that invariant, `on_complete` no longer needs its `Option` handling of the back-pointer; it takes the server once at the top, the same way `on_plugins_resolved` already did. A visible consequence: `server.pendingRequests` is 1 while an HTML route is bundling, and `await server.stop()` waits for the bundle. A build whose plugin never settles therefore keeps the server allocated, as an unsettled `fetch` handler already does. Not covered: a build cancelled by VM teardown never reaches `Route::on_complete` (the completion task returns early on `cancelled`), so at exit the route keeps its ref and, now, its pending request; that is the same state an in-flight `fetch` handler leaves a server in at exit and nothing observes it. The DevServer's own plugin wait uses a different back-pointer and is not changed here. ### Verification `test/js/bun/http/bun-serve-html-build-holds-server.test.ts` (separate small file; `bun-serve-html.test.ts` is too slow under the debug ASAN build for a lifetime test, as `bun-serve-html-hot-reload-drop.test.ts` notes). One fixture, parked in turn in the build (`onLoad`), in the plugin load (`setup()`), and in a plugin load that then rejects (the `on_plugins_rejected` exit has to release the request too). Each child reports `server.pendingRequests` while parked, whether `stop(true)` settled across ten event-loop turns before the route was released, and whether the wrapper became collectable afterwards; the test expects `{ pendingRequestsWhileParked: 1, stopBeforeRelease: "pending", collectedAfterwards: true }` plus a clean exit. If `stop()` did settle early, the fixture lets the server get collected before releasing the route, which is the sequence above. Unfixed debug build: all three report `pendingRequestsWhileParked: 0, stopBeforeRelease: "settled"`, and the first two children die with the ASAN reports above (the rejection case has no use-after-free to hit; it fails on the report). Fixed: the three pass in under a second each. Also run on the fixed debug build: `bun-serve-html-405.test.ts`, `bun-serve-html-hot-reload-drop.test.ts`, `test/bake/serve-plugins-dev-server.test.ts` (all pass), and `bun-serve-html.test.ts`, where everything that does not need the DevServer passes, including `serve plugins > concurrent requests to multiple routes during plugin load`; its `development: true` cases fail in this container with `EMFILE while initializing file watcher for development server` (inotify instance limit) before reaching any of this code. </details>
igorls
pushed a commit
that referenced
this pull request
Aug 21, 2026
...wo parallel vecs (oven-sh#39145) ### Problem - `LOLHTMLContext` in `src/runtime/api/html_rewriter.rs` keeps two vecs, `selectors` and `element_handlers`, that describe one thing: entry `i` of each is the selector and the handler object from the same `rewriter.on(selector, handlers)` call. - The pairing is only held up by convention: `on_()` pushes to both, `build_settings()` zips them back together, and a doc comment plus an invariant comment explain it. The mordant `parallel_vecs` lint flags this (the one baselined finding for this file). ### Fix - Add `ElementHandlerEntry { selector, handler: Box<ElementHandler> }` and store `element_handlers: Vec<ElementHandlerEntry>`. One vec, one push in `on_()`, and `build_settings()` destructures each entry instead of zipping. - No behavior change: the same values are pushed in the same order, the handler is still boxed (the lol-html closures built in `build_settings()` hold raw pointers into the box, so it must not move when the vec reallocates), and the body of the `build_settings()` loop is unchanged. The `#[expect(clippy::vec_box)]` comes off `element_handlers` because it is no longer a `Vec<Box<_>>`; `document_handlers` keeps its own. - Remove the `parallel_vecs:src/runtime/api/html_rewriter.rs` line from `mordant-baseline.toml`. - Tests, in `test/js/workerd/html-rewriter.test.js` (`on() registrations`), pin down the two things this storage has to get right. They pass before and after this change, since it is a refactor: - Many selectors registered on one rewriter, with two rejected `on()` calls in the middle, each still run the handlers they were registered with, on two transforms of the same rewriter. - `on()` called from inside a handler, often enough to reallocate the registry while lol-html is still calling the handlers registered before the transform started: the running transform is unaffected and the next one picks the additions up. With the `Box` removed from `ElementHandlerEntry` this test fails under ASAN with a heap-use-after-free (report in the details below), so the boxing is now covered rather than only commented. - Verified: - `bun bd test` on `test/js/workerd/html-rewriter.test.js` (165 tests, including the new ones), `html-rewriter-end-error.test.ts`, `html-rewriter-leak.test.ts`, `test/js/web/html/html-rewriter-doctype.test.ts` and the HTMLRewriter regression tests: all pass. - `cargo clippy -p bun_runtime --no-deps`: clean. - `cargo dylint --all -p bun_runtime` with this baseline: nothing over the baseline. The same command with the baseline line removed but the source change stashed reports exactly the one `parallel_vecs` finding for this file, so the removed line is the one this change fixes. - Regenerating the baseline with `MORDANT_BASELINE_WRITE=1` also drops two entries this PR does not touch (`always_unwrapped_option:src/install/PackageInstall.rs`, `narrowed_two_ways:src/runtime/node/node_crypto_binding.rs`); those findings were already fixed on main by other changes and are left for a separate cleanup. ### Background - `HTMLRewriter.on(selector, handlers)` parses the CSS selector with lol-html and wraps the JS handler object in an `ElementHandler` (the protected `element`/`comments`/`text` callbacks). Nothing is handed to lol-html at that point; registrations are collected in `LOLHTMLContext`, which is shared by the rewriter and every transform it starts, because `transform()` can run more than once. - `build_settings()` runs at transform time and turns each registration into a `(selector, ElementContentHandlers)` pair for lol-html. Its closures capture a `NonNull<ElementHandler>` pointing into the heap allocation owned by the `Box`, which is why the handler has to stay boxed even though clippy would normally suggest otherwise. An `on()` call after a transform has started (for example from inside a handler) pushes onto the same vec, which is what makes the reallocation case reachable from JS. - `mordant-baseline.toml` is the ratchet for the mordant lint pack run by the Rust lints workflow: it records the accepted number of findings per (lint, file), and CI reports anything above those counts. Removing the line here means a reintroduction of the pattern in this file would be reported. <details> <summary>ASAN report from the new test with the Box removed from ElementHandlerEntry</summary> ``` ERROR: AddressSanitizer: heap-use-after-free READ of size 8 #3 <ElementHandler as HandlerLike>::global src/runtime/api/html_rewriter.rs #4 handler_callback::<ElementHandler, Element, ...> src/runtime/api/html_rewriter.rs #5 ElementHandler::on_element src/runtime/api/html_rewriter.rs #6 build_settings::{closure#0} src/runtime/api/html_rewriter.rs #8 lol_html ContentHandlersDispatcher::handle_start_tag freed by thread T0 here: oven-sh#13 RawVec<ElementHandlerEntry>::grow_one oven-sh#15 Vec<ElementHandlerEntry>::push oven-sh#16 HTMLRewriter::on_ src/runtime/api/html_rewriter.rs ``` </details> <!-- robobun:evidence:begin --> --- **no test proof** · iteration 2 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/workerd/html-rewriter.test.js <!-- robobun:evidence:end --> --------- Co-authored-by: Alistair Smith <hi@alistair.sh>
igorls
pushed a commit
that referenced
this pull request
Aug 22, 2026
oven-sh#39947) ### Problem - A worker whose entry point goes through a package.json `imports` or `exports` map leaks 12 KiB (3 `PathBuffer`s, more on Windows) when its thread exits. On an ASAN build LeakSanitizer reports `Direct leak of 12288 byte(s)` allocated in `module_bufs` (`src/resolver/package_json.rs`), reached from `resolve_entry_point_specifier` on the worker thread. - Cause: `MODULE_BUFS` is a thread local `Cell<*mut ModuleBufs>` with nothing that frees the box. The resolver's other per thread buffers (`BufsSlot` in `resolver.rs`, `LazyPathBuf` in `bun_paths`) got a destructor in oven-sh#30875. This one did not. ### Fix - Wrap the pointer in `ModuleBufsSlot`, whose `Drop` destroys the box when the thread exits. Same shape as `BufsSlot`. Access is unchanged, so the recursion notes on the thread local still hold, and the static TLS template is still one pointer. - Correct because the destructor runs when the thread's TLS is torn down, after every resolver frame on that thread has returned. The main thread's box lives for the process, as before. - Verified: `test/js/web/workers/worker-entry-point.test.ts` (new file) runs a worker through an `imports` alias in a child with `detect_leaks=1`. It fails on main with the report above and passes with this change (checked both ways with a debug build). `test/js/bun/binary/tls-segment-size.test.ts` still passes. ### Background - The resolver keeps a few large scratch buffers per thread instead of on the stack. They are boxed on first use and only a pointer sits in TLS, so the TLS segment stays small on every platform. - A worker thread resolves its own entry point and preloads, so it is the common short lived thread that touches these buffers. The bundler's pool threads live as long as the pool. - The ASAN CI lanes run test children with `detect_leaks=1`. The test sets that itself (plus the repo's `test/leaksan.supp`) so that a local ASAN build checks it too. A build without ASAN ignores the options and checks the behaviour only. <details><summary>Notes</summary> Found through oven-sh#39811, whose worker test resolves an `imports` alias and failed on the ASAN lanes because of this leak. oven-sh#39811 carries this change until this lands and is otherwise independent of it. oven-sh#35060 (overflow bundle threads, open) includes the same change as one of its hunks, because its threads are short lived too. The case is in its own file, for the worker entry point resolution cases, rather than in `worker.test.ts`: three of that file's stress cases go over their budget on a debug build on a slow machine, which would hide whether this case itself flips. oven-sh#39811 adds its worker case to the same file. Without `print_suppressions=0` LeakSanitizer prints a "Suppressions used" table to stderr on exit when an unrelated, suppressed allocation exists in the process, so the test passes that along with the suppressions file when the environment does not already set `LSAN_OPTIONS`. </details> <!-- robobun:evidence:begin --> --- **[review]** gate passed · iteration 1 · 2 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 1 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/web/workers/worker-entry-point.test.ts bun test v1.4.0 (4199361) test/js/web/workers/worker-entry-point.test.ts: 41 | LSAN_OPTIONS: 42 | bunEnv.LSAN_OPTIONS ?? 43 | `print_suppressions=0:suppressions=${path.join(import.meta.dir, "..", "..", "..", "leaksan.supp")}`, 44 | }, 45 | ); 46 | expect(stderr).toBe(""); ^ error: expect(received).toBe(expected) - "" + " + ================================================================= + ==385090==ERROR: LeakSanitizer: detected memory leaks + + Direct leak of 12288 byte(s) in 1 object(s) allocated from: + #0 0x000007dd95c8 in malloc crtstuff.c + #1 0x00000be19934 in std::sys::alloc::unix::alloc /root/.rustup/toolchains/nightly-2026年07月20日-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/sys/alloc/unix.rs:31:18 + #2 0x00000be184b9 in <std::alloc::System>::alloc_impl /root/.rustup/toolchains/nightly-2026年07月20日-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/alloc.rs:149:78 + #3 ... (truncated) release without fix: all passed bun test v1.4.0-canary.1 (2e16ac4) test/js/web/workers/worker-entry-point.test.ts: (pass) package.json imports alias as the entry point > the worker runs and its thread exits without leaking [11.86ms] 1 pass 0 fail 3 expect() calls Ran 1 test across 1 file. [218.00ms] __F:0:S:0 ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: all passed $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/web/workers/worker-entry-point.test.ts bun test v1.4.0 (4199361) test/js/web/workers/worker-entry-point.test.ts: (pass) package.json imports alias as the entry point > the worker runs and its thread exits without leaking [3743.31ms] 1 pass 0 fail 3 expect() calls Ran 1 test across 1 file. [6.05s] __F:0:S:0 release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 667ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [0/5] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu) nightly-2026年07月20日-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026年07月19日) �[1m�[92m Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) �[1m�[92m Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno) �[1m�[92m Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr) �[1m�[92m Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys) �[1m�[92m Compiling�[0m bun_safety v0.0.0 (/workspace/bun/src/safety) �[1m�[92m Compiling�[0m bun_base64 v0.0.0 (/workspace/bun/src/base64) �[1m�[92m Compiling�[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys) �[1m�[92m Compiling�[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys) �[1m�[92m Compiling�[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd) �[1m�[92m Compiling�[0m bun_picohttp v0.0.0 (/workspace/bun/src/picohttp) �[1m�[92m Compiling�[0m bun_brotli v0.0.0 (/workspace/bun/src/brotli) �[1m�[92m Compiling�[0m bun_outpu ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/resolver/package_json.rs | 23 +++++++++--- test/js/web/workers/worker-entry-point.test.ts | 50 ++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 5 deletions(-) ``` </details> **gate history** · 1 passed · 1 rejected · iteration 1 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/resolver/package_json.rs 2 2 0 test/js/web/workers/worker-entry-point.test.ts 1 2 0 ``` </details> **root cause** · written by the author bot With --target bun or node, the resolver short-circuits node:, bun: and hardcoded builtin specifiers into an external result whose primary path is the bare specifier rather than an absolute file path, and entry-point resolution passed that through, so enqueue_entry_item either tripped the absolute-path assert, reported a misleading "File not found", or for bun:wrap collided with the runtime's pre-registered source and left the build with no entry points. The fix marks entry-point resolutions with their own ImportKind so the resolver no longer applies externalization rules to them, and resolv... <!-- robobun:evidence:end -->
igorls
pushed a commit
that referenced
this pull request
Aug 24, 2026
...40064) ### Problem - GitHub closes only the first reference after a keyword, so "Fixes #1, #2" leaves #2 open. "Supersedes #3" links nothing, and no reference closes a pull request. - The last 1000 merged PRs name 274 such references. PR oven-sh#32292 is open although merged oven-sh#36135 says "Supersedes oven-sh#32292". ### Fix - `.github/workflows/close-linked-issues.yml` runs on `pull_request_target` `closed` (a merge into the default branch of `oven-sh/bun`) and on `workflow_dispatch` with a PR number and `dry_run`. Everything is inline in one `actions/github-script` step, with no checkout. - Each open target is closed as `completed` with the comment "Closed as completed by #N." or "Superseded by #N.". Closed or missing targets, the PR itself and other repositories are skipped. - The parser has no regex. A closing keyword (close, fix, resolve, supersede, replace, any tense) must lead the reference, alone or in a list. A negated, hedged or noun keyword, or one whose subject is another reference, does not count ("may fix", "the rm fix #1", "oven-sh#100 supersedes #1"). - Verified: `test/internal/close-linked-issues.test.ts` (333 cases) runs the YAML's script against fake `github`, `context` and `core`. Also the 1000-PR parse (Notes). ### Background - GitHub's own keywords are close, fix and resolve (-s, -ed). Each links one reference, and only a merge into the default branch closes it. - `pull_request_target` runs in the base repository with a write token, also for fork PRs. That is safe only when no PR-controlled code runs. Here the description is the only PR input, parsed as text. <details><summary>Notes</summary> A close through the API does not create the "closed this in #N" timeline link that GitHub makes for its own closes. The comment carries the PR number instead. How the parser was calibrated. I pulled the descriptions of the last 1000 merged PRs and listed every line with a keyword next to a reference. The keyword families, list shapes and reference forms in the script are the ones that appear there. A reference is `#1`, `owner/repo#1`, an issue or pull URL (bare or in `<>`), or a markdown link. Four lines would have been wrong with a plain keyword-then-reference rule, and each led to a rule: - "the open `rm` fix oven-sh#37521" (oven-sh#38379): "fix" as a noun. Base forms (fix, close, resolve, supersede, replace) count only at the start of a sentence or line, or after will, should, does, and, and a few similar words. "to" is not one of them ("unable to fix #1", "how to fix #1"). - "May also fix oven-sh#12318 / oven-sh#10046, untested" (oven-sh#38242): hedged. may, might, could, would, partially and the negations disqualify the keyword, looking past adverbs such as "also". - "Supersedes the closed oven-sh#26040" (oven-sh#36289) and "a comment on closed oven-sh#35351" (oven-sh#35365): "closed" as an adjective. A determiner or preposition before the keyword disqualifies it. - "supersedes oven-sh#33130's optimisation" (oven-sh#35843): a number that continues into a word is not a reference. Review added: a reference before the keyword is the subject ("oven-sh#100 supersedes #1"), also through "which" or "that" ("reverts oven-sh#100, which fixed #1") and across a removed span ("oven-sh#100 ~~also~~ fixes #1"). A hedge two words before the keyword disqualifies it ("hopefully this fixes #1", "could this fix #1?"). A clause that starts with if, when, once, until or unless is not a statement. The tokenizer keeps a line break as a token so that "Fixes #1" on one line and "Fixes #2" on the next stay two statements. Code spans, fences, indented code, blockquotes, HTML comments and strikethrough are skipped. The block stripping follows CommonMark for fences (also inside a blockquote), indented code, blockquotes with lazy continuation, setext underlines and HTML comments, and GFM for `~~` flanking. Result over the 1000 descriptions: 274 distinct references in 135 PRs. I checked the current state of all of them through GraphQL. All but one are closed (202 issues completed, 5 duplicates, 66 pull requests). The one open target is PR oven-sh#32292, superseded by merged oven-sh#36135. No open target is a false positive. Every review change kept this result. Patterns that are deliberately not handled: a bulleted list under "Closes:" on its own line (not seen in the sample), references separated by whitespace only ("#1 #2"), "fix for #1", and GH-1 style references. A `?` after the list is not treated as a question. The block parser tracks no list containers, so a second paragraph of a list item indented by four spaces is read as an indented code block and skipped. A removed span or inline comment reads as one word, so "Fixes <!-- n --> #1" finds nothing. The test suite covers: the phrases above, stopping at the right place in real sentences, CRLF descriptions, URLs with fragments or a `/files` suffix, case-insensitive `Owner/Repo#1`, the fake API where a lookup, an update or a comment fails, the `dry_run` input, an invalid `pr_number` input, an unmerged PR, a PR merged into a non-default branch, the merge event body against a later edit, and a description with no closing statement. The first revision of this PR checked out the repository and ran `scripts/close-linked-issues.ts`. Jarred asked for no checkout and no script file, so the script moved inline into the workflow and the test now reads it out of the YAML. </details> <!-- robobun:evidence:begin --> --- **[stamp-90s]** gate passed · iteration 9 · 2 files touched <details><summary>passes on PR (with fix)</summary> ```console Test-only change. Debug/ASAN (expected pass): $ bun bd test 'test/internal/close-linked-issues.test.ts' $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test test/internal/close-linked-issues.test.ts bun test v1.4.1 (4448a2e) test/internal/close-linked-issues.test.ts: (pass) finds "Fixes oven-sh#39852" [176.21ms] (pass) finds "Closes oven-sh#31772. Fixes oven-sh#31771." [22.28ms] (pass) finds "- Fixes oven-sh#39930" [12.28ms] (pass) finds "Fixes: oven-sh#30429" [10.46ms] (pass) finds "FIXES #1" [7.86ms] (pass) finds "(Fixes #1)" [8.97ms] (pass) finds "**Fixes #1**" [10.20ms] (pass) finds "__Fixes #1__" [9.83ms] (pass) finds "_Fixes #1_" [11.25ms] (pass) finds "Fixes **#1**" [9.72ms] (pass) finds "**Fixes** #1" [7.13ms] (pass) finds "**Fixes:** #1" [8.11ms] (pass) finds "Fixes #1 and **#2**" [11.47ms] (pass) finds "Fixes **#1**, **#2**" [9.13ms] (pass) finds "## Why (fixes oven-sh#13771, closes oven-sh#30543)" [16.08ms] (pass) finds "Closes oven-sh#11418" [19.46ms] (pass) finds "Resolves #1. Resolved #2. Resolve #3." [12.09ms] (pass) finds "Fixes oven-sh#34055, oven-sh#30327, oven-sh#24394, oven-sh#20816, oven-sh#32403, oven-sh#11898, oven-sh#10056." [17.11ms] (pass) finds "Fixes oven-sh#18192 and oven-sh#31675 as a consequence" [10.45ms] (pass) finds "Fixes #1, #2, and #3" [10.96ms] (pass) finds "Fixes #1 & #2" [7.63ms] (pass) finds "Closes oven-sh#33280, Closes oven-sh#32864 and Closes oven-sh#29696 (the timer in oven-sh#32949 is orthogonal)" [20.29ms] (pass) finds "Closes oven-sh#33182 and oven-sh#32947 on top of current main (which already has oven-sh#36304 for catalogs)." [16.12ms] (pass) finds "Fixes #1,\n#2" [7.76ms] (pass) finds "Fixes #1, #2,\nand #3" [9.27ms] (pass) finds "Fixes #1\nand #2" [8.57ms] (pass) finds "Fixes #1\n& #2" [6.80ms] (pass) finds "Fixes #1 and\n#2" [7.31ms] (pass) finds "Supersedes oven-sh#39908 (same change, moved from a fork branch)" [13.21ms] (pass) finds "Supersedes oven-sh#38778 and oven-sh#38391. Carries the entry point arm of oven-sh#35053." [14.43ms] (pass) finds "Supersedes oven-sh#39193 and keeps its three tests." [11.48ms] (pass) finds "This supersedes oven-sh#33306 and oven-sh#32803. Their tests are kept here." [13.73ms] (pass) finds "- This replaces oven-sh#33793. Its ... (truncated) Exit: 0 ``` </details> <details><summary>diff hotspot</summary> ``` .github/workflows/close-linked-issues.yml | 950 ++++++++++++++++++++++++++++++ test/internal/close-linked-issues.test.ts | 598 +++++++++++++++++++ 2 files changed, 1548 insertions(+) ``` </details> **gate history** · 29 passed · 0 rejected · iteration 9 <details><summary>evidence per changed file</summary> ``` file reads edits tests .github/workflows/close-linked-issues.yml 6 12 0 test/internal/close-linked-issues.test.ts 3 11 0 ``` </details> <!-- robobun:evidence:end -->
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
What does this PR do?
Updates elysia to version 1.4.29
Compare: elysiajs/elysia@1.4.12...1.4.29
Auto-updated by this workflow