Skip to content

Conversation

@michaelversus
Copy link
Owner

Migrate to Swift Concurrency with Structured Concurrency

Overview

This MR migrates SwiftFindRefs from legacy GCD (DispatchQueue.concurrentPerform) to modern Swift Concurrency using structured concurrency (withTaskGroup). The migration improves code quality, type safety, and maintainability while maintaining equivalent performance.

🎯 Key Changes

Core Implementation

  • Replaced DispatchQueue.concurrentPerform with withTaskGroup

    • Migrated from GCD-based parallel execution to Swift Concurrency task groups
    • Eliminated manual thread synchronization code
  • Removed ThreadSafeSet with NSLock

    • Replaced manual locking mechanism with Swift's built-in structured concurrency
    • Removed @unchecked Sendable annotation and manual lock management
    • Reduced code complexity by ~15 lines
  • Made APIs async/await

    • IndexStoreFinder.fileReferences() methods are now async throws
    • CompositionRoot.run() is now async throws
    • Updated to AsyncParsableCommand for native async support

Test Updates

  • Updated all test methods to use async/await patterns
  • Added Sendable conformance to mock types for thread safety

📊 Performance

Benchmark Results

Test Configuration:

  • Project: Large
  • Symbol: Some (class)
  • References Found: 136 files

Performance Comparison:

  • Old (GCD): ~3.6-3.8 seconds, 134-169% CPU usage
  • New (Swift Concurrency): ~3.3-4.6 seconds, 131-165% CPU usage
  • Result: ✅ Equivalent performance with no regression

Key Metrics

  • Correctness: Identical results (136 references)
  • Performance: Equivalent execution times
  • CPU Utilization: Effective multi-core usage (130-175%)
  • Stability: Consistent performance across multiple runs

🔧 Technical Details

Before (GCD)

DispatchQueue.concurrentPerform(iterations: index.recordNames.count) { i in
    let recordName = index.recordNames[i]
    if recordContainsSymbol(store: store, recordName: recordName, query: query) {
        let filename = index.sourcePath(for: recordName)
        referencedFiles.insert(filename) // Manual lock required
    }
}

After (Swift Concurrency)

await withTaskGroup(of: String?.self) { group in
    for recordName in index.recordNames {
        group.addTask {
            guard recordContainsSymbol(store: store, recordName: recordName, query: query) else {
                return nil
            }
            return index.sourcePath(for: recordName)
        }
    }
    // Automatic synchronization, no locks needed
}

✨ Benefits

  1. Structured Concurrency

    • Automatic task management and cancellation
    • Better error handling and propagation
    • No manual synchronization required
  2. Type Safety

    • Compile-time guarantees with Sendable conformance
    • Eliminated @unchecked Sendable annotations
    • Better isolation checking
  3. Code Quality

    • Cleaner, more maintainable code
    • Reduced complexity (~15 lines removed)
    • Modern Swift 6.2 patterns
  4. Future-Proof

    • Ready for Swift 6 strict concurrency checking
    • Aligned with Apple's recommended concurrency patterns
    • Better integration with async/await ecosystem

🧪 Testing

  • ✅ All 54 tests passing
  • ✅ Benchmark verification completed
  • ✅ Result correctness verified (identical output)
  • ✅ Performance regression testing passed

🔍 Migration Strategy

This migration follows Swift Concurrency best practices:

  1. ✅ Replaced GCD with structured concurrency
  2. ✅ Removed manual synchronization primitives
  3. ✅ Added proper Sendable conformance
  4. ✅ Maintained backward compatibility (same results)
  5. ✅ Verified performance equivalence

📚 References

@michaelversus michaelversus self-assigned this Jan 14, 2026
@codecov-commenter
Copy link

Codecov Report

❌ Patch coverage is 94.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.47%. Comparing base (54f5ed5) to head (6d1aa94).

Files with missing lines Patch % Lines
Sources/SwiftFindRefs/SwiftFindRefs.swift 0.00% 2 Missing ⚠️
...es/SwiftFindRefs/IndexStore/IndexStoreFinder.swift 93.75% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master       #3      +/-   ##
==========================================
- Coverage   95.50%   95.47%   -0.03%     
==========================================
  Files          20       20              
  Lines        1089     1082       -7     
==========================================
- Hits         1040     1033       -7     
  Misses         49       49              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@michaelversus michaelversus merged commit 6355d8e into master Jan 14, 2026
1 check passed
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.

3 participants