You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[swift6] Fix urlsession losing a cancellation while an interceptor completes asynchronously - #25849
With an OpenAPIInterceptor that completes intercept asynchronously (e.g. a token refresh), a cancel arriving before the data task exists was dropped and the request was sent anyway. The same happened when a cancel arrived while the retry interceptor was working.
RequestTask now remembers a cancel for the current execution:
cancel() records it. Once the data task exists it is stored first and the flag checked after, so a cancel that came earlier cancels the task before it is resumed, and one that comes later finds it.
A cancelled request does not call the retry interceptor, and .retry is ignored if a cancel lands while the interceptor decides.
A cancelled execution always ends with ErrorResponse.error(-1, nil, nil, URLError(.cancelled)), like a cancelled data task: also when the interceptor fails after the cancel, or when the cancel lands while a retry is decided.
Reactive wrappers.#25182 ruled out a RequestTask that remembers a cancel, because the reactive wrappers call cancel() when a subscription ends and can execute a builder again. This change scopes the cancel to one execution, so that keeps working:
The public execute(completion:) clears the flag before starting, so a cancel from an earlier subscription never stops the next one. With Combine's Deferred, every subscription re-executes the same builder; RxSwift builds a new one per subscription, so its late cancel() on disposal can't reach a retry at all.
Retries still go through execute(completion:), so subclass overrides see them, but a private marker makes that call keep the flag, so a cancel during a retry still holds.
testExecuteAfterCancelSendsRequest covers re-executing a builder after a cancel. Separately, I checked RxSwift .retry() and Combine Deferred.retry() after a failed request, with synchronous and asynchronous interceptors: every retry was sent and succeeded.
The alamofire library is unaffected: its request exists as soon as execute(completion:) returns.
Known limit: the flag has no execution identity. A late cancel() from an earlier execution that lands after a new execute() has cleared the flag cancels the new run, and the completion of an earlier cancelled task that arrives after that can still be retried. The standard wrappers rarely hit this, and a generation token would close it; left out to keep this change small.
Tests: RequestCancellationTests in the asyncAwaitLibrary sample covers cancel during an async intercept (also when the interceptor then fails), cancel before and during a retry, an uncancelled retry going through an overridden execute(completion:), and re-executing a builder after a cancel. They run without a server. The three cancellation tests fail without this change; the retry and re-execute tests guard behavior that already worked. The sample's host app traps at launch on an iOS 27 simulator because it doesn't adopt the scene lifecycle (pre-existing), so they were run on iOS 26.5.
Fixes URLSession requests losing a cancellation when an interceptor completes asynchronously (e.g., token refresh), and when a cancel arrives during a retry decision. The request now reports URLError.cancelled and is never sent.
Bug Fixes
RequestTask records a cancel even before the data task exists, and clears it on each new execute() so Combine and RxSwift wrappers still work after disposal.
A cancelled request skips the retry interceptor; .retry is ignored if a cancel lands while the interceptor decides. Retries use the overridable execute(completion:) so subclasses keep working.
Adds RequestCancellationTests covering cancel during intercept, before/during retry, and re-execution after cancel.
The Petstore sample tests now only assert that an upload response has a message instead of matching the server's exact message text.
Written for commit a80fd26. Summary will update on new commits.
The failing "Samples Swift 6 Petstore" check is unrelated to this change: only PetAPITests.test3UploadFile in the default sample fails. The upload succeeds, but the test expects File uploaded to ./<name> in the server's reply, and the swaggerapi/petstore:latest server now answers Uploaded <name>.png, 881 bytes. That image published 1.0.8 (Oct 30) and 1.0.9 (Nov 17), and this workflow has failed since its last pass on Oct 15, including on the v7.27.0 and v7.28.0 pushes. This PR doesn't touch uploads or response parsing; the cancellation tests, which run without a server, pass.
Hi @Robuske, thanks for opening this PR.
Can you please fix the unit test?
Maybe we should not look into the returned text because it can make the test flanky.
Thanks
Can you please fix the unit test?
Maybe we should not look into the returned text because it can make the test flanky.
Done in a80fd26: the upload tests in the default, alamofireLibrary, urlsessionLibrary and apiNonStaticMethod samples now only check that the server's reply has a message, not its wording. They still fail if the upload errors. Thanks!
This branch has not been deployed
No deployments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #25848. Follow-up to #25188 (fixes #25182), as discussed in #25188 (comment).
With an
OpenAPIInterceptorthat completesinterceptasynchronously (e.g. a token refresh), a cancel arriving before the data task exists was dropped and the request was sent anyway. The same happened when a cancel arrived while theretryinterceptor was working.RequestTasknow remembers a cancel for the current execution:cancel()records it. Once the data task exists it is stored first and the flag checked after, so a cancel that came earlier cancels the task before it is resumed, and one that comes later finds it.retryinterceptor, and.retryis ignored if a cancel lands while the interceptor decides.ErrorResponse.error(-1, nil, nil, URLError(.cancelled)), like a cancelled data task: also when the interceptor fails after the cancel, or when the cancel lands while a retry is decided.Reactive wrappers. #25182 ruled out a
RequestTaskthat remembers a cancel, because the reactive wrappers callcancel()when a subscription ends and can execute a builder again. This change scopes the cancel to one execution, so that keeps working:execute(completion:)clears the flag before starting, so a cancel from an earlier subscription never stops the next one. With Combine'sDeferred, every subscription re-executes the same builder; RxSwift builds a new one per subscription, so its latecancel()on disposal can't reach a retry at all.execute(completion:), so subclass overrides see them, but a private marker makes that call keep the flag, so a cancel during a retry still holds.testExecuteAfterCancelSendsRequestcovers re-executing a builder after a cancel. Separately, I checked RxSwift.retry()and CombineDeferred.retry()after a failed request, with synchronous and asynchronous interceptors: every retry was sent and succeeded.The
alamofirelibrary is unaffected: its request exists as soon asexecute(completion:)returns.Known limit: the flag has no execution identity. A late
cancel()from an earlier execution that lands after a newexecute()has cleared the flag cancels the new run, and the completion of an earlier cancelled task that arrives after that can still be retried. The standard wrappers rarely hit this, and a generation token would close it; left out to keep this change small.Tests:
RequestCancellationTestsin theasyncAwaitLibrarysample covers cancel during an async intercept (also when the interceptor then fails), cancel before and during a retry, an uncancelled retry going through an overriddenexecute(completion:), and re-executing a builder after a cancel. They run without a server. The three cancellation tests fail without this change; the retry and re-execute tests guard behavior that already worked. The sample's host app traps at launch on an iOS 27 simulator because it doesn't adopt the scene lifecycle (pre-existing), so they were run on iOS 26.5.PR checklist
./bin/utils/export_docs_generators.shwas not run because no generator options changed.Summary by cubic
Fixes URLSession requests losing a cancellation when an interceptor completes asynchronously (e.g., token refresh), and when a cancel arrives during a retry decision. The request now reports
URLError.cancelledand is never sent.Bug Fixes
RequestTaskrecords a cancel even before the data task exists, and clears it on each newexecute()so Combine and RxSwift wrappers still work after disposal..retryis ignored if a cancel lands while the interceptor decides. Retries use the overridableexecute(completion:)so subclasses keep working.RequestCancellationTestscovering cancel during intercept, before/during retry, and re-execution after cancel.Written for commit a80fd26. Summary will update on new commits.