Skip to content

[miniflare] Hold the local Artifacts Git port instead of probing it - #17182

Merged
danlapid merged 4 commits into
mainfrom
dlapid/artifacts-git-port-race
Nov 26, 2026
Merged

danlapid merged 4 commits into
mainfrom
dlapid/artifacts-git-port-race

Conversation

@danlapid

@danlapid danlapid commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Local Artifacts sometimes fails to start with:

MiniflareCoreError [ERR_ADDRESS_IN_USE]: Address already in use (socket "artifacts-<id>-git")

This makes the Artifacts tests flaky. On workerd's "Run workers-sdk tests" check it caused 10 of the 12 failures in the last day of runs, about 8% of runs, each time on a different test in test/plugins/artifacts/. It also shows up in this repo's own CI, on the Windows runtime partition.

The cause is how the Git port is picked. Miniflare chose a free port with get-port (or the port saved in git-port), released it, and wrote it into workerd's config. workerd bound it only after the Git sidecar thread had started and the new workerd process had loaded its config. Any other process could take the port in that window: another Miniflare's workerd binding port 0, or an outbound loopback connection given it as its source port. Each Miniflare instance without persistence gets a fresh tmpPath, so in tests every start picks a new port this way.

The controller now keeps listening on the Git port for as long as the namespace's backend lives (GitRelay in git-relay.ts). It forwards each connection to workerd's Git socket, which now binds port 0. Miniflare passes the ports workerd reports to ArtifactsController.commitUpdate(), which points each relay at its socket. The Git port still comes from git-port when that port is free, so clones keep their origin. Since workerd no longer owns the port, it also stays the same across reloads.


  • 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: no user-facing behavior changes beyond the fix. The plugin README is updated.

Testing:

  • New test "the Git port is held from the moment it is chosen and forwarded to workerd": the port get() returns must already be bound, and connections must reach the port given to commitUpdate(). It fails with the old probe-then-release behavior (expected 'bound' to be 'EADDRINUSE') and passes with this change.
  • New test "Git keeps its remote and keeps working across a reload": info/refs still answers after setOptions() starts a new workerd with a new Git socket port.
  • Ran both new tests and the existing restart test 5 times: all passed.
  • The full Miniflare suite passes (126 files, 1896 tests), run locally on macOS only, not on Windows or Linux.
  • pnpm check:type, oxfmt --check, and oxlint --deny-warnings --type-aware pass on the changed files.

🤖 Generated with Claude Code


Devin Review

Miniflare chose a free port for each Artifacts namespace's Git
remote, released it, and wrote it into workerd's config. workerd
bound it only after the Git sidecar thread had started and the new
process had loaded its config. Any other process on the machine
could take the port in that window, and Miniflare then failed to
start with ERR_ADDRESS_IN_USE on the `artifacts-<id>-git` socket.

The controller now keeps listening on the Git port for as long as
the namespace's backend lives, and forwards each connection to
workerd's Git socket, which binds port 0. The port reported for that
socket is handed to the controller when the config update commits.
The Git port still comes from `git-port` when it's free, so clones
keep their `origin`, and it now also stays put across reloads.

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: 3113e16

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

@ask-bonk

ask-bonk Bot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

LGTM!

github run

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@17182

@cloudflare/build-output-utils

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

@cloudflare/codemods

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

@cloudflare/config

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

@cloudflare/containers-shared

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

create-cloudflare

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

@cloudflare/deploy-helpers

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

@cloudflare/kv-asset-handler

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

miniflare

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

@cloudflare/pages-functions

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

@cloudflare/pages-shared

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

@cloudflare/runtime-types

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

@cloudflare/unenv-preset

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

@cloudflare/vite-plugin

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

@cloudflare/vitest-plugin

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

@cloudflare/workers-auth

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

@cloudflare/workers-editor-shared

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

@cloudflare/workers-utils

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

wrangler

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

commit: 3113e16

@danlapid
danlapid marked this pull request as ready for review November 25, 2026 22:05
@workers-devprod
workers-devprod requested review from a team and dario-piotrowicz and removed request for a team November 25, 2026 22:06
@workers-devprod

workers-devprod commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Codeowners approval required for this PR:

  • ✅ @cloudflare/wrangler
Show detailed file reviewers

clanky-the-clanker[bot]

This comment was marked as resolved.

…orwarding

If anything after the Git listener opened threw synchronously, such
as constructing the sidecar thread, the listener stayed open: the
failed backend had already left `#backends`, so nothing closed it,
and it kept both the port and the process alive. Everything after
the listener opens now runs inside the cleanup that closes it.

When workerd stops for a reload, or crashes, its Git sockets' ports
are released, but the listener kept forwarding to them until the
next successful update. If that update failed, another local
process could take the port and be sent the next Git request,
token included. `ArtifactsController.detachRuntime()` now drops
every listener's target before workerd is restarted and when it
crashes, so connections are refused until `commitUpdate()` sets the
new ports.

Also document that `GitRelay.close()` cuts off transfers in
progress, and say in the changeset that existing clones keep their
remote.

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 74ab79e9.

This review, of 247c5ea4

💬 Approved with comments — The fix is correct and well tested, and the follow-up commit handles failed starts and stale forwarding. One INFO remains: the relay's server has no lasting error listener.

Findings: 1 info

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


📋 Code Quality: 💬 1 info

One INFO from the last review is still open. The changes since then are correct.

Recommendation: 💬 Optional Nits

  • [INFO] GitRelay's server has no lasting error listener after listen() resolves, so a later server error would be unhandled. (packages/miniflare/src/plugins/artifacts/git-relay.ts:35)
View full review
  • INFO (still open): in git-relay.ts, the listen() helper removes its temporary error handler once the server is listening. After that only a connection listener is attached. If the server later emits an error, such as an accept failure from EMFILE, nothing handles it and it would crash the host process (Miniflare, Wrangler or Vite).
  • detachRuntime() is called before updateConfig and in the crash handler. It is paired with commitUpdate(), so the relays are pointed at the new ports on reload and on crash-restart.
  • #start / #startSidecar now close the relay on any failure after the listener opens, and the new test covers this.

✅ All other checks passed

🔒 Security: ✅ LGTM

The relay binds only to 127.0.0.1 and forwards only to the loopback port that workerd reports. Connections are refused until that port is known and again after detachRuntime(), so a relay cannot forward to a stale port while workerd restarts.


📖 AGENTS.md: ✅ LGTM

No issues.


⚡ Performance: ✅ LGTM

No performance concerns.


📝 Documentation: ✅ LGTM

The README explains the relay and why the Git port is held.


Reviewed commit: 247c5ea4

Address review feedback on the Artifacts Git listener:

- Give the listener's server a lasting `error` listener. Once it was
  listening it had none, so an accept failure, such as running out of
  file descriptors, would have been thrown in the host process.
- Detach Git forwarding inside the persist root startup lock, right
  before the old workerd stops, so that failing to take the lock no
  longer leaves a running workerd unreachable over Git.
- Have the detach test check that the listener still accepts the
  connection, so a listener that released its port fails the test.

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 3113e16c.

This review, of 74ab79e9

✅ Approved — The last open note is fixed: the relay's server now keeps a lasting error listener. detachRuntime() now runs inside the startup lock, and nothing new came up in this pass.

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

The relay listens only on 127.0.0.1 and forwards only to the loopback port that workerd reports. Connections are refused until commitUpdate() sets that port, and again after detachRuntime(). That call now runs inside the startup lock and in the crash handler, so a relay never forwards to a stale port while workerd restarts.


📖 AGENTS.md: ✅ LGTM

No issues.


📋 Code Quality: ✅ LGTM

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

  • Fixed since the last review: after listen() resolves, git-relay.ts now adds a lasting error listener to the server. An accept failure such as EMFILE now costs only that one connection and no longer reaches the host process.
  • Where detachRuntime() runs: it now runs inside the startup-lock callback, right before runtime.updateConfig(). If the lock can't be taken, forwarding to the running workerd stays in place. The crash handler also detaches. The next commitUpdate() then points the relays at the new socket ports, after both a reload and a crash restart.
  • The Git sockets on port 0 are among the sockets whose ports updateConfig waits for, so commitUpdate() gets real ports.
  • The tests cover these cases:
    • the port is held as soon as it is chosen;
    • connections are forwarded;
    • connections are refused after detach (the connection must open and receive nothing);
    • a failed start is cleaned up;
    • Git keeps working across a reload.

⚡ Performance: ✅ LGTM

No performance concerns.


📝 Documentation: ✅ LGTM

The plugin README and the changeset describe the relay and why the Git port stays the same.


Reviewed commit: 74ab79e9

A reload that ends a Container session stops workerd before taking
the persist root startup lock, and `Miniflare.dispose()` stops it
before closing the Git listeners. In both cases the listeners kept
forwarding to the port workerd had released, which another local
process could take and be sent Git requests and their tokens. Both
now call `detachRuntime()` before stopping workerd, like the config
update and crash paths already did.

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 — No findings. The new detachRuntime() calls before runtime.dispose(), in the Container-session reload and in Miniflare.dispose(), mean that every path that stops workerd now stops Git forwarding first.

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

The relay listens only on 127.0.0.1 and forwards only to the loopback port workerd reports. Forwarding now stops before every path that stops workerd: a reload, a Container-session reload, a crash and dispose(). So a relay never sends Git traffic, and the tokens it carries, to a port workerd has released and another process could take.


📖 AGENTS.md: ✅ LGTM

No issues.


📋 Code Quality: ✅ LGTM

🔄 Since last review: 0 findings resolved, 0 preserved, 0 new

  • Container-session reload (index.ts): detachRuntime() now runs before runtime.dispose(). It runs again right before updateConfig() inside the startup lock. The second call has no effect, because it only clears each relay's target port. If updateConfig() fails after the detach, the relays refuse connections until a later commitUpdate() gives them new ports.
  • Miniflare.dispose(): detachRuntime() runs synchronously before workerd is told to stop. It only sets a field on each relay, so it cannot throw and skip the shutdown. The listeners still close later, in artifactsController.dispose(). In between, they no longer forward to a port workerd has released.
  • Crash handler: unchanged and still correct.
  • The tests already check that connections open and receive nothing after a detach.

⚡ Performance: ✅ LGTM

No performance concerns.


📝 Documentation: ✅ LGTM

The plugin README and the changeset match the relay behaviour, including why the Git port now stays the same.


Reviewed commit: 3113e16c

@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.

It's a shame we have to add this complexity to Miniflare.

@workers-devprod workers-devprod 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.

Codeowners reviews satisfied

@danlapid
danlapid merged commit 07d2051 into main Nov 26, 2026
99 of 100 checks passed
@github-project-automation github-project-automation Bot moved this from Untriaged to Approved in workers-sdk Nov 26, 2026
@danlapid
danlapid deleted the dlapid/artifacts-git-port-race branch November 26, 2026 15:53
@github-project-automation github-project-automation Bot moved this from Approved to Done in workers-sdk Nov 26, 2026
brandhaug added a commit to brandhaug/b2b-saas-starter that referenced this pull request Nov 30, 2026
## pnpm-workspace.yaml (default)

## Dependency Updates

| Package | From | To | Type |
| --- | --- | --- | --- |
| `@cloudflare/vitest-plugin` | 1.9.2 | 1.10.0 | minor |
| `@cloudflare/workers-types` | 5.20261125.1 | 5.20261127.1 | minor |
| `miniflare` | 5.20261123.1-beta | 5.20261127.0-beta | minor |
| `wrangler` | 4.168.0 | 4.169.0 | minor |

## Release Notes

<details>
<summary><b>@<!---->cloudflare/vitest-plugin</b> (1.9.2 →
1.10.0)</summary>

### Minor Changes

- [#17161](cloudflare/workers-sdk#17161)
[`e46c7c6`](cloudflare/workers-sdk@e46c7c6)
Thanks [@<!---->thisisamank](https://github.com/thisisamank)! - Add
RealtimeKit bindings

Bind an existing RealtimeKit app to a Worker in your Wrangler
configuration file:

  ```jsonc
  {
    "realtimekit": [
      {
        "binding": "RTK",
        "app_id": "<APP_ID>",
        "remote": true
      }
    ]
  }
  ```

RealtimeKit has no local simulator, so set `remote: true` to use the
real app during local development. Calls during development, including
calls on returned meetings, go through the existing remote bindings
proxy. The experimental configuration API supports
`bindings.realtimeKit({ id: "<APP_ID>", dev: { remote: true } })`, and
the `wrangler-to-cf` codemod converts `realtimekit` entries. Deployments
upload only the binding name and `app_id`. `wrangler types` generates
`RealtimeKitBinding` for these bindings.

### Patch Changes

- [#17203](cloudflare/workers-sdk#17203)
[`41bacf7`](cloudflare/workers-sdk@41bacf7)
Thanks [@<!---->jamesopstad](https://github.com/jamesopstad)! - Accept
`fedramp-high` in `CLOUDFLARE_COMPLIANCE_REGION`

`cloudflare.config.ts` writes the FedRAMP High region as `fedramp-high`,
but `CLOUDFLARE_COMPLIANCE_REGION` only accepted `fedramp_high` and
rejected the other spelling with `Expected "fedramp-high" to be one of
["public","fedramp_high"]`. Both spellings are now accepted and mean the
same region, so a value copied from `cloudflare.config.ts` into
`CLOUDFLARE_COMPLIANCE_REGION` works.

- [#17140](cloudflare/workers-sdk#17140)
[`b645124`](cloudflare/workers-sdk@b645124)
Thanks [@<!---->dependabot](https://github.com/apps/dependabot)! -
Update `DEFAULT_COMPAT_DATE` to 2026-11-24

  Use the bundled

…[full
notes](https://github.com/cloudflare/workers-sdk/releases/tag/%40cloudflare/vitest-plugin%401.10.0)

</details>

<details>
<summary><b>miniflare</b> (5.20261123.1-beta →
5.20261127.0-beta)</summary>

### Minor Changes

- [#17161](cloudflare/workers-sdk#17161)
[`e46c7c6`](cloudflare/workers-sdk@e46c7c6)
Thanks [@<!---->thisisamank](https://github.com/thisisamank)! - Add
RealtimeKit bindings

Bind an existing RealtimeKit app to a Worker in your Wrangler
configuration file:

  ```jsonc
  {
    "realtimekit": [
      {
        "binding": "RTK",
        "app_id": "<APP_ID>",
        "remote": true
      }
    ]
  }
  ```

RealtimeKit has no local simulator, so set `remote: true` to use the
real app during local development. Calls during development, including
calls on returned meetings, go through the existing remote bindings
proxy. The experimental configuration API supports
`bindings.realtimeKit({ id: "<APP_ID>", dev: { remote: true } })`, and
the `wrangler-to-cf` codemod converts `realtimekit` entries. Deployments
upload only the binding name and `app_id`. `wrangler types` generates
`RealtimeKitBinding` for these bindings.

### Patch Changes

- [#17182](cloudflare/workers-sdk#17182)
[`07d2051`](cloudflare/workers-sdk@07d2051)
Thanks [@<!---->danlapid](https://github.com/danlapid)! - Fix local
Artifacts sometimes failing to start with `ERR_ADDRESS_IN_USE`

Miniflare chose a free port for an Artifacts namespace's Git remote,
released it, and had workerd bind it later, so another process could
take the port in between. Miniflare now keeps listening on the Git port
itself and forwards connections to workerd. Existing clones keep
working: a namespace's Git remote still uses the port it had last time
while that port is free, and now also keeps it across configuration
reloads.

- [#17140](cloudflare/workers-sdk#17140)
[`b645124`](cloudflare/workers-sdk@b645124)
Thanks [@<!---->dependabot](https://github.com/apps/dependabot)! -
Update `DEFAUL

…[full
notes](https://github.com/cloudflare/workers-sdk/releases/tag/miniflare%405.20261127.0-beta)

</details>

<details>
<summary><b>wrangler</b> (4.168.0 → 4.169.0)</summary>

### Minor Changes

- [#17183](cloudflare/workers-sdk#17183)
[`ebc7b50`](cloudflare/workers-sdk@ebc7b50)
Thanks [@<!---->gpanders](https://github.com/gpanders)! - Accept
`linux/arm64` images in `wrangler containers push` and `wrangler
containers build`

`wrangler containers push` now accepts local images built for
`linux/amd64` or `linux/arm64`. `wrangler containers build --platform`
accepts the same two platforms. The default platform is still
`linux/amd64`.

- [#17088](cloudflare/workers-sdk#17088)
[`43da328`](cloudflare/workers-sdk@43da328)
Thanks [@<!---->efalcao](https://github.com/efalcao)! - Add the
`oidc_tokens` binding

An OIDC token binding issues short-lived OpenID Connect tokens for the
Worker's own identity, for one audience. Exchange them for cloud
credentials, or send them to an API as a bearer token, instead of
storing long-lived credentials as secrets:

  ```jsonc
"oidc_tokens": [{ "binding": "API_TOKEN", "audience":
"https://api.example.com" }]
  ```

`env.API_TOKEN.getToken()` returns a newly signed JWT. Set `"alg":
"RS256"` for verifiers that don't accept the default, ES256. Wrangler
validates the audience (1 to 2048 printable ASCII characters, no
whitespace), uploads the binding, generates its `OidcTokenBinding` type,
and prints it in the bindings table. After a deploy, `wrangler deploy`
prints the issuer and subject to put in the verifier's trust policy. The
subject contains the Worker's immutable ID, which the deploy output
doesn't otherwise show. The binding isn't available in local development
yet. Accounts must be enabled for the binding before they can deploy it.

- [#17161](cloudflare/workers-sdk#17161)
[`e46c7c6`](cloudflare/workers-sdk@e46c7c6)
Thanks [@<!---->thisisamank](https://github.com/thisisamank)!

…[full
notes](https://github.com/cloudflare/workers-sdk/releases/tag/wrangler%404.169.0)

</details>

---
*This PR was auto-generated by
[catalog-update-action](https://github.com/brandhaug/catalog-update-action).*

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

[miniflare] Local Artifacts Git socket port race causes ERR_ADDRESS_IN_USE on parallel startup

3 participants