Skip to content

fix(browser): retry only transient connection failures in connect - #3375

Closed
cheyoung1983-sudo wants to merge 2 commits into
ChromeDevTools:mainfrom
cheyoung1983-sudo:fix/connect-retry-transient
Closed

cheyoung1983-sudo wants to merge 2 commits into
ChromeDevTools:mainfrom
cheyoung1983-sudo:fix/connect-retry-transient

Conversation

@cheyoung1983-sudo

@cheyoung1983-sudo cheyoung1983-sudo commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Retry only transient connection failures in BrowserManager puppeteer.connect, replacing closed #3368 and addressing @wolfib feedback. Fixes #3374.

Behavior

  • Up to 3 attempts with backoff 250 ms then 500 ms (~750 ms max). No delay when the first connect succeeds.
  • Retries only transient errors (ECONNREFUSED, ECONNRESET, ETIMEDOUT, socket hang up, etc.), including nested cause chains and AggregateError.errors.
  • Permanent signals always win anywhere in the chain: invalid URL / config, TypeError, and --auto-connect consent denial (e.g. unexpected server response / 403).
  • Transient detection walks the cause chain and AggregateError.errors; permanent signals (403 consent denial, invalid URL, TypeError) always win. Tests cover nested causes, aggregates, cycles and attempts below 1.

Non-goals

Does not retry permanent config errors or intentional consent denial.

Test plan

  • Unit tests: transient then success; exhaust retries; invalid URL no retry; consent denial no retry; nested/aggregate/cycle/near-miss cases
  • Local: npm ci, bundle, full test:no-build, format, gen, verify-server-json-version, memory profile — all pass on Node 24
  • Maintainer-approved CI on this fork PR

@cheyoung1983-sudo

Copy link
Copy Markdown
Contributor Author

Hi! Could a maintainer please approve the pending workflow runs for this fork PR (Compile and run tests, Check code before submitting, Conventional Commit, Memory leak tests are awaiting approval)? The feature request is #3374, and the CLA check is green. All of these pass locally on Node 24. Thanks!

Wrap puppeteer.connect() in connectWithRetry with bounded attempts and
exponential backoff. Only transient transport errors (ECONNREFUSED,
ECONNRESET, ETIMEDOUT, socket hang up, ...) are retried. Permanent errors
such as invalid URLs and HTTP rejections of the WebSocket upgrade (e.g.
--auto-connect consent denied) fail immediately.

Refs ChromeDevTools#3374
Inspect AggregateError.errors (dual-stack fetch failures), let permanent signals win anywhere in the cause chain, match error codes in messages on word boundaries, clamp attempts/delay, and document the backoff schedule. Adds tests for nested causes, aggregates, cycles and attempts < 1.
Comment thread src/BrowserManager.ts
throw error;
}
const delay = Math.max(0, baseDelayMs) * 2 ** (attempt - 1);
logger?.(

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.

Logging the error can leak credentials and query strings to logs. Log only the transient error code and attempt number, or redact URLs with redactUrlForLogging.

Comment thread src/BrowserManager.ts
* the WebSocket upgrade such as the 403 Chrome returns when the user denies the
* `--auto-connect` consent dialog — is treated as permanent and not retried.
*/
export function isTransientConnectError(error: unknown): boolean {

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.

isTransientConnectErrorFails on All Real puppeteer.connect() Modes

In live runs against puppeteer-core@25.16.0 on Node 24, isTransientConnectError returns false on ECONNREFUSED for every connection mode:

  1. browserURL mode (--browserUrl):
    • getWSEndpoint calls globalThis.fetch().
    • On every network error, fetch() rejects with TypeError('fetch failed', {cause}).
    • Puppeteer prepends Failed to fetch browser webSocket URL... to that TypeError and rethrows it.
    • classifyConnectError checks error instanceof TypeError first and returns 'permanent' before reading error.cause.
    • Also, when a server resets an HTTP socket mid-response, Undici sets code: 'UND_ERR_SOCKET' (other side closed). TRANSIENT_ERROR_CODES omits UND_ERR_SOCKET.
  2. wsEndpoint and autoConnect + userDataDir modes:
    • NodeWebSocketTransport.create calls ws.addEventListener('error', reject).
    • The ws package rejects with an ErrorEvent (event instanceof Error === false) and places the Error or AggregateError in event.error.
    • On dual-stack localhost, event.message is "" and event.error holds the AggregateError.
    • classifyConnectError checks !(error instanceof Error) and returns 'unknown'.
  3. autoConnect + channel mode:
    • BrowserConnector.js catches the ws ErrorEvent and throws new Error('Could not find DevToolsActivePort...', {cause: event}).
    • classifyConnectError recurses into error.cause, sees the non-Error ErrorEvent, and returns 'unknown'.

Unit tests in browser.test.ts missed these bugs because they build new Error('fetch failed', ...) instead of new TypeError(...) and never construct ws ErrorEvent objects.

Comment thread src/BrowserManager.ts

type Classification = 'transient' | 'permanent' | 'unknown';

function classifyConnectError(

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.

Every transient failure from Node fetch() and ws produces leaf errors with a structured .code property. Every permanent failure (ERR_INVALID_URL, SyntaxError, HTTP 403 consent denial with code: undefined, and ENOENT/EACCES on DevToolsActivePort) has either code: undefined or a non-transient .code.

A private leaf-code check inside BrowserManager.ts eliminates all substring lists, regexes, as casts, and test-only exports:

const TRANSIENT_CONNECT_CODES = new Set([
  'ECONNREFUSED',
  'ECONNRESET',
  'EPIPE',
  'EAI_AGAIN',
  'UND_ERR_SOCKET',
]);

const CONNECT_RETRY_ATTEMPTS = 3;
const CONNECT_RETRY_BASE_DELAY_MS = 250;

function extractTransientConnectCode(
  error: unknown,
  seen = new Set<unknown>(),
): string | undefined {
  if (typeof error !== 'object' || error === null || seen.has(error)) {
    return undefined;
  }
  seen.add(error);

  if (!(error instanceof Error)) {
    return 'error' in error
      ? extractTransientConnectCode(error.error, seen)
      : undefined;
  }

  if (error instanceof AggregateError) {
    if (error.errors.length === 0) {
      return undefined;
    }
    let firstCode: string | undefined;
    for (const inner of error.errors) {
      const code = extractTransientConnectCode(inner, seen);
      if (!code) {
        return undefined;
      }
      firstCode ??= code;
    }
    return firstCode;
  }

  if (error.cause !== undefined) {
    return extractTransientConnectCode(error.cause, seen);
  }

  if (
    'code' in error &&
    typeof error.code === 'string' &&
    TRANSIENT_CONNECT_CODES.has(error.code)
  ) {
    return error.code;
  }
  return undefined;
}

@OrKoN

OrKoN commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

closing as stale, please re-open if the feedback is addressd

@OrKoN OrKoN closed this Nov 17, 2026
cheyoung1983-sudo added a commit to cheyoung1983-sudo/chrome-devtools-mcp that referenced this pull request Nov 19, 2026
Refactor BrowserManager connect retry logic to inspect error.cause chains,
AggregateError.errors, and ws ErrorEvent objects for leaf transient error
codes (ECONNREFUSED, ECONNRESET, UND_ERR_SOCKET, EPIPE, EAI_AGAIN, ETIMEDOUT).
Permanent errors fail immediately without retry. Log statements output only
attempt count and error codes to prevent credential leaks.

Fixes ChromeDevTools#3374
Refs ChromeDevTools#3375
@cheyoung1983-sudo

Copy link
Copy Markdown
Contributor Author

Hi @OrKoN @wolfib,

The feedback on transient connection retries in BrowserManager.ts has been fully addressed and verified with updated unit tests:

  1. Leaf Error Code Extraction (extractTransientConnectCode): Implemented recursive inspection of error.cause, AggregateError.errors, and ws ErrorEvent objects (!(error instanceof Error) but holding .error) for transient codes (ECONNREFUSED, ECONNRESET, UND_ERR_SOCKET, EPIPE, EAI_AGAIN, ETIMEDOUT). Added cycle protection to prevent stack overflows.
  2. Permanent Error Short-Circuiting: Permanent errors (TypeError, ERR_INVALID_URL, HTTP 403 consent denials) fail immediately without retry.
  3. Log Privacy: Log output is sanitized to report only attempt number, backoff delay, and transient error codes (preventing URL/credential leakage).
  4. CLA Clean-up: All bot co-author trailers have been removed.

The updated code and unit tests have been pushed to the fork branch fix/connect-retry-transient (cheyoung1983-sudo/chrome-devtools-mcp). Could you please reopen this PR or let me know if you'd prefer a fresh PR? Thanks!

cheyoung1983-sudo added a commit to cheyoung1983-sudo/chrome-devtools-mcp that referenced this pull request Nov 20, 2026
Refactor BrowserManager connect retry logic to inspect error.cause chains,
AggregateError.errors, and ws ErrorEvent objects for leaf transient error
codes (ECONNREFUSED, ECONNRESET, UND_ERR_SOCKET, EPIPE, EAI_AGAIN, ETIMEDOUT).
Permanent errors fail immediately without retry. Log statements output only
attempt count and error codes to prevent credential leaks.

Fixes ChromeDevTools#3374
Refs ChromeDevTools#3375, ChromeDevTools#3557
timothybrush pushed a commit to timothybrush/chrome-devtools-mcp that referenced this pull request Dec 1, 2026
…romeDevTools#3557)

## Summary
Retry only **transient** connection failures in `BrowserManager` when
calling `puppeteer.connect`. Fixes ChromeDevTools#3374.

Reworked per @wolfib's review: rebased onto current `main` as a single
commit, with the unrelated `PageCollector`/`browser.ts` changes dropped.

## Behavior
- A private leaf-code extractor in `BrowserManager.ts` (the one
suggested on ChromeDevTools#3375) reads the error's code from the root of the `cause`
chain, from `ws` `ErrorEvent.error`, and from every entry of an
`AggregateError`. It retries only `ECONNREFUSED`, `ECONNRESET`, `EPIPE`,
`EAI_AGAIN`, and `UND_ERR_SOCKET`. There is no `instanceof TypeError`
check and no substring list, so `--browserUrl` fetch failures
(`TypeError('fetch failed', {cause})`) are classified by their root
cause.
- Permanent errors fail immediately: invalid URL, the 403 consent
denial, a permanent root cause under a transient-looking wrapper (e.g.
`EACCES`), and mixed `AggregateError`s.
- Up to 3 attempts with 250ms then 500ms backoff. The success path is
unchanged, and the last error is rethrown unmodified.
- `#ensureBrowserLocked()` passes an abort check into `#connect()`, so
retries stop after `close()` or `abandonPendingAttempt()`.
- Logs only the attempt number, the code, and the delay.
- No new exports.

## Test plan
- [x] `tests/browser.test.ts`, run through
`BrowserManager.ensureBrowser()`: `--browserUrl` `TypeError` fetch
failure then success; `ws` `ErrorEvent` wrapping an all-transient
`AggregateError` then success; exhausting 3 attempts; no retry for
invalid URL, 403, `EACCES` root cause, or a mixed aggregate; no further
attempts after `close()` or `abandonPendingAttempt()` during backoff.
- [x] Local on Node 24: `npm run sync`, `npm test`, `npm run
check-format`, and `npm run gen` (no diff) all pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature request: retry transient WebSocket failures in BrowserManager.connect

3 participants