Fix the pool exhaustion model for a DB dependency
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 afinallyblock,"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_sizeplusmax_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]) -> intExample 1
Input
first_pool_exhaustion_index(5, 10, "none", ["ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok", "ok"])Output
16Example 2
Input
first_pool_exhaustion_index(5, 10, "finally", ["ok", "error", "ok", "error", "ok", "ok", "error"])Output
0Example 3
Input
first_pool_exhaustion_index(1, 0, "after", ["error", "ok"])Output
2