Skip to content

Windows: browse server fails to start — findPort() race condition in Node.js polyfill #486

Closed

Description

@nikobenho

Summary

On Windows, browse goto <url> fails 100% of the time with "Server failed to start within 15s". The root cause is a race condition in findPort() when running under the Node.js polyfill (bun-polyfill.cjs).

Environment

  • Windows 11 Pro
  • gstack v0.11.18.2
  • Node.js v20.11.1
  • Bun 1.3.11

Root cause

findPort() in server.ts tests port availability by calling Bun.serve({ port }) then immediately testServer.stop(). In real Bun, Bun.serve() is synchronous — the port binds and releases instantly.

In the Node.js polyfill, Bun.serve() wraps http.createServer() + server.listen(), which is async. stop() wraps server.close(), also async. Neither has completed by the time findPort() returns the port.

The timeline:

  1. findPort() calls polyfill Bun.serve({ port: X }) → queues async listen()
  2. testServer.stop() → queues async close()
  3. findPort() returns port X (neither listen nor close has executed yet)
  4. await browserManager.launch() — event loop runs, test server's listen() now binds port X
  5. Real Bun.serve({ port: X }) → EADDRINUSE because the test server's close() hasn't completed

Reproduction

Minimal script proving the race condition:

// Save as test-race.js, run with: node test-race.js
const path = require('path');
const polyfillPath = path.join(
  process.env.USERPROFILE, '.claude', 'skills', 'gstack', 'browse', 'dist', 'bun-polyfill.cjs'
);
require(polyfillPath);

async function test() {
  const port = 10000 + Math.floor(Math.random() * 50000);
  // Simulate findPort():
  const testServer = Bun.serve({ port, fetch: () => new Response('ok') });
  testServer.stop();
  // Simulate browserManager.launch() delay:
  await new Promise(r => setTimeout(r, 500));
  // Simulate real server bind:
  const http = require('http');
  const s = http.createServer((req, res) => res.end('ok'));
  s.on('error', (e) => {
    console.log('FAILED:', e.message); // Always hits EADDRINUSE
    process.exit(1);
  });
  s.listen(port, '127.0.0.1', () => {
    console.log('SUCCESS');
    s.close();
  });
}
test();

This fails 100% of the time on Windows.

Fix

Replace Bun.serve() port testing in findPort() with net.createServer() using proper async bind/close:

async function findPort() {
  const net = require('net');
  function checkPort(port) {
    return new Promise((resolve, reject) => {
      const srv = net.createServer();
      srv.once('error', (err) => reject(err));
      srv.listen(port, '127.0.0.1', () => {
        srv.close(() => resolve(port));
      });
    });
  }
  // ... same retry logic, using await checkPort(port) instead of Bun.serve()
}

This properly waits for both bind AND close to complete before returning the port.

Verified locally — 5/5 cold starts succeed, browse commands work normally.

Related issues

This is distinct from the stdio array fix in v0.11.18.2 — that fixed the spawn format, this fixes the port selection race condition.

Activity

  1. BemnetMussa commented on Mar 25, 2026

    @BemnetMussa

    I'll take this one. This looks like a classic TOCTOU (Time-of-Check to Time-of-Use) race condition. Windows handles TCP socket teardown (TIME_WAIT) a bit slower than Unix, which is why findPort says a port is free, but the OS hasn't fully released it by the time the server tries to bind to it.

    I'll put up a PR that hardens the server startup logic (either by binding to ephemeral port 0 or adding a robust EADDRINUSE retry loop) so it's completely immune to this race condition.

  2. added 2 commits that reference this issue on Mar 25, 2026
    ec879a8
    1d4b1ad
  3. evb87-tech commented on Mar 25, 2026

    @evb87-tech

    @BemnetMussa Hey, apologies — I didn't see your comment until after I'd already pushed the fix. Wasn't trying to snipe your issue. If you'd prefer to take a different approach (like the ephemeral port 0 idea you mentioned), happy to close mine in favor of yours. Just let me know.

  4. BemnetMussa commented on Mar 25, 2026

    @BemnetMussa

    @evb87-tech Great catch on the polyfill's stop() being fire-and-forget—that definitely explains why the internal probe was colliding with the startup!

    In #493, I took an approach. While fixing the probe is valuable, "Probe-then-Bind" is inherently a TOCTOU (Time-of-Check to Time-of-Use) risk. Even with a perfect probe, a separate process—or another gstack agent—can claim the port in the millisecond window before the server binds.

    The reason I believe #493 is the more production-grade fix:

    ✅ Self-Healing

    • Introduces a retry-on-bind loop
    • If the port is taken (external process, ghost socket, or slow OS teardown), the server recovers automatically instead of crashing

    🔧 Polyfill Hardening

    • Fixes the unhandled async behavior in the polyfill’s listen()
    • Adds a .ready Promise to align behavior with native Bun’s predictability

    Perhaps we can combine both ideas, but I’d argue that resilience (retrying) is a more robust standard for a tool like gstack than probing (checking).

  5. garrytan commented on May 26, 2026

    @garrytan
    Owner

    Fixed in #490 (9d179598). Closing as resolved — thanks @nikobenho.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions