Repository navigation
fix: settle pending upload stream reads when a net.request ends - #53341
Conversation
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.
dsanders11
left a comment
There was a problem hiding this comment.
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.
|
Thanks, both are fixed in f38bc0d and your tests are in as written.
The same push fixes the ASan use-after-poison this PR's first run hit. Poison history pointed at cppgc poisoning a dead |
…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
left a comment
There was a problem hiding this comment.
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.
|
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. |
|
Release Notes Persisted
|
|
I was unable to backport this PR to "44-x-y" cleanly; |
|
I was unable to backport this PR to "43-x-y" cleanly; |
|
I have automatically backported this PR to "45-x-y", please check out #53368 |
|
@MarshallOfSound has manually backported this PR to "44-x-y", please check out #53373 |
|
@MarshallOfSound has manually backported this PR to "43-x-y", please check out #53374 |
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)
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)
Description of Change
net.requestnever told its chunked upload getter when the request ended. A protocol handler that had parked abody.read()on the upload stream then waited forever for aGetSizereply that could not come, and the stream'sSelfKeepAlivekept it rooted.SimpleURLLoaderWrapper::OnCompleteandCancelnow abort the getter, so the pending read rejects with the request's net error.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-timecallback; 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 withERR_FAILEDbeforerequest.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.api-net-speccases: a handler parks an upload-stream read and the request is aborted or failed (the read rejects withERR_FAILED), and a response completes while a write is still in flight (the write callback getsERR_ABORTED).mojo::ReceiverSetState::Entry::OnDisconnect. Withpoison_history_sizeon, ASan attributes the poison to cppgc'sUnmarkedObjectsPoisonerat the start of a sweep: aSimpleURLLoaderWrapperhad been found dead but not yet finalized when the network service's disconnect for one of its observer receivers arrived.UtilityProcessWrapperhas the sameReceiverSetshape. Both now get a cppgc pre-finalizer that drops the receivers before the sweep, asReplyChanneland 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.requestchunked upload stream inside a protocol handler never settling when the request failed or was aborted.