Skip to content

Conversation

@ahoppen
Copy link
Member

@ahoppen ahoppen commented Mar 20, 2024

  • Explanation: DownloadTaskManager had a strong reference to URLSession, which retained its delegate, which was the DownloadTaskManager. This formed a retain cycle.
    Make the reference from URLSession to the delegate weak and only keep DownloadTaskManager alive as long as DownloadTasks need it. This causes the DownloadTaskManager to be deallocated once nobody holds a reference to it anymore and all the tasks it manages are finished.
    Finally, we need to call invalidate on the URLSession to tell it that we’re done and that it should release its delegate (which is now the WeakDownloadTaskManager wrapper).
    This retain cycle was causing a leak in sourcekit-lsp. I verified that the leak no longer exists with this patch.
  • Scope: The change should be transparent to all users of DataTaskManager and DownloadTaskManager and only prevent the memory leak
  • Risk: I don’t see a risk with this change since the {Data|Download}TaskManager is kept alive as long as there is anything left that might call it.
  • Testing: I verified that the leak no longer exists with this patch.
  • Issue: rdar://125012584
  • Reviewer: @MaxDesiatov on Fix a memory leak in DownloadTaskManager and DataTaskManager #7408

`DownloadTaskManager` had a strong reference to `URLSession`, which retained its delegate, which was the `DownloadTaskManager`. This formed a retain cycle.

Make the reference from `URLSession` to the delegate weak and only keep `DownloadTaskManager` alive as long as `DownloadTask`s need it. This causes the `DownloadTaskManager` to be deallocated once nobody holds a reference to it anymore and all the tasks it manages are finished.

Finally, we need to call `invalidate` on the `URLSession` to tell it that we’re done and that it should release its delegate (which is now the `WeakDownloadTaskManager`wrapper).

rdar://125012584
@ahoppen ahoppen added the swift 6.0 Related to Swift 6.0 release branch label Mar 20, 2024
@ahoppen
Copy link
Member Author

ahoppen commented Mar 20, 2024

@swift-ci Please test

@ahoppen
Copy link
Member Author

ahoppen commented Mar 25, 2024

@swift-ci Please test Linux

@ahoppen ahoppen merged commit 9f17143 into swiftlang:release/6.0 Mar 25, 2024
@ahoppen ahoppen deleted the ahoppen/6.0/download-data-task-manager-leak branch March 25, 2024 22:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug swift 6.0 Related to Swift 6.0 release branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants