Fix the leak counter for a Go fetch helper
Your task
An AI-written Go helper dials a backend, writes a request and reads the reply. Its defer conn.Close() sits after the error checks, so every error return before it leaks a file descriptor, and the service runs out of them under load. You are writing a checker that counts those leaking returns from a function's statements.
An assistant wrote count_leaked_returns(statements). It is in the editor. It has a bug. Find it and fix it.
Input and output:
statements: the function's statements in source order. The ones that matter areacquire(a connection was opened),defer_close(its close was deferred) andearly_return(an error return). Anything else is ordinary work.- Return the number of early returns that leak a connection.
Rules the tests check:
- Trim each statement and compare it without regard to case.
- An early return leaks when a connection has been acquired and no close has been deferred for it yet.
- A
defer_closebefore anyacquirecovers nothing. - A
defer_closecovers only the connection acquired most recently. A newacquireopens a new connection with no close deferred, even if an earlier one had its close deferred.
Examples
count_leaked_returns(statements: list[str]) -> intExample 1
Input
count_leaked_returns(["acquire", "write", "early_return", "read", "early_return", "defer_close", "parse"])Output
2Example 2
Input
count_leaked_returns(["acquire", "defer_close", "write", "early_return", "read", "early_return"])Output
0Example 3
Input
count_leaked_returns(["dial_error", "early_return", "acquire", "defer_close"])Output
0