Fix the leak counter for a Go fetch helper

Review the AI's codeEasy10 min

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 are acquire (a connection was opened), defer_close (its close was deferred) and early_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_close before any acquire covers nothing.
  • A defer_close covers only the connection acquired most recently. A new acquire opens a new connection with no close deferred, even if an earlier one had its close deferred.

Examples

count_leaked_returns(statements: list[str]) -> int
Example 1
Inputcount_leaked_returns(["acquire", "write", "early_return", "read", "early_return", "defer_close", "parse"])
Output2
Example 2
Inputcount_leaked_returns(["acquire", "defer_close", "write", "early_return", "read", "early_return"])
Output0
Example 3
Inputcount_leaked_returns(["dial_error", "early_return", "acquire", "defer_close"])
Output0