Skip to content

Forbid get-port, and fix the inspector-proxy test flakes - #17185

Open
danlapid wants to merge 7 commits into
mainfrom
dlapid/no-probe-then-bind-ports
Open

danlapid wants to merge 7 commits into
mainfrom
dlapid/no-probe-then-bind-ports

Conversation

@danlapid

@danlapid danlapid commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

This adds a lint rule against get-port, removes the uses that can let the listener choose its port, and fixes the two inspector-proxy test flakes seen on workerd's "Run workers-sdk tests" check.

Why get-port is banned

get-port finds a free port and releases it. The caller then hands the number to whatever listens on it later, and any other process can take the port in between. Every port it picks without a preferred number is in the OS's ephemeral range, the same range that every listen(0) and every outbound connection draws from. In a busy test run that window is crossed often enough to fail CI with ERR_ADDRESS_IN_USE. That was the most common workers-sdk flake on workerd's CI (#17182 fixes that one).

oxlint.config.mts now restricts imports of get-port across the repo, Miniflare's workers included. The message explains the race and the fix: let the code that listens choose the port by listening on port 0 and reading back the port it got (server.address().port, Miniflare's ready URL or getInspectorURL(), or the ports workerd reports through --control-fd). If the port must be known before something else listens on it, keep a listener on it for as long as it is needed. The allowed paths are now a shared constant, so the per-file override can reuse them without get-port.

Audit

I looked for get-port and for code that listens on port 0, reads the port and closes the listener.

Fixed here, by letting the listener choose:

  • packages/miniflare/test/plugins/core/inspector-proxy/index.spec.ts: see below.
  • packages/wrangler/e2e/pages-dev.test.ts: passes --port 0 --inspector-port 0 and reads the URL from Ready on, as e2e/dev.test.ts already does.
  • packages/wrangler/e2e/startWorker.test.ts: the port-change test starts on port 0, pins the port it got, then moves to port 0 again, fetching the URL from worker.url (with port 0 the server listens on only one of localhost's addresses). Pinning restarts workerd on the same port, as every reload does, so a small window remains while the old workerd exits. The test no longer adds its own window on top.
  • packages/mock-npm-registry/tests/publish-package.test.ts: the fake upstream registry listens on port 0.
  • fixtures/start-worker-node-test: server.port: 0. Also removed the unused get-port devDependency from it and from fixtures/no-bundle-import.

Every other listen(0) in the repo keeps its listener open for as long as the port is in use: Miniflare's loopback server, the Hyperdrive proxies, the containers SSH proxy, and the test servers.

Still using get-port, allowed per file in one override with a comment for each group (the override says not to add files):

  • packages/miniflare/src/plugins/artifacts/controller.ts: [miniflare] Hold the local Artifacts Git port instead of probing it #17182 removes this use. The entry should go when that lands.
  • Preferred default ports: packages/wrangler/src/utils/memoizeGetPort.ts (8787 and 9229 for wrangler dev), packages/vite-plugin-cloudflare/src/debug.ts and packages/vitest-plugin/src/pool/index.ts (9229). Each one tries the documented default port and falls back to another port when it is taken. These are not race-free: a fallback port can be taken before Miniflare listens on it. Fixing them means Miniflare tries the default port itself and falls back to port 0 on EADDRINUSE, and the "using port X instead" messages move to after Miniflare is ready. That is a behaviour change across three packages, so it should be its own PR. The two wrangler unit tests in the override (utils-memoizeGetPort.test.ts, dev.test.ts) only mock get-port to test this logic.
  • packages/vite-plugin-cloudflare/src/plugins/tunnel.ts: guesses the port Vite's preview server will choose, so the tunnel can start before the server listens. Not race-free either. It needs the tunnel to start after preview is listening.
  • packages/create-cloudflare/e2e/helpers/{framework,workers}-helpers.ts: pass --port to each framework template's dev and preview server. Those servers take only a port number and don't report the port they listen on in a common format.
  • packages/mock-npm-registry/src/index.ts and the Verdaccio part of its test: Verdaccio runs in a child process, listens on the port named in its config file, and must keep that port across restarts. A listener that holds the port and forwards to Verdaccio on a Unix socket would fix it.

Inspector-proxy test flakes

inspectors.length undefined in "/json should provide a list of a single worker inspector"

The test fetched http://localhost:${port}/json, but the inspector proxy listens only on 127.0.0.1. Node resolves localhost to ::1 first. Ports on 127.0.0.1 and ::1 are separate, so another server can listen on [::1]:${port} while the proxy holds 127.0.0.1:${port}. Other tests in the suite do listen there, for example Miniflare instances with host: "::1". When one did, the request reached that server, which answered with a JSON object instead of the proxy's array. A standalone check with a [::1] server and a 127.0.0.1 server on the same port gets the [::1] server's JSON for localhost, and the right array for 127.0.0.1.

get-port doesn't explain this one: that test uses inspectorPort: 0. The tests now connect to the host getInspectorURL() reports (127.0.0.1:${port}) instead of localhost.

Unhandled ECONNRESET after "should allow debugging workers created via setOptions"

InspectorProxy's WebSocket to workerd's inspector had no error listener. That test calls setOptions() right after ready, while the proxy's connection to the first workerd is still opening. Miniflare kills that workerd with SIGKILL to start the next one, which resets the connection. The resulting error event had no listener, so it was thrown as an uncaught exception. Disposing a proxy before its connection opened also failed the same way, with "WebSocket was closed before the connection was established".

The proxy now logs runtime connection errors at debug level. In the same class, this.#runtimeWs?.OPEN and this.#devtoolsWs.OPEN read the constant WebSocket.OPEN (always 1), not the connection state. So a DevTools message that arrived before the runtime connection opened was passed to send(), which threw WebSocket is not open: readyState 0 (CONNECTING). These checks now use readyState, and DevTools messages are queued until the runtime connection opens. Proxies are listed as soon as they are created, so DevTools can connect in that window. This is a Miniflare change, with a changeset.

Port-change tests without get-port

Three tests needed a fixed port to move away from, and got it from get-port. They now start on port 0 and call setOptions() with the port they got, then move to port 0 for a new port. To make that race-free, InspectorProxyController.updateConnection() no longer closes and reopens its server when inspectorPort changes to the port it already listens on. A restart to a new port on the same host now listens on the new address before closing the old one, so port 0 can't be given the old port back. A move to another host closes the old server first instead, because the old host may be reachable from places the new one isn't. If a same-host move fails, the old server keeps listening and its proxies connect to the restarted workerd. If a move to another host fails, the inspector is unavailable. Either way the next setOptions() tries the move again. A failed move no longer leaves a rejected listen where Miniflare waits for readiness, which used to block every request even after the inspector was disabled. Retiring a server now also terminates its DevTools WebSocket connections: closeAllConnections() doesn't close upgraded connections, so any move with DevTools attached used to hang setOptions() waiting for the old server to close.

Testing

  • New tests for the runtime connection being reset, for disposing before it opens, and for DevTools messages sent before it opens. Against the old InspectorProxy, each one fails with an unhandled error: ECONNRESET, "closed before the connection was established", and readyState 0 (CONNECTING).
  • New tests for failed inspector moves: the old server keeps serving and a retry works; a failed move to another host stops serving the old host, and dispose() still resolves; a same-port host change listens again afterwards; disabling the inspector after a failed move lets dispatchFetch() through; DevTools attached through the old port reach the restarted workerd's Worker; and a port or host change completes with DevTools attached. Each fails without the controller change it covers.
  • Checked that the rule reports a new get-port import in a file outside the override.
  • pnpm check:lint, pnpm check:type and oxfmt --check pass.
  • Full Miniflare suite passes (126 files, 1904 tests), on macOS only.
  • Stress: the full Miniflare suite with 5 concurrent runs of the inspector-proxy file, three rounds. The first round caught a mistake in one of my new tests, which expected ECONNRESET but under load sometimes got EPIPE, the same reset landing during the handshake write. Fixed. Since then, four rounds with all suite files and all inspector-proxy runs passing, the last on the final commit. Neither original flake reproduced in any round. So the evidence for the fixes is the cause analysis and the deterministic tests above, not the absence of failures.
  • mock-npm-registry tests pass. The startWorker e2e port-change test passes locally (remote: false). The pages-dev e2e and start-worker-node-test fixture changes were not run locally; they rely on CI.

  • Tests
    • Tests included/updated
    • Automated tests not possible - manual testing has been completed as follows:
    • Additional testing not necessary because:
  • Public documentation
    • Cloudflare docs PR(s):
    • Documentation not necessary because: lint configuration, test changes and an internal Miniflare fix with no API change.

🤖 Generated with Claude Code


Devin Review

danlapid and others added 2 commits November 25, 2026 18:02
The inspector proxy's WebSocket to workerd had no `error` listener.
Miniflare kills workerd whenever it restarts or is disposed, which can
reset that connection, even before it opens, and the reset was thrown
as an uncaught ECONNRESET. "should allow debugging workers created via
setOptions" hit this by calling setOptions() right after `ready`. The
proxy now logs these errors at debug level.

Its `OPEN` checks read the `WebSocket.OPEN` constant rather than the
connection state, so a DevTools message that arrived before the runtime
connection opened made `send()` throw. DevTools messages are now
queued until the connection opens.

"/json should provide a list of a single worker inspector" fetched
`localhost`, which Node tries as ::1 first, while the proxy listens on
127.0.0.1 only. When another test's server held the same port number
on ::1, the request reached that server. The tests now connect to the
host getInspectorURL() reports.

The tests that changed ports used get-port, whose port can be taken
before Miniflare listens on it. They now start on port 0 and set the
port they got. updateConnection() no longer restarts the server when
inspectorPort changes to the port it already listens on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
get-port finds a free port and releases it, so another process can
take the port before the code it was chosen for listens on it. This
caused ERR_ADDRESS_IN_USE flakes.

Restrict get-port imports in oxlint, with a message pointing to
listening on port 0 and reading back the port. Switch the tests that
can do that: wrangler's pages-dev and startWorker e2e tests, the mock
npm registry's fake upstream, and the start-worker fixture. Remaining
uses that need a preferred default port, a third-party server's port,
or another PR (#17182) are allowed per file, with
the reason for each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@changeset-bot

changeset-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: ab58821

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 9 packages
Name Type
miniflare Patch
@cloudflare/deploy-helpers Patch
@cloudflare/dev-helpers Patch
@cloudflare/pages-shared Patch
@cloudflare/remote-bindings Patch
@cloudflare/runtime-types Patch
@cloudflare/vite-plugin Patch
@cloudflare/vitest-plugin Patch
wrangler Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

devin-ai-integration[bot]

This comment was marked as resolved.

@pkg-pr-new

pkg-pr-new Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
@cloudflare/autoconfig

npm i https://pkg.pr.new/@cloudflare/autoconfig@17185

@cloudflare/build-output-utils

npm i https://pkg.pr.new/@cloudflare/build-output-utils@17185

@cloudflare/codemods

npm i https://pkg.pr.new/@cloudflare/codemods@17185

@cloudflare/config

npm i https://pkg.pr.new/@cloudflare/config@17185

@cloudflare/containers-shared

npm i https://pkg.pr.new/@cloudflare/containers-shared@17185

create-cloudflare

npm i https://pkg.pr.new/create-cloudflare@17185

@cloudflare/deploy-helpers

npm i https://pkg.pr.new/@cloudflare/deploy-helpers@17185

@cloudflare/kv-asset-handler

npm i https://pkg.pr.new/@cloudflare/kv-asset-handler@17185

miniflare

npm i https://pkg.pr.new/miniflare@17185

@cloudflare/pages-functions

npm i https://pkg.pr.new/@cloudflare/pages-functions@17185

@cloudflare/pages-shared

npm i https://pkg.pr.new/@cloudflare/pages-shared@17185

@cloudflare/runtime-types

npm i https://pkg.pr.new/@cloudflare/runtime-types@17185

@cloudflare/test-server

npm i https://pkg.pr.new/@cloudflare/test-server@17185

@cloudflare/unenv-preset

npm i https://pkg.pr.new/@cloudflare/unenv-preset@17185

@cloudflare/vite-plugin

npm i https://pkg.pr.new/@cloudflare/vite-plugin@17185

@cloudflare/vitest-plugin

npm i https://pkg.pr.new/@cloudflare/vitest-plugin@17185

@cloudflare/workers-auth

npm i https://pkg.pr.new/@cloudflare/workers-auth@17185

@cloudflare/workers-editor-shared

npm i https://pkg.pr.new/@cloudflare/workers-editor-shared@17185

@cloudflare/workers-utils

npm i https://pkg.pr.new/@cloudflare/workers-utils@17185

wrangler

npm i https://pkg.pr.new/wrangler@17185

commit: ab58821

@ask-bonk

ask-bonk Bot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

@danlapid Bonk workflow was cancelled.

View workflow run · To retry, trigger Bonk again.

@danlapid
danlapid marked this pull request as ready for review November 26, 2026 03:39
@workers-devprod
workers-devprod requested review from a team and petebacondarwin and removed request for a team November 26, 2026 03:39
@workers-devprod

Copy link
Copy Markdown
Contributor

Codeowners approval required for this PR:

  • @cloudflare/wrangler
Show detailed file reviewers
  • .changeset/inspector-proxy-runtime-reset.md: [@cloudflare/wrangler]
  • fixtures/no-bundle-import/package.json: [@cloudflare/wrangler]
  • fixtures/start-worker-node-test/package.json: [@cloudflare/wrangler]
  • fixtures/start-worker-node-test/src/config-errors.test.js: [@cloudflare/wrangler]
  • oxlint.config.mts: [@cloudflare/wrangler]
  • packages/miniflare/src/plugins/core/inspector-proxy/inspector-proxy-controller.ts: [@cloudflare/wrangler]
  • packages/miniflare/src/plugins/core/inspector-proxy/inspector-proxy.ts: [@cloudflare/wrangler]
  • packages/miniflare/test/plugins/core/inspector-proxy/index.spec.ts: [@cloudflare/wrangler]
  • packages/mock-npm-registry/tests/publish-package.test.ts: [@cloudflare/wrangler]
  • packages/wrangler/e2e/pages-dev.test.ts: [@cloudflare/wrangler]
  • packages/wrangler/e2e/startWorker.test.ts: [@cloudflare/wrangler]
  • pnpm-lock.yaml: [@cloudflare/wrangler]

clanky-the-clanker[bot]

This comment was marked as resolved.

@petebacondarwin petebacondarwin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

CI appears red and there are AI review comments to address

@github-project-automation github-project-automation Bot moved this from Untriaged to In Review in workers-sdk Nov 26, 2026
The startWorker e2e test fetched 127.0.0.1 on the port the server got
through port 0, but with port 0 the server listens on only one of
`localhost`'s addresses, ::1 on the CI runners. Fetch the URL the
worker reports instead.

InspectorProxyController's same-port check threw when the server was
not listening, which is its state after a failed restart, so a later
update could not recover. A restart now listens on the new address
before closing the old one. If that fails, the old server keeps
serving and the options stay as they were, so a retry tries again.
Listening first also keeps port 0 from returning the old port. When
the new port is the old one on another host, the old server still
closes first.

The zod bridge's override no longer turns off the get-port ban.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
devin-ai-integration[bot]

This comment was marked as resolved.

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Superseded by the review of 28f1ca94.

This review, of 45c31334

✅ Approved — The earlier WARNING about updateConnection() not recovering after a failed restart is fixed: the same-port check no longer throws, and #restartServer() keeps the old server serving when the new port fails to bind. No new issues found.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

No security concerns.


📖 AGENTS.md: ✅ LGTM

Follows the repository conventions.


📋 Code Quality: ✅ LGTM

🔄 Since last review: 1 finding resolved, 0 preserved, 0 new

Earlier finding: fixed. updateConnection() (inspector-proxy-controller.ts:329-333) now reads the port through #getListeningPort(), which returns undefined for a closed or rejected server instead of throwing. #restartServer() (lines 89-114) listens on the new server before it closes the old one. If the bind fails, the old server keeps serving and the host and port options go back to their previous values, so a later retry binds again. The new test "keeps serving, and can retry, when a new port fails to bind" covers this.

The server closes first only when the new port is the old port on a different host. On that path a failed bind leaves #server rejected, the same as before this pull request.

The other changes also look correct:

  • the readyState checks, the runtime error listener and the queue of early DevTools messages in inspector-proxy.ts
  • the zod bridge override in oxlint.config.mts, which now keeps the get-port restriction
  • the e2e and fixture tests that now use port 0
  • the removal of get-port from the fixtures and the lockfile

⚡ Performance: ✅ LGTM

No performance concerns.


📝 Documentation: ✅ LGTM

The changeset and the lint message are accurate.


Reviewed commit: 45c31334

When setOptions() failed to move the inspector server to another
host on the same port, the old server had already been closed and
the rejected listen was stored as the server. Miniflare waits on it
for readiness, even once the inspector is disabled, so every later
request failed with the bind error. Keep the old server and options
instead, and listen again on the next update.

A failed move also left the proxies connected to the workerd that
setOptions() had just stopped. Connect them to the new runtime
before rethrowing, so the server that kept listening debugs the
running Workers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
devin-ai-integration[bot]

This comment was marked as resolved.

clanky-the-clanker[bot]

This comment was marked as resolved.

A failed move to another host kept the old server listening and,
since the last commit, serving the restarted runtime's Workers. The
old host may be reachable from places the new one isn't, for example
0.0.0.0 when moving to 127.0.0.1, so it must not keep serving. Close
the old server before listening whenever the host changes. Same-host
port changes still listen first and keep the old server on failure.

dispose() no longer rejects with ERR_SERVER_NOT_RUNNING when a
failed move left a closed server, and the changeset now says when
the old server keeps serving.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
devin-ai-integration[bot]

This comment was marked as resolved.

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Superseded by the review of 2d2caef8.

This review, of 97276ce1

✅ Approved — Both earlier notes (changeset wording and dispose() after a failed move) are fixed, and no new issues turned up in the controller, proxy, lint or test changes.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

Any host change closes the old inspector server before the new one listens. A failed move to another host therefore never leaves the old host (for example 0.0.0.0) serving.


📖 AGENTS.md: ✅ LGTM

The change follows the repository's conventions, and the Miniflare change includes a changeset.


📋 Code Quality: ✅ LGTM

dispose() now returns early when the stored server is not listening, so it resolves after a failed close-first move. A bind that was rejected is still rethrown. updateConnection() and #restartServer() are consistent: options roll back on failure, the proxies reconnect before the error is rethrown, and the old server closes first only when the host changes. The inspector-proxy.ts changes (readyState checks, the runtime error listener, the queue for early DevTools messages) are correct.


⚡ Performance: ✅ LGTM

No performance concerns.


📝 Documentation: ✅ LGTM

The changeset now matches #restartServer(). After a failed move, the old server keeps serving only for a port change on the same host. A failed move to another host leaves the inspector unavailable until a later setOptions() succeeds.


Reviewed commit: 97276ce1

server.closeAllConnections() doesn't close upgraded connections, so
with DevTools attached, closing the old inspector server waited for
the DevTools WebSocket, which only closes when its proxy is disposed
after the restart. Any port or host change in setOptions() then hung.
Terminate the retired server's DevTools connections before closing
it, and on dispose().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
devin-ai-integration[bot]

This comment was marked as resolved.

@clanky-the-clanker clanky-the-clanker Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Superseded by the review of ab588216.

This review, of 2d2caef8

✅ Approved — No issues found in the DevTools connection termination or its tests, and the earlier inline notes are fixed in the code at this commit.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

Any host change still closes the old inspector server before the new one listens, so a failed move never leaves the old host serving.


📖 AGENTS.md: ✅ LGTM

The change follows the repository's conventions. Tests take expect from the test context, and the Miniflare change includes a changeset.


📋 Code Quality: ✅ LGTM

Each HTTP server is mapped to its DevTools WebSocketServer through a WeakMap. #closeServer() and dispose() terminate the upgraded clients, and closeAllConnections() handles the rest. The terminated sockets go through the existing readyState-checked close path in InspectorProxy. dispose() still rethrows an initial bind failure. The new tests for DevTools staying attached through a port change and a host change wait for the client close event, so a regression would fail the test rather than pass.


⚡ Performance: ✅ LGTM

No performance concerns.


📝 Documentation: ✅ LGTM

The changeset matches what #restartServer() does after a failed move.


Reviewed commit: 2d2caef8

A host change closes the old server before the new one listens on
port 0, so the OS may give it the same port again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@clanky-the-clanker clanky-the-clanker Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Approved — The only change since the last review fixes the host-move test, which now checks the host instead of the port, and no issues remain.

The decision is advisory: this review is a comment and never approves, blocks or requests changes on the pull request.


✅ All checks passed

🔒 Security: ✅ LGTM

Any host change still closes the old inspector server before the new one listens, so a failed move never leaves the old host serving.


📖 AGENTS.md: ✅ LGTM

The change follows the repository's conventions. Tests take expect from the test context, and the Miniflare change includes a changeset.


📋 Code Quality: ✅ LGTM

The only change since the last review is in the DevTools-attached move test in packages/miniflare/test/plugins/core/inspector-proxy/index.spec.ts.

  • Host change: the test now checks that the inspector URL has the new host. It no longer compares ports. This is correct: a host change closes the old server before the new one listens on port 0, so the OS can return the same port. getInspectorURL() builds the hostname from the configured host, so the check is deterministic.
  • Same-host port change: the test still checks that the port changed. That holds because the new server listens before the old one closes.
  • The test still waits for the client close event and a dispatchFetch(). If DevTools connections stopped being terminated, the test would fail or hang instead of passing.

⚡ Performance: ✅ LGTM

No performance concerns.


📝 Documentation: ✅ LGTM

The changeset still matches what #restartServer() does after a failed move.


Reviewed commit: ab588216

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In Review

Development

Successfully merging this pull request may close these issues.

3 participants