node icon indicating copy to clipboard operation
node copied to clipboard

http2: session.destroy() drops final GOAWAY when a write is in flight

Open emerzon opened this issue 1 month ago • 1 comments

Version

v27.0.0-pre (f88a1d25e9dc48a7f838280b236c4d74f76231a3)

For comparison, the same reproducer sends GOAWAY with the installed v22.23.2 binary.

Platform

Linux SAGAN-10 6.18.40.1-microsoft-standard-WSL2 #1 SMP PREEMPT_DYNAMIC Fri Jul 31 22:12:15 UTC 2026 x86_64 x86_64 x86_64 GNU/Linux

Subsystem

http2

What steps will reproduce the bug?

Run this standalone h2c reproducer. It queues a large response, pauses the raw client so the server has a socket write in progress, then sends another HEADERS frame whose handler calls session.destroy().

'use strict';

const http2 = require('node:http2');
const net = require('node:net');

const PREFACE = Buffer.from('PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n');
const NAMES = {
  0: 'DATA',
  1: 'HEADERS',
  4: 'SETTINGS',
  7: 'GOAWAY',
  8: 'WINDOW_UPDATE',
};

function frame(type, flags, streamId, payload = Buffer.alloc(0)) {
  const header = Buffer.alloc(9);
  header.writeUIntBE(payload.length, 0, 3);
  header[3] = type;
  header[4] = flags;
  header.writeUInt32BE(streamId & 0x7fffffff, 5);
  return Buffer.concat([header, payload]);
}

const body = Buffer.alloc(256 * 1024 * 1024, 'a');
const server = http2.createServer();
let firstWriteDone = false;

server.on('session', (session) => session.on('error', () => {}));
server.on('stream', (stream) => {
  stream.on('error', () => {});
  if (stream.id === 1) {
    stream.respond({ 'content-type': 'text/plain' });
    stream.end(body, () => {
      firstWriteDone = true;
      console.log('first response write completed');
    });
    console.log('first response queued');
    return;
  }

  console.log(`destroying; firstWriteDone=${firstWriteDone}`);
  stream.session.destroy();
});

server.listen(0, '127.0.0.1', () => {
  const socket = net.connect({
    host: '127.0.0.1',
    port: server.address().port,
    noDelay: true,
  });
  let input = Buffer.alloc(0);
  let sawGoaway = false;
  let totalBytes = 0;

  socket.on('connect', () => {
    socket.write(Buffer.concat([
      PREFACE,
      // SETTINGS_INITIAL_WINDOW_SIZE = 2^31 - 1
      frame(4, 0, 0, Buffer.from([0x00, 0x04, 0x7f, 0xff, 0xff, 0xff])),
      // Increase the connection window by almost 2 GiB.
      frame(8, 0, 0, Buffer.from([0x7f, 0xff, 0x00, 0x00])),
      frame(1, 0x05, 1, Buffer.from([0x82, 0x86, 0x84, 0x41, 0x01, 0x78])),
    ]));

    // Keep the client paused so the server's first write remains in progress.
    setTimeout(() => {
      socket.write(frame(
        1,
        0x05,
        3,
        Buffer.from([0x82, 0x86, 0x84, 0x41, 0x01, 0x78]),
      ));
    }, 1500);

    setTimeout(() => {
      socket.on('readable', readAll);
      readAll();
    }, 2500);
  });

  function readAll() {
    let chunk;
    while ((chunk = socket.read()) !== null) {
      totalBytes += chunk.length;
      input = Buffer.concat([input, chunk]);
      while (input.length >= 9) {
        const length = input.readUIntBE(0, 3);
        if (input.length < 9 + length) break;
        const type = input[3];
        if (type !== 0) console.log(`received ${NAMES[type] || type}`);
        if (type === 7) sawGoaway = true;
        input = input.subarray(9 + length);
      }
    }
  }

  socket.on('error', (error) => console.log(`socket error: ${error.code}`));
  socket.on('end', () => {
    clearTimeout(deadline);
    console.log(
      `RESULT sawGoaway=${sawGoaway} totalMB=${(totalBytes / 1048576).toFixed(1)}`,
    );
    server.close();
  });

  const deadline = setTimeout(() => {
    console.log(`TIMEOUT sawGoaway=${sawGoaway}`);
    socket.destroy();
    server.close();
  }, 8000);
});
$ node repro.js
first response queued
destroying; firstWriteDone=false
first response write completed
received SETTINGS
received WINDOW_UPDATE
received SETTINGS
received HEADERS
RESULT sawGoaway=false totalMB=256.1

How often does it reproduce? Is there a required condition?

It reproduced in every run on the current main checkout (including a fresh 6/6 run set and two later confirmation runs).

The required condition is that session.destroy() is called while an earlier socket write is still in progress. In this reproducer, destroy() is called from a stream handler while Node is processing incoming HTTP/2 data and the large response write is stalled by the paused client.

What is the expected behavior? Why is that the expected behavior?

The peer should receive the final GOAWAY before the socket closes. The http2session.destroy([error][, code]) documentation defines code as the HTTP/2 error code sent in the final GOAWAY frame.

The same reproducer on Node.js v22.23.2 produces:

first response queued
first response write completed
destroying; firstWriteDone=true
received SETTINGS
received SETTINGS
received HEADERS
received GOAWAY
RESULT sawGoaway=true totalMB=256.1

What do you see instead?

The current main checkout closes the TCP connection with a bare FIN after the body. No GOAWAY frame is delivered.

This makes an intentional session shutdown indistinguishable from an abrupt transport failure to peers and connection pools that use GOAWAY to decide which requests may need to be retried.

Additional information

The apparent ordering in src/node_http2.cc is:

  1. FinishClose() calls nghttp2_session_terminate_session() and SendPendingData(), but an earlier socket write is still active, so the GOAWAY remains pending in nghttp2.
  2. FinishClose() then marks the session destroyed.
  3. When the active write completes, OnStreamAfterWrite() sees is_destroyed() and returns after the done callback, before MaybeScheduleWrite() can serialize and send the pending GOAWAY.
  4. Calling SendPendingData() after destruction is not sufficient because it also returns immediately when is_destroyed() is set.

This suggests the final destroyed/done transition needs to wait until the queued terminal GOAWAY write finishes, or needs an explicit terminal-write state that permits that one final flush.

The issue is adjacent to the receive-callback close handling fixed by #65116, but it is a different symptom: that change prevents an assertion failure, while this report concerns loss of the final protocol frame when another write is already active.

emerzon avatar Oct 18 '26 14:10 emerzon

On macOS x64 with a local v28.0.0-pre build, this also reproduces with respondWithFile() and a single HTTPS download using curl --limit-rate 1M, without custom frames or held write callbacks.

With an 8 MiB file and shutdown initiated after 1 second, no GOAWAY was received with either session.destroy() or session.destroy(new Error(...)) in 3/3 runs each. In comparison, session.close() delivered GOAWAY and allowed the download to complete in 3/3 runs.

RFC 9113 §6.8 recommends sending GOAWAY before closing a connection, and the Node.js documentation describes destroy()’s code argument as the error code sent in the final GOAWAY. Preserving this notification when the transport is still writable seems worth fixing.

inoway46 avatar Nov 02 '26 16:11 inoway46