Katkat

Implement Concurrent Any-True Shot

TemporalSoftware Engineer · Technical Screen

Last updated

This question tests the ability to manage concurrent asynchronous tasks, specifically implementing logic to return the first 'True' result while efficiently cancelling remaining pending tasks.

Problem Statement

Implement a function any_true(tasks) that takes a list of asynchronous functions (each returning a boolean) and returns True as soon as the first function returns True. If all functions return False, the method should return False. If any function raises an exception, it should be treated as a False result unless no other tasks are running.

Crucially, once a True result is observed, your implementation must attempt to cancel all other pending tasks to save resources.

You may use standard library primitives (e.g., asyncio in Python). Assume the input tasks is a list of awaitable objects.

Function Signature

async def any_true(tasks: List[Callable[[], Awaitable[bool]]]) -> bool:
    pass

Example

  • Input: [task_a, task_b, task_c] where task_a takes 5s, task_b takes 1s, and task_c takes 10s.
  • Output: True (after 1s, assuming task_b returns True).
  • Requirement: task_a and task_c should be cancelled immediately upon task_b returning True.

Constraints

  • The number of tasks can range from 0 to 1000.
  • Each task is an independent async function.
  • Handle potential race conditions where multiple tasks return True simultaneously.

Hints

Hint 1

Use `asyncio.create_task` to schedule all functions to run concurrently.

Hint 2

Consider using `asyncio.wait` with `FIRST_COMPLETED` to monitor the progress of the tasks.

Hint 3

Maintain a set of task references so that once a `True` is found, you can iterate through the set and call `cancel()` on all remaining tasks.

Follow-up questions

  • How would your implementation change if we needed to return the index of the task that first returned True?
  • What are the implications of task cancellation not being instantaneous in the underlying runtime?
  • How would you implement a timeout mechanism to ensure the entire operation doesn't hang indefinitely?