Repository navigation
feat(http): trace Bun.serve requests - #11269
devin-ai-integration[bot] wants to merge 3 commits into
Conversation
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
Overall package sizeSelf size: 9.57 MB Dependency sizes| name | version | self size | total size | |------|---------|-----------|------------| | import-in-the-middle | 3.5.3 | 131.25 kB | 531.9 kB | | opentracing | 0.14.7 | 194.81 kB | 194.81 kB | | dc-polyfill | 0.1.11 | 25.74 kB | 25.74 kB |🤖 This report was automatically generated by heaviest-objects-in-the-universe |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #11269 +/- ##
=======================================
Coverage 99.15% 99.15%
=======================================
Files 1136 1136
Lines 188318 188381 +63
Branches 86 86
=======================================
+ Hits 186729 186797 +68
+ Misses 1589 1584 -5
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
🎉 All green!🧪 All tests passed 🎯 Code Coverage (details) 🔗 Commit SHA: a4bd403 | Docs | View more details | Give us feedback! |
BenchmarksBenchmark execution time: 2026-11-23 19:12:13 Comparing candidate commit a4bd403 in PR branch Found 0 performance improvements and 0 performance regressions! Performance is the same for 2465 metrics, 22 unstable metrics.
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
| if (process.versions.bun && !disabledInstrumentations.has('http')) { | ||
| require('../bun') | ||
| } |
There was a problem hiding this comment.
This is probably fine for now but of course once we support more than one Bun feature the http disabled check will need to be removed.
There was a problem hiding this comment.
[babysit-pr] Agreed, no change for now. This gate is scoped to bun-serve because it only produces HTTP spans. Any future Bun-native instrumentation should get its own gate keyed on its own integration name rather than reusing this one.
pabloerhard
left a comment
There was a problem hiding this comment.
I think the naming of the files is to general and we should consider renaming the following files:
packages/datadog-instrumentations/src/helpers/bun.js → packages/datadog-instrumentations/src/helpers/bun-requests.js
packages/datadog-instrumentations/src/bun.js → packages/datadog-instrumentations/src/bun-serve.js
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a7251934aa
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (!start.hasSubscribers) return fetch.apply(this, arguments) | ||
|
|
||
| const url = new URL(request.url) | ||
| const address = server.requestIP(request) |
There was a problem hiding this comment.
Handle server.fetch calls without a second callback argument
When an application invokes server.fetch(request) directly, Bun can invoke the fetch callback without the second server argument, so this dereference throws before the application handler executes. Reproduced on the available Bun 1.2.14 runtime: the uninstrumented call returns its normal response, whereas loading this instrumentation with the start channel enabled produces TypeError: undefined is not an object (evaluating 'server.requestIP'). Network requests do supply the argument, so the network-only fixtures miss this regression. Resolve the server from the callback receiver when necessary, or safely omit the peer-address lookup for direct dispatch. This also violates the instrumentation-failure isolation requirement in AGENTS.md.
AGENTS.md reference: AGENTS.md:L104-L106
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
[babysit-pr] Fixed in 792ade3. Confirmed on Bun 1.4.5 that server.fetch(request) calls the handler without the server argument while still binding the server as this. The instrumentation now uses server ?? this for requestIP, passes the application's original arguments through unchanged, and defaults the Host header from the request URL so http.url stays valid. Added an integration test for direct dispatch, which fails with the reported TypeError without the fix.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
a725193 to
b2f7b58
Compare
Bun omits the server argument when an application calls server.fetch(request) directly, so resolve it from the bound receiver, and default the Host header so the span URL stays valid. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
[babysit-pr] @pabloerhard the renames you suggested are in: helpers/bun.js is now helpers/bun-requests.js, and bun.js is now bun-serve.js. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 792ade3ced
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (!finished) { | ||
| errors.set(request, { | ||
| error, | ||
| // Bun invokes its error callback outside the fetch handler's async context. | ||
| handle: AsyncResource.bind(function () { |
There was a problem hiding this comment.
Finish direct-dispatch failures without awaiting Bun's error callback
When server.fetch(request) throws or rejects, Bun propagates the failure directly without invoking the server's error callback. Consequently, this entry is never removed and the request span never finishes. Reproduced with Bun 1.2.14 using this instrumentation: direct dispatch publishes start/error/exit but no finish. Repeated failures retain requests and their bound contexts indefinitely; if a subsequent network request throws the same Error object, the error callback selects the stale direct-dispatch entry and runs in the wrong request context. Handle direct-dispatch failures separately, completing their spans while preserving the original throw/rejection.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
[babysit-pr] Fixed in a4bd403. Confirmed on Bun 1.4.5 that a throwing or rejecting direct server.fetch(request) call never reaches the error callback. Direct dispatch (no server argument) now finishes its span as soon as the handler fails, without storing an entry for the error callback, and still rethrows the original error to the caller. Added integration tests for the sync and async cases that check the 500 span, its error message, and that the caller still sees the original error.
| const wrapHandler = (fetch, route) => function (request, server) { | ||
| if (!start.hasSubscribers) return fetch.apply(this, arguments) | ||
|
|
||
| const url = new URL(request.url) |
There was a problem hiding this comment.
Guard URL parsing before invoking the application handler
When an incoming request contains a malformed Host header such as [, Bun can supply a request.url that the WHATWG URL parser rejects. Reproduced on Bun 1.2.14: an uninstrumented handler receives this request and returns 200, whereas enabling this wrapper makes new URL(request.url) throw and returns 500 without invoking the application handler. Since this parsing occurs outside the guarded handler execution, tracing changes the application's behavior for these inputs. Fall back to invoking the original handler without instrumentation when the URL cannot be parsed.
AGENTS.md reference: AGENTS.md:L104-L106
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
[babysit-pr] Fixed in a4bd403. Confirmed on Bun 1.4.5 that Host headers like [, a b, or an empty value give a request.url the URL parser rejects, while an untraced handler still returns 200. The wrapper now uses URL.parse and calls the original handler untraced when it returns null, which avoids a try/catch on the hot path. Added an integration test that sends Host: [ over a raw socket and expects the application's 200 response.
Bun rethrows direct server.fetch() failures without calling its error callback, so finish those spans immediately instead of keeping them for a callback that never runs. Requests whose URL cannot be parsed now reach the application untraced instead of failing before the handler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a4bd403117
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if (url === null) return fetch.apply(this, arguments) | ||
| // Direct `server.fetch(request)` calls omit the server argument but still bind the server as `this`. | ||
| const direct = server === undefined | ||
| const address = (server ?? this).requestIP(request) |
There was a problem hiding this comment.
Allow direct dispatch after the Bun server has stopped
When server.fetch(request) is called after server.stop(true), the callback can receive neither the server argument nor a bound receiver, so this dereference throws before the application handler runs. Fresh evidence beyond the earlier direct-dispatch finding: on the available Bun 1.2.14 runtime, stopping the server first leaves uninstrumented direct dispatch working normally, but the current wrapper throws TypeError evaluating (server ?? this).requestIP. Safely omit the peer-address lookup when neither server reference is available, preserving direct dispatch for in-process requests after shutdown.
AGENTS.md reference: AGENTS.md:L104-L106
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
[babysit-pr] No change: this does not reproduce on the Bun this repo tests. On the pinned Bun 1.4.4 (and 1.4.5), calling server.fetch(request) after server.stop(true) still binds the server as this, and requestIP returns null, so the wrapper reaches the application handler normally. The failure needs Bun 1.2.14, which CI does not run. A guard for it could not be covered by a test here, and AGENTS.md asks for supported-source proof before adding defenses like this. If we decide to support older Bun releases, this is a one-character change (?.requestIP) along with a CI job on that version.
What does this PR do?
Part of experimental Bun support. Trace native
Bun.serverequests through the existing HTTP server plugin and web helpers. Runtime changes are gated byprocess.versions.bun.web.requestspans with HTTP tags, distributed context extraction, configured header tags, error handling, and existing CORS propagation response-header behavior.http.route. Preserve staticResponseroutes on Bun's native fast path, without server tracing.hono.requestspans, including default-export applications.server.reload, including Elysia's automatically reloaded native routes.Motivation
Native Bun servers bypass Node HTTP server events and otherwise produce no inbound server spans. Reuse the HTTP plugin rather than duplicate span, propagation, and header behavior.
Additional Notes
Validation
Bun 1.4.4 / Node v24.19.0, after merging current master without rebasing:
npm run lintstill reports the initialized OpenFeature submodule'stools/ufc/rules-resources.test.mjsas uncovered by test globs. The same failure reproduces in the unchanged base checkout; no submodule or lint configuration change is included here.Before/after regression proof: the new shared-error-context, WebSocket, client-abort, and static-fast-path tests all fail against the pre-fix implementation and pass with this update. The Elysia regression also exercises its normal
.get('/users/:id').listen(...)startup, including automatic reload.One intermediate run terminated with a native Bun SIGSEGV in the async-fetch test. Its cause is unclassified: the exact test subsequently passed 20/20 times on both the pre-fix and candidate revisions, and the final complete Bun suite passed. This is not being classified as an unrelated failure.
Reproducible performance measurement
Workload: loopback HTTP/1.1 GET
/, two-bytehibody, 50,000 measured requests after 5,000 warmup requests, concurrency 20, five fresh-process trials per mode. Alternate mode order each round; report median requests/second. The Bun server and untraced Bun fetch client are separate processes; a Node driver provides a local trace-agent stub. Trace export is included for traced function handlers. Linux x64, Bun 1.4.4 for both server/client, Node v24.19.0 driver.Baseline: pre-fix implementation at merge commit
e0aa1a261(original Bun implementation plus the same current master). Candidate: this update. Both runs use the identical benchmark script from this branch:Candidate static-route performance is within approximately 2% of its uninitialized control; unlike the baseline it performs no per-request JavaScript adaptation or cloning. These are local throughput measurements, not production latency estimates. The benchmark prints every trial as JSON for repeatability. Kept URL parsing readable rather than retaining an unproven manual-parser micro-optimization.
Scope / limitations
Responseroutes intentionally have no server span, distributed extraction, or tracing response-header injection, including static entries inside method maps. Use a function route when tracing is needed. HTML-bundle routes remain unsupported.require('hono'). Normalimport { Hono } from 'hono'yields only the underlyingweb.request, withouthono.requestor a Hono route name. The default-export fixture imports Hono through CommonJS; ESM loader support is separate work and is not implemented here.web.requestspans through itsserver.reloadpath; this does not add Elysia-specific middleware spans.CI status
Current snapshot: 579 passed, 1 failed, 1 queued, 52 cancelled, and 6 skipped. Bun runtime, HTTP/Hono, instrumentation, lint, and EditorConfig checks passed.
All Green exhausted its 30 polling attempts and cancelled three still-queued workflows: Serverless, System Tests, and Test Optimization. This is an aggregator timeout, not a Bun assertion failure. Team freeze guard remains queued.
The initial Event Hubs attempt had 30 connection-refused failures at
127.0.0.1:7071immediately after its host-lock readiness signal. Its retry was cancelled while queued, so this failure remains unclassified rather than being labelled unrelated. The same job passed all 30 tests on the unchanged target branch. No unrelated test changes or skips were added.Rerunning the three cancelled workflows was denied with
Resource not accessible by integration; a maintainer needs to rerun them, then All Green after they finish. The previous revision also hit an All Green timeout; no merge or public-comment changes were made.Link to Devin session: https://datadog-poc.devinenterprise.com/sessions/e0c443c51e3947ab94efea770d17a670
Open in Devin Desktop: https://datadog-poc.devinenterprise.com/desktop/session/e0c443c51e3947ab94efea770d17a670?variant=devin
Requested by: @eam1813