Short-Circuit Async Boolean: Cancel Early, Return Fast
Data Structure DesignModel answerLast updated
Implement an async function that resolves true the moment any concurrent task returns true, cancelling all remaining work immediately.
Background
Async runtimes let you fire off many tasks simultaneously, but the standard library's high-level helpers often don't give you fine-grained control over what happens when one result changes the answer for everyone else. This problem asks you to build exactly that kind of control.
Task
Write an async function first_true(tasks) that accepts a list of zero-argument async callables, each of which resolves to a bool. Run all of them concurrently, then:
- Return
Trueas soon as any task resolves to a truthy value. - If a task raises an exception, treat it the same as a
Falseresult — do not let it short-circuit or propagate. - Once a truthy result is observed, cancel every task that is still running before returning. Don't leave dangling work behind.
- If every task finishes without producing a truthy result (including any that raised), return
False.
Signature
async def first_true(tasks: List[Callable[[], Awaitable[bool]]]) -> bool:
pass
Example
tasks = [slow_false, fast_true, very_slow_false]
# slow_false → False after 5 s
# fast_true → True after 1 s
# very_slow_false → False after 10 s
result = await first_true(tasks)
# Returns True after ~1 s.
# slow_false and very_slow_false are cancelled immediately.
Constraints
0 ≤ len(tasks) ≤ 1000- Each element is an independent async callable; calling it returns a fresh coroutine.
- Multiple tasks may finish at roughly the same time — handle that correctly.
- You may use Python's
asynciostandard library.
What to cover in your answer
- How you schedule and monitor the tasks.
- How and when you cancel remaining work, including edge cases like an outer timeout cancelling your function.
- Correctness arguments for the edge cases: empty input, all exceptions, simultaneous truthy results.
- Complexity analysis and any higher-scale alternatives.
- Common mistakes and why they are wrong.
Hints
Hint 1
asyncio.gather resolves everything before you can inspect partial results — look at a primitive that lets you react to each task as it finishes rather than waiting for the whole batch.
Hint 2
Calling cancel() on a task only schedules the cancellation; the task hasn't actually stopped yet. Think about what you need to await afterward, and where that await should live so it runs even if your function exits unexpectedly.
Hint 3
An empty list, a list where every task raises, and the case where your caller imposes a timeout and cancels first_true itself are three separate edge cases — make sure your control flow handles all three without leaking tasks.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core problem is: run N tasks simultaneously, stop as soon as one says yes, and clean up the rest. Python's asyncio gives you the right tool — asyncio.wait with return_when=FIRST_COMPLETED — which wakes you up as soon as at least one task finishes without forcing you to wait for the others.
Clarify the contract first
Three things worth confirming before writing a line of code:
- Input type. Each element is a callable that, when invoked, returns an awaitable. You call
fn()to create a coroutine, then wrap it in a task. Don't confuse this with passing pre-built coroutines or futures. - Exceptions. They count as
False. One reasonable alternative is to re-raise when every task failed and none returned anything; flagging that interpretation shows good judgment even if you go with the simpler path. - Empty input. Nothing can be true, so return
False. This matchesany([])in Python.
Algorithm
- Call
asyncio.create_task(fn())for every callable to start them all immediately. - Loop with
asyncio.wait(pending, return_when=FIRST_COMPLETED). Each iteration hands you adoneset and a shrinkingpendingset. - For each finished task: skip if cancelled or faulted, return
Trueif its result is truthy. - When
pendingempties with no truthy result, returnFalse. - In a
finallyblock, cancel everything still inpendingand thenawait asyncio.gather(*pending, return_exceptions=True)to let cancellations fully unwind.
The finally block is the detail that separates a working solution from a correct one. It fires on three exit paths: an early return True, normal return False, and an outer cancellation (e.g., a caller-imposed timeout). Without it, orphaned tasks keep running invisibly.
Solution
import asyncio
from typing import Awaitable, Callable, List
async def first_true(tasks: List[Callable[[], Awaitable[bool]]]) -> bool:
if not tasks:
return False
# Schedule everything concurrently right away.
pending: set = {asyncio.create_task(fn()) for fn in tasks}
try:
while pending:
done, pending = await asyncio.wait(
pending, return_when=asyncio.FIRST_COMPLETED
)
for task in done:
if task.cancelled():
continue # treat as False
if task.exception() is not None:
continue # failure == False
if task.result():
return True # short-circuit
return False
finally:
# Runs whether we return True, return False, or are cancelled ourselves.
for task in pending:
task.cancel()
if pending:
# Await so tasks finish their cleanup before we exit.
await asyncio.gather(*pending, return_exceptions=True)
Why this is correct
Early exit. FIRST_COMPLETED wakes the loop as soon as at least one task finishes. We inspect every task in that batch, so a truthy result is never delayed past its actual completion time.
Exceptions are safe. Calling task.exception() retrieves and suppresses the stored exception; asyncio won't log "exception was never retrieved." We then move on without propagating it.
Simultaneous truthy results. If several tasks finish truthy in the same event-loop tick, they all land in the same done set. We return True on the first one encountered. Because the event loop is single-threaded there is no data race on pending — this is the "race condition" the problem warns about, and it resolves naturally.
Cancellation is complete. cancel() injects a CancelledError at the task's next await; it is cooperative, not instantaneous. The gather(..., return_exceptions=True) call blocks until every cancelled task has fully unwound and run its own cleanup. Skipping this step produces "Task was destroyed but it is pending" warnings and potential resource leaks.
Complexity
Each asyncio.wait call registers a completion callback on every task in pending, costing O(k) per iteration. In the worst case tasks finish one at a time, giving O(n²) total bookkeeping overhead — negligible for n ≤ 1000.
For very large n, one O(n) alternative: attach add_done_callback to each task once at creation. The callback pushes results into an asyncio.Queue. The main coroutine drains the queue, short-circuits on the first truthy value, and cancels everything on exit. This avoids re-registering callbacks on every wait call.
Edge cases
| Scenario | Behavior |
|---|---|
| Empty list | Returns False immediately, no tasks scheduled |
| All tasks raise | Every task is skipped as a fault; loop exits; returns False |
All tasks return False | Loop drains completely; returns False |
Caller cancels first_true | finally fires, all children cancelled and awaited |
Truthy non-bool (e.g., 1) | if task.result(): catches it; use is True for strict typing |
Common mistakes
Using asyncio.gather for everything. It waits for all tasks to finish before you can act, which defeats the whole point. Unless you pass return_exceptions=True and process results afterward, it also propagates the first exception rather than treating it as False.
Cancelling without awaiting. Calling task.cancel() and returning immediately leaves tasks mid-flight. Always follow up with gather(..., return_exceptions=True).
No finally block. If the caller wraps first_true in asyncio.wait_for and it times out, the outer cancellation bypasses any cleanup you put after the loop. finally is the only reliable place.
Sequential execution. Writing for fn in tasks: result = await fn() gives you no concurrency at all — the whole purpose of the problem is lost.
Using FIRST_EXCEPTION. This aborts asyncio.wait on the first faulted task, which contradicts the contract that exceptions count as False.
Interesting follow-up directions
- Return the index of the winning task. Build a
dict[Task, int]at creation time. If multiple tasks land truthy in the same batch, define a deterministic tie-break (smallest index) and state it explicitly. - Cancellation isn't instantaneous. CPU-bound loops, blocking calls, or
CancelledError-swallowing code can delay or prevent it. In production you'd wrap blocking work inrun_in_executorand document that tasks must not suppressCancelledErrorwithout re-raising. - Bounded concurrency. With 1000 tasks you might want a semaphore to cap simultaneous I/O, while still short-circuiting as soon as a truthy result arrives.