← Back to Pull requests

perf: stop counting every client to check for a connected one #6287

Merged
Nabeel-akk merged 6 files (60 lines) on Dec 01, 2026 10:21 UTC
View on GitHub
Nabeel-akk Nabeel-akk commented on Dec 01, 2026 04:46 UTC
Author

This relates to...

nodejs/undici#6279

Rationale

Agent checks whether a pool still has a connected client every time one of that pool's connections closes, so it can drop the pool when it is idle. PoolBase[kConnected] answers that question by adding up kConnected over every client, and each client reads socket.destroyed. A pool holds one client per open response, so with long-lived responses (SSE, long polling, streaming RPC) each closing connection walks the whole pool. Socks5ProxyAgent has the same check.

The check only needs a yes/no answer, so it does not have to visit clients after the first connected one.

Changes

  • New internal kHasConnectedClient symbol.

  • DispatcherBase answers it generically with kConnected > 0, so any dispatcher keeps working.

  • PoolBase overrides it and returns on the first connected client.

  • Agent and Socks5ProxyAgent use it instead of kConnected > 0.

  • New test in test/agent-connection-management.js: a pool with 100 clients, only the first connected, answers true after reading exactly one client's kConnected. It fails without the PoolBase override.
  • kConnected itself is unchanged — stats and kFree still need the count.

    Status

  • I have read and agreed to the [Developer's Certificate of Origin][cert]

  • Tested

  • Benchmarked (optional)

  • Documented

  • Review ready

  • In review

  • Merge ready
  • [cert]: https://github.com/nodejs/undici/blob/main/CONTRIBUTING.md#developers-certificate-of-origin

    Tests

    node --test test/agent-connection-management.js test/pool.js \
      test/pool-retired-clients.js test/pool-connection-error-memory-leak.js \
      test/client-reconnect.js test/client.js test/dispatcher.js \
      test/socks5-proxy-agent.js
    # tests 150, pass 148, skipped 2, fail 0
    

    npm run lint passes on the changed files.

    I did not benchmark it: on this Windows host the reproduction from the issue runs into ephemeral-port pressure before the numbers get interesting, and the results were not stable enough to be worth quoting. The added test pins the behaviour that matters (one client read instead of all of them).

    AI assistance

    Prepared with AI assistance (OpenCode, DeepSeek V4.1 Flash Free) under my direction; the regression test and the reasoning above were checked against the code.

    Diff: 60 lines (+53 / -7) across 6 files Reviewer: mcollina Review duration: 335m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.35) × (1 − Review Confidence (0.79)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.35 · 60 lines diff across 6 files
    0.35
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.68 · 3 substantive comment(s)
    0.68
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    78%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.246
    Real PR Conversation Timeline
    7 items
    mcollina mcollina approved these changes on Dec 01, 2026 08:47 UTC
    Approved Reviewer

    lgtm

    Copilot Copilot commented on code on Dec 01, 2026 08:57 UTC
    Code Review
    lib/dispatcher/agent.js:1
    @@ -106,7 +106,7 @@ class Agent extends DispatcherBase {
             // no connected clients and is not busy, but it still has pending work.
             // Closing it here lets the replacement Client finish those requests
             // and then destroys that new connection with ClientDestroyedError.
    -        if (dispatcher[kConnected] > 0 || dispatcher[kBusy]) {
    +        if (dispatcher[kHasConnectedClient] || dispatcher[kBusy]) {

    Agent.Options.factory accepts any public Dispatcher (types/agent.d.ts:24), but only DispatcherBase supplies the new getter. A custom dispatcher exposing kConnected without inheriting that getter is now removed and closed on disconnect or connectionError despite another connection remaining open, if it has no busy or pending work. Fall back to dispatcher[kConnected] > 0 when kHasConnectedClient is absent, and add a regression test for this factory case.

    Copilot Copilot commented on code on Dec 01, 2026 08:57 UTC
    Code Review
    lib/dispatcher/pool-base.js:1
    @@ -215,6 +215,17 @@ class PoolBase extends DispatcherBase {
         return this[kNeedDrain]
       }
     
    +  // A pool can hold one client per open response, so stop at the first
    +  // connected client instead of counting all of them.
    +  get [kHasConnectedClient] () {
    +    for (let i = 0; i < this[kClients].length; i++) {
    +      if (this[kClients][i][kConnected]) {

    MockPool reports kConnected === 1 until explicitly closed (lib/mock/mock-pool.js:43–44), but this inherited getter ignores that state. When an Agent factory returns mockAgent.get(origin), the last passthrough disconnect now closes and unregisters the pool, losing its configured interceptors. Override kHasConnectedClient in MockPool to respect its synthetic connectivity and add a regression test.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Dec 01, 2026 08:57 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    The new connectivity check can prematurely close and unregister mock or custom dispatchers, losing configured interceptors or disrupting connections that remain open.

    <details open>
    <summary><strong>2 open issues</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Custom dispatchers may close while connections remain open · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> MockPool disconnect drops configured interceptors · New

  • </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    Optimizes Undici’s idle-pool checks by checking for any connected client instead of counting every connected client.

    Changes:

  • Adds an internal connectivity getter with a default implementation and an early-exit pool override.

  • Updates Agent and Socks5ProxyAgent cleanup checks to use it.

  • Adds a regression test for early exit while leaving connection counts unchanged.
  • | File | Description |
    | ---- | ----------- |
    | test/​agent-connection-management.js | Verifies the pool check stops at the first connected client. |
    | lib/​dispatcher/​socks5-proxy-agent.js | Uses the new getter during pool cleanup. |
    | lib/​dispatcher/​pool-base.js | Adds the early-exit connectivity getter. |
    | lib/​dispatcher/​dispatcher-base.js | Provides a default getter based on the connection count. |
    | lib/​dispatcher/​agent.js | Uses the new getter during idle-dispatcher cleanup. |
    | lib/​core/​symbols.js | Defines the internal connectivity symbol. |
    </details>

    <sub>Review effort: Max</sub>

    codecov-commenter codecov-commenter commented on Dec 01, 2026 09:12 UTC
    Contributor

    Codecov Report


    :white_check_mark: All modified and coverable lines are covered by tests.
    :white_check_mark: Project coverage is 91.78%. Comparing base (2bcc4b8) to head (9395082).
    :warning: Report is 3 commits behind head on main.

    <details><summary>Additional details and impacted files</summary>

    @@            Coverage Diff             @@
    ##             main    #6287      +/-   ##
    ==========================================
    - Coverage   91.78%   91.78%   -0.01%     
    ==========================================
      Files         113      113              
      Lines       44920    44941      +21     
    ==========================================
    + Hits        41232    41251      +19     
    - Misses       3688     3690       +2     
    

    </details>

    :umbrella: View full report in Codecov by Harness.
    :loudspeaker: Have feedback on the report? Share it here.
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

  • </details>

    metcoder95 metcoder95 approved these changes on Dec 01, 2026 10:21 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    Nabeel-akk Nabeel-akk
    Labels
    risk: low confidence: 78.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 34.9% (LOW) · Higher = larger blast radius
    34.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 78.7% · Lower = rushed or shallow review
    78.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.4% · Safe to merge
    7.4%
    Repository