Fix the replay of a bounded connection pool

Review the AI's codeEasy15 min

Your task

An assistant sped up a script that enriches 50,000 users with asyncio.gather, and it fell over on the full set. Every task grabbed a Postgres connection at once, and a task that failed never gave its connection back. The fix caps how many tasks run at a time and releases the connection on errors too. The team wants a replay of that pool.

An assistant wrote simulate_bounded_pool(duration_ms, succeeded, limit, release_on_error). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • duration_ms: how long each task holds its connection, in milliseconds, in input order.
  • succeeded: true for each task that succeeds. If the two lists differ in length, use only as many tasks as the shorter list has.
  • limit: how many connections the pool has.
  • release_on_error: true when a failed task still gives its connection back.
  • Return one integer per task, in input order: its finish time, or -1 when it produces no result.

Rules the tests check:

  • When limit is 0 or less, every task gets -1.
  • The pool's connections are numbered from 0, and all are free at time 0.
  • Tasks start in input order. Each takes the connection that becomes free earliest. On a tie, the lowest number wins. A leaked connection is never taken again.
  • If every connection has leaked, the task gets -1.
  • A task starts when its connection is free and ends its duration later. A negative duration counts as 0.
  • A task that succeeds gets its end time. Its connection is free again at that end time.
  • A task that fails gets -1. With release_on_error, its connection is free again at the task's end time, the same as after a success. Without it, the connection has leaked.

Examples

simulate_bounded_pool(duration_ms: list[int], succeeded: list[bool], limit: int, release_on_error: bool) -> list[int]
Example 1
Inputsimulate_bounded_pool([100, 100, 100], [True, True, True], 2, True)
Output[100, 100, 200]
Example 2
Inputsimulate_bounded_pool([100, 100, 100], [True, True, True], 5, True)
Output[100, 100, 100]
Example 3
Inputsimulate_bounded_pool([50, 50, 50], [True, False, True], 1, False)
Output[50, -1, -1]