Repository navigation
Description
Background
Asyncband currently provides two nearby but different contracts:
oneshottransfers one value from one sender to one receiver;OnceCellstores one initialized value, with initialization driven through the cell API.
Neither directly models one producer completing a result that can be observed by multiple independent waiters, including waiters created after completion. This pattern is known as Deferred in Cats Effect, Promise in ZIO, and CompletableDeferred in Kotlin coroutines.
The primitive is useful when one operation publishes a handshake result, negotiated metadata, configuration, or initialization outcome to several dependent operations. It does not run that operation and does not spawn tasks; it only stores and distributes its eventual result.
Tracked by #218.
Proposed minimum contract
The API should separate producer and observer capabilities, provisionally called Completer<T> and Completion<T>:
- there is one completion capability and a cloneable observer capability;
- the value can be completed exactly once;
- completion wakes all current observers;
- observers created or awaited after completion immediately see the same value;
- cancelling one wait only unsubscribes that waiter;
- dropping the completer without a value transitions observers to an explicit closed state rather than leaving them pending forever;
- the primitive remains runtime agnostic and makes progress only through explicit calls, drop, and polling.
The final module and type names remain an API decision. Completion describes the mechanism without importing JavaScript's full Promise scheduling and chaining expectations.
Design considerations
Shared value representation
A value cannot be moved independently into multiple observers without an ownership policy. The main options are:
- store
Arc<T>internally and returnArc<T>, avoiding aClonebound but exposing shared ownership; - return a borrow tied to the observer handle, which is allocation-efficient but complicates owned futures and lifetimes;
- require
T: Clonewhen awaiting, which keeps returned values ordinary but excludes non-cloneable results and makes wake cost depend on observer count; or - return a dedicated guard that dereferences to
T, hiding but not eliminating shared storage.
This choice is observable and must be settled before implementation. Requiring T: Clone on the primitive itself should be avoided unless a concrete API benefit justifies it.
Producer cardinality
A single non-cloneable completer makes the producer role clear and gives completer drop an unambiguous closed transition. A cloneable completer would support racing producers, but then closure could occur only after every producer is dropped and the API would overlap more heavily with OnceCell::set.
The preferred initial direction is one non-cloneable completer. complete(value) should report failure and return ownership of value if another completion has already won or no observers remain, rather than silently discarding it.
Completion payload versus transport error
The primitive should store an arbitrary T. Callers can choose T = Result<V, E> when completion itself represents success or failure. Closure caused by dropping the completer is transport state and must remain distinct from a user-provided error value.
Observer lifecycle
Completion<T> should be cloneable. Dropping one observer must not affect other observers or erase an already completed value. The issue should decide whether dropping all observers lets the completer detect disconnection and recover a submitted value, mirroring channel-style producer feedback, or whether completion remains valid without current observers.
Cancellation and waiter cleanup
A pending wait is cancel safe: dropping it removes or invalidates only its waiter registration. Completion racing with cancellation must result in either that waiter receiving the shared result or being cleanly removed, with no lost wake-up and no stale waker retained indefinitely.
Relationship with existing primitives
OnceCell may provide useful storage concepts, but shared completion adds a wait-only capability, explicit producer closure, and multi-observer wake-up semantics. oneshot may provide endpoint and error naming patterns, but changing oneshot to clone its receiver would alter its ownership contract. The new primitive should therefore remain nominally distinct even if it reuses internal machinery.
Key trade-offs
Arc<T>or a guard versus borrowed output versusT: Clone.- A single completer with simple closure semantics versus multiple racing completers.
- Channel-style disconnected feedback versus completion that remains valid with zero current observers.
- Reusing
OnceCellor oneshot internals versus a small dedicated state machine. - Returning a named wait future versus an
async fn, especially for owned and cancellation-safe variants.
Non-goals
The first version should not include:
- task spawning or execution ownership;
- promise chaining, callbacks, executors, or microtask scheduling;
- reset or reuse after completion;
- progress updates or multiple values;
- built-in timeout, retry, or cancellation of the producer's work;
- implicit error aggregation.
Acceptance criteria
- Producer and observer capabilities are distinct and documented.
- Exactly one value can win completion, and losing completion attempts preserve ownership of their value.
- Every current and future observer receives the same completed result under the selected ownership model.
- Dropping the completer before completion produces a documented closed result.
- Cancelling or dropping one observer does not affect other observers and does not leak its waker.
- Races among completion, completer drop, observer drop, and waiter cancellation have deterministic regression tests.
- The distinction from
oneshotandOnceCellis documented with examples. - No executor, timer, or runtime-specific dependency is introduced.
- Repository build, test, lint, and formatting workflows pass through
cargo x.
Activity
QwQBiG commentedon Aug 29, 2026
Hi @tisonkun! Thanks again for merging #233 and for encouraging me to explore another async primitive :P
I’d like to work on this issue. The shared-state,
WaitSet, cancellation-safety, and waker-lifecycle concerns are closely related to what I learned while implementingwatch.For the shared-value ownership choice, I plan to store and return
Arc<T>, avoiding aT: Clonebound and following the owning-snapshot approach already used bywatch. For the implementation, I’ll follow the establishedWaitSetand lock-safety patterns from #233 and #234 while keeping the new primitive nominally distinct fromoneshotandOnceCell.I'll take this one then! I’d be happy to adjust the ownership model if you prefer a different direction. ^w^
tisonkun commentedon Aug 29, 2026
@QwQBiG Go ahead!
Actually I may review once more on the
Arc<T>return value ofwatch. Basically a primitive expose basic contract while users can decide on their own whether or not to clone, or wrap inArc.But I didn't deep dive into that so perhaps your design is more proper. You may take a look at OnceMap's (maybe singleflight?) history about some historical design examples on the
Clonebound.BTW, we have
oneshotthat can have similar semantics to "one-shot completion". So examples showing where this new shared one-shot completion primitive outperforms other primitives would be appreciated.QwQBiG commentedon Aug 29, 2026
Thanks for the pointer! I went through the
OnceMaphistory again :POnceMapneeds owned clones because its entries can be removed, and its docs suggestV = Arc<T>when cloning the underlying value would be expensive. #109 also removed the unrelatedK: Clonebound once it was no longer necessary.Completion<T>has a simpler lifetime story: once completed, its value is never replaced or removed, and an observer keeps the shared storage alive. Sowait(&self) -> Result<&T, WaitError>can expose the stored value directly without forcing eitherArc<T>orT: Clone. Callers can then borrow it, clone it when useful, or chooseT = Arc<U>when they need an owned shared result.I'll keep #222 focused on that contract. A fresh pair of eyes from you on watch would be chef's kiss — that'd really round things out. ^w^
And yes, I’ll add a small fan-out example with multiple existing observers plus a late observer. It should make the difference from
oneshotconcrete: reproducing that contract withoneshotwould require one channel per observer and manual distribution.