Repository navigation
[Foundation] Avoid racing native NSUrlSessionTask cleanup in NSUrlSessionHandler. Fixes #20345. - #26668
Conversation
…sionHandler. Fixes #20345. `NSUrlSessionHandler` had several independent code paths that could clean up the same `NSUrlSessionTask` at the same time: `RemoveInflightData` (called from the cancellation registration, from `DidCompleteWithError` and when the response stream finished), the delegate callbacks going through `GetInflightData`, the disposal callback of `NSUrlSessionDataTaskStreamContent`, and `Dispose` of the handler itself. Each of those paths cancelled the task, and `RemoveInflightData` additionally disposed the managed `NSUrlSessionTask` wrapper. Disposing the wrapper releases the underlying native object, so as soon as two paths ran concurrently - or a delegate callback arrived after cleanup had already happened - we could end up messaging an already released native task. That is exactly what the crash reports in the issue show: an `objc_release_x8` inside `__NSCFURLSessionConnection` dealloc, and a separate crash where `NSUrlSessionTask.Cancel` was invoked on a garbage pointer. The fix is to establish a single owner for the cleanup of each task: * `RemoveInflightData` now decides ownership by the result of removing the task from the inflight dictionary. Only the caller that actually removed the entry cancels the `CancellationTokenSource` and the native task; everybody else returns immediately. * `GetInflightData` no longer cancels the task when the inflight data is missing or already cancelled. Missing or cancelled inflight data means another path already owns the task, so the callback just returns null and bails out of the delegate method as before. * The disposal callback of the response content no longer cancels the data task. The cancellation is already handled by the code path that removes the inflight data. * We no longer dispose the managed `NSUrlSessionTask` wrappers (neither in `RemoveInflightData` nor in `Dispose`). `NSURLSession` may still invoke delegate callbacks for a task after we're done with it, and managed callbacks may still hold on to the wrapper, so releasing the native task at that point is not safe. The wrappers are collected by the GC once nothing references them anymore. Verified with the NativeAOT iOS stress repro from the issue: the unpatched implementation crashed twice within ~20 seconds (both of the signatures mentioned above), while the patched version ran the same workload for 3m41s without crashing. The focused `NSUrlSessionHandler` tests pass as well. Fixes #20345. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8ede0128-a776-42ec-bfb4-9c076d67a378
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
The regression test does not exercise handler disposal while an active request and late delegate callbacks are still in progress.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 1
Open (1)
What changed in this PR
Fixes NSUrlSessionTask cleanup races by ensuring only one cleanup path cancels each task and managed wrappers remain alive for late callbacks.
Changes:
- Makes inflight removal the cleanup ownership decision.
- Removes unsafe task wrapper disposal.
- Adds a concurrent cancellation/response-disposal stress test.
| File | Description |
|---|---|
src/Foundation/NSUrlSessionHandler.cs |
Updates task cleanup and delegate callback handling. |
tests/monotouch-test/System.Net.Http/NSUrlSessionHandlerTest.cs |
Adds a regression stress test. |
Extend the networking stress regression with a deterministic hanging response and a dedicated worker that disposes NSUrlSessionHandler while the response stream is still active. This covers the task-wrapper lifetime path called out during review and verifies that late delegate callbacks complete safely. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8ede0128-a776-42ec-bfb4-9c076d67a378
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
The stress test can complete via the shared cancellation token without proving handler disposal completed request cleanup.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 1
Resolved since last review (1)
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
…dler Complete pending SendAsync calls and active response streams when the handler takes ownership of inflight requests during disposal. This ensures native task cancellation cannot leave managed operations waiting indefinitely after the inflight dictionary has been cleared. Strengthen the regression test with a request token independent of the stress-loop duration and a five-second bound that verifies handler disposal itself unblocks the active stream. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8ede0128-a776-42ec-bfb4-9c076d67a378
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
The regression test does not cover handler disposal while SendAsync is still pending.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 1
Resolved since last review (1)
Add a deterministic server endpoint that accepts a request without returning response headers. Dispose NSUrlSessionHandler while SendAsync is still pending and require the task to complete as canceled within five seconds. This directly covers the managed CompletionSource cancellation performed by the handler disposal path. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8ede0128-a776-42ec-bfb4-9c076d67a378
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Concurrent sends can escape handler disposal, and one pending-send assertion can be swallowed by the worker loop.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 1
Open (2)
Resolved since last review (1)
Set the disposed state while holding the inflight-request lock and check that state under the same lock before adding a newly created task. Requests that lose this race now complete their managed state and cancel the native task instead of being added after the disposal snapshot. Require the pending-SendAsync regression to observe a canceled task so other fault outcomes cannot be swallowed by the stress worker. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8ede0128-a776-42ec-bfb4-9c076d67a378
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Handler disposal publishes stream terminal state without synchronization with active reads, leaving the new cleanup path racy.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 1
Resolved since last review (2)
Publish and observe the response stream terminal exception and completion state while holding the stream data lock. This makes handler disposal reliably visible to a concurrent ReadAsync and avoids relying on unsynchronized field access. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8ede0128-a776-42ec-bfb4-9c076d67a378
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Revalidate the exact inflight request while holding the handler dictionary lock before publishing an HTTP response. This gives response publication and handler disposal a single ordering point, so a request removed by disposal cannot subsequently complete successfully. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8ede0128-a776-42ec-bfb4-9c076d67a378
…networking-crash # Conflicts: # tests/dotnet/UnitTests/expected/MacOSX-CoreCLR-R2R-size.txt
✅ API diff for current PR / commitNET (empty diffs)✅ API diff vs stableNET (empty diffs)ℹ️ Generator diffGenerator Diff: vsdrops (html) vsdrops (raw diff) gist (raw diff) - Please review changes) Pipeline on Agent |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
🚀 [CI Build #6d78772] Test results 🚀Test results✅ All tests passed on VSTS: test results. 🎉 All 269 tests passed 🎉 Tests counts✅ assembly-processing: All 1 tests passed. Html Report (VSDrops) Download macOS tests✅ Tests on macOS Sonoma (14): All 5 tests passed. Html Report (VSDrops) Download Linux Build VerificationPipeline on Agent |
…Task cleanup in NSUrlSessionHandler. Fixes #20345. (#26730) `NSUrlSessionHandler` had several independent code paths that could clean up the same `NSUrlSessionTask` at the same time: `RemoveInflightData` (called from the cancellation registration, from `DidCompleteWithError` and when the response stream finished), the delegate callbacks going through `GetInflightData`, the disposal callback of `NSUrlSessionDataTaskStreamContent`, and `Dispose` of the handler itself. Each of those paths cancelled the task, and `RemoveInflightData` additionally disposed the managed `NSUrlSessionTask` wrapper. Disposing the wrapper releases the underlying native object, so as soon as two paths ran concurrently - or a delegate callback arrived after cleanup had already happened - we could end up messaging an already released native task. That is exactly what the crash reports in the issue show: an `objc_release_x8` inside `__NSCFURLSessionConnection` dealloc, and a separate crash where `NSUrlSessionTask.Cancel` was invoked on a garbage pointer. The fix is to establish a single owner for the cleanup of each task: * `RemoveInflightData` now decides ownership by the result of removing the task from the inflight dictionary. Only the caller that actually removed the entry cancels the `CancellationTokenSource` and the native task; everybody else returns immediately. * `GetInflightData` no longer cancels the task when the inflight data is missing or already cancelled. Missing or cancelled inflight data means another path already owns the task, so the callback just returns null and bails out of the delegate method as before. * The disposal callback of the response content no longer cancels the data task. The cancellation is already handled by the code path that removes the inflight data. * We no longer dispose the managed `NSUrlSessionTask` wrappers (neither in `RemoveInflightData` nor in `Dispose`). `NSURLSession` may still invoke delegate callbacks for a task after we're done with it, and managed callbacks may still hold on to the wrapper, so releasing the native task at that point is not safe. The wrappers are collected by the GC once nothing references them anymore. * Disposing the handler now completes pending `SendAsync` calls and active response streams before cancelling their native tasks. The response stream publishes and observes its terminal state under its data lock, so concurrent reads reliably see disposal. * The disposed state, inflight dictionary, cancellation registration, and native task startup are coordinated under the same lock. Disposal cannot cancel a task and then allow `SendAsync` to resume it afterward, and completed requests unregister their callbacks so long-lived request tokens do not retain task wrappers and response state. Fixes #20345 🤖 Pull request created by Copilot Backport of #26668. --------- Copilot-Session: 8ede0128-a776-42ec-bfb4-9c076d67a378
…lling. Fixes #10113 (#27394) Backport of #26886. Includes prerequisite #26668 first: the stream notifications rely on its terminal-state locking and handler-disposal behavior. The earlier proxy-support dependency is already backported. Fixes #10113 🤖 Pull request created by Copilot --------- Co-authored-by: Rolf Bjarne Kvinge <rokvin@microsoft.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>



NSUrlSessionHandlerhad several independent code paths that could clean up the sameNSUrlSessionTaskat the same time:RemoveInflightData(called from the cancellation registration, fromDidCompleteWithErrorand when the response stream finished), the delegate callbacks going throughGetInflightData, the disposal callback ofNSUrlSessionDataTaskStreamContent, andDisposeof the handler itself.Each of those paths cancelled the task, and
RemoveInflightDataadditionally disposed the managedNSUrlSessionTaskwrapper. Disposing the wrapper releases the underlying native object, so as soon as two paths ran concurrently - or a delegate callback arrived after cleanup had already happened - we could end up messaging an already released native task. That is exactly what the crash reports in the issue show: anobjc_release_x8inside__NSCFURLSessionConnectiondealloc, and a separate crash whereNSUrlSessionTask.Cancelwas invoked on a garbage pointer.The fix is to establish a single owner for the cleanup of each task:
RemoveInflightDatanow decides ownership by the result of removing the task from the inflight dictionary. Only the caller that actually removed the entry cancels theCancellationTokenSourceand the native task; everybody else returns immediately.GetInflightDatano longer cancels the task when the inflight data is missing or already cancelled. Missing or cancelled inflight data means another path already owns the task, so the callback just returns null and bails out of the delegate method as before.The disposal callback of the response content no longer cancels the data task. The cancellation is already handled by the code path that removes the inflight data.
We no longer dispose the managed
NSUrlSessionTaskwrappers (neither inRemoveInflightDatanor inDispose).NSURLSessionmay still invoke delegate callbacks for a task after we're done with it, and managed callbacks may still hold on to the wrapper, so releasing the native task at that point is not safe. The wrappers are collected by the GC once nothing references them anymore.Disposing the handler now completes pending
SendAsynccalls and active response streams before cancelling their native tasks. The response stream publishes and observes its terminal state under its data lock, so concurrent reads reliably see disposal.The disposed state, inflight dictionary, cancellation registration, and native task startup are coordinated under the same lock. Disposal cannot cancel a task and then allow
SendAsyncto resume it afterward, and completed requests unregister their callbacks so long-lived request tokens do not retain task wrappers and response state.Verified with the NativeAOT iOS stress repro from the issue: the unpatched implementation crashed twice within ~20 seconds (both of the signatures mentioned above), while the patched version ran the same workload for 3m41s without crashing. The focused
NSUrlSessionHandlerstress test also passes for the full 15-second CI duration, including bounded coverage for handler disposal with both an active response stream and aSendAsyncwaiting for response headers. Its client/server timing uses a recorded per-run seed that is included in assertion failures and can be replayed withNSURLSESSIONHANDLER_STRESS_SEED. Intentionally hanging server connections are released when the client disconnects, and worker iterations are paced while retaining 18 concurrent race lanes, so long stress runs do not exhaust simulator file descriptors or the macOS ephemeral-port range.Fixes #20345
🤖 Pull request created by Copilot