Skip to content

Fix rare crashes in IOSBackgroundTaskScheduler with on entering callbacks #3751

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

Merged
merged 4 commits into from
Jul 28, 2025

Conversation

laevandus
Copy link
Contributor

@laevandus laevandus commented Jul 28, 2025

🔗 Issue Links

Resolves: https://linear.app/stream/issue/IOS-983

🎯 Goal

Rare crashes with mutating onEntering callback mutations

📝 Summary

🛠 Implementation

🎨 Showcase

🧪 Manual Testing Notes

N/A

☑️ 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

Summary by CodeRabbit

  • Bug Fixes
    • Resolved rare crashes related to background and foreground callbacks by enhancing synchronization.
  • Tests
    • Added a test to ensure thread safety when starting and stopping app state updates concurrently.
  • Documentation
    • Updated the changelog with details about the fixed crash issue.

@laevandus laevandus requested a review from a team as a code owner July 28, 2025 10:05
@laevandus laevandus added 🐞 Bug An issue or PR related to a bug 🌐 SDK: StreamChat (LLC) Tasks related to the StreamChat LLC SDK labels Jul 28, 2025
Copy link

coderabbitai bot commented Jul 28, 2025

"""

Walkthrough

Thread-safety was introduced to the IOSBackgroundTaskScheduler by serializing the assignment and invocation of its background and foreground callback closures using a private serial queue. Additionally, a new test was added to stress the concurrency of starting and stopping app state updates, verifying the absence of race conditions.

Changes

Cohort / File(s) Change Summary
Thread-safety in callback handling
Sources/StreamChat/WebSocketClient/BackgroundTaskScheduler.swift
Wrapped assignments and invocations of onEnteringBackground and onEnteringForeground in a serial queue for thread-safety.
Concurrency test for scheduler
Tests/StreamChatTests/WebSocketClient/BackgroundTaskScheduler_Tests.swift
Added a test that concurrently starts and stops app state update listening to check for concurrency issues.
Changelog update
CHANGELOG.md
Added a fixed issue entry documenting the crash fix related to "on entering" callbacks in IOSBackgroundTaskScheduler.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Thread(s)
    participant Scheduler as IOSBackgroundTaskScheduler
    participant Queue as Serial Queue

    loop 100 iterations (concurrent)
        alt Even index
            Test->>Queue: async { assign onEnteringBackground/onEnteringForeground }
            Queue->>Scheduler: set closure
        else Odd index
            Test->>Queue: async { clear onEnteringBackground/onEnteringForeground }
            Queue->>Scheduler: clear closure
        end
    end

    Note over Scheduler: All closure assignments/clears are serialized via Queue
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Assessment against linked issues

Objective Addressed Explanation
Prevent crash in IOSBackgroundTaskScheduler.startListeningForAppStateUpdates due to concurrency issues (IOS-983)

Poem

In the warren where threads may race,
A scheduler hops with careful grace.
With queues now guarding every leap,
No more crashes disturb our sleep.
Tests run wild, but all is well—
The code is safe, as rabbits tell! 🐇✨
"""

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a669340 and 80cadac.

📒 Files selected for processing (1)
  • CHANGELOG.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/backgroundschedulercrash

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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 generate unit tests to generate unit tests for 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.

@laevandus laevandus enabled auto-merge (squash) July 28, 2025 10:06
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
Tests/StreamChatTests/WebSocketClient/BackgroundTaskScheduler_Tests.swift (1)

78-87: Effective crash test for race condition validation.

This concurrency test effectively reproduces the conditions that would trigger the original race condition. The alternating pattern of starting and stopping app state updates with concurrent execution is well-designed to stress test the thread safety improvements.

The absence of assertions is appropriate for a crash test - the success condition is simply not crashing.

Consider adding a brief comment explaining this is a crash test:

+    // Crash test: Verifies no race conditions when concurrently starting/stopping app state updates
     func test_callingAppStateUpdatesConcurretly() {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 35fb0e9 and a7c90dc.

📒 Files selected for processing (2)
  • Sources/StreamChat/WebSocketClient/BackgroundTaskScheduler.swift (3 hunks)
  • Tests/StreamChatTests/WebSocketClient/BackgroundTaskScheduler_Tests.swift (1 hunks)
🔇 Additional comments (4)
Sources/StreamChat/WebSocketClient/BackgroundTaskScheduler.swift (4)

85-88: LGTM: Proper serialization of callback assignment.

The use of queue.async for callback assignment prevents race conditions during concurrent calls to startListeningForAppStateUpdates. The asynchronous dispatch ensures the assignment doesn't block the caller while maintaining thread safety.


106-109: LGTM: Consistent callback clearing pattern.

The callback clearing follows the same async pattern as assignment, ensuring thread-safe cleanup of callbacks when stopping app state updates.


125-126: LGTM: Safe callback invocation pattern.

The synchronous read of the callback followed by invocation outside the queue is the correct pattern. This prevents blocking the serial queue during callback execution while ensuring thread-safe access to the callback closure.


130-131: LGTM: Consistent foreground callback pattern.

This follows the same safe invocation pattern as the background callback handler, maintaining consistency and thread safety.

Comment on lines 124 to +126
@objc private func handleAppDidEnterBackground() {
onEnteringBackground()
let callback = queue.sync { onEnteringBackground }
callback()
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Running the callback on the calling thread (not on the queue)

@Stream-SDK-Bot
Copy link
Collaborator

Stream-SDK-Bot commented Jul 28, 2025

SDK Size

title develop branch diff status
StreamChat 7.92 MB 7.92 MB 0 KB 🟢
StreamChatUI 4.84 MB 4.84 MB 0 KB 🟢

Copy link
Member

@nuno-vieira nuno-vieira left a comment

Choose a reason for hiding this comment

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

LGTM! ✅

@martinmitrevski
Copy link
Contributor

@laevandus can you also fix this in StreamCore?

Copy link

Public Interface

🚀 No changes affecting the public interface.

Copy link

1 Error
🚫 Please use more than one word.
c7fe20c

Generated by 🚫 Danger

Copy link

Public Interface

🚀 No changes affecting the public interface.

1 similar comment
Copy link

Public Interface

🚀 No changes affecting the public interface.

Copy link

@laevandus laevandus merged commit 0eb718b into develop Jul 28, 2025
13 of 14 checks passed
@laevandus laevandus deleted the fix/backgroundschedulercrash branch July 28, 2025 14:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🐞 Bug An issue or PR related to a bug 🌐 SDK: StreamChat (LLC) Tasks related to the StreamChat LLC SDK
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants