Skip to content

Swift 6: complete concurrency checking (LLC and UIKit) #3661

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 33 commits into
base: develop
Choose a base branch
from

Conversation

laevandus
Copy link
Contributor

@laevandus laevandus commented May 5, 2025

Important

StreamChatUI changes are in #3660 and will be merged to here. This PR can be reviewed already.

🔗 Issue Links

Resolves IOS-735

🎯 Goal

  • Set Swift version to 6 and implement complete concurrency checking

📝 Summary

  • Sendable conformance to types
  • @Sendable to completion handlers
  • Many thread-safety related changes to @unchecked Sendable types (internal classes have manual handling and found many which did not guard that state properly)
  • Fixes warnings in the demo app (adding @Sendable to completion handlers creates warnings at callsites)
  • Backported AllocatedUnfairLock which is needed for static concurrency safe properties (our Atomic property wrapper can't be used)

🛠 Implementation

🧪 Manual Testing Notes

Manual regression testing round when UIKit changes are merged into this branch.

☑️ Contributor Checklist

  • I have signed the Stream CLA (required)
  • This change should be manually QAed
  • Changelog is updated with client-facing changes
  • Changelog is updated with new localization keys
  • New code is covered by unit tests
  • Documentation has been updated in the docs-content repo

@laevandus laevandus requested a review from a team as a code owner May 5, 2025 12:26
@laevandus laevandus added the 🌐 SDK: StreamChat (LLC) Tasks related to the StreamChat LLC SDK label May 5, 2025
@laevandus laevandus marked this pull request as draft May 5, 2025 12:27
Copy link

github-actions bot commented May 5, 2025

1 Warning
⚠️ Big PR
1 Message
📖 There seems to be app changes but CHANGELOG wasn't modified.
Please include an entry if the PR includes user-facing changes.
You can find it at CHANGELOG.md.

Generated by 🚫 Danger

Comment on lines 71 to 72
if: ${{ github.event.inputs.record_snapshots != 'true' }}
# if: ${{ github.event.inputs.record_snapshots != 'true' }}
if: false # disable Xcode 15 builds
Copy link
Contributor Author

@laevandus laevandus May 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Disabled Xcode 15 builds (it is hard to support it when complete concurrency checking is enabled). Hard means avoiding compiler crashes.

@Stream-SDK-Bot
Copy link
Collaborator

SDK Size

title develop branch diff status
StreamChat 7.2 MB 7.28 MB +81 KB 🟢
StreamChatUI 4.72 MB 4.73 MB +17 KB 🟢

@@ -26,7 +26,7 @@ final class StreamAudioWaveformAnalyser: AudioAnalysing {
private let audioSamplesExtractor: AudioSamplesExtractor
private let audioSamplesProcessor: AudioSamplesProcessor
private let audioSamplesPercentageNormaliser: AudioValuePercentageNormaliser
private let outputSettings: [String: Any]
nonisolated(unsafe) private let outputSettings: [String: Any]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nonisolated(unsafe) because value is Any

@Stream-SDK-Bot
Copy link
Collaborator

Stream-SDK-Bot commented May 5, 2025

SDK Performance

target metric benchmark branch performance status
MessageList Hitches total duration 10 ms 10.85 ms -8.5% 🔽 🟡
Duration 2.6 s 2.54 s 2.31% 🔼 🟢
Hitch time ratio 4 ms per s 4.28 ms per s -7.0% 🔽 🟡
Frame rate 75 fps 78.23 fps 4.31% 🔼 🟢
Number of hitches 1 1.0 0.0% 🟰 🟢


import Foundation

/// Erase type for structs which recursively contain themselves.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is easier to use a type instead of a closure when dealing with Sendable.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, this is a nice approach

@@ -131,15 +131,19 @@ open class StreamAudioPlayer: AudioPlaying, AppStateObserverDelegate {
open func play() {
do {
try audioSessionConfigurator.activatePlaybackSession()
player.play()
MainActor.ensureIsolated {
player.play()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that AVPlayer and some asset related methods require main actor


// MARK: -

private static let queue = DispatchQueue(label: "io.getstream.stream-runtime-check", target: .global())
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternative is to skip using queue here and making everything nonisolated(unsafe), especially because these are internal runtime checkes.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would do that without a queue here actually

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll revert, makes sense

@laevandus laevandus changed the title Swift 6: complete concurrency checking Swift 6: complete concurrency checking (LLC and UIKit) May 5, 2025
Copy link
Contributor

@martinmitrevski martinmitrevski left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good in general, left some comments to discuss


// MARK: -

private static let queue = DispatchQueue(label: "io.getstream.stream-runtime-check", target: .global())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would do that without a queue here actually

static var maxAttachmentSize: Int64 { 100 * 1024 * 1024 }

private let decoder: RequestDecoder
private let encoder: RequestEncoder
private let session: URLSession
/// Keeps track of uploading tasks progress
@Atomic private var taskProgressObservers: [Int: NSKeyValueObservation] = [:]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

did it complain about Atomic?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stored property '_taskProgressObservers' of 'Sendable'-conforming class 'StreamCDNClient' is mutable

Alternative is to use backwards compatible AllocatedUnfairLock (I added it for mutable static properties).
@Atomic is OK in many places because the class/type is @unchecked Sendable. In this particular case it is directly Sendable.

Property wrappers can't ensure concurrency safeness (there is a long thread about it on Swift forums)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does look cleaner:

     /// Keeps track of uploading tasks progress
-    private nonisolated(unsafe) var _taskProgressObservers: [Int: NSKeyValueObservation] = [:]
-    private let queue = DispatchQueue(label: "io.getstream.stream-cdn-client", target: .global())
+    private let taskProgressObservers = AllocatedUnfairLock([Int: NSKeyValueObservation]())

     init(
         encoder: RequestEncoder,
@@ -149,13 +148,13 @@ final class StreamCDNClient: CDNClient, Sendable {

             if let progressListener = progress {
                 let taskID = task.taskIdentifier
-                queue.async {
-                    self._taskProgressObservers[taskID] = task.progress.observe(\.fractionCompleted) { [weak self] progress, _ in
+                taskProgressObservers.withLock { observers in
+                    observers[taskID] = task.progress.observe(\.fractionCompleted) { [weak self] progress, _ in
                         progressListener(progress.fractionCompleted)
                         if progress.isFinished || progress.isCancelled {
-                            self?.queue.async { [weak self] in
-                                self?._taskProgressObservers[taskID]?.invalidate()
-                                self?._taskProgressObservers[taskID] = nil
+                            self?.taskProgressObservers.withLock { observers in
+                                observers[taskID]?.invalidate()
+                                observers[taskID] = nil
                             }
                         }
                     }

WDYT, let's use the snippet above?

@@ -131,15 +131,19 @@ open class StreamAudioPlayer: AudioPlaying, AppStateObserverDelegate {
open func play() {
do {
try audioSessionConfigurator.activatePlaybackSession()
player.play()
MainActor.ensureIsolated {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mentioned it on the other PR as well - why do we need to use ensureIsolated?

import os

@available(iOS, introduced: 13.0, deprecated: 16.0, message: "Use OSAllocatedUnfairLock instead")
final class AllocatedUnfairLock<State>: @unchecked Sendable {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

where do we use an unfair lock?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only a couple of places in TestTools. If we prefer not to add this type, we can use some nonisolated(unsafe) in test tools (I am OK to do that).

Screenshot 2025-05-23 at 14 46 49


import Foundation

/// Erase type for structs which recursively contain themselves.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, this is a nice approach

try action()
} else {
try DispatchQueue.main.sync {
return try MainActor.assumeIsolated {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can remove it, I think it was Xcode 15 which did not understand that this is OK (different compiler version). It is OK now.

_endIndex = { baseCollection.endIndex }
_position = { baseCollection[$0] }
_startIndex = { baseCollection.startIndex }
self.baseCollection = Array(baseCollection)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we change this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stored property '_endIndex' of 'Sendable'-conforming generic struct 'StreamCollection' has non-sendable type '() -> StreamCollection<Element>.Index' (aka '() -> Int')

At first I tried to make closures @Sendable, which requires BaseCollection to be Sendable. All good until I saw that StreamCollection is in some cases initialized with a list of MessageDTO. MessageDTO can't be Sendable, therefore I can't do this.

Fortunately we want to remove StreamCollection in v5 anyway.

Copy link
Contributor Author

@laevandus laevandus May 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed it and don't have a better alternative to offer here.

pongTimeoutTimer = timerType.schedule(timeInterval: Self.pongTimeoutTimeInterval, queue: timerQueue) { [weak self] in
log.info("WebSocket Pong timeout. Reconnect")
self?.delegate?.disconnectOnNoPongReceived()
queue.sync {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Problem here is that connectionDidChange is called from thread X and timer calls sendPing from thread Y which in turn will also access the _pingTimerControl (possible threading issue).

AllocatedUnfairLock would be more readable here.

Since we haven't heard about crashes with ping controller, I am open to keep it as is as well and not do these changes.

@laevandus laevandus marked this pull request as ready for review May 23, 2025 11:57
# Conflicts:
#	Sources/StreamChat/Repositories/MessageRepository.swift
Copy link

coderabbitai bot commented May 29, 2025

Important

Review skipped

More than 25% of the files skipped due to max files limit. The review is being skipped to prevent a low-quality review.

193 files out of 300 files are above the max files limit of 100. Please upgrade to Pro plan to get higher limits.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

# Conflicts:
#	.github/workflows/smoke-checks.yml
#	Sources/StreamChat/Repositories/AuthenticationRepository.swift
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🌐 SDK: StreamChat (LLC) Tasks related to the StreamChat LLC SDK
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants