Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Tests / XToolTests / ConcurrentMapTests.swift

ConcurrentMapTests.swift227 lines · 8.3 KiBRaw
1import Testing
2@testable import XUtils
3
4@Suite(.timeLimit(.minutes(1)))
5struct ConcurrentMapTests {
6 @Test(arguments: [[], [7], [3, 1, 3, 2], Array(0..<10)], [nil, 1, 2, Int.max] as [Int?])
7 func nonThrowingTransform(input: [Int], maxConcurrency: Int?) async {
8 // No `try` is needed when the transform cannot throw.
9 let result = await input.concurrentMap(maxConcurrency: maxConcurrency) { String($0 * 2) }
10 #expect(result == input.map { String($0 * 2) })
11 }
12
13 @Test func emptyInputDoesNotCallTransform() async throws {
14 let result = try await [Int]().concurrentMap { _ throws(MapError) -> Int in
15 Issue.record("An empty sequence must not invoke the transform")
16 throw .failed(0)
17 }
18 #expect(result.isEmpty)
19 }
20
21 @Test func singlePassSequence() async {
22 var next = 0
23 let input = AnySequence(AnyIterator<Int> {
24 defer { next += 1 }
25 return next < 4 ? next : nil
26 })
27 #expect(input.underestimatedCount == 0)
28
29 let result = await input.concurrentMap(maxConcurrency: 1) { $0 * 2 }
30
31 #expect(result == [0, 2, 4, 6])
32 }
33
34 @Test func optionalResults() async {
35 let result = await (0..<4).concurrentMap { value -> Int? in
36 value.isMultiple(of: 2) ? nil : value
37 }
38 #expect(result == [nil, 1, nil, 3])
39 }
40
41 @Test func nestedOptionalResults() async {
42 let input: [Int??] = [.none, .some(.none), .some(.some(3))]
43 let result = await input.concurrentMap { $0 }
44 #expect(result == input)
45 }
46
47 @Test(arguments: [2, 4, Int.max])
48 func concurrentExecutionPreservesInputOrder(maxConcurrency: Int) async {
49 let started = AsyncStream<Int>.makeStream()
50 let finished = AsyncStream<Int>.makeStream()
51 let gates = (0..<4).map { _ in AsyncStream<Void>.makeStream() }
52 let task = Task {
53 await (0..<4).concurrentMap(maxConcurrency: maxConcurrency) { value in
54 started.continuation.yield(value)
55 for await _ in gates[value].stream {}
56 finished.continuation.yield(value)
57 return value * 2
58 }
59 }
60 defer { task.cancel() }
61
62 // Fill the concurrency window before allowing any transform to finish.
63 let initialCount = min(maxConcurrency, 4)
64 var starts = started.stream.makeAsyncIterator()
65 var startedValues: [Int] = []
66 for _ in 0..<initialCount {
67 if let value = await starts.next() {
68 startedValues.append(value)
69 }
70 }
71 #expect(startedValues.sorted() == Array(0..<initialCount))
72
73 // Finish the newest transform first, keeping the first one suspended while work is replenished.
74 var finishes = finished.stream.makeAsyncIterator()
75 var pending = Set(startedValues)
76 var next = initialCount
77 while let value = pending.max() {
78 pending.remove(value)
79 gates[value].continuation.finish()
80 #expect(await finishes.next() == value)
81 if next < 4 {
82 #expect(await starts.next() == next)
83 pending.insert(next)
84 next += 1
85 }
86 }
87 #expect(await task.value == [0, 2, 4, 6])
88 }
89
90 @Test(arguments: [1, 2, 3, 25, 100, Int.max])
91 func limitsConcurrentTransforms(maxConcurrency: Int) async {
92 let checkpoints = AsyncStream<Int>.makeStream()
93 let gates = (0..<25).map { _ in AsyncStream<Void>.makeStream() }
94 let task = Task {
95 // Both closures below run in the producer task. Only immutable snapshots
96 // cross to the test through the checkpoint stream.
97 var submitted = 0
98 let input = AnySequence(AnyIterator<Int> {
99 guard submitted < gates.count else { return nil }
100 defer { submitted += 1 }
101 return submitted
102 })
103 return await input._concurrentMap(maxConcurrency: maxConcurrency) { value in
104 for await _ in gates[value].stream {}
105 return value * 2
106 } willWaitForNext: {
107 checkpoints.continuation.yield(submitted)
108 }
109 }
110 defer { task.cancel() }
111
112 // No transform can finish yet. The hook proves submission has reached
113 // group.next(), rather than merely being paused by the scheduler.
114 let initialCount = min(maxConcurrency, gates.count)
115 var waits = checkpoints.stream.makeAsyncIterator()
116 #expect(await waits.next() == initialCount)
117
118 // Each completed transform frees exactly one slot. Check the next submission
119 // boundary before releasing another transform, including while draining.
120 for value in gates.indices {
121 gates[value].continuation.finish()
122 #expect(await waits.next() == min(initialCount + value + 1, gates.count))
123 }
124 let result = await withTaskCancellationHandler {
125 await task.value
126 } onCancel: {
127 task.cancel()
128 }
129
130 #expect(result == (0..<25).map { $0 * 2 })
131 }
132
133 @Test @MainActor func actorIsolatedTransform() async {
134 var visited: [Int] = []
135 let result = await (0..<4).concurrentMap(maxConcurrency: 2) { @MainActor value in
136 MainActor.assertIsolated()
137 visited.append(value)
138 return value * 2
139 }
140
141 #expect(visited.sorted() == [0, 1, 2, 3])
142 #expect(result == [0, 2, 4, 6])
143 }
144
145 @Test func preservesTypedError() async {
146 // This signature also checks that concurrentMap preserves the error type.
147 func map() async throws(MapError) -> [Int] {
148 try await [42].concurrentMap { value throws(MapError) -> Int in
149 throw .failed(value)
150 }
151 }
152
153 await #expect(throws: MapError.failed(42)) {
154 try await map()
155 }
156 }
157
158 @Test func failureCancelsUnfinishedTransforms() async {
159 let started = AsyncStream<Int>.makeStream()
160 let failureGate = AsyncStream<Void>.makeStream()
161 let siblingGate = AsyncStream<Void>.makeStream()
162 let cancelled = AsyncStream<Int>.makeStream()
163 let task = Task {
164 try await (0..<10).concurrentMap(maxConcurrency: 3) { value async throws(MapError) -> Int in
165 #expect(value < 3, "A failure must not schedule the remaining inputs")
166 started.continuation.yield(value)
167 if value == 1 {
168 for await _ in failureGate.stream {}
169 throw .failed(value)
170 }
171 // This stream only finishes when the task is cancelled.
172 for await _ in siblingGate.stream {}
173 #expect(Task.isCancelled)
174 cancelled.continuation.yield(value)
175 return value
176 }
177 }
178 defer { task.cancel() }
179
180 var starts = started.stream.makeAsyncIterator()
181 for _ in 0..<3 {
182 _ = await starts.next()
183 }
184 failureGate.continuation.finish()
185
186 await #expect(throws: MapError.failed(1)) {
187 try await withTaskCancellationHandler {
188 try await task.value
189 } onCancel: {
190 // Let the suite's time limit break a regression in sibling cancellation.
191 task.cancel()
192 }
193 }
194 // The task group must wait for both cancelled transforms to exit.
195 cancelled.continuation.finish()
196 var cancelledValues: [Int] = []
197 for await value in cancelled.stream {
198 cancelledValues.append(value)
199 }
200 #expect(cancelledValues.sorted() == [0, 2])
201 }
202
203 @Test func parentCancellationReachesTransforms() async {
204 let started = AsyncStream<Void>.makeStream()
205 let gate = AsyncStream<Void>.makeStream()
206 let task = Task {
207 try await [1].concurrentMap { _ in
208 started.continuation.yield(())
209 for await _ in gate.stream {}
210 try Task.checkCancellation()
211 }
212 }
213 defer { task.cancel() }
214
215 var starts = started.stream.makeAsyncIterator()
216 _ = await starts.next()
217 task.cancel()
218
219 await #expect(throws: CancellationError.self) {
220 try await task.value
221 }
222 }
223
224 private enum MapError: Error, Equatable {
225 case failed(Int)
226 }
227}