diff --git a/Evolution/NNNN-share.md b/Evolution/NNNN-share.md new file mode 100644 index 00000000..494c0e7f --- /dev/null +++ b/Evolution/NNNN-share.md @@ -0,0 +1,187 @@ +# Share + +## Introduction + +Many of the AsyncSequence adopting types only permit a one singular consumption. However there are many times that the same produced values are useful in more than one place. Out of that mechanism there are a few approaches to share, distribute, and broadcast those values. This proposal will focus on one concept; sharing. Sharing is where each consumption independently can make forward progress and get the same values but do not replay from the beginning of time. + +## Motivation + +There are many potential usages for the sharing concept of AsyncSequences. + +One such example is the case where a source of data as an asynchronous sequence needs to be consumed by updating UI, logging, and additionally a network connection. This particular case does not matter on which uses but instead that those uses are independent of each other. It would not be expected for networking to block or delay the updates to UI, nor should logging. This example case also illustrates that the isolation of each side might be different and that some of the sides may not tolerate coalescing or dropping values. + +There are many other use cases that have been requested for this family of algorithms. Since the release of AsyncAlgorithms it has perhaps been the most popularly requested set of behaviors as additions to the package. + +## Proposed solution + +AsyncAlgorithms will introduce a new extension function on AsyncSequence that will provide a shareable asynchronous sequence that will produce the same values upon iteration from multiple instances of it's AsyncIterator. Those iterations can take place in multiple isolations. + +When values from a differing isolation cannot be coalesced, the two options available are either awaiting (an exertion of back-pressure across the sequences) or buffering (an internal back-pressure to a buffer). Replaying the values from the beginning of the creation of the sequence is a distinctly different behavior that should be considered a different use case. This then leaves the behavioral characteristic of this particular operation of share as; sharing a buffer of values started from the initialization of a new iteration of the sequence. Control over that buffer should then have options to determine the behavior, similar to how AsyncStream allows that control. It should have options to be unbounded, buffering the oldest count of elements, or buffering the newest count of elements. + +It is critical to identify that this is one algorithm in the family of algorithms for sharing values. It should not attempt to solve all behavioral requirements but instead serve a common set of them that make cohesive sense together. This proposal is not mutually exclusive to the other algorithms in the sharing family. + +## Detailed design + +A new extension will be added to return a `Sendable` `AsyncSequence`. This extension will take a buffering policy to identify how the buffer will be handled when iterations do not consume at the same rate. + +The `Sendable` annotation identifies to the developer that this sequence can be shared and stored in an existental `any`. + +```swift +extension AsyncSequence where Element: Sendable { + public func share( + bufferingPolicy: AsyncBufferSequencePolicy = .bounded(1) + ) -> some AsyncSequence & Sendable +} +``` + +The buffer internally to the share algorithm will only extend back to the furthest element available but there will only be a singular buffer shared across all iterators. This ensures that with the application of the buffering policy the storage size is as minimal as possible while still allowing all iterations to avoid dropping values and keeping the memory usage in check. The signature reuses the existing `AsyncBufferSequencePolicy` type to specify the behavior around buffering either responding to how it should limit emitting to the buffer or what should happen when the buffer is exceeded. + +## Runtime Behavior + +The runtime behaviors fall into a few categories; ordering, iteration isolation, cancellation, and lifetimes. To understand the beahviors there are a terms useful to define. Each creation of the AsyncIterator of the sequence and invocation of next will be referred to a side of the share iteration. The back pressure to the system to fetch a new element or termination is refered to as demand. The limit which is the pending gate for awaiting until the buffer has been serviced used for the `AsyncBufferSequencePolicy.bounded(_ : Int)` policy. The last special definition is that of the extent which is specifically in this case the lifetime of the asynchronous sequence itself. + +When the underlying type backing the share algorithm is constructed a new extent is created; this is used for tracking the reference lifetime under the hood and is used to both house the iteration but also to identify the point at which no more sides can be constructed. When no more sides can be constructed and no sides are left to iterate then the backing iteration is canceled. This prevents any un-referenced task backing the iteration to not be leaked by the algorith itself. + +That construction then creates an initial shared state and buffer. No task is started initially; it is only upon the first demand that the task backing the iteration is started; this means on the first call to next a task is spun up servicing all potential sides. The order of which the sides are serviced is not specified and cannot be relied upon, however the order of delivery within a side is always guarenteed to be ordered. The singular task servicing the iteration will be the only place holding any sort of iterator from the base `AsyncSequence`; so that iterator is isolated and not sent from one isolation to another. That iteration first awaits any limit availability and then awaits for a demand given by a side. After-which it then awaits an element or terminal event from the iterator and enqueues the elements to the buffer. + +The buffer itself is only held in one location, each side however has a cursor index into that buffer and when values are consumed it adjusts the indexes accordingly; leaving the buffer usage only as big as the largest deficit. This means that new sides that are started post initial start up will not have a "replay" effect; that is a similar but distinct algorithm and is not addressed by this proposal. Any buffer size sensitive systems that wish to adjust behavior should be aware that specifying a policy is a suggested step. However in common usage similar to other such systems servicing desktop and mobile applications the common behavior is often unbounded. Alternatively desktop or mobile applications will often want `.bounded(1)` since that enforces the slowest consumption to drive the forward progress at most 1 buffered element. All of the use cases have a reasonable default of `.bounded(1)`; mobile, deskop, and server side uses. Leaving this as the default parameter keeps the progressive disclosure of the beahviors - such that the easiest thing to write is correct for all uses, and then more advanced control can be adjusted by passing in a specific policy. This default argument diverges slightly from AsyncStream, but follows a similar behavior to that of Combine's `share`. + +As previously stated, the isolation of the iteration of the upstream/base AsyncSequence is to a detached task, this ensures that individual sides can have independent cancellation. Those cancellations will have the effect of remvoing that side from the shared iteration and cleaning up accordingly (including adjusting the trimming of the internal buffer). + +Representing concurrent access is difficult to express all potential examples but there are a few cases included with this proposal to illustrate some of the behaviors. If a more comprehensive behavioral analysis is needed, it is strongly suggested to try out the pending pull request to identify how specific behaviors work. Please keep in mind that the odering between tasks is not specified, only the order within one side of iteration. + +Practically this all means that a given iteration may be "behind" another and can eventually catch up (provided it is within the buffer limit). + +```swift +let exampleSource = [0, 1, 2, 3, 4].async.share(bufferingPolicy: .unbounded) + +let t1 = Task { + for await element in exampleSource { + if element == 0 { + try? await Task.sleep(for: .seconds(1)) + } + print("Task 1", element) + } +} + +let t2 = Task { + for await element in exampleSource { + if element == 3 { + try? await Task.sleep(for: .seconds(1)) + } + print("Task 2", element) + } +} + +await t1.value +await t2.value + +``` + +This example will print a possible ordering of the following: + +``` +Task 2 0 +Task 2 1 +Task 2 2 +Task 1 0 +Task 2 3 +Task 2 4 +Task 1 1 +Task 1 2 +Task 1 3 +Task 1 4 +``` + +The order of the interleaving of the prints are not guaranteed; however the order of the elements per iteration is. Likewise in this buffering case it is guaranteed that all values are represented in the output. + +If the creation were instead altered to the following: + +```swift +let exampleSource = [0, 1, 2, 3, 4].async.share(bufferingPolicy: .bufferingLatest(2)) +``` + +The output would print the possible ordering of: + +``` +Task 2 0 +Task 2 1 +Task 2 2 +Task 1 0 +Task 2 4 +Task 1 3 +Task 1 4 +``` + +Some values are dropped due to the buffering policy, but eventually they reach consistency. Which similarly works for the following: + +``` +let exampleSource = [0, 1, 2, 3, 4].async.share(bufferingPolicy: .bufferingOldest(2)) +``` + +``` +Task 2 0 +Task 2 1 +Task 2 2 +Task 1 0 +Task 2 4 +Task 1 1 +Task 1 2 +``` + +However in this particular case the newest values are the dropped elements. + +The `.bounded(N)` policy enforces consumption to prevent any side from being beyond a given amount away from other sides' consumption. + +```swift +let exampleSource = [0, 1, 2, 3, 4].async.share(bufferingPolicy: .bounded(1)) + +let t1 = Task { + for await element in exampleSource { + if element == 0 { + try? await Task.sleep(for: .seconds(1)) + } + print("Task 1", element) + } +} + +let t2 = Task { + for await element in exampleSource { + if element == 3 { + try? await Task.sleep(for: .seconds(1)) + } + print("Task 2", element) + } +} + +await t1.value +await t2.value +``` + +Will have a potential ordering output of: + +``` +Task 2 0 +Task 2 1 +Task 1 0 +Task 1 1 +Task 2 2 +Task 1 2 +Task 1 3 +Task 1 4 +Task 2 3 +Task 2 4 +``` + +In that example output Task 2 can get element 0 and 1 but must await until task 1 has caught up to the specified buffering. This limit means that no additional iteration (and no values are then dropped) is made until the buffer count is below the specified value. + + +## Effect on API resilience + +This is an additive API and no existing systems are changed, however it will introduce a few new types that will need to be maintained as ABI interfaces. Since the intent of this is to provide a mechanism to store AsyncSequences to a shared context the type must be exposed as ABI (for type sizing). + +## Alternatives considered + +It has been considered that the buffering policy would be nested inside the `AsyncShareSequence` type. However since this seems to be something that will be useful for other types it makes sense to use an existing type from a top level type. However if it is determined that a general form of a buffering policy would require additional behaviors this might be a debatable placement to move back to an interior type similar to AsyncStream. + + diff --git a/Package.swift b/Package.swift index c97097b4..b34c676a 100644 --- a/Package.swift +++ b/Package.swift @@ -4,34 +4,11 @@ import PackageDescription import CompilerPluginSupport // Availability Macros -let availabilityTags = [Availability("AsyncAlgorithms")] -let versionNumbers = ["1.0"] -// Availability Macro Utilities -enum OSAvailability: String { - // This should match the package's deployment target - case initialIntroduction = "macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0" - case pending = "macOS 9999, iOS 9999, tvOS 9999, watchOS 9999" - // Use 10000 for future availability to avoid compiler magic around - // the 9999 version number but ensure it is greater than 9999 - case future = "macOS 10000, iOS 10000, tvOS 10000, watchOS 10000" -} - -struct Availability { - let name: String - let osAvailability: OSAvailability - - init(_ name: String, availability: OSAvailability = .initialIntroduction) { - self.name = name - self.osAvailability = availability - } -} - -let availabilityMacros: [SwiftSetting] = versionNumbers.flatMap { version in - availabilityTags.map { - .enableExperimentalFeature("AvailabilityMacro=\($0.name) \(version):\($0.osAvailability.rawValue)") - } -} +let availabilityMacros: [SwiftSetting] = [ + .enableExperimentalFeature("AvailabilityMacro=AsyncAlgorithms 1.0:macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0"), + .enableExperimentalFeature("AvailabilityMacro=AsyncAlgorithms 1.1:macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0"), +] let package = Package( name: "swift-async-algorithms", diff --git a/Sources/AsyncAlgorithms/AsyncShareSequence.swift b/Sources/AsyncAlgorithms/AsyncShareSequence.swift new file mode 100644 index 00000000..9367f678 --- /dev/null +++ b/Sources/AsyncAlgorithms/AsyncShareSequence.swift @@ -0,0 +1,693 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import Synchronization +import DequeModule + +@available(AsyncAlgorithms 1.1, *) +extension AsyncSequence where Element: Sendable, Self: SendableMetatype, AsyncIterator: SendableMetatype { + /// Creates a shared async sequence that allows multiple concurrent iterations over a single source. + /// + /// The `share` method transforms an async sequence into a shareable sequence that can be safely + /// iterated by multiple concurrent tasks. This is useful when you want to broadcast elements from + /// a single source to multiple consumers without duplicating work or creating separate iterations. + /// + /// Each element from the source sequence is delivered to all active iterators. + /// Elements are buffered according to the specified buffering policy to handle timing differences + /// between consumers. + /// + /// The base sequence is iterated in it's own task to ensure that cancellation is not polluted from + /// one side of iteration to another. + /// + /// ## Example Usage + /// + /// ```swift + /// let numbers = [1, 2, 3, 4, 5].share.map { + /// try? await Task.sleep(for: .seconds(1)) + /// return $0 + /// } + /// + /// let shared = numbers.share() + /// + /// // Multiple tasks can iterate concurrently + /// let consumer1 = Task { + /// for await value in shared { + /// print("Consumer 1: \(value)") + /// } + /// } + /// + /// let consumer2 = Task { + /// for await value in shared { + /// print("Consumer 2: \(value)") + /// } + /// } + /// + /// await consumer1.value + /// await consumer2.value + /// ``` + /// + /// - Parameter bufferingPolicy: The policy controlling how elements are enqueued to the shared buffer. Defaults to `.bounded(1)`. + /// - `.bounded(n)`: Limits the buffer to `n` elements, applying backpressure to the source when that limit is reached + /// - `.bufferingOldest(n)`: Keeps the oldest `n` elements, discarding newer ones when full + /// - `.bufferingNewest(n)`: Keeps the newest `n` elements, discarding older ones when full + /// - `.unbounded`: Allows unlimited buffering (use with caution) + /// + /// - Returns: A sendable async sequence that can be safely shared across multiple concurrent tasks. + /// + public func share(bufferingPolicy: AsyncBufferSequencePolicy = .bounded(1)) -> some AsyncSequence & Sendable { + // The iterator is transferred to the isolation of the iterating task + // this has to be done "unsafely" since we cannot annotate the transfer + // however since iterating an AsyncSequence types twice has been defined + // as invalid and one creation of the iterator is virtually a consuming + // operation so this is safe at runtime. + // The general principal of `.share()` is to provide a mecahnism for non- + // shared AsyncSequence types to be shared. The parlance for those is + // that the base AsyncSequence type is not Sendable. If the iterator + // is not marked as `nonisolated(unsafe)` the compiler will claim that + // the value is "Capture of 'iterator' with non-Sendable type 'Self.AsyncIterator' in a '@Sendable' closure;" + // Since the closure returns a disconnected non-sendable value there is no + // distinct problem here and the compiler just needs to be informed + // that the diagnostic is overly pessimistic. + nonisolated(unsafe) let iterator = makeAsyncIterator() + return AsyncShareSequence( { + iterator + }, bufferingPolicy: bufferingPolicy) + } +} + +// An async sequence that enables safe concurrent sharing of a single source sequence. +// +// `AsyncShareSequence` wraps a base async sequence and allows multiple concurrent iterators +// to consume elements from the same source. It handles all the complexity of coordinating +// between multiple consumers, buffering elements, and managing the lifecycle of the underlying +// iteration. +// +// ## Key Features +// +// **Single Source Iteration**: The base sequence's iterator is created and consumed only once +// **Concurrent Safe**: Multiple tasks can safely iterate simultaneously +// **Configurable Buffering**: Supports various buffering strategies for different use cases +// **Automatic Cleanup**: Properly manages resources and cancellation across all consumers +// +// ## Internal Architecture +// +// The implementation uses several key components: +// `Side`: Represents a single consumer's iteration state +// `Iteration`: Coordinates all consumers and manages the shared buffer +// `Extent`: Manages the overall lifecycle and cleanup +// +// This type is typically not used directly; instead, use the `share()` method on any +// async sequence that meets the sendability requirements. +@available(AsyncAlgorithms 1.1, *) +struct AsyncShareSequence: Sendable where Base.Element: Sendable, Base: SendableMetatype, Base.AsyncIterator: SendableMetatype { + // Represents a single consumer's connection to the shared sequence. + // + // Each iterator of the shared sequence creates its own `Side` instance, which tracks + // that consumer's position in the shared buffer and manages its continuation for + // async iteration. The `Side` automatically registers itself with the central + // `Iteration` coordinator and cleans up when deallocated. + // + // ## Lifecycle + // + // **Creation**: Automatically registers with the iteration coordinator + // **Usage**: Tracks buffer position and manages async continuations + // **Cleanup**: Automatically unregisters and cancels pending operations on deinit + final class Side { + // Tracks the state of a single consumer's iteration. + // + // - `continuation`: The continuation waiting for the next element (nil if not waiting) + // - `position`: The consumer's current position in the shared buffer + struct State { + var continuation: UnsafeContinuation, Never>? + var position = 0 + + // Creates a new state with the position adjusted by the given offset. + // + // This is used when the shared buffer is trimmed to maintain correct + // relative positioning for this consumer. + // + // - Parameter adjustment: The number of positions to subtract from the current position + // - Returns: A new `State` with the adjusted position + func offset(_ adjustment: Int) -> State { + State(continuation: continuation, position: position - adjustment) + } + } + + let iteration: Iteration + let id: Int + + init(_ iteration: Iteration) { + self.iteration = iteration + id = iteration.registerSide() + } + + deinit { + iteration.unregisterSide(id) + } + + func next(isolation actor: isolated (any Actor)?) async throws(Failure) -> Element? { + try await iteration.next(isolation: actor, id: id) + } + } + + // The central coordinator that manages the shared iteration state. + // + // `Iteration` is responsible for: + // Managing the single background task that consumes the source sequence + // Coordinating between multiple consumer sides + // Buffering elements according to the specified policy + // Handling backpressure and flow control + // Managing cancellation and cleanup + // + // ## Thread Safety + // + // All operations are synchronized using a `Mutex` to ensure thread-safe access + // to the shared state across multiple concurrent consumers. + final class Iteration: Sendable { + // Represents the state of the background task that consumes the source sequence. + // + // The iteration task goes through several states during its lifecycle: + // `pending`: Initial state, holds the factory to create the iterator + // `starting`: Transitional state while the task is being created + // `running`: Active state with a running background task + // `cancelled`: Terminal state when the iteration has been cancelled + enum IteratingTask { + case pending(@Sendable () -> sending Base.AsyncIterator) + case starting + case running(Task) + case cancelled + + var isStarting: Bool { + switch self { + case .starting: true + default: false + } + } + + func cancel() { + switch self { + case .running(let task): + task.cancel() + default: + break + } + } + } + // The complete shared state for coordinating all aspects of the shared iteration. + // + // This state is protected by a mutex and contains all the information needed + // to coordinate between multiple consumers, manage buffering, and control + // the background iteration task. + struct State: Sendable { + // Defines how elements are stored and potentially discarded in the shared buffer. + // + // `unbounded`: Store all elements without limit (may cause memory growth) + // `bufferingOldest(Int)`: Keep only the oldest N elements, ignore newer ones when full + // `bufferingNewest(Int)`: Keep only the newest N elements, discard older ones when full + enum StoragePolicy: Sendable { + case unbounded + case bufferingOldest(Int) + case bufferingNewest(Int) + } + + var generation = 0 + var sides = [Int: Side.State]() + var iteratingTask: IteratingTask + private(set) var buffer = Deque() + private(set) var finished = false + private(set) var failure: Failure? + var cancelled = false + var limit: UnsafeContinuation? + var demand: UnsafeContinuation? + + let storagePolicy: StoragePolicy + + init(_ iteratorFactory: @escaping @Sendable () -> sending Base.AsyncIterator, bufferingPolicy: AsyncBufferSequencePolicy) { + self.iteratingTask = .pending(iteratorFactory) + switch bufferingPolicy.policy { + case .bounded: self.storagePolicy = .unbounded + case .bufferingOldest(let bound): self.storagePolicy = .bufferingOldest(bound) + case .bufferingNewest(let bound): self.storagePolicy = .bufferingNewest(bound) + case .unbounded: self.storagePolicy = .unbounded + } + } + + // Removes elements from the front of the buffer that all consumers have already processed. + // + // This method finds the minimum position across all active consumers and removes + // that many elements from the front of the buffer. It then adjusts all consumer + // positions to account for the removed elements, maintaining their relative positions. + // + // This optimization prevents the buffer from growing indefinitely when all consumers + // are keeping pace with each other. + mutating func trimBuffer() { + if let minimumIndex = sides.values.map({ $0.position }).min(), minimumIndex > 0 { + buffer.removeFirst(minimumIndex) + sides = sides.mapValues { + $0.offset(minimumIndex) + } + } + } + + // Private state machine transitions for the emission of a given value. + // + // This method ensures the continuations are properly consumed when emitting values + // and returns those continuations for resumption. + private mutating func _emit(_ value: T, limit: Int) -> (T, UnsafeContinuation?, UnsafeContinuation?, Bool) { + let belowLimit = buffer.count < limit || limit == 0 + defer { + if belowLimit { + self.limit = nil + } + demand = nil + } + if case .cancelled = iteratingTask { + return (value, belowLimit ? self.limit : nil, demand, true) + } else { + return (value, belowLimit ? self.limit : nil, demand, false) + } + } + + // Internal state machine transitions for the emission of a given value. + // + // This method ensures the continuations are properly consumed when emitting values + // and returns those continuations for resumption. + // + // If no limit is specified it interprets that as an unbounded limit. + mutating func emit(_ value: T, limit: Int?) -> (T, UnsafeContinuation?, UnsafeContinuation?, Bool) { + return _emit(value, limit: limit ?? .max) + } + + // Adds an element to the buffer according to the configured storage policy. + // + // The behavior depends on the storage policy: + // **Unbounded**: Always appends the element + // **Buffering Oldest**: Appends only if under the limit, otherwise ignores the element + // **Buffering Newest**: Appends if under the limit, otherwise removes the oldest and appends + // + // - Parameter element: The element to add to the buffer + mutating func enqueue(_ element: Element) { + let count = buffer.count + + switch storagePolicy { + case .unbounded: + buffer.append(element) + case .bufferingOldest(let limit): + if count < limit { + buffer.append(element) + } + case .bufferingNewest(let limit): + if count < limit { + buffer.append(element) + } else if count > 0 { + buffer.removeFirst() + buffer.append(element) + } + } + } + + mutating func finish() { + finished = true + } + + mutating func fail(_ error: Failure) { + finished = true + failure = error + } + } + + let state: Mutex + let limit: Int? + + init(_ iteratorFactory: @escaping @Sendable () -> sending Base.AsyncIterator, bufferingPolicy: AsyncBufferSequencePolicy) { + state = Mutex(State(iteratorFactory, bufferingPolicy: bufferingPolicy)) + switch bufferingPolicy.policy { + case .bounded(let limit): + self.limit = limit + default: + self.limit = nil + } + } + + func cancel() { + let (task, limitContinuation, demand, cancelled) = state.withLock { state -> (IteratingTask?, UnsafeContinuation?, UnsafeContinuation?, Bool) in + if state.sides.count == 0 { + defer { + state.iteratingTask = .cancelled + state.cancelled = true + } + return state.emit(state.iteratingTask, limit: limit) + } else { + state.cancelled = true + return state.emit(nil, limit: limit) + } + } + task?.cancel() + limitContinuation?.resume(returning: cancelled) + demand?.resume() + } + + func registerSide() -> Int { + state.withLock { state in + defer { state.generation += 1 } + state.sides[state.generation] = Side.State() + return state.generation + } + } + + func unregisterSide(_ id: Int) { + let (side, continuation, cancelled, iteratingTaskToCancel) = state.withLock { state -> (Side.State?, UnsafeContinuation?, Bool, IteratingTask?) in + let side = state.sides.removeValue(forKey: id) + state.trimBuffer() + let cancelRequested = state.sides.count == 0 && state.cancelled + if let limit, state.buffer.count < limit { + defer { state.limit = nil } + if case .cancelled = state.iteratingTask { + return (side, state.limit, true, nil) + } else { + defer { + if cancelRequested { + state.iteratingTask = .cancelled + } + } + return (side, state.limit, false, cancelRequested ? state.iteratingTask : nil) + } + } else { + if case .cancelled = state.iteratingTask { + return (side, nil, true, nil) + } else { + defer { + if cancelRequested { + state.iteratingTask = .cancelled + } + } + return (side, nil, false, cancelRequested ? state.iteratingTask : nil) + } + } + } + if let continuation { + continuation.resume(returning: cancelled) + } + if let side { + side.continuation?.resume(returning: .success(nil)) + } + if let iteratingTaskToCancel { + iteratingTaskToCancel.cancel() + } + } + + func iterate() async -> Bool { + if let limit { + let cancelled = await withUnsafeContinuation { (continuation: UnsafeContinuation) in + let (resume, cancelled) = state.withLock { state -> (UnsafeContinuation?, Bool) in + if state.buffer.count >= limit { + state.limit = continuation + if case .cancelled = state.iteratingTask { + return (nil, true) + } else { + return (nil, false) + } + } else { + assert(state.limit == nil) + if case .cancelled = state.iteratingTask { + return (continuation, true) + } else { + return (continuation, false) + } + } + } + if let resume { + resume.resume(returning: cancelled) + } + } + if cancelled { + return false + } + } + + // await a demand + await withUnsafeContinuation { (continuation: UnsafeContinuation) in + let hasPendingDemand = state.withLock { state in + for (_, side) in state.sides { + if side.continuation != nil { + return true + } + } + state.demand = continuation + return false + } + if hasPendingDemand { + continuation.resume() + } + } + return state.withLock { state in + switch state.iteratingTask { + case .cancelled: + return false + default: + return true + } + } + } + + func cancel(id: Int) { + unregisterSide(id) // doubly unregistering is idempotent but has a side effect of emitting nil if present + } + + struct Resumption { + let continuation: UnsafeContinuation, Never> + let result: Result + + func resume() { + continuation.resume(returning: result) + } + } + + func emit(_ result: Result) { + let (resumptions, limitContinuation, demandContinuation, cancelled) = state.withLock { state -> ([Resumption], UnsafeContinuation?, UnsafeContinuation?, Bool) in + var resumptions = [Resumption]() + switch result { + case .success(let element): + if let element { + state.enqueue(element) + } else { + state.finish() + } + case .failure(let failure): + state.fail(failure) + } + for (id, side) in state.sides { + if let continuation = side.continuation { + if side.position < state.buffer.count { + resumptions.append(Resumption(continuation: continuation, result: .success(state.buffer[side.position]))) + state.sides[id]?.position += 1 + state.sides[id]?.continuation = nil + } else if state.finished { + state.sides[id]?.continuation = nil + if let failure = state.failure { + resumptions.append(Resumption(continuation: continuation, result: .failure(failure))) + } else { + resumptions.append(Resumption(continuation: continuation, result: .success(nil))) + } + } + } + } + state.trimBuffer() + return state.emit(resumptions, limit: limit) + } + + if let limitContinuation { + limitContinuation.resume(returning: cancelled) + } + if let demandContinuation { + demandContinuation.resume() + } + for resumption in resumptions { + resumption.resume() + } + } + + private func nextIteration(_ id: Int) async -> Result.Element?, AsyncShareSequence.Failure> { + return await withTaskCancellationHandler { + await withUnsafeContinuation { continuation in + let (res, limitContinuation, demandContinuation, cancelled) = state.withLock { state -> (Result?, UnsafeContinuation?, UnsafeContinuation?, Bool) in + guard let side = state.sides[id] else { + return state.emit(.success(nil), limit: limit) + } + if side.position < state.buffer.count { + // There's an element available at this position + let element = state.buffer[side.position] + state.sides[id]?.position += 1 + state.trimBuffer() + return state.emit(.success(element), limit: limit) + } else { + // Position is beyond the buffer + if let failure = state.failure { + return state.emit(.failure(failure), limit: limit) + } else if state.finished { + return state.emit(.success(nil), limit: limit) + } else { + state.sides[id]?.continuation = continuation + return state.emit(nil, limit: limit) + } + } + } + if let limitContinuation { + limitContinuation.resume(returning: cancelled) + } + if let demandContinuation { + demandContinuation.resume() + } + if let res { + continuation.resume(returning: res) + } + } + } onCancel: { + cancel(id: id) + } + } + + private func iterationLoop(factory: @Sendable () -> sending Base.AsyncIterator) async { + var iterator = factory() + do { + while await iterate() { + if let element = try await iterator.next() { + emit(.success(element)) + } else { + emit(.success(nil)) + } + } + } catch { + emit(.failure(error as! Failure)) + } + } + + func next(isolation actor: isolated (any Actor)?, id: Int) async throws(Failure) -> Element? { + let (factory, cancelled) = state.withLock { state -> ((@Sendable () -> sending Base.AsyncIterator)?, Bool) in + switch state.iteratingTask { + case .pending(let factory): + state.iteratingTask = .starting + return (factory, false) + case .cancelled: + return (nil, true) + default: + return (nil, false) + } + } + if cancelled { return nil } + if let factory { + let task: Task + // for the fancy dance of availability and canImport see the comment on the next check for details +#if canImport(_Concurrency, _version: 6.2) + if #available(macOS 26.0, iOS 26.0, tvOS 26.0, visionOS 26.0, *) { + task = Task(name: "Share Iteration") { [factory, self] in + await iterationLoop(factory: factory) + } + } else { + task = Task.detached(name: "Share Iteration") { [factory, self] in + await iterationLoop(factory: factory) + } + } +#else + task = Task.detached(name: "Share Iteration") { [factory, self] in + await iterationLoop(factory: factory) + } +#endif + // Known Issue: there is a very small race where the task may not get a priority escalation during startup + // this unfortuantely cannot be avoided since the task should ideally not be formed within the critical + // region of the state. Since that could lead to potential deadlocks in low-core-count systems. + // That window is relatively small and can be revisited if a suitable proof of safe behavior can be + // determined. + state.withLock { state in + precondition(state.iteratingTask.isStarting) + state.iteratingTask = .running(task) + } + } + + // withTaskPriorityEscalationHandler is only available for the '26 releases and the 6.2 version of + // the _Concurrency library. This menas for Darwin based OSes we have to have a fallback at runtime, + // and for non-darwin OSes we need to verify against the ability to import that version. + // Using this priority escalation means that the base task can avoid being detached. +#if canImport(_Concurrency, _version: 6.2) + if #available(macOS 26.0, iOS 26.0, tvOS 26.0, visionOS 26.0, *) { + return try await withTaskPriorityEscalationHandler { + return await nextIteration(id) + } onPriorityEscalated: { old, new in + let task = state.withLock { state -> Task? in + switch state.iteratingTask { + case .running(let task): + return task + default: + return nil + } + } + task?.escalatePriority(to: new) + }.get() + } else { + return try await nextIteration(id).get() + } +#else + return try await nextIteration(id).get() +#endif + + } + } + + // Manages the lifecycle of the shared iteration. + // + // `Extent` serves as the ownership boundary for the shared sequence. When the + // `AsyncShareSequence` itself is deallocated, the `Extent` ensures that the + // background iteration task is properly cancelled and all resources are cleaned up. + // + // This design allows multiple iterators to safely reference the same underlying + // iteration coordinator while ensuring proper cleanup when the shared sequence + // is no longer needed. + final class Extent: Sendable { + let iteration: Iteration + + init(_ iteratorFactory: @escaping @Sendable () -> sending Base.AsyncIterator, bufferingPolicy: AsyncBufferSequencePolicy) { + iteration = Iteration(iteratorFactory, bufferingPolicy: bufferingPolicy) + } + + deinit { + iteration.cancel() + } + } + + let extent: Extent + + + init(_ iteratorFactory: @escaping @Sendable () -> sending Base.AsyncIterator, bufferingPolicy: AsyncBufferSequencePolicy) { + extent = Extent(iteratorFactory, bufferingPolicy: bufferingPolicy) + } +} + +@available(AsyncAlgorithms 1.1, *) +extension AsyncShareSequence: AsyncSequence { + typealias Element = Base.Element + typealias Failure = Base.Failure + + struct Iterator: AsyncIteratorProtocol { + let side: Side + + init(_ iteration: Iteration) { + side = Side(iteration) + } + + mutating func next(isolation actor: isolated (any Actor)?) async throws(Failure) -> Element? { + try await side.next(isolation: actor) + } + } + + func makeAsyncIterator() -> Iterator { + Iterator(extent.iteration) + } +} diff --git a/Tests/AsyncAlgorithmsTests/Support/GatedSequence.swift b/Tests/AsyncAlgorithmsTests/Support/GatedSequence.swift index 9167a4c1..160b0db0 100644 --- a/Tests/AsyncAlgorithmsTests/Support/GatedSequence.swift +++ b/Tests/AsyncAlgorithmsTests/Support/GatedSequence.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// public struct GatedSequence { + public typealias Failure = Never let elements: [Element] let gates: [Gate] var index = 0 @@ -44,6 +45,15 @@ extension GatedSequence: AsyncSequence { await gate.enter() return element } + + public mutating func next(isolation actor: isolated (any Actor)?) async throws(Never) -> Element? { + guard gatedElements.count > 0 else { + return nil + } + let (element, gate) = gatedElements.removeFirst() + await gate.enter() + return element + } } public func makeAsyncIterator() -> Iterator { diff --git a/Tests/AsyncAlgorithmsTests/TestShare.swift b/Tests/AsyncAlgorithmsTests/TestShare.swift new file mode 100644 index 00000000..372c9cd4 --- /dev/null +++ b/Tests/AsyncAlgorithmsTests/TestShare.swift @@ -0,0 +1,576 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import AsyncAlgorithms +import Synchronization + +@available(macOS 15.0, *) +final class TestShare: XCTestCase { + + // MARK: - Basic Functionality Tests + + func test_share_delivers_elements_to_multiple_consumers() async { + let source = [1, 2, 3, 4, 5] + let shared = source.async.share() + let gate1 = Gate() + let gate2 = Gate() + + async let consumer1 = Task.detached { + var results = [Int]() + var iterator = shared.makeAsyncIterator() + gate1.open() + await gate2.enter() + while let value = await iterator.next(isolation: nil) { + results.append(value) + } + return results + } + + async let consumer2 = Task.detached { + var results = [Int]() + var iterator = shared.makeAsyncIterator() + gate2.open() + await gate1.enter() + while let value = await iterator.next(isolation: nil) { + results.append(value) + } + return results + } + let results1 = await consumer1.value + let results2 = await consumer2.value + + XCTAssertEqual(results1, [1, 2, 3, 4, 5]) + XCTAssertEqual(results2, [1, 2, 3, 4, 5]) + } + + func test_share_with_single_consumer() async { + let source = [1, 2, 3, 4, 5] + let shared = source.async.share() + + var results = [Int]() + for await value in shared { + results.append(value) + } + + XCTAssertEqual(results, [1, 2, 3, 4, 5]) + } + + func test_share_with_empty_source() async { + let source = [Int]() + let shared = source.async.share() + + var results = [Int]() + for await value in shared { + results.append(value) + } + + XCTAssertEqual(results, []) + } + + // MARK: - Buffering Policy Tests + + func test_share_with_bounded_buffering() async { + var gated = GatedSequence([1, 2, 3, 4, 5]) + let shared = gated.share(bufferingPolicy: .bounded(2)) + + let results1 = Mutex([Int]()) + let results2 = Mutex([Int]()) + let gate1 = Gate() + let gate2 = Gate() + + let consumer1 = Task { + var iterator = shared.makeAsyncIterator() + gate1.open() + await gate2.enter() + // Consumer 1 reads first element + if let value = await iterator.next(isolation: nil) { + results1.withLock { $0.append(value) } + } + // Delay to allow consumer 2 to get ahead + try? await Task.sleep(for: .milliseconds(10)) + // Continue reading + while let value = await iterator.next(isolation: nil) { + results1.withLock { $0.append(value) } + } + } + + let consumer2 = Task { + var iterator = shared.makeAsyncIterator() + gate2.open() + await gate1.enter() + // Consumer 2 reads all elements quickly + while let value = await iterator.next(isolation: nil) { + results2.withLock { $0.append(value) } + } + } + + // Advance the gated sequence to make elements available + gated.advance() // 1 + gated.advance() // 2 + gated.advance() // 3 + gated.advance() // 4 + gated.advance() // 5 + + await consumer1.value + await consumer2.value + + // Both consumers should receive all elements + XCTAssertEqual(results1.withLock { $0 }.sorted(), [1, 2, 3, 4, 5]) + XCTAssertEqual(results2.withLock { $0 }.sorted(), [1, 2, 3, 4, 5]) + } + + func test_share_with_unbounded_buffering() async { + let source = [1, 2, 3, 4, 5] + let shared = source.async.share(bufferingPolicy: .unbounded) + + let results1 = Mutex([Int]()) + let results2 = Mutex([Int]()) + let gate1 = Gate() + let gate2 = Gate() + + let consumer1 = Task { + var iterator = shared.makeAsyncIterator() + gate2.open() + await gate1.enter() + while let value = await iterator.next(isolation: nil) { + results1.withLock { $0.append(value) } + // Add some delay to consumer 1 + try? await Task.sleep(for: .milliseconds(1)) + } + } + + let consumer2 = Task { + var iterator = shared.makeAsyncIterator() + gate1.open() + await gate2.enter() + while let value = await iterator.next(isolation: nil) { + results2.withLock { $0.append(value) } + } + } + + await consumer1.value + await consumer2.value + + XCTAssertEqual(results1.withLock { $0 }, [1, 2, 3, 4, 5]) + XCTAssertEqual(results2.withLock { $0 }, [1, 2, 3, 4, 5]) + } + + func test_share_with_bufferingLatest_buffering() async { + var gated = GatedSequence([1, 2, 3, 4, 5]) + let shared = gated.share(bufferingPolicy: .bufferingLatest(2)) + + let fastResults = Mutex([Int]()) + let slowResults = Mutex([Int]()) + let gate1 = Gate() + let gate2 = Gate() + + let fastConsumer = Task.detached { + var iterator = shared.makeAsyncIterator() + gate2.open() + await gate1.enter() + while let value = await iterator.next(isolation: nil) { + fastResults.withLock { $0.append(value) } + } + } + + let slowConsumer = Task.detached { + var iterator = shared.makeAsyncIterator() + gate1.open() + await gate2.enter() + // Read first element immediately + if let value = await iterator.next(isolation: nil) { + slowResults.withLock { $0.append(value) } + } + // Add significant delay to let buffer fill up and potentially overflow + try? await Task.sleep(for: .milliseconds(50)) + // Continue reading remaining elements + while let value = await iterator.next(isolation: nil) { + slowResults.withLock { $0.append(value) } + } + } + + // Release all elements quickly to test buffer overflow behavior + gated.advance() // 1 + try? await Task.sleep(for: .milliseconds(5)) + gated.advance() // 2 + try? await Task.sleep(for: .milliseconds(5)) + gated.advance() // 3 + try? await Task.sleep(for: .milliseconds(5)) + gated.advance() // 4 + try? await Task.sleep(for: .milliseconds(5)) + gated.advance() // 5 + + await fastConsumer.value + await slowConsumer.value + + let slowResultsArray = slowResults.withLock { $0 } + + // Slow consumer should get the first element plus the latest elements in buffer + // With bufferingLatest(2), when buffer overflows, older elements are discarded + XCTAssertTrue(slowResultsArray.count >= 1, "Should have at least the first element") + XCTAssertEqual(slowResultsArray.first, 1, "Should start with first element") + + // Due to bufferingLatest policy, the slow consumer should favor newer elements + // It may miss some middle elements but should get the latest ones + let receivedSet = Set(slowResultsArray) + XCTAssertTrue(receivedSet.isSubset(of: Set([1, 2, 3, 4, 5]))) + + // With bufferingLatest, we expect the slow consumer to get newer elements + // when it finally catches up after the delay + if slowResultsArray.count > 1 { + let laterElements = Set(slowResultsArray.dropFirst()) + // Should have received some of the later elements (4, 5) due to bufferingLatest + XCTAssertTrue(laterElements.contains(4) || laterElements.contains(5) || + laterElements.contains(3), + "BufferingLatest should favor keeping newer elements") + } + } + + func test_share_with_bufferingOldest_buffering() async { + var gated = GatedSequence([1, 2, 3, 4, 5]) + let shared = gated.share(bufferingPolicy: .bufferingOldest(2)) + + let fastResults = Mutex([Int]()) + let slowResults = Mutex([Int]()) + let gate1 = Gate() + let gate2 = Gate() + + let fastConsumer = Task { + var iterator = shared.makeAsyncIterator() + gate2.open() + await gate1.enter() + while let value = await iterator.next(isolation: nil) { + fastResults.withLock { $0.append(value) } + } + } + + let slowConsumer = Task { + var iterator = shared.makeAsyncIterator() + gate1.open() + await gate2.enter() + // Read first element immediately + if let value = await iterator.next(isolation: nil) { + slowResults.withLock { $0.append(value) } + } + // Add significant delay to let buffer fill up and potentially overflow + try? await Task.sleep(for: .milliseconds(50)) + // Continue reading remaining elements + while let value = await iterator.next(isolation: nil) { + slowResults.withLock { $0.append(value) } + } + } + + // Release all elements quickly to test buffer overflow behavior + gated.advance() // 1 + try? await Task.sleep(for: .milliseconds(5)) + gated.advance() // 2 + try? await Task.sleep(for: .milliseconds(5)) + gated.advance() // 3 + try? await Task.sleep(for: .milliseconds(5)) + gated.advance() // 4 + try? await Task.sleep(for: .milliseconds(5)) + gated.advance() // 5 + + await fastConsumer.value + await slowConsumer.value + + let slowResultsArray = slowResults.withLock { $0 } + + // Slow consumer should get the first element plus the oldest elements that fit in buffer + // With bufferingOldest(2), when buffer overflows, newer elements are ignored + XCTAssertTrue(slowResultsArray.count >= 1, "Should have at least the first element") + XCTAssertEqual(slowResultsArray.first, 1, "Should start with first element") + + // Due to bufferingOldest policy, the slow consumer should favor older elements + let receivedSet = Set(slowResultsArray) + XCTAssertTrue(receivedSet.isSubset(of: Set([1, 2, 3, 4, 5]))) + + // With bufferingOldest, when the buffer is full, newer elements are ignored + // So the slow consumer should be more likely to receive earlier elements + if slowResultsArray.count > 1 { + let laterElements = Array(slowResultsArray.dropFirst()) + // Should have received earlier elements due to bufferingOldest policy + // Elements 4 and 5 are less likely to be received since they're newer + let hasEarlierElements = laterElements.contains(2) || laterElements.contains(3) + let hasLaterElements = laterElements.contains(4) && laterElements.contains(5) + + // BufferingOldest should favor keeping older elements when buffer is full + // So we should be more likely to see earlier elements than later ones + XCTAssertTrue(hasEarlierElements || !hasLaterElements, + "BufferingOldest should favor keeping older elements over newer ones") + } + } + + // MARK: - Cancellation Tests + + func test_share_cancellation_of_single_consumer() async { + let shared = Indefinite(value: 42).async.share() + + let finished = expectation(description: "finished") + let iterated = expectation(description: "iterated") + + let task = Task { + var firstIteration = false + for await _ in shared { + if !firstIteration { + firstIteration = true + iterated.fulfill() + } + } + finished.fulfill() + } + + // Wait for the task to start iterating + await fulfillment(of: [iterated], timeout: 1.0) + + // Cancel the task + task.cancel() + + // Verify the task finishes + await fulfillment(of: [finished], timeout: 1.0) + } + + func test_share_cancellation_with_multiple_consumers() async { + let shared = Indefinite(value: 42).async.share() + + let consumer1Finished = expectation(description: "consumer1Finished") + let consumer2Finished = expectation(description: "consumer2Finished") + let consumer1Iterated = expectation(description: "consumer1Iterated") + let consumer2Iterated = expectation(description: "consumer2Iterated") + + let consumer1 = Task { + var firstIteration = false + for await _ in shared { + if !firstIteration { + firstIteration = true + consumer1Iterated.fulfill() + } + } + consumer1Finished.fulfill() + } + + let consumer2 = Task { + var firstIteration = false + for await _ in shared { + if !firstIteration { + firstIteration = true + consumer2Iterated.fulfill() + } + } + consumer2Finished.fulfill() + } + + // Wait for both consumers to start + await fulfillment(of: [consumer1Iterated, consumer2Iterated], timeout: 1.0) + + // Cancel only consumer1 + consumer1.cancel() + + // Consumer1 should finish + await fulfillment(of: [consumer1Finished], timeout: 1.0) + + // Consumer2 should still be running, so cancel it too + consumer2.cancel() + await fulfillment(of: [consumer2Finished], timeout: 1.0) + } + + func test_share_cancellation_cancels_source_when_no_consumers() async { + let source = Indefinite(value: 1).async + let shared = source.share() + + let finished = expectation(description: "finished") + let iterated = expectation(description: "iterated") + + let task = Task { + var iterator = shared.makeAsyncIterator() + if await iterator.next(isolation: nil) != nil { + iterated.fulfill() + } + // Task will be cancelled here, so iteration should stop + while await iterator.next(isolation: nil) != nil { + // Continue iterating until cancelled + } + finished.fulfill() + } + + await fulfillment(of: [iterated], timeout: 1.0) + task.cancel() + await fulfillment(of: [finished], timeout: 1.0) + } + + // MARK: - Error Handling Tests + + func test_share_propagates_errors_to_all_consumers() async { + let source = [1, 2, 3, 4, 5].async.map { value in + if value == 3 { + throw TestError.failure + } + return value + } + let shared = source.share() + + let consumer1Results = Mutex([Int]()) + let consumer2Results = Mutex([Int]()) + let consumer1Error = Mutex(nil) + let consumer2Error = Mutex(nil) + let gate1 = Gate() + let gate2 = Gate() + + let consumer1 = Task { + do { + var iterator = shared.makeAsyncIterator() + gate2.open() + await gate1.enter() + while let value = try await iterator.next() { + consumer1Results.withLock { $0.append(value) } + } + } catch { + consumer1Error.withLock { $0 = error } + } + } + + let consumer2 = Task { + do { + var iterator = shared.makeAsyncIterator() + gate1.open() + await gate2.enter() + while let value = try await iterator.next() { + consumer2Results.withLock { $0.append(value) } + } + } catch { + consumer2Error.withLock { $0 = error } + } + } + + await consumer1.value + await consumer2.value + + // Both consumers should receive the first two elements + XCTAssertEqual(consumer1Results.withLock { $0 }, [1, 2]) + XCTAssertEqual(consumer2Results.withLock { $0 }, [1, 2]) + + // Both consumers should receive the error + XCTAssertTrue(consumer1Error.withLock { $0 is TestError }) + XCTAssertTrue(consumer2Error.withLock { $0 is TestError }) + } + + // MARK: - Timing and Race Condition Tests + + func test_share_with_late_joining_consumer() async { + var gated = GatedSequence([1, 2, 3, 4, 5]) + let shared = gated.share(bufferingPolicy: .unbounded) + + let earlyResults = Mutex([Int]()) + let lateResults = Mutex([Int]()) + + // Start early consumer + let earlyConsumer = Task { + var iterator = shared.makeAsyncIterator() + while let value = await iterator.next(isolation: nil) { + earlyResults.withLock { $0.append(value) } + } + } + + // Advance some elements + gated.advance() // 1 + gated.advance() // 2 + + // Give early consumer time to consume + try? await Task.sleep(for: .milliseconds(10)) + + // Start late consumer + let lateConsumer = Task { + var iterator = shared.makeAsyncIterator() + while let value = await iterator.next(isolation: nil) { + lateResults.withLock { $0.append(value) } + } + } + + // Advance remaining elements + gated.advance() // 3 + gated.advance() // 4 + gated.advance() // 5 + + await earlyConsumer.value + await lateConsumer.value + + // Early consumer gets all elements + XCTAssertEqual(earlyResults.withLock { $0 }, [1, 2, 3, 4, 5]) + // Late consumer only gets elements from when it joined + XCTAssertTrue(lateResults.withLock { $0.count <= 5 }) + } + + func test_share_iterator_independence() async { + let source = [1, 2, 3, 4, 5] + let shared = source.async.share() + + var iterator1 = shared.makeAsyncIterator() + var iterator2 = shared.makeAsyncIterator() + + // Both iterators should independently get the same elements + let value1a = await iterator1.next(isolation: nil) + let value2a = await iterator2.next(isolation: nil) + + let value1b = await iterator1.next(isolation: nil) + let value2b = await iterator2.next(isolation: nil) + + XCTAssertEqual(value1a, 1) + XCTAssertEqual(value2a, 1) + XCTAssertEqual(value1b, 2) + XCTAssertEqual(value2b, 2) + } + + // MARK: - Memory and Resource Management Tests + + func test_share_cleans_up_when_all_consumers_finish() async { + let source = [1, 2, 3] + let shared = source.async.share() + + var results = [Int]() + for await value in shared { + results.append(value) + } + + XCTAssertEqual(results, [1, 2, 3]) + + // Create a new iterator after the sequence finished + var newIterator = shared.makeAsyncIterator() + let value = await newIterator.next(isolation: nil) + XCTAssertNil(value) // Should return nil since source is exhausted + } + + func test_share_multiple_sequential_consumers() async { + let source = [1, 2, 3, 4, 5] + let shared = source.async.share(bufferingPolicy: .unbounded) + + // First consumer + var results1 = [Int]() + for await value in shared { + results1.append(value) + } + + // Second consumer (starting after first finished) + var results2 = [Int]() + for await value in shared { + results2.append(value) + } + + XCTAssertEqual(results1, [1, 2, 3, 4, 5]) + XCTAssertEqual(results2, []) // Should be empty since source is exhausted + } +} + +// MARK: - Helper Types + +fileprivate enum TestError: Error, Equatable { + case failure +}