Skip to content

Conversation

@dreampiggy
Copy link
Contributor

@dreampiggy dreampiggy commented Nov 24, 2025

New Pull Request Checklist

  • I have read and understood the CONTRIBUTING guide

  • I have read the Documentation

  • I have searched for a similar pull request in the project and found none

  • I have updated this branch with the latest master to avoid conflicts (via merge from master or rebase)

  • I have added the required tests to prove the fix/feature I am adding

  • I have updated the documentation (if necessary)

  • I have run the tests and they pass

  • I have run the lint and it passes (pod lib lint)

This merge request fixes / refers to the following issues: ...

Pull Request Description

This close #3849

Actually I think this is inddeed thread-unsafe. But I have no idea why pre iOS-26 does not have such a issue...

Anyway, use @synchronized can be safe guraded in -[SDWebImageCombinedOperation cancel] method, which use @synchronized (self)

Summary by CodeRabbit

  • Refactor
    • Enhanced internal thread-safety mechanisms for operation handling to improve stability and reliability during concurrent image caching and loading operations.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Nov 24, 2025

Walkthrough

Thread-safety improvements to SDWebImageManager by wrapping assignments to operation.cacheOperation and operation.loaderOperation with @synchronized blocks. Changes affect cache and download processing methods to prevent race conditions when updating internal operation references from dispatch callbacks.

Changes

Cohort / File(s) Summary
Thread-Safety Synchronization Pattern
SDWebImage/Core/SDWebImageManager.m
Replaces direct assignments of operation.cacheOperation and operation.loaderOperation with a local variable pattern wrapped in @synchronized (operation) blocks. Applied consistently across callCacheProcessForOperation, callOriginalCacheProcessForOperation, and callDownloadProcessForOperation methods to ensure atomic updates to operation properties.

Sequence Diagram

sequenceDiagram
    participant Main as Main Thread
    participant Cache as Cache Queue
    participant Download as Download Queue
    
    rect rgb(200, 220, 255)
    Note over Main, Download: BEFORE: Unsafe concurrent assignment
    Cache->>Main: queryImageForKey() returns
    Download->>Main: download completes
    Note over Main: Race condition:<br/>Both try to set operation.cacheOperation<br/>operation.loaderOperation
    Main->>Main: ❌ Garbage pointer dereference
    end
    
    rect rgb(200, 255, 220)
    Note over Main, Download: AFTER: Synchronized assignment
    Cache->>Main: queryImageForKey() returns
    Main->>Main: ⬇️ Create local variable
    Main->>Main: `@synchronized` (operation) { assign }
    Download->>Main: download completes
    Main->>Main: ⬇️ Create local variable
    Main->>Main: `@synchronized` (operation) { assign }
    Note over Main: ✓ Atomic updates prevent corruption
    end
Loading

Estimated Code Review Effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Single file with consistent, repetitive synchronization pattern reduces complexity
  • Straightforward additions of @synchronized blocks with minimal logic variance
  • Attention areas:
    • Verify all three methods (callCacheProcessForOperation, callOriginalCacheProcessForOperation, callDownloadProcessForOperation) correctly wrap assignments to prevent race conditions
    • Confirm that both cacheOperation and loaderOperation are properly synchronized in all relevant locations
    • Validate that the synchronization scope captures the entire assignment operation

Poem

🐰 Two rabbits raced to set the op,
But crashes made our springtime stop!
With @synchronized held tight and dear,
Thread safety hops—the path is clear! 🌿✨

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: using @synchronized to ensure thread-safe cache/loader operations, and references the specific iOS 26 issue being fixed.
Linked Issues check ✅ Passed The PR directly addresses the thread-safety crash in issue #3849 by implementing @synchronized blocks around operation.cacheOperation and operation.loaderOperation assignments, matching the root cause identified in the crash stack.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing the thread-safety issue in SDWebImageManager.m by adding @synchronized protection to cache and loader operation assignments, with no extraneous modifications.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

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 (2)
SDWebImage/Core/SDWebImageManager.m (2)

311-333: Good alignment of cacheOperation locking with cancel’s monitor

Wrapping the operation.cacheOperation assignments in @synchronized(operation) is a solid fix: it uses the same monitor object as @synchronized(self) in SDWebImageCombinedOperation’s -isCancelled and -cancel, which removes races between the cancel path and manager-side cache-operation mutations while keeping the potentially heavy queryImageForKey: calls outside the lock.

One optional improvement you might consider (for both normal and original cache paths) is to immediately cancel a newly-assigned cache operation if the combined operation was already cancelled before this assignment ran, to avoid doing unnecessary work after user cancellation:

-        @synchronized (operation) {
-            operation.cacheOperation = cacheOperation;
-        }
+        @synchronized (operation) {
+            operation.cacheOperation = cacheOperation;
+            if (operation.isCancelled) {
+                [cacheOperation cancel];
+                operation.cacheOperation = nil;
+            }
+        }

Same pattern would apply in callOriginalCacheProcessForOperation: after the other cacheOperation assignment.

Also applies to: 368-388, 783-807


442-477: loaderOperation synchronization is consistent; consider mirroring the post-cancel guard

The new @synchronized(operation) around operation.loaderOperation = loaderOperation; correctly brings the download sub-operation under the same monitor used by SDWebImageCombinedOperation’s -cancel, so cancel and assignment can’t race anymore.

For symmetry with the cache side and to avoid starting network work for already-cancelled combined operations, you could optionally add a post-assignment check here:

-        @synchronized (operation) {
-            operation.loaderOperation = loaderOperation;
-        }
+        @synchronized (operation) {
+            operation.loaderOperation = loaderOperation;
+            if (operation.isCancelled) {
+                [loaderOperation cancel];
+                operation.loaderOperation = nil;
+            }
+        }

This doesn’t affect correctness of the current fix, but tightens cancel semantics and resource usage.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2053b12 and da6cb39.

📒 Files selected for processing (1)
  • SDWebImage/Core/SDWebImageManager.m (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Unit Test (macOS)
  • GitHub Check: Unit Test (visionOS)
  • GitHub Check: Unit Test (iOS)
  • GitHub Check: Cocoapods Lint
  • GitHub Check: Cocoapods Demo

@dreampiggy dreampiggy merged commit 38a6471 into SDWebImage:master Nov 27, 2025
5 of 8 checks passed
@dreampiggy dreampiggy added this to the 5.21.4 milestone Nov 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

operation.cacheOperation Crash Only in iOS 26.

1 participant