|
| 1 | +import Foundation |
| 2 | +import Testing |
| 3 | + |
| 4 | +@testable import TelemetryDeck |
| 5 | + |
| 6 | +struct SignalCacheConcurrencyTests { |
| 7 | + |
| 8 | + /// Repro for https://github.com/TelemetryDeck/SwiftSDK/issues/265: |
| 9 | + /// |
| 10 | + /// count() with barrier blocks because it waits for ALL pending GCD operations. |
| 11 | + /// |
| 12 | + /// The bug: When count() uses `.barrier`, it must wait for all prior async blocks |
| 13 | + /// to complete before executing. If those blocks do work before calling push(), |
| 14 | + /// count() is blocked for their entire duration. |
| 15 | + /// |
| 16 | + /// This test queues async blocks with artificial delays to create pending work, |
| 17 | + /// then immediately calls count() to measure blocking. |
| 18 | + @Test |
| 19 | + func count_barrierCausesMainThreadBlock() { |
| 20 | + if #available(iOS 16, macOS 13, tvOS 16, visionOS 1, watchOS 9, *) { |
| 21 | + let cache = SignalCache<SignalPostBody>(logHandler: nil) |
| 22 | + let stressQueue = DispatchQueue(label: "com.telemetrydeck.stressdaqueue", attributes: .concurrent) |
| 23 | + |
| 24 | + // Queue 50 operations that each take 2ms BEFORE reaching push() |
| 25 | + // With barrier bug: count() waits for ALL of these (~100ms total) |
| 26 | + // With fix: count() returns immediately (~0ms) |
| 27 | + for i in 0..<50 { |
| 28 | + stressQueue.async { |
| 29 | + Thread.sleep(forTimeInterval: 0.002) |
| 30 | + cache.push(Self.makeSignal(id: "\(i)")) |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + // Immediately call count() - this is what the timer callback does |
| 35 | + let start = CFAbsoluteTimeGetCurrent() |
| 36 | + _ = cache.count() |
| 37 | + let elapsed = CFAbsoluteTimeGetCurrent() - start |
| 38 | + |
| 39 | + // With barrier bug: ~100ms (50 * 2ms serialized wait) |
| 40 | + // With fix (no barrier): < 10ms (just reads array.count) |
| 41 | + #expect(elapsed < 0.010, "count() blocked for \(elapsed)s - barrier flag causing contention") |
| 42 | + } else { |
| 43 | + print("skipping test on incompatible OS") |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + /// Validates thread safety of concurrent push and pop operations. |
| 48 | + /// After fix, pop() uses barrier flag to ensure exclusive access during mutation. |
| 49 | + @Test |
| 50 | + func concurrentPushAndPop_maintainsDataIntegrity() async { |
| 51 | + if #available(iOS 16, macOS 13, tvOS 16, visionOS 1, watchOS 9, *) { |
| 52 | + let cache = SignalCache<SignalPostBody>(logHandler: nil) |
| 53 | + let pushCount = 500 |
| 54 | + |
| 55 | + await withTaskGroup(of: Void.self) { group in |
| 56 | + // Concurrent pushes |
| 57 | + for i in 0..<pushCount { |
| 58 | + group.addTask { |
| 59 | + cache.push(Self.makeSignal(id: "\(i)")) |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + // Concurrent pops (some will return empty arrays, that's fine) |
| 64 | + for _ in 0..<50 { |
| 65 | + group.addTask { |
| 66 | + _ = cache.pop() |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + await group.waitForAll() |
| 71 | + } |
| 72 | + |
| 73 | + // Drain remaining signals |
| 74 | + var totalPopped = 0 |
| 75 | + var batch = cache.pop() |
| 76 | + while !batch.isEmpty { |
| 77 | + totalPopped += batch.count |
| 78 | + batch = cache.pop() |
| 79 | + } |
| 80 | + |
| 81 | + // We should have popped some signals (exact count varies due to concurrency) |
| 82 | + // The key assertion is that we don't crash or corrupt data |
| 83 | + #expect(cache.count() == 0, "Cache should be empty after draining") |
| 84 | + } else { |
| 85 | + print("skipping test on incompatible OS") |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + |
| 90 | + /// Validates pop() correctly handles concurrent access without data races. |
| 91 | + /// Without barrier on pop(), concurrent calls can corrupt the array. |
| 92 | + /// Run multiple iterations to increase probability of catching race condition. |
| 93 | + @Test |
| 94 | + func pop_isThreadSafe() async { |
| 95 | + if #available(iOS 16, macOS 13, tvOS 16, visionOS 1, watchOS 9, *) { |
| 96 | + for iteration in 0..<10 { |
| 97 | + let cache = SignalCache<SignalPostBody>(logHandler: nil) |
| 98 | + let signalCount = 200 |
| 99 | + |
| 100 | + for i in 0..<signalCount { |
| 101 | + cache.push(Self.makeSignal(id: "\(iteration)_\(i)")) |
| 102 | + } |
| 103 | + |
| 104 | + let allPopped = await withTaskGroup(of: [SignalPostBody].self, returning: [[SignalPostBody]].self) { group in |
| 105 | + for _ in 0..<20 { |
| 106 | + group.addTask { |
| 107 | + cache.pop() |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + var collected: [[SignalPostBody]] = [] |
| 112 | + for await batch in group { |
| 113 | + collected.append(batch) |
| 114 | + } |
| 115 | + return collected |
| 116 | + } |
| 117 | + |
| 118 | + let totalPopped = allPopped.flatMap { $0 }.count |
| 119 | + let remaining = cache.count() |
| 120 | + |
| 121 | + #expect( |
| 122 | + totalPopped + remaining == signalCount, |
| 123 | + "Iteration \(iteration): Total signals (popped + remaining) should equal original count" |
| 124 | + ) |
| 125 | + } |
| 126 | + } else { |
| 127 | + print("skipping test on incompatible OS") |
| 128 | + } |
| 129 | + |
| 130 | + } |
| 131 | + |
| 132 | + // MARK: - Helpers |
| 133 | + |
| 134 | + private static func makeSignal(id: String) -> SignalPostBody { |
| 135 | + SignalPostBody( |
| 136 | + receivedAt: Date(), |
| 137 | + appID: UUID().uuidString, |
| 138 | + clientUser: id, |
| 139 | + sessionID: id, |
| 140 | + type: "test", |
| 141 | + floatValue: nil, |
| 142 | + payload: [:], |
| 143 | + isTestMode: "true" |
| 144 | + ) |
| 145 | + } |
| 146 | +} |
0 commit comments