Skip to content

http: don't destroy connections still writing a response - #67915

Open
glasser wants to merge 4 commits into
nodejs:mainfrom
glasser:http-close-idle-writable-finished
Open

glasser wants to merge 4 commits into
nodejs:mainfrom
glasser:http-close-idle-writable-finished

Conversation

@glasser

@glasser glasser commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

closeIdleConnections() skips a connection only while its response is not finished, but finished is set as soon as end() is called, before the queued data has been written to the socket. A response to a slow client can therefore be destroyed mid-write by closeIdleConnections(), or by server.close() which calls it, truncating the body while the end() callback and 'finish' still fire on the server.

This checks writableFinished instead, which is only true once everything has been handed to the socket (finished && outputSize === 0 && socket.writableLength === 0). A connection that passes the new check has written everything, so destroying it loses nothing. closeAllConnections() is unchanged.

The new test ends a 32 MiB response and calls server.close() while the body is still queued; it fails on current main with Error: aborted on the client and passes with the change. The existing test-http-server-close-idle* tests still pass.

(Note that a connection skipped by the sweep reverts to a normal keep-alive connection after its response; nothing automatically cleans up non-idle connections later. #66000 fixes that issue and this PR is compatible with that one (they merge cleanly with tests passing).)

Fixes: #67910
Refs: #43890

AI disclosure

As described in the issue, the bug was found and the initial draft of the fix and test were written with help from a coding agent. I reviewed and verified the change (including rewriting comments).

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

Review requested:

  • @nodejs/http
  • @nodejs/net

@nodejs-github-bot nodejs-github-bot added http Issues and PRs related to the http subsystem. needs-ci PRs that need a full CI run. labels Nov 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Caution

AgentScan found account activity patterns that may be consistent with automation. This is a heuristic, not proof that this pull request was opened by an agent or violates policy. AI-assisted contributions are permitted, but automated tooling must not open pull requests without advance approval, and contributors must personally understand, test, verify, and take responsibility for every submitted change. See the AgentScan analysis, AI use policy, and automation policy for additional context.

@glasser

glasser commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

AgentScan is correct that (as acknowledged) this change was originally written by an AI agent, but I understand and stand by the submitted version of the change. (Its main signal for concluding agent activity is that I pushed a stack of AI-generated PRs to an open source repo I maintained quickly before going on Thanksgiving vacation; turning those PRs into real PRs worthy of release is my main job this week :) )

Note that the test added in the PR works a bit differently from the test in the issue. The issue is a bit more "realistic" — it just shows an HTTP client that pauses and has delays, as can happen via network delays. The PR's test is deterministic without timeouts by calling server.close() directly within the request handler (which doesn't reflect realistic usage).

closeIdleConnections() skips a connection only while its response is
not `finished`, but `finished` is set as soon as end() is called, before
the queued data has been written to the socket. A response to a slow
client can therefore be destroyed mid-write by closeIdleConnections(),
or by server.close() which calls it, truncating the body while the end()
callback and 'finish' still fire. Check `writableFinished` instead,
which is only true once everything has been handed to the socket.

Fixes: nodejs#67910
Refs: nodejs#43890
Signed-off-by: David Glasser <glasser@apollographql.com>
@codecov

codecov Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.59%. Comparing base (f3af49d) to head (0cb68ce).
⚠️ Report is 70 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #67915      +/-   ##
==========================================
+ Coverage   90.58%   90.59%   +0.01%     
==========================================
  Files         802      802              
  Lines      286655   287053     +398     
  Branches    55373    55439      +66     
==========================================
+ Hits       259666   260061     +395     
+ Misses      17092    17084       -8     
- Partials     9897     9908      +11     
Files with missing lines Coverage Δ
lib/internal/http/server.js 96.77% <100.00%> (+0.31%) ⬆️

... and 61 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

Thanks for the fix! Two non-blocking suggestions for the test:

Without #66000, it takes ~5s to pass for me: the connection goes back to keep-alive after the response, so server.close() waits for the client agent's idle timeout. Passing agent: false to get() makes it finish right away (~60ms), and it still fails without the fix. This should stop mattering once #66000 lands, but it keeps the test fast either way.

Also, res.writableFinished is false right after end() even for a 2-byte body, so that assert doesn't really show data is still queued. Maybe add assert.ok(res.socket.writableLength > 0)?

Use a non-keep-alive client so server.close() does not wait for the
client's idle connection to time out, and assert that part of the body
is still queued in Node (socket.writableLength > 0) rather than only that
the response is not writableFinished, which is true right after end()
even for a tiny body.

Signed-off-by: David Glasser <glasser@apollographql.com>
@glasser

glasser commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@inoway46 Thanks! I pushed a commit that improves the test as you suggested.
(This commit was coding-agent-authored and I found the text it generated to be reasonable.)

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

Thanks for applying it! LGTM

@pimterry pimterry added the request-ci Add this label to start a Jenkins CI on a PR. Only starts once the PR has an approving review. label Dec 3, 2026
@github-actions github-actions Bot removed the request-ci Add this label to start a Jenkins CI on a PR. Only starts once the PR has an approving review. label Dec 3, 2026
@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@glasser

glasser commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@pimterry Should I be concerned about the failures from Jenkins? When I click on the status checks and the bot-provided link and log in I can't read anything (glasser is missing the Overall/Read permission).

@pimterry

pimterry commented Dec 3, 2026

Copy link
Copy Markdown
Member

@glasser The new test is failing on some but not all Windows builds, I guess it's flaky on Windows? Fails like this:

duration_ms: 514.002
exitcode: 1
severity: fail
stack: |-
  node:internal/assert/utils:146
    throw error;
    ^

  AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:

    assert.ok(res.socket.writableLength > 0)

      at IncomingMessage.<anonymous> (C:\workspace\node-test-binary-windows-js-suites\node\test\parallel\test-http-server-close-idle-pending-response.js:27:12)
      at IncomingMessage.<anonymous> (C:\workspace\node-test-binary-windows-js-suites\node\test\common\index.js:512:15)
      at IncomingMessage.emit (node:events:514:20)
      at endReadableNT (node:internal/streams/readable:2166:12)
      at process.processTicksAndRejections (node:internal/process/task_queues:90:21) {
    generatedMessage: true,
    code: 'ERR_ASSERTION',
    actual: false,
    expected: true,
    operator: '==',
    diff: 'simple'
  }

  Node.js v28.0.0-pre
...

We'll need to fix that before this can land.

@glasser

glasser commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@pimterry That line was suggested by @inoway46 and I'll admit I didn't evaluate it in as much depth as I could have. I'm going to remove it again and we can see if that makes Windows better — maybe @inoway46 has more insight into whether this shows a problem with my patch (on Windows, say) or whether that assertion was just a bit too much?

Looks like it doesn't pass on Windows.
@glasser

glasser commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

It looks like this is the same behavior described at

// However, in Windows, the mechanism of acceptance is loose, the following code is a workaround

ie, more work has to be done on Windows to ensure that we actually have some buffered-in-JS data. (The issue seems just to be that on Windows the bug condition isn't always quite triggered. It doesn't seem like the issue is "the fix doesn't work".)

Ideas include:

  • Just leave off the assertion
  • Only run the assertion on not-Windows
  • Copy the code from the other test so that this test consistently buffers even on Windows
  • Move the code from the other test to a shared helper instead of copy-and-pasting

Thoughts?

@inoway46

inoway46 commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Sorry I missed this when I suggested the assertion. I checked whether the 32 MiB response actually leaves data queued after res.end() on Windows. On both an unfixed nightly and a build of this PR, socket.writableLength was zero in all 1,000 runs, and the client always received the full body.

Could we flush the headers first and defer socket.uncork() until after server.close()? That kept a 2-byte body queued in every run. The client hit ECONNRESET in all 1,000 runs on the unfixed nightly and received the full body in all 1,000 runs with the fix. 2-byte test · Unfixed nightly run · PR build run

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@nodejs-github-bot

Copy link
Copy Markdown
Collaborator

@inoway46

inoway46 commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

I don’t have Jenkins access to see who triggered CI, but the current test also passes on Windows without the fix. @glasser, could we update it before running full CI again?

If you’d prefer to land the fix first, I’m happy to send a follow-up PR for the test.

Instead of writing a large body and hoping it gets buffered, simulate
buffering by using `cork`, and temporarily stop `uncork` calls from
having effect. This should make the test work on Windows.

Signed-off-by: David Glasser <glasser@apollographql.com>
@glasser

glasser commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

OK, I think I pushed a cork version that hopefully will work everywhere!

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

The updated test LGTM, thanks! @pimterry, could you take another look when you get a chance?

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

Labels

agentscan:mixed-signals http Issues and PRs related to the http subsystem. needs-ci PRs that need a full CI run.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

http: server.close() destroys connections that are still writing a response, truncating them

4 participants