Repository navigation
Description
What version of workerd are you using?
1.20260722.1 (also present in 1.20260423.1 and 1.20260317.1 — not bisected further; the code path involved, src/workerd/api/hyperdrive.c++, has not materially changed across these).
Binaries tested (all from @cloudflare/workerd-darwin-arm64 / the workerd npm package, as vendored by workers-sdk's miniflare):
$ ./workerd --version
workerd 2026-07-22
Platform: macOS 26 (Darwin 25.5.0), arm64.
What happened?
workerd's hyperdrive binding (Hyperdrive::connect() in src/workerd/api/hyperdrive.c++) assumes its designator always resolves to an external (raw TCP) service, because that is the only configuration Wrangler/Hyperdrive tooling has ever produced. If the designator instead resolves to a Worker service (e.g. a config typo, or a deliberate experiment binding a Hyperdrive-shaped binding at another Worker), calling .connect() on the binding crashes the entire workerd process with SIGSEGV instead of throwing a JS-catchable error.
This is unsupported/unintended usage, but a runtime should never segfault in response to a misconfiguration reachable from a config file + JS binding call — it should throw (e.g. TypeError) like the analogous "worker doesn't export a connect() handler" case already does correctly (see below).
Discovery context
Found while locally prototyping a Hyperdrive-over-remote-binding relay for local dev (routing a hyperdrive binding's designator at another Worker service instead of external, as a workaround/experiment), as a follow-up to cloudflare/workers-sdk#14710 and #14712. Not encountered via any production Hyperdrive config; no Hyperdrive config id, account id, or credentials are involved in this reproduction — it is 100% local and self-contained.
What did you expect to happen?
Either:
connect()throws a catchable JS error (e.g.TypeError: Hyperdrive binding designator must be an external service), same as the existing, correctly-handled case where the connect target Worker doesn't export aconnect()handler (workerd/api/global-scope.c++:232,Handler does not export a connect() function.); or- it works, if pointing a Hyperdrive-shaped binding at a Worker service is meant to be a supported extension point.
Either way: no SIGSEGV, and no impact on other requests/isolates sharing the same workerd process.
How can we reproduce it?
This reproduces with plain workerd serve and a hand-written .capnp config — no workers-sdk, wrangler, or miniflare involved, and no real Postgres/MySQL anywhere. The hyperdrive binding's database/user/password/scheme fields are dummy placeholders; they are never actually used before the crash.
Two Workers:
- worker-a: has a
hyperdrivebinding namedHYPERDRIVE, whosedesignatoris"worker-b"(a Worker service, notexternal). Itsfetch()handler callsenv.HYPERDRIVE.connect(). - worker-b: an ordinary Worker that is the (incorrect) target of that designator.
config.capnp
using Workerd = import "/workerd/workerd.capnp";
const config :Workerd.Config = (
services = [
(name = "worker-a", worker = .workerA),
(name = "worker-b", worker = .workerB),
],
sockets = [
( name = "http", address = "*:8080", http = (), service = "worker-a" ),
]
);
const workerA :Workerd.Worker = (
modules = [
(name = "worker", esModule = embed "worker-a.js"),
],
compatibilityDate = "2026-07-01",
compatibilityFlags = ["experimental", "nodejs_compat"],
bindings = [
(
name = "HYPERDRIVE",
hyperdrive = (
# This is the crux of the reproduction: the designator names a Worker
# service ("worker-b"), not an `external` service as Hyperdrive
# bindings normally use in production.
designator = "worker-b",
database = "postgres",
user = "postgres",
password = "postgres",
scheme = "postgresql",
),
),
],
);
const workerB :Workerd.Worker = (
modules = [
(name = "worker", esModule = embed "worker-b-withhandler-nopipe.js"),
],
compatibilityDate = "2026-07-01",
compatibilityFlags = ["experimental", "nodejs_compat"],
);worker-a.js
export default {
async fetch(request, env, ctx) {
try {
const socket = env.HYPERDRIVE.connect();
await socket.opened;
return new Response("connected: " + JSON.stringify({
readable: !!socket.readable,
writable: !!socket.writable,
}));
} catch (err) {
return new Response("caught error (expected, this is fine): " + err.stack, {
status: 500,
});
}
},
};worker-b-withhandler-nopipe.js (the crashing target — exports a connect() handler)
export default {
async fetch(request, env, ctx) {
return new Response("target-worker fetch() called");
},
async connect(socket, env, ctx) {
await socket.opened;
// Deliberately do nothing else -- no data is ever piped.
},
};Run it
workerd serve config.capnp --experimental --verbose
# in another terminal:
curl -v http://localhost:8080/curl gets back 200 OK with body connected: {"readable":true,"writable":true} — i.e. the Hyperdrive-side JS connect() call appears to succeed and the HTTP response is flushed to the client — but within roughly a second afterward, the whole workerd process dies with SIGSEGV (confirmed reproducible across 3 separate runs, same relative crash-stack shape each time):
*** Received signal #11: Segmentation fault: 11
stack: 1070c3427 1070c3427 1070c3287 1050f444b 1050c7cf7 1050ca227 1070c9ec7 1050ca77b 1070c9d67 1070caa9f 1070c82c7 1070c8cb3 1045b7e97 10712386f 107123b97 107122403 1071221c3 1045a48f3 1809bbdff
A second run (different ASLR slide, same relative offsets between stack entries, confirming the same code path):
*** Received signal #11: Segmentation fault: 11
stack: 10553b427 10553b427 10553b287 10356c44b 10353fcf7 103542227 105541ec7 10354277b 105541d67 105542a9f 1055402c7 105540cb3 102a2fe97 10559b86f 10559bb97 10559a403 10559a1c3 102a1c8f3 1809bbdff
I was not able to symbolicate these addresses in my environment (no task_for_pid/debugger-attach entitlement available, and no crash report was generated by the OS), so I can't point to an exact line with certainty — see "Suspected root cause" below for candidates found by reading the source.
What narrows down the crash location
- The crash does not require any data to flow over the socket. It reproduces identically whether
worker-b'sconnect()handler pipes the stream (socket.readable.pipeTo(socket.writable)) or does nothing butawait socket.opened. So the bug is in the connect handshake completing, not in subsequent stream I/O. - The crash requires
worker-bto actually accept the CONNECT (i.e. have aconnect()handler that runs to theresponse.accept()point inServiceWorkerGlobalScope::connect(),src/workerd/api/global-scope.c++:198). Ifworker-bhas noconnect()handler at all, there is no crash — instead you get a clean, catchable JS error, exactly as designed:This confirms the missing-handler path (Received a connect event but we lack a handler. Did you remember to export a connect() function? workerd/io/io-context.c++:444: info: uncaught exception; exception = workerd/api/global-scope.c++:232: failed: jsg.Error: Handler does not export a connect() function. workerd/api/hyperdrive.c++:39: warning: failed to connect to local database; e = ... Handler does not export a connect() function.JSG_FAIL_REQUIRE(Error, "Handler does not export a connect() function.")) is safe, and the crash is specific to the success path where the CONNECT is actually accepted cross-Worker. - The HTTP response to the original
fetch()request onworker-ais delivered successfully before the crash, meaning the crash happens in background/deferred work — most likely during teardown of the synthetic connect pipe/IoContext(s) involved, not during the initial connect handshake itself.
Suspected root cause (unconfirmed candidates — for triage, not a definitive diagnosis)
I was not able to get a symbolicated backtrace in my environment, so none of these are confirmed; they're what stood out while reading the code paths that Hyperdrive::connect() exercises when its designator is a Worker service, which is a path that (as far as I can tell) has never been exercised in production because Hyperdrive designators are always external.
-
src/workerd/api/hyperdrive.c++:109-115(Hyperdrive::connectToDb()):auto connectReq = kj::newHttpClient(*service)->connect( kj::str(getHost(), ":", getPort()), headers, kj::HttpConnectSettings{}); auto status = co_await connectReq.status; if (status.statusCode >= 200 && status.statusCode < 300) { co_return kj::mv(connectReq.connection); }
kj::newHttpClient(*service)returns akj::Own<kj::HttpClient>temporary that is never bound to a variable — only the result of->connect(...)(aConnectRequest, whose.statusis thenco_awaited and whose.connectionis used) is kept. Compare with the only other in-tree caller of this exact overload,src/workerd/io/worker-interface.c++:118:return kj::newHttpClient(*workerInterface).attach(kj::mv(workerInterface));which explicitly keeps the returned
kj::Own<kj::HttpClient>alive (and ties the wrappedWorkerInterface's lifetime to it).hyperdrive.c++does neither. If the specifickj::HttpClientadapter/coroutine machinery involved in bridging aWorkerInterface's (i.e. a Worker's)connect()back through this adapter is not as fully self-contained as theexternal-service path (which is far better trodden), this early-destroyed temporary is a natural place to look for a dangling reference. -
src/workerd/io/io-context.c++,IoContext::getSubrequestChannel/getSubrequestNoChecks(~line 1000-1030): builds a stack-localTraceContext tracingfor the"hyperdrive_connect"operation name and only attaches it to the returnedWorkerInterfaceif (tracing.isObserved()). Worth checking whether tracing/span state differs meaningfully, and is handled correctly, when the destination channel resolves to a full Worker (with its own isolate lock,IoContext, and tracer) versus a raw external TCP connection (which has none of that). -
src/workerd/io/worker-entrypoint.c++:619-699(WorkerEntrypoint::connect) andsrc/workerd/api/global-scope.c++:185-233(ServiceWorkerGlobalScope::connect): both appear to assume the caller is genuine CONNECT ingress — i.e. a real listeningtcp-type socket accepting an external connection (see the comment atglobal-scope.c++:216-218: "We set isDefaultFetchPort to false here ... but this is not relevant on the TCP server side"). In this repro, the same code path is instead reached synthetically, as the target of a Hyperdrive.connect()subrequest issued from another Worker'sIoContextvia thekj::newHttpClient(WorkerInterface&)adapter — i.e. two independentIoContexts (worker-a's and worker-b's) share a synthetic in-process pipe rather than a real accepted socket. An ordering/lifetime assumption around that cross-IoContextteardown (worker-a's request finishing and releasing the HyperdriveSocket/subrequest channel while worker-b'sconnect()handler and itsIncomingRequest::drain()are still unwinding, or vice versa) seems like a plausible place for a use-after-free.
Additional notes
- This is very likely not reachable from any real production Hyperdrive configuration today — Hyperdrive designators are always
externalservices provisioned by Cloudflare's control plane. It surfaced only while experimenting with routing ahyperdrive-shaped binding at a Worker service directly. - Regardless of "is this configuration supported," a config-file-reachable SIGSEGV is a process-wide crash (all in-flight requests/isolates in that
workerdprocess go down with it), so it seems worth hardeningHyperdrive::connect()/ the underlyingconnect()plumbing to fail gracefully (e.g. reject non-externaldesignators explicitly, or otherwise ensure the same safe-JS-error behavior as the "no connect handler" case) regardless of whether the feature of Hyperdrive-over-Worker-designator is ever supported. - Full repro files (config + both worker scripts + raw crash logs from two separate runs) are available and can be attached/pasted in full if useful; omitted here only for length.
Activity
mack-erel commentedon Jul 25, 2026
Some follow-up analysis after reading the source more closely — I think the crash is a lifetime asymmetry between
externaland Worker service targets, which suggests the missing.attachis a symptom rather than the whole fix.In
Hyperdrive::connectToDb()(src/workerd/api/hyperdrive.c++:101-133), theservicereturned bycontext.getSubrequestChannel(...)is a coroutine-frame local. Atco_return kj::mv(connectReq.connection)the frame — and theserviceOwnwith it — is destroyed, so the returned stream has to be self-sustaining.For an external target that holds:
ExternalTcpService::startRequestreturns{this, kj::NullDisposer::instance}(server.c++:2006) — a non-owning pointer to a server-lifetime singleton, so destroying theserviceOwnis a no-op.co_await addr->connect()the pump promise references only the ownedio_streamand the pipeconnection, notthis(server.c++:2029-2050) — fully self-sustaining once connected.For a Worker target it doesn't:
WorkerService/EntrypointService::startRequestreturns an owning per-requestWorkerInterfacewith its ownIoContext(server.c++:3519+).WorkerEntrypoint::connectcaptures[this, ...]and runs on the worker's ownIoContextviacontext.run(...)(worker-entrypoint.c++:619); the connect-handler promise keeps referencing it, and the socket can outlive the handler viactx.waitUntil()(global-scope.c++:185-232, see the neuter/deferredNeutercomment at 200-202).So at
co_returnthe owningWorkerInterface+ itsIoContextare torn down while the cross-IoContextpipe is still pumping — which lines up with the observed "crash happens in deferred/background work, after the initial handshake" symptom.That's why copying
asHttpClient's.attach(kj::mv(workerInterface))pattern (worker-interface.c++:118) ontohyperdrive.c++:109isn't sufficient on its own: theserviceOwnstill dies atco_return, and the adapter's connect-pump promise still references theWorkerInterface. A correct fix would need to attach both the adapter and theWorkerInterfaceOwnto the returned stream so they live as long as the socket, and even then the neuter /waitUntil× cross-IoContextteardown ordering would need care.Given that, the two useful outcomes here seem separable:
externalHyperdrive designator with a catchable error at bind/connect time, exactly like the existing "worker doesn't export aconnect()handler" path (global-scope.c++:232) — no SIGSEGV regardless of whether the feature is ever supported. Happy to send a PR for this if it'd be welcome.Context for why this matters: we hit this while prototyping local-dev support for remote Hyperdrive bindings (cloudflare/workers-sdk#14842). We're going with a local TCP bridge there rather than a Worker designator precisely because of this crash — which, I noticed afterwards, is the same conclusion the miniflare
hyperdrive-proxy.tscode already reached (its comment notes the Worker-designator SIGSEGV). So this issue is really just about the defensive guard, not about unblocking that work.mack-erel commentedon Jul 25, 2026
I took a first pass at a defensive guard along the lines above. Two upfront caveats: it is unverified — I don't have a workerd build environment (no Bazel 9.1.1 / clang-format 18.1.8 here), so this has not been compiled, clang-formatted, or run against the repro — and it embeds a design question I'd want a maintainer to decide before it's worth polishing into a PR.
Approach: reject at config-link time, not connect time
The connect path (
Hyperdrive::connectToDb→IoContext::getSubrequestChannel→IoChannelFactory::startSubrequest) deliberately hides the concrete service type behindWorkerInterface, so the service class isn't cleanly available there. It is available at the server layer, where the codebase already doeskj::tryDowncast<WorkerService>to report config errors (e.g. thediskSvcbinding check). So the guard resolves each hyperdrive designator inmakeWorkerImpl'slinkCallbackand, if it downcasts toWorkerService, reports a config error:External/network/disk services aren't
WorkerService, so the downcast fails and the real Hyperdrive path (external.tcp) is untouched.The design question
This is fail-fast at config load (
errorReporter.addError→ workerd refuses to start), consistent with how other invalid bindings are handled, and it prevents the SIGSEGV strictly earlier than connect time. But it's a different behavior from theconnect()-handler precedent (global-scope.c++:232), which throws a runtime, JS-catchable error. If you'd rather this be catchable at.connect()time (worker keeps running,try/catchsees the error), the alternative is to substitute the hyperdrive channel with a stub whosestartRequest/connect throwsJSG_FAIL_REQUIRE(likeInvalidConfigService) instead of erroring at link time.I lean config-time (the designator type is statically knowable, unlike a missing handler), but this is really your call. Happy to build/verify/clang-format and open a proper PR once there's a preferred direction — or if it's easier for someone with the build set up to just take the patch and run with it, that's fine too.
Unverified patch (server.c++, +50/-5)
mack-erel commentedon Jul 26, 2026
I set up a workerd build locally and verified this end-to-end. Summary: the crash reproduces on a fresh build, a guard fixes it cleanly, and — interestingly — actually enabling a Worker-service designator needs more than the client-side lifetime fix.
Repro confirmed on a from-source build
Built
//src/workerd/server:workerd(fastbuild) and ran the minimal repro from the issue.curlgets200 "connected"and then the process dies with*** Received signal #11during connection teardown — matching the "crash happens in deferred work, after the handshake" behavior noted above.I tried the actual client-side lifetime fix — it removes the crash but data still doesn't flow
Mirroring
connectImpl/asHttpClient(worker-interface.c++:117), I madeHyperdrive::connectToDb()keep the adapter +WorkerInterfacealive on the returned stream:Result (built + run): the SIGSEGV is gone —
connect()/socket.openedresolve and the process survives — but bytes don't round-trip through a Worker-service target; the socket fails with a catchableError: Network connection lostinstead. So there's a second, target-side teardown issue (thenewNeuterableIoStream/deferredNeuter+ctx.waitUntil()path inglobal-scope.c++:200-228) beyond the client-sideOwnI fixed. Theexternal.tcppath is unaffected — I verified a real byte round-trip through anexternal.tcpdesignator still works with this change.Takeaway: this looks like a guard fix, not a quick functional-enablement — making a Worker-service designator actually usable is more than a couple of lines, whereas preventing the crash is small and safe.
Two guard variants, both built and verified
Both compile and behave as expected on the from-source binary:
kj::tryDowncast<WorkerService>, mirroring the existingdiskSvccheck) and callserrorReporter.addError. workerd exits with:Worker "worker-a"'s binding "HYPERDRIVE" is a Hyperdrive binding whose designator refers to the service "worker-b", but that service is a Worker. Hyperdrive designators must reference an 'external' service, not a Worker.startRequest(a dedicated stub rather thanInvalidConfigService, whosegetTokenMaybeSyncisKJ_UNREACHABLEand would abort a live channel). workerd starts,.connect()throws a catchable error, and the process keeps serving — matching the existing "no connect handler" UX (global-scope.c++:232).Both leave the
external.tcppath untouched (external/network/disk aren'tWorkerService, so detection never fires). Happy to open a PR with whichever you prefer — I'd lean toward the runtime-catchable variant since it matches the existing no-handler precedent, but config-time is the stricter/lower-risk option. I can clang-format and send it once you point me at the preferred direction.(Context: this came out of prototyping local-dev support for remote Hyperdrive bindings, cloudflare/workers-sdk#14842 — which uses a local TCP bridge with an
external.tcpdesignator precisely because, as the above confirms, a Worker-service designator isn't a viable path today.)robertgrace4546-sketch commentedon Jul 30, 2026
mack-erel commentedon Jul 30, 2026
Gentle ping — it's been a few days, and both guard variants are built and verified locally, so this is only waiting on a direction.
@fhanau you implemented the inbound
connect()handler in #6059, so you're likely closest to this code path — would you (or whoever owns Hyperdrive's connect plumbing) have a preference between the two guards described above? Briefly: (1) config-time reject (refuse to start with a config error) or (2) runtime catchable (start normally,.connect()throws a catchable error, process keeps serving — matching the existing "no connect handler" UX atglobal-scope.c++:232). Either is small and self-contained, and both leave theexternal.tcppath untouched. I can clang-format and open the PR the same day.One clarification, since it affects how this thread reads: I don't believe the comment above is from a maintainer — the account has no other activity in this repo — so I haven't treated it as a decision. Happy to be corrected if it was official.
api: keep Hyperdrive subrequest channel alive for the CONNECT stream
api: keep Hyperdrive subrequest channel alive for the CONNECT stream
api: keep Hyperdrive subrequest channel alive for the CONNECT stream (#…