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:

  1. Concurrent execution: Start all entries in tasks right away on the asyncio event loop so overall latency is bounded by the fastest True rather than the sum of runtimes.
  2. 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 returning True. If any_true itself is cancelled externally (such as by an outer timeout), cancel and await all still-running child tasks before letting cancellation propagate.
  3. All-False & empty inputs: Return False immediately when tasks is empty, and return False when every task finishes without producing True (provided the final completing batch did not fail).
  4. Exception semantics & tie-breaking:
    • Any exception raised by a task counts as False whenever at least one other task is still running, or when another task completing on the same event-loop turn returns True. Ensure every completed task's exception is inspected so the runtime never emits unretrieved-exception warnings.
    • If zero tasks return True and 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 in tasks.

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

  1. Restate the problem and pin down the edge rules

    We are given 0 to 1000 asynchronous checks that each eventually resolve to True, resolve to False, or raise an exception. Two contract details in starter.py are 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 when callable(item) is true and awaiting the resulting object. 2. An exception raised while other tasks are still running (or alongside a True in the same event-loop turn) counts as False; only when zero tasks ever return True and 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 fastest True, not the sum of task durations. 2. Short-circuit on True: Resolve to True as soon as any task produces True. 3. Cancel leftovers cleanly: Once True is seen (or if any_true itself is cancelled externally), cancel every unfinished task and await their cleanup before returning. 4. Handle False, empty input, simultaneous completions, and errors: Return False on [] or when every task finishes without True (unless the final completing batch raised).

  2. Why awaiting tasks one by one fails

    A beginner's first instinct with async/await is to loop over the functions and await each one in sequence:

    async def any_true_sequential(tasks):
        for fn in tasks:
            try:
                if await fn():
                    return True
            except Exception:
                pass
        return False
    

    Look 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 for loop does not even start check_replica_2 until both check_cache and check_replica_1 finish! With 1000 tasks that each take 1 second and return False, a sequential loop takes 1000 seconds instead of 1 second. And asyncio.gather(*tasks) is not enough either, because gather waits until every task finishes (800 ms for check_archive) instead of returning at 50 ms.

  3. Key idea: launch all tasks, then wake up on `FIRST_COMPLETED`

    In Python asyncio, calling an async def function only creates a coroutine object — it does not start running yet. Wrapping it in asyncio.create_task(...) registers an asyncio.Task with the event loop (the single-threaded scheduler that switches between tasks whenever one pauses at an await), so all n tasks start making progress together.

    Once all tasks are in a pending set, we loop with asyncio.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` tasks
    

    asyncio.wait sleeps until at least one task finishes, then splits the set into done (tasks that completed on this event-loop step) and pending (tasks still running — the exact set we will need to cancel!).

  4. Phase 1: Normalize inputs and schedule every task concurrently

    First, write a tiny helper _run_one(item) so any_true works seamlessly whether the caller passes zero-argument async functions (check_replica_2) or already-created coroutine/awaitable objects (check_replica_2()). Doing if callable(item): item = item() inside _run_one has a bonus safety benefit: if calling item() raises synchronously before returning a coroutine, that exception is captured safely inside the Task rather than aborting the setup loop partway through!

    We also record each task's 0-based position in an order dictionary 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, pending
    
  5. Phase 2: Inspect every task in a completed batch safely

    When await asyncio.wait(...) returns, done can contain several tasks at once if they finished in the same event-loop tick. Three subtle details make the batch loop rock-solid:

    1. Check task.cancelled() BEFORE task.exception(): In asyncio, calling task.exception() on a cancelled task raises CancelledError! Skipping cancelled tasks first avoids that crash, and checking task.exception() before task.result() prevents a failing task from blowing up any_true while other tasks are still running.
    2. Inspect the entire done batch in order before returning: Never return True directly inside the for loop! Finishing the loop over done calls task.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 by order.get guarantees we always pick the earliest input error if several tasks fail together.
    3. Overwrite last_error = batch_error after each non-True batch: If Task 0 fails at 10 ms while Task 1 is still running, last_error temporarily holds Task 0's error. When Task 1 finishes with False at 60 ms, batch_error is None, overwriting last_error = None so any_true returns False. last_error stays non-None after while pending only if the very last batch to finish had an exception and no True!
    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 False
    

    Notice while pending: also handles tasks = [] cleanly (asyncio.wait(set()) raises ValueError, so skipping the loop returns False right away).

  6. Phase 3: Cancel remaining tasks and wait for cleanup in `finally`

    In asyncio, calling task.cancel() does not stop a task instantaneously — it merely schedules an asyncio.CancelledError to be injected at that task's next await point so its try / finally blocks (closing sockets, releasing locks) can run. If any_true returned the instant it called task.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 their CancelledErrors. Placing _cancel_and_wait(pending) inside any_true's own finally: block covers every exit path with one line: - Early return True: pending holds all unfinished sibling tasks -> all are cancelled and awaited. - All tasks finished (False or re-raised error): pending is empty -> _cancel_and_wait does nothing. - Caller cancels any_true (for example via asyncio.wait_for timeout): CancelledError interrupts await asyncio.wait(...), finally cancels 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)
    
  7. 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_west fails early, probe_east finishes False later) with Example 3 (probe_fast finishes False early, probe_slow fails 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!
    
  8. 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 returns True, because all n tasks execute concurrently rather than sequentially.
  • CPU time: O(n²) in the worst case across all event-loop wakeups, where n is len(tasks). Each call to asyncio.wait(pending, ...) attaches and later removes a completion callback on each of the p currently pending tasks (O(p) work); if all n tasks return False one by one at distinct times, that totals n + (n - 1) + ... + 1 = O(n²) callback steps (about 500,000 tiny pointer operations for the max constraint n = 1000, taking only a few milliseconds), plus O(n log n) total across batches for sorting done sets.
  • Space: O(n) memory, because we hold at most n asyncio.Task objects in pending and n index entries in the order dictionary at once.

Edge cases

  • Empty input (tasks = []): Returns False immediately; the while pending: check avoids calling asyncio.wait(set()), which would raise ValueError.
  • Single task that raises: Because pending becomes empty right away (no other tasks remain running), its exception is re-raised rather than swallowed as False.
  • Early exception followed by a slower False or True: As in Example 2, an early exception sets last_error, which is either short-circuited by a later True (return True) or overwritten by None when a slower False batch finishes (return False).
  • Multiple tasks finishing in the same event-loop step: done holds all of them; if any returned True, True wins (even alongside exceptions in the same batch), and if pending is now empty with multiple exceptions, sorting done by order.get re-raises the earliest one in input order while still retrieving every exception so asyncio logs no warnings.
  • Caller passes already-created coroutine objects or Tasks: _run_one checks callable(item) so raw awaitables work directly alongside zero-argument async functions.
  • Caller times out or cancels any_true externally: Wrapping the loop in try / finally guarantees all still-running child tasks are cancelled and awaited before CancelledError / TimeoutError propagates upward.

Common mistakes

  • Awaiting functions sequentially in a for loop. Produces the right boolean on non-raising inputs, yet destroys concurrency so latency equals the sum of task runtimes.
  • Using asyncio.gather directly. gather cannot short-circuit on the first True, and with default return_exceptions=False an early exception aborts gather while leaving sibling tasks running uncancelled in the background.
  • Calling task.result() without checking task.cancelled() and task.exception() first. task.result() immediately re-raises a child's exception, breaking the rule that early exceptions count as False, and task.exception() itself raises CancelledError if you do not check task.cancelled() first!
  • Returning True immediately from inside for task in done: without inspecting the rest of done. Any sibling task in done that 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 next await); without await asyncio.gather(*tasks, return_exceptions=True), cancelled tasks are still executing cleanup code after any_true has already returned.
  • Passing raw coroutines directly to asyncio.wait. Python 3.11+ forbids passing bare coroutine objects to asyncio.wait (TypeError: Passing coroutines is forbidden, use tasks explicitly); always wrap with asyncio.create_task.

Alternative approaches

  • asyncio.Queue / done-callback counter (O(n) CPU bookkeeping): Instead of calling asyncio.wait in a loop (O(n²) callback registrations in the worst case), attach task.add_done_callback(queue.put_nowait) once per task and await queue.get() up to n times. For n <= 1000 asyncio.wait is simpler and naturally groups simultaneous same-tick completions into batches, whereas a completion queue scales linearly if n grows to 100,000+.
  • asyncio.TaskGroup with a custom signal exception (Python 3.11+): Wrap each task so exceptions become False while True raises a private _FoundTrue exception; TaskGroup then automatically cancels and awaits all sibling tasks on exit. However, preserving the exact "re-raise only if the final batch failed" rule and unpacking ExceptionGroup (except*) makes this trickier for beginners than asyncio.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] (returning None or -1 instead of False) and replace the boolean found_true with winning_index = None, using the order dictionary we already built (order[task]). Inside for task in sorted(done, key=order.get):, set if task.result() and winning_index is None: winning_index = order[task], and keep iterating through the rest of done before returning winning_index after the inner loop! Continuing through done retrieves any simultaneous exceptions cleanly, and sorting by order.get guarantees that if two tasks return True on 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 schedules CancelledError at the task's next await, so CPU-heavy loops, synchronous blocking calls (time.sleep, blocking disk/socket reads), threads launched via loop.run_in_executor, or except Exception: / finally: blocks that swallow or delay CancelledError will 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 returned True, so tasks should be read-only or idempotent (safe to repeat or roll back without duplicate side effects); and (2) awaiting _cancel_and_wait can stall any_true if a buggy task ignores CancelledError, 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 wrap any_true directly with await asyncio.wait_for(any_true(tasks), timeout=5.0) (or async with asyncio.timeout(5.0): in Python 3.11+): when the timer expires, any_true receives CancelledError and our finally block automatically cancels and awaits every child task before TimeoutError surfaces! If instead timing out should cleanly return False, compute deadline = asyncio.get_running_loop().time() + timeout up front, pass timeout=max(0.0, deadline - loop.time()) into asyncio.wait(...) on each loop iteration, and return False whenever done comes back empty (letting finally cancel and clean up pending).

Follow-up questions

Similar questions

More Temporal interview questions

All 2 Temporal questions →