Repository navigation
fix(runtime): abort pending TLS connections on transport close - #5043
Conversation
hqhq1025
left a comment
There was a problem hiding this comment.
One P2 remains on this head. The new connector signal fixes the direct-Agent case, but the same transport still leaves a pending proxied TLS connector outside its shutdown authority. Local validation passed: build:test, Runtime 3,333 passed / 13 skipped, focused transport 11/11, Runtime typecheck, changed-file Biome, and diff checks. Hosted test and label are green, and the branch cleanly merges with current main (9cb5cc93c).
Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.
| const directDispatcher = new Agent(); | ||
| // The direct dispatcher does not own sockets until their connector calls | ||
| // back. Abort the connector too, including a still-pending TLS handshake. | ||
| const directConnections = new AbortController(); |
There was a problem hiding this comment.
[P2] Abort pending proxy connectors as well as direct ones
This controller is wired only into directDispatcher. When proxy settings select the proxyDispatcher at line 93, its connector receives no transport-scoped abort signal, so close() still depends on ProxyAgent.destroy() even while the CONNECT/TLS connector has not handed its socket to that dispatcher. I reproduced this with a local HTTP CONNECT proxy that returned 200 and then withheld the TLS response: transport.close() completed, but the tunnel socket was still open 750 ms later until the probe destroyed it. The same Host-exit delay therefore remains for supported proxy configurations. Please give the proxy connector equivalent close-time cancellation and extend the two new aborted/non-aborted handshake cases to the proxy path (and verify the custom SOCKS connector too).
|
Fixed in commit The cancellation signal now covers pending HTTP CONNECT, HTTPS proxy TLS, and SOCKS connections, including target TLS handshakes. I also wired cancellation into the proxy connection probe and bot fetch paths to prevent timeout or abort cleanup from leaving connections pending. |
hqhq1025
left a comment
There was a problem hiding this comment.
Technical result: GO. I found no P0-P3 issues on the current head.
The follow-up now propagates the transport-scoped connection abort through the direct connector, HTTP CONNECT proxy and target TLS connectors, HTTPS proxy TLS, and the SOCKS negotiation/target TLS path. The same cancellation authority is also used by the proxy probe and proxied bot fetch. The previous shutdown leak no longer reproduces in the real local-socket coverage, including both request-aborted and transport-close cases at each proxy stage.
Validation on 41678d8dced76ecdc352bf6639b7e27dbbf73505: build:test; Runtime 3,353 passed / 13 skipped; focused proxy transport 34/34; Runtime typecheck; full lint and format checks; ASF headers; changed-file Biome; and git diff --check. Hosted test is green, GitHub reports the PR mergeable, and the branch cleanly merges with current main (8d5c4612c46b19270f00fe7aea33c39dff23dbe5).
Residual scope: I did not exercise native Windows/macOS socket behavior or live external proxy services; the protocol stages were covered with real local HTTP, HTTPS, and SOCKS sockets on Linux.
Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.
me2seeks
left a comment
There was a problem hiding this comment.
Automated review (Command Code) — not an approval
The root cause is real and correctly identified: Client[kDestroy] cannot reach a socket whose TLS handshake has not settled, so a pending handshake survives until undici's connect timeout. Passing a signal into the connectors is the right fix, and the new tests target the right paths. One consequence of the chosen signal lifetime.
P2 (Should-Fix) — because the cancellation signal is transport-scoped, every connection the transport opens is retained for the transport's lifetime.
The transport creates one AbortController and uses its signal as the connector signal for every connection:
// packages/runtime/src/network/scoped-fetch-transport.ts:74-75
const connections = new AbortController();
const directDispatcher = new Agent({ connect: { signal: connections.signal } });// :88
proxyDispatcher ??= buildProxyDispatcher(proxySnapshot, connections.signal) as Dispatcher;connections is aborted only in close() (:106), so it lives as long as the transport. Node registers the signal handed to net.Socket/tls.connect as an 'abort' listener and does not remove it when the socket closes — { once: true } only fires on abort. Each connection therefore leaves one listener plus a hard reference to its closed socket on that controller.
Measured directly (25 sequential connections through a listener-counting probe on a shared signal, socket closed after each):
after 25 closed sockets -> live abort listeners on the transport signal: 25
The same mechanism applies to the proxy connectors, which now feed connections.signal into proxyTls/requestTls (packages/runtime/src/network/proxy-dispatcher.ts:32, 41).
Concrete path: buildHostAiSdkBackend creates one transport for the backend's lifetime and hands transport.fetch to the AI SDK (packages/runtime-host/src/server/execution-model-composition.ts:147-151), closing it only in dispose(). Since undici reaps idle connections, a long session that talks to a provider accumulates one retained TLS socket per connection — small per connection, unbounded in aggregate, with no functional symptom.
Smallest sound fix: scope the signal to the connection attempt, not the dispatcher — build a per-attempt child controller, link it to the transport controller until the connector calls back, then remove that listener, so the retained-per-connection listener disappears while close() still cancels in-flight handshakes.
P3 (Nice-to-have) — a redundant socket timer in the SOCKS path.
packages/runtime/src/network/proxy-dispatcher.ts:91 arms socket.setTimeout(30_000, onTimeout) covering both TCP setup and SOCKS negotiation, while the socks client already arms its own 30 s negotiation timeout and new Socket({ signal }) (:89) already handles cancellation. The added constant is a second, non-configurable deadline unrelated to the request's own timeout. Drop it, or keep only a TCP-connect bound and say why.
P3 (Nice-to-have) — the PR's test-count claim does not match the file. The suite has 9 cases on the base and 31 on the head, while the description reports 11 passing. Treat the reported green result as unverified; the added cases should be re-run before merge.
Review-relevant risks. No credential, logging, release or licensing effect was identified. Note one behavior change worth a maintainer's eye: sockets aborted at close() now surface AbortError/ABORT_ERR rather than a plain Error. Existing classification maps that to network, but I did not verify the effect on every provider-failure classifier.
Required conclusion.
- Optimal for the actual problem? Yes for the stated defect — the direct-transport change is minimal and correct, and the proxy paths have the same unreachable-socket problem. Not optimal as written, because the cancellation signal outlives each connection.
- Production code that can be deleted? The redundant 30 s socket timer above. The PR also correctly removes base dead code (the unused
buildConnectorin the direct path). - Low-quality tests to delete or replace? Two candidates, reason-based rather than executed:
immediate close rejects pending and subsequent requestsdials127.0.0.1:1, so the in-flight fetch rejects withECONNREFUSEDon the base too and exercises no cancellation; and thehttp-connectvariants of the stalled-stage cases cover a socket plaindestroy()already closes. The stalled-TLS and stalled-SOCKS cases are the ones doing real work — keep those. - Deeper refactor required? Not structural. Move the cancellation signal from dispatcher lifetime to connection-attempt lifetime (sketch in P2).
- Ready to merge? Functionally yes; needs either the per-attempt signal fix or an explicit decision that retaining one closed socket per connection for a backend-lifetime transport is acceptable.
- Residual risks / verification gaps: I did not run the suite, and the reported counts do not match the file. The fix depends on Node honoring
options.signaland on the vendored undici spreading unknown connector options intonet.connect/tls.connect; a future undici that filtersBuildOptionswould silently disable the abort.
Approval boundary. This is automated review; it is not an approval. Per CONTRIBUTING.md, the merge decision requires an independent human review. No approve was submitted.
|
Fixed in commit 096d342 : ) The fix removes abort listeners when connection attempts settle or sockets close, limits the SOCKS socket timeout to TCP setup, and updates the regression tests and PR description. |
me2seeks
left a comment
There was a problem hiding this comment.
Follow-up (Command Code) — verified resolved
I re-checked the head after your push.
The P2 is fixed, and better than I proposed. The new abortable-connector module owns only the pending socket and, as its own comment says, releases the abort listener on socket close — so the transport-scoped signal no longer retains one closed socket per connection. I measured that retention on the previous head (25 closed sockets left 25 live listeners); with this change the listener is removed at close, so the leak is gone. Keeping undici's timeout and TLS session cache while owning just the pending socket is the right boundary.
The P3 items (the redundant SOCKS socket timer, the test-count claim) are minor and I would not block on them.
Thanks for the careful fix. (Automated review; not an approval.)
hqhq1025
left a comment
There was a problem hiding this comment.
Technical result: GO. I found no P0-P3 issues on this exact head.
The new connector wrapper retains the transport cancellation authority only while a socket is establishing, removes its listener when the connector settles or the socket closes, and preserves cancellation across direct TLS, HTTP/HTTPS proxy tunnels, and SOCKS TCP/negotiation/target-TLS stages. The previous proxy-shutdown P2 remains fixed, and the closed-socket retention reported on the prior head no longer reproduces. The SOCKS fallback deadline now covers TCP setup only; negotiation remains owned by SocksClient.
Validation on 096d342381086ec4640c8551b0655a4681440fd6: build:test; Runtime 3,364 passed / 13 skipped; focused network transport 42/42; OpenAI Responses WebSocket 17/17; Runtime typecheck; full lint and format checks; ASF headers; changed-file Biome; git diff --check; hosted test; and a clean merge with current main (d2e6c1f273b7daa23ff75b84c8a30dca3f316713).
Residual scope: I did not exercise native Windows/macOS socket behavior or live external proxy services; the protocol stages were covered with real local sockets on Linux.
Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.
2bc027e to
1b01416
Compare
hqhq1025
left a comment
There was a problem hiding this comment.
Code review result: no P0-P3 findings on exact head 1b014163347d1513f228f36e8f9acb219bd2c18a.
The change gives each connection attempt explicit cancellation ownership. abortSocket removes its transport-signal listener when the connector settles or the socket closes (packages/runtime/src/network/abortable-connector.ts:24-66). The transport aborts pending connections before destroying its direct and proxy dispatchers (packages/runtime/src/network/scoped-fetch-transport.ts:73-115). HTTP CONNECT, HTTPS proxy TLS, SOCKS TCP/negotiation, and target TLS are covered through the proxy connector and upgraded-tunnel hooks (packages/runtime/src/network/proxy-dispatcher.ts:37-142); proxy probes and bot fetches propagate the same signal (packages/runtime/src/network/proxy-test.ts:44-105, packages/runtime/src/bots/proxied-fetch.ts:44-110). No persistence schema or migration is changed.
Validation on this head: clean install; build:test; Runtime 3,543 passed / 13 skipped / 0 failed; focused transport 42/42; OpenAI Responses WebSocket 17/17; Runtime typecheck; full lint and format checks; ASF headers; and git diff --check. The six changed file blobs are identical to the previously reviewed 096d342381086ec4640c8551b0655a4681440fd6 head. The branch merges cleanly with current main c7d205a42dc32073edbb74f0954489e9388568c1 (merge tree 33d95b7bf2ce1b0e3883ca1a54e4f6575d24bced).
The PR is not merge-ready while the hosted test check is red. Its reported WorkHub candidate_set_stale failure did not reproduce: that exact test passed 5/5 on this head, 3/3 on the exact base, and also passed inside the local Runtime Host full run. The local Runtime Host run instead had one environment-specific sandbox-boundary failure which reproduces on the base and corresponds to this runner rejecting user-namespace setup; it is outside the six-file network diff. A green hosted rerun is still required.
Residual scope: native Windows/macOS socket behavior and live external proxy services were not exercised; protocol stages used real local sockets on Linux.
Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.
Generated-by: OpenAI Codex
Cover HTTP CONNECT, HTTPS proxy and SOCKS negotiation, and propagate cancellation through proxy probes and bot requests. Generated-by: OpenAI Codex
Dispose cancellation listeners after connection setup or socket close, preserve proxy tunnel cancellation, and limit the SOCKS socket deadline to TCP setup. Add retention and error-classification regressions. Generated-by: OpenAI Codex
1b01416 to
5ed9f02
Compare
hqhq1025
left a comment
There was a problem hiding this comment.
Re-review result
Exact head: 5ed9f02da4d65e830610f96482946b19e44c83b3
I found no P0-P3 issue on this head. The previously reported proxy shutdown and closed-socket listener-retention issues remain fixed.
Each connection attempt keeps transport cancellation authority only while its socket is establishing, and removes the listener when the connector settles or the socket closes (packages/runtime/src/network/abortable-connector.ts:24-66). Transport shutdown aborts pending connectors before destroying the direct and proxy dispatchers (packages/runtime/src/network/scoped-fetch-transport.ts:66-119). The same boundary covers HTTP CONNECT, HTTPS proxy TLS, SOCKS TCP/negotiation/target TLS, proxy probes, and bot fetches (packages/runtime/src/network/proxy-dispatcher.ts:32-142, packages/runtime/src/network/proxy-test.ts:35-106, packages/runtime/src/bots/proxied-fetch.ts:36-111). No persistence schema or migration is changed.
The three patches are range-diff equivalent to the previously reviewed series at 1b014163347d1513f228f36e8f9acb219bd2c18a; all six changed-file blobs are byte-identical. Current-head validation nevertheless completed against the rebased tree:
- Clean install and
build:testpassed. - Full Runtime: 3549 passed, 13 skipped, 0 failed.
- Focused network transport and OpenAI Responses WebSocket: 59/59 passed.
- Full typecheck, lint, format, ASF-header, and
git diff --checkpassed. - The latest hosted
testrun is successful; an earlier superseded run was cancelled. - The branch is 3 commits ahead / 0 behind current
main99cfeb7e94728dfece75e7a47677c82c7506bb39, and the merge tree is clean.
Remaining coverage gaps: I did not exercise native Windows/macOS socket behavior or live external proxy services; the protocol stages were exercised with real local sockets on Linux.
Automated review notice: This comment was posted by an automated review agent operated by hqhq1025. It is not an independent human review and does not replace one.
Astro-Han
left a comment
There was a problem hiding this comment.
Reviewed at this head by three independent AI reviewers (different model families). No P0–P2 findings; one note inline and a few minor observations below.
The root cause is right: dispatcher.destroy() rejects queued requests but cannot reach a socket still inside the connector (TLS handshake, CONNECT, SOCKS negotiation), so Host shutdown could wait for the connect timeout (#5009). One reviewer reproduced this against a server that never answers the TLS handshake: with the old code the socket was still open 2 s after close; at this head it closes immediately, and callers still see kind: network. The same cancellation now covers direct TLS, HTTP CONNECT (including TLS through the tunnel), HTTPS proxies, SOCKS TCP / negotiation / TLS, proxy probes and bot fetches. Abort listeners are removed when the connector settles or the socket closes, each transport has its own controller so closing one does not affect another, and double destroy is harmless. The stalled-server tests use real loopback sockets and fail on the base commit.
Minor observations (not blocking):
- On close, a stream already running through a CONNECT or SOCKS proxy now fails with
UND_ERR_SOCKET"closed" instead of "transport closed"; nothing in the repo depends on the message. - Listener-release-on-success tests only use plain-HTTP targets; HTTPS through a CONNECT tunnel or SOCKS is not covered by a regression test.
- SOCKS time limits change to 30 s TCP + 30 s negotiation + 10 s TLS, where the old TLS handshake had no limit.
Not verified: end-to-end requests through real external proxies, and packaged Host on Windows/macOS.
Automated review notice: This review was posted by an automated review agent operated by Astro-Han. It combines independent reviews from several AI models. It is not an independent human review and does not replace one.
| let dispose = () => {}; | ||
| // Undici returns the socket immediately, although its TS signature is void. | ||
| // Regression coverage exercises this boundary with real TCP/TLS sockets. | ||
| const socket = connect(options, (...args) => { |
There was a problem hiding this comment.
Note (not graded): cancellation relies on Undici's connector returning the socket synchronously, which its TypeScript signature does not promise, and silently skips cancellation when the return is not a Socket (e.g. an async connector). The comment and the real-socket tests cover today's Undici version well; it may be worth a test that fails loudly if the return shape changes, so an Undici upgrade cannot quietly disable this fix.
Astro-Han
left a comment
There was a problem hiding this comment.
Approved at @Astro-Han's explicit request: independent automated reviews of this head from multiple model families found no blocking (P0–P2) issues, and CI is green. Remaining P3 notes are non-blocking.
Summary
Abort pending direct and proxied connections when a connection-effect transport closes, preventing sockets from surviving teardown and delaying Host exit. Fixes #5009.
Undici dispatchers cannot destroy sockets that their connectors have not handed over yet. The transport now cancels pending direct TLS, HTTP CONNECT target TLS, HTTPS proxy TLS (including HTTP forwarding), and SOCKS setup/target TLS before destroying its dispatchers. Proxy probes and bot fetches use the same cancellation path.
Follow-up: explicitly release cancellation listeners when connection attempts settle or sockets close, avoiding retention of every closed socket by a backend-lifetime signal. Keep Undici's TLS cache, connection timeout and existing ALPN defaults. The SOCKS socket timeout now bounds TCP setup only; SocksClient owns the negotiation deadline.
Verification
A stalled-server control isolates this path from the rest of shutdown. Pointing the Host's models.dev refresh at a local server that accepts and never completes the handshake makes the four lifecycle tests #5009 names deterministic:
0cb4fc32b, this branch's merge base1b0141633, this branchOne machine, one worktree, one stalled server; the sides differ only by this PR. The failures split nine
Error: process <pid> did not exitand threesettle(5_000)assertions, which are the two signatures #5009 reports —settlewaits for the same five-second process exit, so both surfaces are one stall. On an unmodified network those tests fail about once in 36 executions here, which is why a stalled server rather than repetition is what makes the link legible.Real loopback TCP/TLS and proxy fixtures cover pending stages, prior request cancellation, listener cleanup, normal SOCKS responses/authentication/remote DNS, and network error classification.
Local validation uses macOS arm64, Node 24.19.0 and npm 11.19.0. Linux sandbox validation is left to CI because Docker/Podman is unavailable locally. External proxy services, native Windows behavior and full Desktop E2E were not exercised. The connector wrapper relies on current Undici 8.10.1 returning a Socket at runtime; real-socket regressions protect that dependency boundary.
AI use
Tool(s) and scope: OpenAI Codex assisted with diagnosis, code changes, regression tests, local validation, and this PR description. Codex submitted this PR on the user's behalf; the human contributor is responsible for reviewing and deciding to submit the contribution and remains accountable for its contents. Automated checks do not replace independent human review.
Checklist
Does this PR entail a change in behavior?