Fix the pool exhaustion model for a DB dependency

Review the AI's codeEasy12 min

Your task

An AI wrote a FastAPI database dependency that opens a session and returns it, with nothing that ever closes it. After a few hours of traffic the service fails with "QueuePool limit of size 5 overflow 10 reached". Your team models the connection pool to find the request that would first time out under each cleanup style.

An assistant wrote first_pool_exhaustion_index(pool_size, max_overflow, teardown, outcomes). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • pool_size, max_overflow: the pool's base size and how many extra connections it may open. Together they are its capacity.
  • teardown: how the dependency gives a connection back: "finally" closes it in a finally block, "after" closes it after the handler returns.
  • outcomes: one entry per request, in order: "ok" when the handler succeeded, anything else when it raised an error.
  • Return the number of the first request that finds no free connection, counting from 1, or 0 if every request gets one.

Rules the tests check:

  • The capacity is pool_size plus max_overflow. At the start no connection is held.
  • Before each request takes a connection: if the number held is already at or above the capacity, return that request's number.
  • Otherwise the request takes one connection. Whether it gives it back depends on teardown, compared exactly, case included:
    • "finally": always given back.
    • "after": given back only when the outcome is "ok".
    • Any other value, such as "none" or "yield": never given back.

Examples

first_pool_exhaustion_index(pool_size: int, max_overflow: int, teardown: str, outcomes: list[str]) -> int
Example 1
Inputfirst_pool_exhaustion_index(5, 10, "none", ["ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok"])
Output16
Example 2
Inputfirst_pool_exhaustion_index(5, 10, "finally", ["ok", "error", "ok", "error", "ok", "ok", "error"])
Output0
Example 3
Inputfirst_pool_exhaustion_index(1, 0, "after", ["error", "ok"])
Output2