KatInterview

Short-Circuit Async Boolean: Cancel Early, Return Fast

Data Structure DesignModel answer
MediumModel answerData Structure Designasyncioconcurrencycancellation

Last 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 True as soon as any task resolves to a truthy value.
  • If a task raises an exception, treat it the same as a False result — 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 asyncio standard library.

What to cover in your answer

  1. How you schedule and monitor the tasks.
  2. How and when you cancel remaining work, including edge cases like an outer timeout cancelling your function.
  3. Correctness arguments for the edge cases: empty input, all exceptions, simultaneous truthy results.
  4. Complexity analysis and any higher-scale alternatives.
  5. 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.