Skip to content

usagepool: avoid lock inversion after constructor failure - #7968

Merged
steadytao merged 2 commits into
caddyserver:masterfrom
kojah:fix-usagepool-lock-order
Sep 2, 2026
Merged

steadytao merged 2 commits into
caddyserver:masterfrom
kojah:fix-usagepool-lock-order

Conversation

@kojah

@kojah kojah commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR fixes a lock-order inversion in UsagePool.LoadOrNew when a constructor returns an error.

  • Previously, the failure path held the per-entry lock while acquiring the pool lock to remove the failed entry. UsagePool.Range acquires those locks in the opposite order, so concurrent calls could deadlock.
  • Now, we release the entry lock before acquiring the pool lock, and only remove the entry if it is still the same entry installed by the failed constructor.

This bug only occurs when pools combine LoadOrNew with Range -- it doesn't happen with Caddy's built-in pools, but external modules can combine them.

Testing

Added TestUsagePoolFailedConstructorDoesNotInvertLocks, which coordinates a failed constructor with a concurrent entry read and verifies that the entry lock is released before the failure path waits for the pool lock. The full test suite passes:

$ go test . -run '^TestUsagePoolFailedConstructorDoesNotInvertLocks$' -count=1
ok  	github.com/caddyserver/caddy/v2	0.004s

$ go test -race . -run '^TestUsagePoolFailedConstructorDoesNotInvertLocks$' -count=1
ok  	github.com/caddyserver/caddy/v2	1.012s

$ go test ./...

Assistance Disclosure

I found this bug using a custom Go static analyzer I'm writing (see: https://kojah.github.io/gohawk/analyzers/reliability-and-safety/lockorder/). I used Codex to review the finding and to check whether it was a false positive before submitting this PR.

Signed-off-by: James Ko <317433745+kojah@users.noreply.github.com>
@CLAassistant

CLAassistant commented Aug 29, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@steadytao steadytao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

@steadytao
steadytao enabled auto-merge (squash) September 2, 2026 21:26
@steadytao steadytao added the bug 🐞 Something isn't working label Sep 2, 2026
@steadytao steadytao added this to the v2.11.5 milestone Sep 2, 2026
@steadytao
steadytao merged commit 9968758 into caddyserver:master Sep 2, 2026
26 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug 🐞 Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants