Skip to content

fix: settle pending upload stream reads when a net.request ends - #53341

Merged
MarshallOfSound merged 4 commits into
mainfrom
fix/chunked-upload-stream-hang
Sep 1, 2026
Merged

MarshallOfSound merged 4 commits into
mainfrom
fix/chunked-upload-stream-hang

Conversation

@MarshallOfSound

@MarshallOfSound MarshallOfSound commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Description of Change

  • net.request never told its chunked upload getter when the request ended. A protocol handler that had parked a body.read() on the upload stream then waited forever for a GetSize reply that could not come, and the stream's SelfKeepAlive kept it rooted. SimpleURLLoaderWrapper::OnComplete and Cancel now abort the getter, so the pending read rejects with the request's net error.
  • This is the cause of the cpp heap url loader module keeps a ChunkedDataPipeReadableStream alive … hang seen on the ASan and UBSan shard-3 jobs (three unrelated PRs on 2026-08-31, e.g. this run). That test's handler never responds and drops the one-time callback; the native side only references it weakly (gin_helper/callback.cc), so the test's own GC loop could collect it, which fails the request with ERR_FAILED before request.end() runs. Whether the GC caught it in time is timing-dependent, hence the flake. The handler now holds the callback for the test's duration.
  • New api-net-spec cases: a handler parks an upload-stream read and the request is aborted or failed (the read rejects with ERR_FAILED), and a response completes while a write is still in flight (the write callback gets ERR_ABORTED).
  • The first CI run of this PR hit an ASan use-after-poison in mojo::ReceiverSetState::Entry::OnDisconnect. With poison_history_size on, ASan attributes the poison to cppgc's UnmarkedObjectsPoisoner at the start of a sweep: a SimpleURLLoaderWrapper had been found dead but not yet finalized when the network service's disconnect for one of its observer receivers arrived. UtilityProcessWrapper has the same ReceiverSet shape. Both now get a cppgc pre-finalizer that drops the receivers before the sweep, as ReplyChannel and the IPC renderer classes already do. Locally the 28-file ASan shard reproduced the crash on the first version and runs clean with this one.

Verified locally on an ASan build: the original cpp-heap spec failed 3/3 before and passes after, a standalone repro with the callback still collectable completes instead of hanging, and the new net specs pass.

Checklist

Release Notes

Notes: Fixed a pending read on a net.request chunked upload stream inside a protocol handler never settling when the request failed or was aborted.

When a protocol handler reads the chunked upload body of a net.request
through the stream it is handed, and the request then fails or is aborted,
the handler's pending read was never settled: nothing told the
JSChunkedDataPipeGetter that the request was over, so the GetSize reply the
stream waits on never arrived and its SelfKeepAlive rooted it forever.

Abort the getter from SimpleURLLoaderWrapper::OnComplete and Cancel so the
stream's pending read rejects with the request's net error.

This is also what made the cpp-heap ChunkedDataPipeReadableStream spec hang
under ASan/UBSan: its handler drops the one-time protocol callback, which
is only weakly referenced from C++, so the test's own GC loop could collect
it and fail the request with ERR_FAILED before request.end() ran. The test
now holds the callback for its duration, and a new net spec covers the
abort path directly.
@MarshallOfSound MarshallOfSound added semver/patch backwards-compatible bug fixes target/43-x-y PR should also be added to the "43-x-y" branch. target/44-x-y PR should also be added to the "44-x-y" branch. target/45-x-y PR should also be added to the "45-x-y" branch. labels Aug 31, 2026
@electron-cation electron-cation Bot added the new-pr 🌱 PR opened recently label Aug 31, 2026
@MarshallOfSound
MarshallOfSound enabled auto-merge (squash) August 31, 2026 18:31

@dsanders11 dsanders11 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GPT-5.6 Sol identified two other edge cases not addressed here and provided test cases. One involves another edge case that can leave a hanging promise, and the other is the changes in this PR can clobber the proper request error with the abort error.

      it('should preserve the request error when settling a pending upload stream read', async () => {
        let failRequest: (() => void) | undefined;
        let pendingRead: Promise<number> | undefined;
        const reached = new Promise<void>((resolve, reject) => {
          protocol.interceptStreamProtocol('http', (request, callback) => {
            failRequest = () => callback({ error: -2 } as any);
            (async () => {
              const streamElement = (request.uploadData || []).find((e: any) => e.type === 'stream');
              if (!streamElement) {
                callback({ statusCode: 400, data: null as any });
                reject(new Error('request had no stream upload element'));
                return;
              }
              const body: any = (streamElement as any).body;
              await body.read(new Uint8Array(1024));
              pendingRead = body.read(new Uint8Array(1024));
              resolve();
            })().catch(reject);
          });
        });
        defer(() => protocol.uninterceptProtocol('http'));

        const urlRequest = net.request({ method: 'POST', url: 'http://failed-pending-upload-read' });
        urlRequest.on('error', () => {});
        urlRequest.chunkedEncoding = true;
        urlRequest.write('hello');
        await reached;

        const readError = expect(pendingRead).to.eventually.be.rejectedWith('ERR_FAILED');
        failRequest!();
        await readError;
      });

      it('should settle an in-flight upload write when the response completes early', async () => {
        let completeRequest: (() => void) | undefined;
        const reached = new Promise<void>((resolve, reject) => {
          protocol.interceptStreamProtocol('http', (request, callback) => {
            completeRequest = () => callback({ statusCode: 200, data: null as any });
            const streamElement = (request.uploadData || []).find((e: any) => e.type === 'stream');
            if (!streamElement) {
              callback({ statusCode: 400, data: null as any });
              reject(new Error('request had no stream upload element'));
              return;
            }
            const body: any = (streamElement as any).body;
            body.read(new Uint8Array(1)).then(() => resolve(), reject);
          });
        });
        defer(() => protocol.uninterceptProtocol('http'));

        const urlRequest = net.request({ method: 'POST', url: 'http://early-upload-response' });
        urlRequest.on('error', () => {});
        urlRequest.chunkedEncoding = true;
        const responseReceived = once(urlRequest, 'response');
        let writeCallbackCalled = false;
        const writeCompleted = new Promise<Error | undefined>((resolve) => {
          urlRequest.write(Buffer.alloc(4 * kOneMegaByte), 'buffer', (error?: Error | null) => {
            writeCallbackCalled = true;
            resolve(error || undefined);
          });
        });
        await reached;
        expect(writeCallbackCalled).to.equal(false);

        completeRequest!();
        const [response] = await responseReceived;
        await collectStreamBody(response);
        const writeError = await writeCompleted;
        expect(writeError).to.be.an.instanceOf(Error);
        expect(writeError!.message).to.contain('ERR_ABORTED');
      });

ASan on CI caught a use-after-poison in mojo::ReceiverSetState::Entry::
OnDisconnect. The poison history shows cppgc's UnmarkedObjectsPoisoner
poisoning a SimpleURLLoaderWrapper at the start of a sweep, i.e. after the
GC found it dead but before its destructor ran; the network service's
disconnect for one of the wrapper's URLLoaderNetworkServiceObserver
receivers then landed on the dead object. UtilityProcessWrapper owns the
same kind of ReceiverSet for a utility process's requests.

Give both a cppgc pre-finalizer that drops the receivers before the sweep,
the pattern ReplyChannel and the IPC renderer objects already use.

Also from review:
- Abort() only resets the chunked getter instead of answering GetSize with
  an error, which the network service DCHECKs against; consumers already
  treat the disconnect as the body ending with ERR_FAILED, so a handler's
  pending read reports the request failure rather than the abort.
- A write still in flight when the request ends is rejected with
  ERR_ABORTED instead of never settling, and the request's internal body
  stream no longer re-raises that as an unhandled error.
@MarshallOfSound

Copy link
Copy Markdown
Member Author

Thanks, both are fixed in f38bc0d and your tests are in as written.

  • Error preservation: the getter no longer answers GetSize with an error on abort, it just drops the receiver. The stream then reports the request's failure (ERR_FAILED) instead of being clobbered by the abort. The network service also DCHECKs against a late GetSize reply, so this was worth changing on its own.
  • In-flight write: the pending write promise now lives on the getter and is rejected with ERR_ABORTED before teardown. The request's internal body stream needed an error listener, otherwise the same error surfaced as an unhandled 'error' on it.

The same push fixes the ASan use-after-poison this PR's first run hit. Poison history pointed at cppgc poisoning a dead SimpleURLLoaderWrapper before finalization while an observer receiver's disconnect was still in flight, so both that class and UtilityProcessWrapper get a pre-finalizer that drops their receivers, same pattern as ReplyChannel.

…lloaderwrapper (#53358)

* refactor: move utility process network observer off cppgc heap

Store URLLoaderNetworkObserver in a separate allocation so its mojo receivers
remain accessible while UtilityProcessWrapper is awaiting cppgc sweeping.
This avoids requiring a prefinalizer to disconnect the receivers.

* refactor: move URL loader callbacks off cppgc heap

Route stream and network observer callbacks through a separately allocated
client holding a weak reference to SimpleURLLoaderWrapper. This keeps mojo
dispatch state valid during cppgc sweeping without requiring a prefinalizer.

@dsanders11 dsanders11 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test case for another edge case that leaves a dangling promise in the current state of this PR:

      it('should settle an in-flight upload write when the request is aborted', async () => {
        const reached = new Promise<void>((resolve, reject) => {
          protocol.interceptStreamProtocol('http', (request, callback) => {
            const streamElement = (request.uploadData || []).find((element: any) => element.type === 'stream');
            if (!streamElement) {
              callback({ statusCode: 400, data: null as any });
              reject(new Error('request had no stream upload element'));
              return;
            }
            const body: any = (streamElement as any).body;
            body.read(new Uint8Array(1)).then(() => resolve(), reject);
          });
        });
        defer(() => protocol.uninterceptProtocol('http'));

        const urlRequest = net.request({ method: 'POST', url: 'http://aborted-upload-write' });
        urlRequest.on('error', () => {
          expect.fail('Unexpected error event');
        });
        urlRequest.chunkedEncoding = true;
        let writeCallbackCalled = false;
        const writeCompleted = new Promise<Error | undefined>((resolve) => {
          urlRequest.write(Buffer.alloc(4 * kOneMegaByte), 'buffer', (error?: Error | null) => {
            writeCallbackCalled = true;
            resolve(error || undefined);
          });
        });
        await reached;
        expect(writeCallbackCalled).to.equal(false);

        const aborted = once(urlRequest, 'abort');
        urlRequest.abort();
        await aborted;
        expect(await writeCompleted).to.equal(undefined);
      });

… is aborted

ChunkedBodyStream dropped the pending first-chunk write callback on abort,
so the caller's write callback never fired. Let it settle with the abort
error instead, which is what Node.js does (ECANCELED); no 'error' event
follows because the request is already destroyed by the time it lands.
@MarshallOfSound

Copy link
Copy Markdown
Member Author

I have fixed that issue (not in the way your test indicated as that is wrong when compared to node's equivalent handling), any future findings please file and fix separately, this isn't going to be a catch all fix urlloader PR. All issues you've outlined so far have been pre-existing and unrelated to what was once a trivial flake fix.

@MarshallOfSound
MarshallOfSound merged commit 9a6dbb5 into main Sep 1, 2026
78 checks passed
@MarshallOfSound
MarshallOfSound deleted the fix/chunked-upload-stream-hang branch September 1, 2026 15:31
@release-clerk

release-clerk Bot commented Sep 1, 2026

Copy link
Copy Markdown

Release Notes Persisted

Fixed a pending read on a net.request chunked upload stream inside a protocol handler never settling when the request failed or was aborted.

@github-actions github-actions Bot added the 46-x-y label Sep 1, 2026
@trop

trop Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

I was unable to backport this PR to "44-x-y" cleanly;
you will need to perform this backport manually.

@trop

trop Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

I was unable to backport this PR to "43-x-y" cleanly;
you will need to perform this backport manually.

@trop trop Bot added needs-manual-bp/44-x-y needs-manual-bp/43-x-y and removed target/44-x-y PR should also be added to the "44-x-y" branch. target/43-x-y PR should also be added to the "43-x-y" branch. labels Sep 1, 2026
@trop

trop Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

I have automatically backported this PR to "45-x-y", please check out #53368

@trop trop Bot added in-flight/45-x-y and removed target/45-x-y PR should also be added to the "45-x-y" branch. labels Sep 1, 2026
@trop

trop Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

@MarshallOfSound has manually backported this PR to "44-x-y", please check out #53373

@trop

trop Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

@MarshallOfSound has manually backported this PR to "43-x-y", please check out #53374

MarshallOfSound added a commit that referenced this pull request Sep 1, 2026
fix: settle pending upload stream reads when a net.request ends (#53341)

When a protocol handler reads the chunked upload body of a net.request
through the stream it is handed, and the request then fails or is aborted,
the handler's pending read was never settled: nothing told the
JSChunkedDataPipeGetter that the request was over, so the GetSize reply the
stream waits on never arrived and its SelfKeepAlive rooted it forever.

Abort the getter from SimpleURLLoaderWrapper::OnComplete and Cancel so the
stream's pending read rejects with the request's net error.

This is also what made the cpp-heap ChunkedDataPipeReadableStream spec hang
under ASan/UBSan: its handler drops the one-time protocol callback, which
is only weakly referenced from C++, so the test's own GC loop could collect
it and fail the request with ERR_FAILED before request.end() ran. The test
now holds the callback for its duration, and a new net spec covers the
abort path directly.

(cherry picked from commit 9a6dbb5)
@trop trop Bot added merged/44-x-y PR was merged to the "44-x-y" branch. and removed in-flight/44-x-y labels Sep 1, 2026
jkleinsc pushed a commit that referenced this pull request Sep 1, 2026
fix: settle pending upload stream reads when a net.request ends (#53341)

When a protocol handler reads the chunked upload body of a net.request
through the stream it is handed, and the request then fails or is aborted,
the handler's pending read was never settled: nothing told the
JSChunkedDataPipeGetter that the request was over, so the GetSize reply the
stream waits on never arrived and its SelfKeepAlive rooted it forever.

Abort the getter from SimpleURLLoaderWrapper::OnComplete and Cancel so the
stream's pending read rejects with the request's net error.

This is also what made the cpp-heap ChunkedDataPipeReadableStream spec hang
under ASan/UBSan: its handler drops the one-time protocol callback, which
is only weakly referenced from C++, so the test's own GC loop could collect
it and fail the request with ERR_FAILED before request.end() ran. The test
now holds the callback for its duration, and a new net spec covers the
abort path directly.

(cherry picked from commit 9a6dbb5)
@trop trop Bot added merged/43-x-y PR was merged to the "43-x-y" branch. merged/45-x-y PR was merged to the "45-x-y" branch. and removed in-flight/43-x-y in-flight/45-x-y labels Sep 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

46-x-y merged/43-x-y PR was merged to the "43-x-y" branch. merged/44-x-y PR was merged to the "44-x-y" branch. merged/45-x-y PR was merged to the "45-x-y" branch. new-pr 🌱 PR opened recently semver/patch backwards-compatible bug fixes

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

5 participants