r/iOSProgramming • u/100_rv • 28d ago
Discussion Swift 6.4: Async defer doesn't make cleanup cancellation-safe
I wrote a technical walkthrough of a subtle Swift Concurrency issue I wanted to explore.
Imagine a task writing data into a buffered writer. The task gets cancelled, defer runs, and close() gets called. But if close()invokes a cancellation-aware flush(), that flush can throw CancellationError. If the error is swallowed and the writer is marked closed anyway, the cleanup path has run without achieving its intended postcondition.
The article explores two Swift Evolution proposals:
SE-0493: Async calls in
deferbodiesSE-0504: Task Cancellation Shields
It covers a minimal reproduction, the limits of using Task.detached for cleanup, a narrowly scoped cancellation shield, and a Swift Testing example that checks whether the data was actually flushed rather than merely checking whether close() was called.
One important caveat: the example demonstrates a cancellation-aware cleanup failure, not a claim that every real file API corrupts data when cancelled.
I'd be interested in feedback on the cancellation-shield approach, especially around resource ownership and cleanup guarantees in production code.
1
28d ago
[removed] — view removed comment
1
u/AutoModerator 28d ago
Hey /u/DimensionMindless336, your content has been removed because Reddit has marked your account as having a low Contributor Quality Score. This may result from, but is not limited to, activities such as spamming the same links across multiple subreddits, submitting posts or comments that receive a high number of downvotes, a lack of recent account activity, or having an unverified account.
Please be assured that this action is not a reflection of your participation in our subreddit. This is simply an automated filter in place to reduce spam.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
5
u/dawedev 28d ago
Testing that the data was actually flushed instead of just checking that close() ran is the useful part here, that's where these bugs usually hide. One ownership question: with the shield scoped around the final flush, what happens if that flush hangs on a slow disk or network write? I'd want a timeout or a bounded retry inside the shield, otherwise cancellation stops being a reliable way to end the task. I'd also make close() throw after a failed flush instead of marking the writer closed, so the caller knows the postcondition didn't hold.