Short-Circuit Concurrent Boolean Tasks
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Write an asynchronous helper any_true(tasks) that launches a batch of asynchronous boolean checks concurrently and resolves to True as soon as the earliest check produces True.
async def any_true(tasks: List[Callable[[], Awaitable[bool]]]) -> bool:
Each element of tasks is a zero-argument async callable returning a bool (or an already-instantiated awaitable/coroutine object that resolves to bool). Your implementation must obey these rules:
- Concurrent execution: Start all entries in
tasksright away on theasyncioevent loop so overall latency is bounded by the fastestTruerather than the sum of runtimes. - Immediate short-circuit & cleanup: As soon as any task resolves to
True, cancel every remaining unfinished task and wait for those cancelled tasks to finish unwinding before returningTrue. Ifany_trueitself is cancelled externally (such as by an outer timeout), cancel and await all still-running child tasks before letting cancellation propagate. - All-
False& empty inputs: ReturnFalseimmediately whentasksis empty, and returnFalsewhen every task finishes without producingTrue(provided the final completing batch did not fail). - Exception semantics & tie-breaking:
- Any exception raised by a task counts as
Falsewhenever at least one other task is still running, or when another task completing on the same event-loop turn returnsTrue. Ensure every completed task's exception is inspected so the runtime never emits unretrieved-exception warnings. - If zero tasks return
Trueand at least one task in the last completing event-loop batch (when no tasks remain pending) raises an exception, re-raise that exception. If multiple tasks in that final batch raise on the same event-loop turn, re-raise the exception belonging to the earliest 0-based index intasks.
- Any exception raised by a task counts as
Examples
Example 1
Input:
Four async health checks [check_cache, check_replica_1, check_replica_2, check_archive]:
- check_cache: finishes at 20 ms -> returns False
- check_replica_1: takes 400 ms -> returns False
- check_replica_2: finishes at 50 ms -> returns True
- check_archive: takes 800 ms -> returns True
Output: True (in roughly 50 ms)
Walk-through: All four tasks begin at 0 ms. At 20 ms, check_cache finishes with False while three checks remain active. At 50 ms, check_replica_2 returns True; any_true cancels check_replica_1 and check_archive, waits for their cleanup to complete, and returns True without waiting 400 ms or 800 ms.
Example 2
Input:
Two async probes [probe_west, probe_east]:
- probe_west: raises ConnectionError("unreachable") at 10 ms
- probe_east: finishes at 60 ms -> returns False
Output: False
Walk-through: When probe_west fails at 10 ms, probe_east is still running, so the error is treated as False. When probe_east completes at 60 ms with False, the final batch finished cleanly without True, so any_true returns False.
Example 3
Input:
Two async probes [probe_fast, probe_slow]:
- probe_fast: finishes at 15 ms -> returns False
- probe_slow: raises TimeoutError("gateway stalled") at 70 ms
Output: Raises TimeoutError("gateway stalled")
Walk-through: probe_fast returns False first. When probe_slow fails at 70 ms, no other tasks are still running and no True was ever observed, so TimeoutError propagates to the caller.
Constraints
0 <= len(tasks) <= 1000- Only Python standard library modules (
asyncio,typing) may be used. - Multiple tasks may finish, return
True, or raise exceptions on the exact same event-loop tick.
Step-by-step walkthrough
Restate the problem and pin down the edge rules
We are given
0to1000asynchronous checks that each eventually resolve toTrue, resolve toFalse, or raise an exception. Two contract details instarter.pyare worth locking down right up front: 1. Callers may pass zero-argument async callables (Callable[[], Awaitable[bool]]) or already-created coroutine/awaitable objects, so we normalize each item by calling it first whencallable(item)is true and awaiting the resulting object. 2. An exception raised while other tasks are still running (or alongside aTruein the same event-loop turn) counts asFalse; only when zero tasks ever returnTrueand the final completing batch contains one or more exceptions do we re-raise the earliest failing task's exception in input order.Overall,
any_true(tasks)must deliver four behaviors: 1. Run concurrently: Schedule every task immediately so latency tracks the fastestTrue, not the sum of task durations. 2. Short-circuit onTrue: Resolve toTrueas soon as any task producesTrue. 3. Cancel leftovers cleanly: OnceTrueis seen (or ifany_trueitself is cancelled externally), cancel every unfinished task and await their cleanup before returning. 4. HandleFalse, empty input, simultaneous completions, and errors: ReturnFalseon[]or when every task finishes withoutTrue(unless the final completing batch raised).Why awaiting tasks one by one fails
A beginner's first instinct with
async/awaitis to loop over the functions andawaiteach one in sequence:async def any_true_sequential(tasks): for fn in tasks: try: if await fn(): return True except Exception: pass return FalseLook at what happens on Example 1 (
check_cache:20 ms -> False,check_replica_1:400 ms -> False,check_replica_2:50 ms -> True,check_archive:800 ms -> True):Sequential loop (wrong — 470 ms): t = 0 ms 20 ms 420 ms 470 ms |-- cache --|----- replica_1 -----|-- rep_2 --| -> returns True at 470 ms! Concurrent execution (goal — 50 ms): t = 0 ms 20 ms 50 ms |-- cache -| (F) |-- replica_1 -----X (cancelled at 50 ms!) |-- replica_2 -----| (returns True at 50 ms -> done!) |-- archive -------X (cancelled at 50 ms!)Awaiting inside a
forloop does not even startcheck_replica_2until bothcheck_cacheandcheck_replica_1finish! With1000tasks that each take1second and returnFalse, a sequential loop takes1000seconds instead of1second. Andasyncio.gather(*tasks)is not enough either, becausegatherwaits until every task finishes (800 msforcheck_archive) instead of returning at50 ms.Key idea: launch all tasks, then wake up on `FIRST_COMPLETED`
In Python
asyncio, calling anasync deffunction only creates a coroutine object — it does not start running yet. Wrapping it inasyncio.create_task(...)registers anasyncio.Taskwith the event loop (the single-threaded scheduler that switches between tasks whenever one pauses at anawait), so allntasks start making progress together.Once all tasks are in a
pendingset, we loop withasyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED):create_task() x n inputs --------------------> pending = {T0, T1, T2, ...} | v await asyncio.wait(pending, FIRST_COMPLETED) / \ v v done = {...} pending = {still running} | any True? ----+---- no ----> overwrite last_error, loop if pending | yes v return True ---> finally: cancel & await remaining `pending` tasksasyncio.waitsleeps until at least one task finishes, then splits the set intodone(tasks that completed on this event-loop step) andpending(tasks still running — the exact set we will need to cancel!).Phase 1: Normalize inputs and schedule every task concurrently
First, write a tiny helper
_run_one(item)soany_trueworks seamlessly whether the caller passes zero-argument async functions (check_replica_2) or already-created coroutine/awaitable objects (check_replica_2()). Doingif callable(item): item = item()inside_run_onehas a bonus safety benefit: if callingitem()raises synchronously before returning a coroutine, that exception is captured safely inside theTaskrather than aborting the setup loop partway through!We also record each task's 0-based position in an
orderdictionary so tie-breaking later is 100% deterministic:async def _run_one(item): """Normalize one input into a coroutine: call zero-arg functions first, then await.""" # Accept both zero-argument async functions and already-created awaitables, # while trapping any immediate call error inside this coroutine's Task. if callable(item): item = item() return await item async def start_all(tasks): # order: dict mapping each asyncio.Task -> its 0-based input index, e.g. {task_a: 0, task_b: 1} order = {} # pending: set of currently running asyncio.Task objects that have not completed yet pending = set() # Phase 1: Schedule every input immediately so all tasks run concurrently on the event loop. for index, item in enumerate(tasks): task = asyncio.create_task(_run_one(item)) order[task] = index pending.add(task) return order, pendingPhase 2: Inspect every task in a completed batch safely
When
await asyncio.wait(...)returns,donecan contain several tasks at once if they finished in the same event-loop tick. Three subtle details make the batch loop rock-solid:- Check
task.cancelled()BEFOREtask.exception(): Inasyncio, callingtask.exception()on a cancelled task raisesCancelledError! Skipping cancelled tasks first avoids that crash, and checkingtask.exception()beforetask.result()prevents a failing task from blowing upany_truewhile other tasks are still running. - Inspect the entire
donebatch inorderbefore returning: Neverreturn Truedirectly inside theforloop! Finishing the loop overdonecallstask.exception()on every failed task in the batch — marking those exceptions as "retrieved" so Python never prints"Task exception was never retrieved"warnings — and sorting byorder.getguarantees we always pick the earliest input error if several tasks fail together. - Overwrite
last_error = batch_errorafter each non-Truebatch: If Task 0 fails at10 mswhile Task 1 is still running,last_errortemporarily holds Task 0's error. When Task 1 finishes withFalseat60 ms,batch_errorisNone, overwritinglast_error = Nonesoany_truereturnsFalse.last_errorstays non-Noneafterwhile pendingonly if the very last batch to finish had an exception and noTrue!
async def wait_for_first_true(pending, order): # last_error holds an exception from the most recent completed batch; # each new batch overwrites it so earlier errors count as False while others still run. last_error = None # Phase 2: Wake up each time one or more tasks finish; guard empty input since wait({}) raises. while pending: done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) found_true = False batch_error = None # Inspect every task in `done` sorted by input order: # 1) retrieves every task's exception so asyncio never logs unretrieved-exception warnings, # 2) picks a deterministic error (earliest input index) when multiple tasks fail together. for task in sorted(done, key=order.get): # Check cancelled() BEFORE exception(), because exception() raises on cancelled tasks. if task.cancelled(): continue error = task.exception() if error is None: if task.result(): found_true = True elif batch_error is None: batch_error = error if found_true: return True last_error = batch_error # Phase 3: All tasks finished with no True; re-raise only if the final batch raised. if last_error is not None: raise last_error return FalseNotice
while pending:also handlestasks = []cleanly (asyncio.wait(set())raisesValueError, so skipping the loop returnsFalseright away).- Check
Phase 3: Cancel remaining tasks and wait for cleanup in `finally`
In
asyncio, callingtask.cancel()does not stop a task instantaneously — it merely schedules anasyncio.CancelledErrorto be injected at that task's nextawaitpoint so itstry / finallyblocks (closing sockets, releasing locks) can run. Ifany_truereturned the instant it calledtask.cancel(), those leftover tasks would still be mid-flight when the caller resumed!Awaiting
asyncio.gather(*tasks, return_exceptions=True)waits until every cancelled task has finished unwinding and quietly absorbs theirCancelledErrors. Placing_cancel_and_wait(pending)insideany_true's ownfinally:block covers every exit path with one line: - Earlyreturn True:pendingholds all unfinished sibling tasks -> all are cancelled and awaited. - All tasks finished (Falseor re-raised error):pendingis empty ->_cancel_and_waitdoes nothing. - Caller cancelsany_true(for example viaasyncio.wait_fortimeout):CancelledErrorinterruptsawait asyncio.wait(...),finallycancels and cleans up all child tasks so no orphan tasks leak, and the timeout propagates cleanly to the caller.async def _cancel_and_wait(tasks): """Request cancellation on every task and wait until all of them finish cleaning up.""" for task in tasks: task.cancel() # task.cancel() only schedules CancelledError for the next event-loop turn; # gather(..., return_exceptions=True) waits for finally blocks and absorbs CancelledError. if tasks: await asyncio.gather(*tasks, return_exceptions=True)Walk through the examples and the exception rule
First trace Example 1 (
[check_cache (20 ms, False), check_replica_1 (400 ms, False), check_replica_2 (50 ms, True), check_archive (800 ms, True)]):t = 0 ms Phase 1 creates Tasks c0, r1, r2, ar -> pending = {c0, r1, r2, ar}; enters asyncio.wait t = 20 ms c0 finishes -> done = {c0}, pending = {r1, r2, ar} c0.result() is False -> found_true = False, last_error = None -> loop continues t = 50 ms r2 finishes -> done = {r2}, pending = {r1, ar} r2.cancelled() is False, r2.exception() is None, r2.result() is True -> found_true = True `return True` triggers `finally: await _cancel_and_wait({r1, ar})` r1.cancel() and ar.cancel() fire -> gather(r1, ar, return_exceptions=True) awaits cleanup t ≈ 50 ms r1 and ar exit via CancelledError -> any_true returns True (saved 750 ms!)Now contrast Example 2 (
probe_westfails early,probe_eastfinishesFalselater) with Example 3 (probe_fastfinishesFalseearly,probe_slowfails last):Example 2: probe_west fails at 10 ms, probe_east returns False at 60 ms t = 10 ms: done = {west}, pending = {east} -> batch_error = ConnectionError -> last_error = ConnectionError t = 60 ms: done = {east}, pending = {} -> batch_error = None -> last_error = None Loop ends with pending = {} and last_error = None -> returns False! Example 3: probe_fast returns False at 15 ms, probe_slow fails last at 70 ms t = 15 ms: done = {fast}, pending = {slow} -> batch_error = None -> last_error = None t = 70 ms: done = {slow}, pending = {} -> batch_error = TimeoutError -> last_error = TimeoutError Loop ends with pending = {} and last_error = TimeoutError -> raises TimeoutError!Complete solution
from typing import Awaitable, Callable, List import asyncio async def _run_one(item): """Normalize one input into a coroutine: call zero-arg functions first, then await.""" # Accept both zero-argument async functions and already-created awaitables, # while trapping any immediate call error inside this coroutine's Task. if callable(item): item = item() return await item async def _cancel_and_wait(tasks): """Request cancellation on every task and wait until all of them finish cleaning up.""" for task in tasks: task.cancel() # task.cancel() only schedules CancelledError for the next event-loop turn; # gather(..., return_exceptions=True) waits for finally blocks and absorbs CancelledError. if tasks: await asyncio.gather(*tasks, return_exceptions=True) async def any_true(tasks: List[Callable[[], Awaitable[bool]]]) -> bool: # order: dict mapping each asyncio.Task -> its 0-based input index, e.g. {task_a: 0, task_b: 1} order = {} # pending: set of currently running asyncio.Task objects that have not completed yet pending = set() # Phase 1: Schedule every input immediately so all tasks run concurrently on the event loop. for index, item in enumerate(tasks): task = asyncio.create_task(_run_one(item)) order[task] = index pending.add(task) try: # last_error holds an exception from the most recent completed batch; # each new batch overwrites it so earlier errors count as False while others still run. last_error = None # Phase 2: Wake up each time one or more tasks finish; guard empty input since wait({}) raises. while pending: done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) found_true = False batch_error = None # Inspect every task in `done` sorted by input order: # 1) retrieves every task's exception so asyncio never logs unretrieved-exception warnings, # 2) picks a deterministic error (earliest input index) when multiple tasks fail together. for task in sorted(done, key=order.get): # Check cancelled() BEFORE exception(), because exception() raises on cancelled tasks. if task.cancelled(): continue error = task.exception() if error is None: if task.result(): found_true = True elif batch_error is None: batch_error = error if found_true: return True last_error = batch_error # Phase 3: All tasks finished with no True; re-raise only if the final batch raised. if last_error is not None: raise last_error return False finally: # Always cancel and await leftover tasks — both on early True return and on outer timeout/cancel. await _cancel_and_wait(pending)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine sending four scouts down four mountain trails at the exact same time, each carrying a walkie-talkie to check whether their trail leads out of the valley. Suppose Scout 0 hits a quick dead end at 20 ms, Scout 2 radios back "Found the exit!" at 50 ms, and Scouts 1 and 3 are still trekking along 400 ms and 800 ms trails. You do not wait around for the slower scouts — the instant Scout 2 confirms the exit at 50 ms, you radio Scouts 1 and 3 to turn around and come back so nobody wastes energy, and you report True. Only if every scout reports a dead end do you report False.
Two obvious coding approaches fall short here:
1. A sequential for loop (if await fn(): return True) makes Scout 2 wait at the trailhead until both Scout 0 (20 ms) and Scout 1 (400 ms) finish, turning a 50 ms answer into a 470 ms wait.
2. asyncio.gather(*tasks) launches all scouts together, yet insists on waiting 800 ms for the slowest scout before returning anything, and aborts on an early exception instead of treating early exceptions as False.
Instead, we wrap every input in an asyncio.Task (a scheduled handle that lets Python's event loop — its single-threaded async coordinator — advance all coroutines, or pauseable async functions, concurrently) and loop with asyncio.wait(pending, return_when=FIRST_COMPLETED). Walk through Example 1 ([check_cache (20 ms, False), check_replica_1 (400 ms, False), check_replica_2 (50 ms, True), check_archive (800 ms, True)]):
- At t = 0 ms, all four tasks start running together inside pending.
- At t = 20 ms, check_cache finishes False; three tasks remain in pending, so the loop waits again.
- At t = 50 ms, check_replica_2 finishes True, waking asyncio.wait with pending = {check_replica_1, check_archive}.
- Seeing True, any_true returns True, triggering its finally block to cancel check_replica_1 and check_archive and await their cleanup — finishing in ~50 ms with zero leaked background tasks.
Complexity
- Wall-clock latency: Equal to the duration of the fastest task that returns
True(plus one event-loop turn to cancel and clean up remaining tasks), or the slowest task when no task returnsTrue, because allntasks execute concurrently rather than sequentially. - CPU time:
O(n²)in the worst case across all event-loop wakeups, wherenislen(tasks). Each call toasyncio.wait(pending, ...)attaches and later removes a completion callback on each of thepcurrently pending tasks (O(p)work); if allntasks returnFalseone by one at distinct times, that totalsn + (n - 1) + ... + 1 = O(n²)callback steps (about500,000tiny pointer operations for the max constraintn = 1000, taking only a few milliseconds), plusO(n log n)total across batches for sortingdonesets. - Space:
O(n)memory, because we hold at mostnasyncio.Taskobjects inpendingandnindex entries in theorderdictionary at once.
Edge cases
- Empty input (
tasks = []): ReturnsFalseimmediately; thewhile pending:check avoids callingasyncio.wait(set()), which would raiseValueError. - Single task that raises: Because
pendingbecomes empty right away (no other tasks remain running), its exception is re-raised rather than swallowed asFalse. - Early exception followed by a slower
FalseorTrue: As in Example 2, an early exception setslast_error, which is either short-circuited by a laterTrue(return True) or overwritten byNonewhen a slowerFalsebatch finishes (return False). - Multiple tasks finishing in the same event-loop step:
doneholds all of them; if any returnedTrue,Truewins (even alongside exceptions in the same batch), and ifpendingis now empty with multiple exceptions, sortingdonebyorder.getre-raises the earliest one in input order while still retrieving every exception soasynciologs no warnings. - Caller passes already-created coroutine objects or
Tasks:_run_onecheckscallable(item)so raw awaitables work directly alongside zero-argument async functions. - Caller times out or cancels
any_trueexternally: Wrapping the loop intry / finallyguarantees all still-running child tasks are cancelled and awaited beforeCancelledError/TimeoutErrorpropagates upward.
Common mistakes
- Awaiting functions sequentially in a
forloop. Produces the right boolean on non-raising inputs, yet destroys concurrency so latency equals the sum of task runtimes. - Using
asyncio.gatherdirectly.gathercannot short-circuit on the firstTrue, and with defaultreturn_exceptions=Falsean early exception abortsgatherwhile leaving sibling tasks running uncancelled in the background. - Calling
task.result()without checkingtask.cancelled()andtask.exception()first.task.result()immediately re-raises a child's exception, breaking the rule that early exceptions count asFalse, andtask.exception()itself raisesCancelledErrorif you do not checktask.cancelled()first! - Returning
Trueimmediately from insidefor task in done:without inspecting the rest ofdone. Any sibling task indonethat raised in the exact same tick never has.exception()read, causing Python to print"Task exception was never retrieved"when that task is garbage-collected. - Calling
task.cancel()without awaiting the cancelled tasks.cancel()only requests cooperative cancellation (asking a coroutine to stop at its nextawait); withoutawait asyncio.gather(*tasks, return_exceptions=True), cancelled tasks are still executing cleanup code afterany_truehas already returned. - Passing raw coroutines directly to
asyncio.wait. Python 3.11+ forbids passing bare coroutine objects toasyncio.wait(TypeError: Passing coroutines is forbidden, use tasks explicitly); always wrap withasyncio.create_task.
Alternative approaches
asyncio.Queue/ done-callback counter (O(n)CPU bookkeeping): Instead of callingasyncio.waitin a loop (O(n²)callback registrations in the worst case), attachtask.add_done_callback(queue.put_nowait)once per task andawait queue.get()up tontimes. Forn <= 1000asyncio.waitis simpler and naturally groups simultaneous same-tick completions into batches, whereas a completion queue scales linearly ifngrows to100,000+.asyncio.TaskGroupwith a custom signal exception (Python 3.11+): Wrap each task so exceptions becomeFalsewhileTrueraises a private_FoundTrueexception;TaskGroupthen automatically cancels and awaits all sibling tasks on exit. However, preserving the exact "re-raise only if the final batch failed" rule and unpackingExceptionGroup(except*) makes this trickier for beginners thanasyncio.wait.
Follow-up questions
- How would you adapt the function to return the 0-based position of whichever task produced True first? Change the return type to
Optional[int](returningNoneor-1instead ofFalse) and replace the booleanfound_truewithwinning_index = None, using theorderdictionary we already built (order[task]). Insidefor task in sorted(done, key=order.get):, setif task.result() and winning_index is None: winning_index = order[task], and keep iterating through the rest ofdonebefore returningwinning_indexafter the inner loop! Continuing throughdoneretrieves any simultaneous exceptions cleanly, and sorting byorder.getguarantees that if two tasks returnTrueon the exact same event-loop tick, the smaller input index wins deterministically. - What practical hazards arise because cancelling an async task in Python is cooperative rather than immediate? In
asyncio, cancellation is cooperative:task.cancel()merely schedulesCancelledErrorat the task's nextawait, so CPU-heavy loops, synchronous blocking calls (time.sleep, blocking disk/socket reads), threads launched vialoop.run_in_executor, orexcept Exception:/finally:blocks that swallow or delayCancelledErrorwill keep running for some time. That has two major production consequences: (1) a "cancelled" task can still commit side effects (like charging a card or writing a database row) after another task already returnedTrue, so tasks should be read-only or idempotent (safe to repeat or roll back without duplicate side effects); and (2) awaiting_cancel_and_waitcan stallany_trueif a buggy task ignoresCancelledError, which in production you bound with a short cleanup grace timeout (await asyncio.wait(pending, timeout=1.0)). - How would you enforce an overall deadline so slow or stuck tasks cannot block the caller forever? If timing out should raise
TimeoutError, the caller can wrapany_truedirectly withawait asyncio.wait_for(any_true(tasks), timeout=5.0)(orasync with asyncio.timeout(5.0):in Python 3.11+): when the timer expires,any_truereceivesCancelledErrorand ourfinallyblock automatically cancels and awaits every child task beforeTimeoutErrorsurfaces! If instead timing out should cleanly returnFalse, computedeadline = asyncio.get_running_loop().time() + timeoutup front, passtimeout=max(0.0, deadline - loop.time())intoasyncio.wait(...)on each loop iteration, andreturn Falsewheneverdonecomes back empty (lettingfinallycancel and clean uppending).
Follow-up questions
- How would you adapt the function to return the 0-based position of whichever task produced True first?
- What practical hazards arise because cancelling an async task in Python is cooperative rather than immediate?
- How would you enforce an overall deadline so slow or stuck tasks cannot block the caller forever?
Similar questions
- Real-Time Direct Messaging Service Architecture
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One