[Pitch] swift-async-algorithms: `debounce(for:maxWait:)`

Hi all,

I'd like to pitch an optional maxWait parameter for debounce in swift-async-algorithms.

Introduction

debounce only emits once its source has been quiet for a full interval. A source that never goes quiet for that long is never emitted, however long it runs. maxWait bounds how long an element can be held back.

Motivation

Consider a traffic study where a roadside sensor reports every passing car and the app keeps a running tally. The study can't be repeated cheaply, so the tally is checkpointed to disk in case the app crashes.

let tallies = detections.reductions(TrafficTally()) { tally, detection in
  tally.adding(detection)
}

for await tally in tallies.debounce(for: .seconds(5)) {
  try await studyStore.save(tally)
}

At night a car passes every few minutes, and each one is checkpointed 5 seconds later. During rush hour a car passes every second or two for hours, so there is never a 5 second gap. Every car restarts the quiescence period, and nothing is checkpointed for the entire rush hour. A crash at the end of it loses all of it, which is exactly what the checkpoint was meant to prevent.

throttle isn't a drop-in replacement. It emits the first element immediately, and the last element of a burst is only emitted if another one follows it (#266), so the final state may never be saved. The starvation of debounce has come up before in #260.

Proposed solution

for await tally in tallies.debounce(for: .seconds(5), maxWait: .seconds(60)) {
  try await studyStore.save(tally)
}

The latest element is emitted after the quiescence period, or once maxWait has elapsed since the first element that has not been emitted yet, whichever comes first. After an emission, the next element starts a new batch.

  • At night nothing changes: each car is checkpointed 5 seconds after it passes.
  • During rush hour the tally is checkpointed at least every 60 seconds, so a crash loses about a minute of counts.
  • When traffic thins out, the final tally is checkpointed after 5 seconds of quiet.
  • There is no leading edge, so a single element still waits for the quiescence period.

Detailed design

New overloads, matching the existing pair. The existing overloads and AsyncDebounceSequence are unchanged.

extension AsyncSequence {
  public func debounce<C: Clock>(
    for interval: C.Instant.Duration,
    maxWait: C.Instant.Duration,
    tolerance: C.Instant.Duration? = nil,
    clock: C
  ) -> AsyncDebounceSequence<Self, C>

  public func debounce(
    for interval: Duration,
    maxWait: Duration,
    tolerance: Duration? = nil
  ) -> AsyncDebounceSequence<Self, ContinuousClock>
}

When an element arrives and no earlier element is waiting, it starts a batch and the instant maxWait later becomes the batch's maximum deadline. Later elements replace the pending element and extend the quiescence deadline, but never past the maximum deadline. If the base sequence finishes the pending element is emitted immediately, and errors are rethrown immediately, both as debounce does today. If maxWait is shorter than interval, elements are emitted after maxWait.

Alternatives considered

  • A trailing-only throttle (RxJS auditTime, lodash throttle(..., { leading: false })). It has no separate quiescence period, so the last value can be held for a full window after the source stops.
  • chunks(ofCount:or:). It also bounds the gap, but delivers every element, whereas debounce delivers only the latest. That's the right choice when each element is a snapshot that supersedes the previous one, such as a running tally.
  • A new operator. It would duplicate the debounce state machine, and an optional parameter shares it.

Prior art

lodash's debounce(fn, wait, { maxWait }) is the closest. As far as I know, Combine, RxJS and Kotlin Flow have no equivalent option on debounce and approximate it with auditTime / sample or batching operators such as bufferTimeout and collect(.byTimeOrCount).

Questions for the community

  1. Is this something you'd want in the package?
  2. Is the name maxWait right, or would you prefer something else?
  3. Should maxWait < interval be allowed (currently it acts as a cap) or rejected with a precondition?
  4. Should the availability match the existing debounce (macOS 13 / iOS 16) or use an AsyncAlgorithms 1.x macro?

Answering point 2, perhaps maxHold is worth considering.