Calling debounce is causing async stream to get cancelled early

Hello I was recently testing out the debounce method and I noticed some strange behavior that I didn't expect. It looks the async stream I have set up is getting cancelled early when I'm calling the debounce method but it doesn't do that without the debounce method. This seems like a bug but I'm curious to hear others thoughts on it.

Here is the reproducer I have. Thanks!

@Test
func debounceCancellation() async {
    enum Status {
        case inProgress
        case completed
    }

    let drawStatues = AsyncStream<Status> { continuation in
        Task {
            continuation.yield(.inProgress)
            try! await Task.sleep(for: .seconds(2))
            continuation.yield(.completed)
        }

        continuation.onTermination = { termination in
            switch termination {
            case .cancelled:
                print("Cancelled!")
            case .finished:
                print("Finished!")
            @unknown default:
                fatalError("Unknown case")
            }
        }
    }

    _ = await drawStatues
        .debounce(for: .seconds(2))
        .first(where: { @Sendable in $0 == .completed })

    // Current behavior when using debounce:
    // cancelled -> end
    //
    // Expected behavior without using debounce:
    // end -> cancelled

    print("End")
}

Haven’t looked much into it yet, but my hunch is that the consumer task (AsyncStream) is cancelled when the stream completes, i.e., when the predicate is satisfied.

Yeah, it looks that way but why does that behavior only happen when I call debounce?

My bad, I wasn’t very clear. I assume when the debounce sequence finishes, the internal task running the base sequence gets cancelled, which triggers termination in the AsyncStream. It does seem a little odd to me that Debounce is implemented this way. I think we could improve this. I would open a GitHub issue here: Issues · apple/swift-async-algorithms · GitHub

Oh I see, interesting. Ok sounds good I made an issue here: Calling debounce is causing async stream to get cancelled early · Issue #410 · apple/swift-async-algorithms · GitHub. Thank you!