Skip to content

fix: close HTTP response body explicitly instead of defer inside loop (resource leak)#35

Open
amathxbt wants to merge 1 commit into
asksurf-ai:mainfrom
amathxbt:fix-defer-body-close-loop
Open

fix: close HTTP response body explicitly instead of defer inside loop (resource leak)#35
amathxbt wants to merge 1 commit into
asksurf-ai:mainfrom
amathxbt:fix-defer-body-close-loop

Conversation

@amathxbt

Copy link
Copy Markdown

Problem

In cli/api.go, inside the for _, checkURI := range uris loop, each iteration uses:

defer resp.Body.Close()  // runs when Load() returns, NOT at end of loop iteration
body, err := io.ReadAll(resp.Body)

defer in Go runs when the enclosing function returns, not when the loop iteration ends. With N URI candidates (service-desc, describedby, loader hints, entrypoint), N response bodies stay open simultaneously until Load() exits, holding N HTTP connections from the transport pool. Under connection limits or slow networks this causes pool exhaustion and hard-to-reproduce hangs.

The DecodeResponse error branch also leaks — body is never closed on early return.

Fix

  • Remove defer resp.Body.Close()
  • Call resp.Body.Close() immediately after io.ReadAll (bytes fully consumed, safe to close)
  • Also close in the DecodeResponse error branch to prevent leaking on early return

References

Using "defer resp.Body.Close()" inside the "for _, checkURI := range uris" loop
means the bodies from all loop iterations are only closed when the outer
Load() function returns, not at the end of each iteration. Under a long
URI list this leaks open HTTP connections and file descriptors for the
entire duration of the function.

Fix: close the body immediately after io.ReadAll returns (and also in
the DecodeResponse error branch) so each iteration cleans up after itself.
@amathxbt

Copy link
Copy Markdown
Author

Hey @akasuv @HappySean2845 @hughzhou-gif @ZhimaoL, flagging this one for the team. The defer inside the loop is easy to miss but it means connections are not being released between iterations. Most of the time it is fine but under any kind of network pressure or connection limit it will start causing hangs that are hard to trace back to this. Worth merging before it becomes a production issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant