Skip to content

[AI-3542] Hold credential locks on a pool of their own - #2243

Merged
kanat merged 22 commits into
mainfrom
fix/ai-3542-credential-lock-pool
Nov 25, 2026
Merged

kanat merged 22 commits into
mainfrom
fix/ai-3542-credential-lock-pool

Conversation

@kanat

@kanat kanat commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Why

A connector credential refresh holds a session-level advisory lock on one connection taken from the router's serving pool (40, internal/store/store.go), across the provider round trip (up to the resolver's retrieveTimeout, 30 s). Inside the lock the resolver reads the connector definition and its broken revisions, and oauth2code looks up the OAuth client, each through the same pool. 40 refreshes stalled at a slow token endpoint hold all 40 connections and each waits for a 41st: every query of the router stops. One tenant can cause it with its own slow token URL. The provider app lock (WithProviderAppLock, Slack app create and delete) is taken the same way.

How it works

before                                after
serving pool (40)                     serving pool (40)      lock pool (16)
├─ lock conn 1  (held 30 s)           ├─ read  (one stmt)    ├─ lock conn 1 (held)
├─ ...                                ├─ query (one stmt)    ├─ ...
├─ lock conn 40 (held 30 s)           └─ ...                 └─ lock conn 16 (held)
└─ read inside lock: waits for #41                           lock 17+: waits for a
   every other query: waits too                              lock conn until its ctx

acquireCredentialLock now takes its connection from Store.locks, a pool of 16 on the shared database, opened in OpenShards and closed in Store.Close. A lock holder keeps only that connection between statements; its other statements borrow a serving connection for one statement each, so held locks can never take the serving pool, and no holder waits on a connection another holder keeps. The reads inside the lock stay on the serving pool: putting them on the lock's connection would mean passing it through core.CredentialStore and into the scheme's client lookup, and the separate pool is enough for the guarantee. pgsealed's checkpoint and final save already run on the lock's connection (saveAtRevision with .Conn(conn)).

One customer cannot fill the pool. lockConnsPerCustomer (4) caps the lock pool connections a customer's credential and provider app locks hold at once (lockSlots, counted per router process). A customer's fifth lock waits holding no connection until a slot comes back or its ctx ends, so a customer that stalls its own refreshes leaves 12 of the 16 to the others. The slot is given back however the lock ends: released, failed to acquire, ctx ended, or a panic in the lock or unlock statement (deferred). The map entry of a customer is deleted when its last lock leaves.

A lock cut by the driver's socket deadline fails with the deadline, not driver: bad connection: ended() reports context.DeadlineExceeded once ctx's deadline has passed, even before ctx's own timer has run. That is why a waiter past its deadline no longer fails with an i/o error under load.

A lock or unlock statement that fails or panics discards its connection, so the session ends and Postgres drops the advisory lock; nothing keeps a credential locked for every router. After a panic the discard runs on a goroutine of its own (discardOnPanic): a panic inside database/sql's query leaves the connection's close lock read-held, and a close on the panicking goroutine would block for good. At most one such goroutine blocks per lock pool connection, so at most 16 per router.

The pool size (16) is a choice, not measured; its comment in credential_lock.go says what it bounds: how many credential and provider app locks one router holds at once. A lock past it waits until its ctx ends. It adds up to 16 connections per router to the shared database; idle ones close after 5 minutes (connect).

Changes

  • internal/store: Store.locks and lockConns; acquireCredentialLock takes its connection there; Close closes it.
  • lockConnsPerCustomer, lockSlots: the per-customer cap, taken before the connection and given back by the unlock function (deferred by callers). ended(), discardOnPanic, discard: see above.
  • Tests: see below. assertTheWaitEnded and assertNothingIsHeld now read the lock pool's InUse, which the old GlobalDB reads no longer cover; the store's query counter hooks the lock pool too.
  • pgsealed/AGENTS.md: the rule and its checks.

Validation

Rule Test Mutation that fails it
Held locks leave the serving pool free TestStoreSuite/TestCredentialLocksHeldAtOnceFillTheirOwnPoolAndLeaveTheServingOneFree (40 lockers that read inside their lock; 16 hold, 24 wait, a query still runs within 2 s, then all 40 run) locks back on s.global.Conn; locks: db
Refreshes stalled at the token endpoint leave the router its connections, and still work end to end TestResolverSuite/TestRefreshesStalledAtTheTokenEndpointLeaveTheRouterItsServingConnections (8 refreshes stalled at the fake provider, serving pool cut to 4) locks back on s.global.Conn
The lock pool holds 16 same store test lockConns = 40
The lock pool is on the shared database same store test, sharded suite lock pool on ShardDSN
Close closes the lock pool TestStoreSuite/TestClosingTheStoreClosesItsLockPool Close without s.locks.Close()
One customer's stalled locks leave the lock pool to the others TestStoreSuite/TestOneCustomersStalledLocksLeaveTheLockPoolToOtherCustomers cap raised to 16; provider app lock skips the cap
A customer's slot is given back however its lock ends, and its map entry is deleted at zero TestStoreSuite/TestACustomersLockSlotIsGivenBackHoweverItsLockEnds no release on a failed acquire; no release when ctx ends while over the cap; no delete at zero callers
A provider app lock is held on the lock pool TestStoreSuite/TestAProviderAppLockIsHeldOnTheLockPool provider app lock on s.global
A lock cut by its deadline fails with the deadline TestStoreSuite/TestALockCutByItsDeadlineBeforeTheContextSaysSoFailsWithTheDeadline ended() without the deadline check
A panic in the lock statement gives the slot back and discards its connection TestStoreSuite/TestACustomersLockSlotIsGivenBackWhenTheLockStatementPanics no deferred slot release in acquire; no discardOnPanic in the lock statement
A panic in the unlock statement gives the slot back, discards its connection, leaves no lock held TestStoreSuite/TestACustomersLockSlotIsGivenBackWhenTheUnlockStatementPanics slot given back after the unlock instead of deferred; no discardOnPanic in the unlock
A panic inside database/sql does not block the caller TestStoreSuite/TestADriverPanicInTheLockStatementReachesTheCallerWhoseSlotIsGivenBack go discard(conn) made synchronous (fails on its 5 s deadline)

Ran: go test -tags integration on ./internal/store (TestStoreSuite, TestShardedStoreSuite; only TestEveryHotTableIsReadByIndex fails, locally on Postgres 16, and it fails the same way on main), ./internal/connectors/resolver and ./internal/connectors/credentialstores/pgsealed, the new tests under -race -count=3, go vet -tags integration, gofmt -l. The full integration run is CI's.

Unverified: the Postgres max_connections of the deployed databases, against which the 16 extra connections per router count.

Review rounds

  • Round 1 (no-go): no per-customer cap on the lock pool, and no test that a provider app lock is on it. Fixed with the cap, its tests, and the deadline error.
  • Rounds 2-3: the delete of an emptied customer entry had no test; a panic in the lock or unlock path kept the slot, and no test covered it. Fixed with a deferred release and the panic tests.
  • Round 4: CI failed on tests of the lock paths, and a panicking unlock left the lock held for every router. Fixed by discarding the connection on a panic.
  • Rounds 5-6: no test showed that the discard after a panic does not block the caller. Added it; go.

🤖 Generated with Claude Code

kanat and others added 4 commits November 23, 2026 17:54
A credential lock kept its connection from the serving pool across a
provider round trip, and the statements inside it asked the same pool
for another. Locks now take their connection from a pool of 16 opened
on the shared database and closed with the store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added the docs label Nov 23, 2026

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[security R1] NO-GO: one Blocker.

The serving pool can no longer be taken by stalled refreshes: the three guards the PR adds (locks on their own pool, the pool closed with the store, its size) each fail a PR test when removed. But the new 16-connection lock pool is shared by every tenant on a router, with no bound per tenant. One tenant whose refreshes stall at its own token endpoint can fill it, and then every other tenant's credential locks and provider app locks wait until their own context ends. On main that took 40 stalled refreshes; here it takes 16. See S1.1.

Ruling on the author's question (a per-tenant cap on held credential locks): in scope for this PR, as S1.1.

// never waits on one another holder keeps. 16 lets that many refreshes stall at once before
// another connection's credential has to wait, and adds that many to the 40 a router holds on
// the shared database; idle ones close after 5 minutes (connect). A choice, not measured.
const lockConns = 16

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Blocker] S1.1 Cross-tenant starvation of the lock pool. The 16 lock connections are shared by every customer on the router, and nothing bounds how many one customer holds. A customer's lock is held across its own provider's token round trip, up to retrieveTimeout. So one customer's stalled refreshes can fill the pool, and while they hold it, other customers' credential operations (credential resolution for tool calls, consents, credential writes, revocations) and their WithProviderAppLock calls wait in s.locks.Conn(ctx) (line 95) until their context ends. On main the same starvation needed 40 stalled locks; here it needs 16.

Fix: bound the lock connections one customer holds at once, below lockConns. For example, an in-process count per customer id checked in acquireCredentialLock before s.locks.Conn, with an over-cap caller waiting on its own ctx and holding no connection. Comment the cap's value with its reason.

Test row for StoreSuite (credential_lock_test.go): one customer holds lockConns WithLocked callbacks parked inside fn. Another customer's WithLocked, and its WithProviderAppLock, each on a 3 s context, must still run (no error). Add the same for TestShardedStoreSuite.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 2bf0f1f (docs in ad9d3ae): one customer's locks, credential and provider app together, hold at most 4 of the 16 lock pool connections (lockConnsPerCustomer, counted per Store, so per router process); the fifth waits for a slot holding no connection and gives up with its own context. 4 customers fill the pool. Tests: TestStoreSuite/TestOneCustomersStalledLocksLeaveTheLockPoolToOtherCustomers (16 parked for one customer; another customer's WithLocked and WithProviderAppLock on 3 s contexts run) and TestACustomersLockSlotIsGivenBackHoweverItsLockEnds (panic, ctx end over the cap, no lock connection), both suites. Mutations killed: cap 16, provider app locks skip the slot, release not deferred, no release on a failed acquire, no release on ctx end.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Round-1 review of 8c329bcf2 merged onto main 284349e10. CI: draft, so go and integration are skipped; they run at gh pr ready.

I checked these and found them sound:

  • The lock pool is used only at acquireCredentialLock. Its holders are WithLocked, SaveAtRevision and WithProviderAppLock, called from the resolver (Invalidate, Revoke, retrieve, saveAgain), api/connections.go:528, api/connection_tools.go:310, api/authorizations.go:863 and api/connector_provider_apps.go:268,326.
  • No callback takes a second credential or provider app lock. No caller holds a serving transaction while it locks. So no holder waits on a second lock-pool connection, and the two pools cannot wait on each other in a cycle.
  • The serving-pool reads inside a lock are one statement each. They are bounded by the caller's ctx, as on main, or by the detached retrieveTimeout.
  • There is one lock pool per Store, always on the shared DSN, and Close closes it, also on the openRedis failure path.

Tests run: the resolver and pgsealed suites pass. The store suites pass, except the known local TestEveryHotTableIsReadByIndex and one TestSeeingAUserThisProcessHoldsCostsNoQueryAndNoRedis miss, which passes 5 of 5 times when run alone. Mutations: 7 checked, 1 survived (R1.1).

[Question] R1.4 (the author's question): should one tenant's stalled refreshes be capped below the 16 lock connections? Ticket, not this PR.

Verdict: request changes, for R1.1.

pause := credentialRetryFirst
for {
conn, err := s.global.Conn(ctx)
conn, err := s.locks.Conn(ctx)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Should fix] R1.1 No test shows that a provider app lock is held on the lock pool. The PR claims it in store.go:47 and in the lockConns comment. Mutant: in acquireCredentialLock, take s.global when namespace == providerAppLockNamespace. It survives every ProviderApp|Lock|ConfigToken test in both store suites.

Fix: add this test to StoreSuite. I ran it in a scratch copy: it passes on head, and under the mutant it fails in both suites (Should be zero, but was 1).

func (s *StoreSuite) TestAProviderAppLockIsHeldOnTheLockPool() {
	router := s.router()
	var locks, serving int
	s.Require().NoError(router.ConnectorConfigTokens.WithProviderAppLock(s.ctx, "acme-app", "slack", func() error {
		locks, serving = router.locks.Stats().InUse, router.GlobalDB().Stats().InUse
		return nil
	}))
	s.Equal(1, locks, "the provider app lock keeps a lock pool connection")
	s.Zero(serving, "and no serving one")
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in dce7396: TestStoreSuite/TestAProviderAppLockIsHeldOnTheLockPool (locks InUse 1, serving InUse 0 inside WithProviderAppLock). Mutant R-M2 (s.global for providerAppLockNamespace) now fails it: "Should be zero, but was 1".

)

// maxConns is how many Postgres connections one router holds at most.
// maxConns is how many Postgres connections one router's serving pool holds at most: every

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Nit] R1.2 This comment names only a credential lock's connection, but provider app locks are on the lock pool too. In the same way, pgsealed/AGENTS.md:9 (Flow, step 1) still says "on a pool connection": write "on a lock pool connection". Ticket.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 170d55b: the maxConns comment names credential and provider app locks, and pgsealed/AGENTS.md says "lock pool connection" in steps 1 and 7. Comment-only; no test.

// never waits on one another holder keeps. 16 lets that many refreshes stall at once before
// another connection's credential has to wait, and adds that many to the 40 a router holds on
// the shared database; idle ones close after 5 minutes (connect). A choice, not measured.
const lockConns = 16

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Question] R1.3 Each router now holds up to 16 more connections on the shared database, one lock pool per Store. With two pods and overlapping generations, that is up to 64 more. Is that still "well inside the server's connection limit" (the connect comment)? Not checked: the deployed max_connections. Ticket for the orchestrator, not this PR.

kanat and others added 9 commits November 23, 2026 18:48
…l-lock-pool

# Conflicts:
#	acceleration/internal/store/shards.go
#	acceleration/internal/store/store.go
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One customer's refreshes stalled at a token endpoint it runs could hold all
16 lock pool connections, and every other customer's credential and provider
app locks then waited until their contexts ended. Each customer's locks now
hold at most 4 at once; one more waits for a slot, holding no connection,
until its own context ends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…l-lock-pool

# Conflicts:
#	acceleration/internal/store/shards.go
The driver sets a socket's deadline to the context's, so a pg_try_advisory_lock
it cuts can fail before the context's timer has run. The waiter then returned
driver: bad connection or an i/o timeout instead of context.DeadlineExceeded
(TestAWaiterPastItsDeadline failed 2 of 30 under load, on main too).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Verdict: NO-GO (one small Should fix, test only; everything else is fixed). Head aaa8b49 merged onto main 2ea9511.

Prior findings

  • S1.1 fixed. I reran the attack probe on this head: one customer parks 16 WithLocked, 4 get in and the other 12 wait holding no connection (lock pool InUse = 4); another customer's WithLocked and WithProviderAppLock on 3 s contexts both run. With the cap at 16 the new test fails on Store and Sharded.
  • R1.1 fixed, R1.2 fixed, R1.4 = S1.1 fixed. R1.3 stays a ticket (16 more connections per router on the shared database; deployed max_connections not verified).
  • R1.5 fixed. Without ended() the new test fails; the waiter tests pass with -cpu 1 -count=20. No caller inspects the lock error type (the only DeadlineExceeded check outside store is on outgoing HTTP exchanges), and a connection failure before the deadline still reports as a connection failure.

Slot counter: every exit path gives the slot back (ctx cancel while waiting, failed try, Conn error on a closed store, callback panic, normal end); mutations that drop each of them fail a test. -race on the lock subset passes on both suites. No lock callback takes another lock, so the cap cannot deadlock on hold-and-wait.

New finding

  • N2.1 [Should fix] the delete of an empty customer entry is untested: removing it passes both suites, while the comment promises the map holds only customers locking now. Fix inline. Test: after the lock ends, len(router.lockSlots.customers) is 0.
  • N2.2 [Nit] inline.

Runs: Store + Sharded full (skipping TestEveryHotTableIsReadByIndex) ok; connectors incl. resolver and pgsealed ok; vet with the integration tag clean. 7 mutations, 1 survived (N2.1). Draft, so no CI. Details in the ledger (reviewer-2.md).

l.mu.Lock()
defer l.mu.Unlock()
slots.callers--
if slots.callers == 0 {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

N2.1 [Should fix] Removing this if slots.callers == 0 { delete(...) } passes both suites: callersOf returns 0 for a missing entry and for a stale one. Add a check that len(router.lockSlots.customers) is 0 once a customer's lock ends (e.g. in TestACustomersLockSlotIsGivenBackHoweverItsLockEnds), then rerun that mutation.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 9795335: TestACustomersLockSlotIsGivenBackHoweverItsLockEnds now asserts the slot map holds no entry once the customer's locks ended. With the delete disabled (M5) it fails on Store and Sharded; restored, it passes.

leave()
return bun.Conn{}, nil, err
}
return conn, func() {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

N2.2 [Nit] A panic in tryCredentialLock, or in releaseCredentialLock before leave(), keeps the slot taken for good. defer leave() in this closure (and in the failure path above) costs nothing. Not reachable by a customer, so it does not block.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 048ad65: acquireCredentialLock gives the slot back in a defer unless the lock was taken, and the unlock closure does defer leave(). No test: no seam injects a panic into tryCredentialLock or releaseCredentialLock (both are plain calls on a real connection), so the panic path is not mutation-checked; the non-panic exits stay covered by TestACustomersLockSlotIsGivenBackHoweverItsLockEnds.

kanat and others added 3 commits November 23, 2026 23:27
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ocks end

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…anics

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Delta round 3, 048ad65 merged on current main (1029b8d). Verdict: GO.

R2.1 (fixed). customersLocking() and the assert in TestACustomersLockSlotIsGivenBackHoweverItsLockEnds. Mutant M5 (no delete at zero callers) now fails on Store and Sharded ("a customer whose locks all ended leaves no entry in the map").

R2.2 (fixed in code, one Nit left). acquireCredentialLock gives the slot back by defer on the acquire path and in the unlock closure. I mutated both: dropping the acquire defer, or moving leave() after the release call, leaves the slot counted when a panic comes through. HEAD passes both. The fixer said there is no panic seam. There is one: a context whose Value panics (the bun query hook reads it). See the inline Nit.

Main merge afd0832 (--remerge-diff).

  • git diff 1029b8d34 HEAD --stat names 9 files, all this PR's. No main change is reverted.
  • shards.go: the lock pool is opened after the serving pool; if it fails, the serving pool is closed. A later failure goes through s.Close(), which closes locks (store.go:178). connect fails only on a DSN that does not parse, before any pool opens.
  • releaseCredentialLock(ctx, ...) is main's: it runs the unlock on context.WithTimeout(context.WithoutCancel(ctx), 2s). A request whose context is done still unlocks, so no advisory lock leaks. The unlock closure passes the acquire context.
  • The slot is given back on every path: slot wait fails, no connection, lock miss, error, panic in acquire, unlock, panic in unlock.

S1.1 probe. As written it fails at its own precondition (16 attacker locks cannot all get in: the cap is 4). Adapted to wait for the 4 that can: another customer's WithLocked and WithProviderAppLock both run (0.98 s, 0.68 s). With the cap set to 16 the probes and TestOneCustomersStalledLocksLeaveTheLockPoolToOtherCustomers fail.

Runs. Store and Sharded suites with -testify.m 'Lock|Credential|Provider': ok (66 s). internal/connectors/...: ok. go vet -tags integration and the unit run of internal/store: ok. A broader pattern run shows TestEveryHotTableIsReadByIndex failing on 5 subtests, and the same 5 fail on origin/main 1029b8d, so it is not this PR. gh pr checks: draft, go and integration skipping; CodeQL, labeler and GitGuardian pass.

4 mutations checked (M5, cap 16, acquire defer, release defer), 0 survived. Not checked: the other SDK-generated files the merge brought in (main's).

if err != nil {
return bun.Conn{}, nil, fmt.Errorf("store: wait for a customer's credential lock slot: %w", err)
}
locked := false

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Nit, small -> fix in place] No test for the panic paths of this defer or of the unlock closure's defer leave(): a mutant that drops the acquire defer, or moves leave() after releaseCredentialLock, passes the suites. A seam exists: a context whose Value panics once armed (the bun query hook calls it inside QueryRowContext). Acquire with an unarmed ctx, arm it, s.Panics(unlock), then s.Zero(router.lockSlots.callersOf(...)). For the acquire path, arm it before the call. Both probes pass on HEAD and fail on the mutants (text: rev3-logs/zz_probe_panic_test.go.txt in the ledger).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in fb7989a: TestACustomersLockSlotIsGivenBackWhenTheLockStatementPanics and TestACustomersLockSlotIsGivenBackWhenTheUnlockStatementPanics (credential_lock_test.go, run by both TestStoreSuite and TestShardedStoreSuite; a context whose Value panics once armed). Without the acquire-path deferred leave the first fails; with leave() after the release call instead of deferred the second fails; both pass on head.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kanat
kanat marked this pull request as ready for review November 23, 2026 23:01
kanat and others added 2 commits November 24, 2026 08:45
A panic in pg_advisory_unlock (a query hook reading the context, as
bunotel's BeforeQuery does) left its lock pool connection neither closed
nor back in the pool, still holding the session advisory lock: the
credential stayed locked for every router until the process exited. The
store suites' credential lock tests after the unlock panic test each saw
that extra lock in CI.

Both statements now discard the connection when they panic, on a
goroutine of their own, since a panic inside database/sql's query leaves
the connection's close lock held. The panic tests check that no
credential lock and no lock pool connection is left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kanat

kanat commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed in d59a083 (R4.1, the six credential lock tests failing in the store group).

Cause: a panic in the unlock statement (the test's context panics inside the query hook, before the query is sent) left that lock pool connection out of the pool and never closed, still holding the session advisory lock. Every test after it saw one extra granted lock. In production the credential would stay locked for every router until the process exited.

Fix (internal/store/credential_lock.go): releaseCredentialLock and the lock statement (new tryAdvisoryLock) discard the connection when their statement panics (discardOnPanic), and the panic continues. The discard runs on its own goroutine, because a panic inside database/sql's query leaves the connection's close lock read-held, and a close would then block forever.

Tests: TestACustomersLockSlotIsGivenBackWhenTheUnlockStatementPanics and ...LockStatementPanics now check that no credential lock and no lock pool connection is left (assertThePanickedConnectionIsGone). The lock test first takes and gives back one lock, so the panic happens in the lock statement and not while a connection opens.

Mutations: without the unlock discard, the whole TestStoreSuite fails the same six tests again, plus the unlock test. Without the lock discard, the lock test fails in both suites. With the fix, TestStoreSuite and TestShardedStoreSuite pass twice with no -run filter, except TestEveryHotTableIsReadByIndex. That test also fails on main locally (local Postgres 16, CI uses 19) and this PR does not touch it.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: NO-GO

Delta review round 5: d59a083 (the R4.1 fix plus a merge of main), reviewed merged onto current main.

Prior findings

  • R4.1 (CI: the 6 credential lock tests after the unlock panic test failed): fixed. The whole TestStoreSuite and TestShardedStoreSuite, run twice with no method filter, pass the 6 tests. Only TestEveryHotTableIsReadByIndex fails, and it fails the same way on main locally (Postgres 16 locally, 19 in CI). Mutations: dropping the unlock statement's panic discard fails the unlock panic test in both suites; dropping the lock statement's fails the lock panic test in both.
  • Earlier findings (S1.1, R1.1, R1.2, R1.5, R2.1, R2.2, R3.1): fixed in earlier rounds, not touched by this delta.

Base merge: clean (empty remerge diff); the PR's diff is unchanged apart from hunk offsets. #2230's session limits now apply to both pools, since both open through connect. For the lock pool that is harmless: a held lock sits on an idle connection outside any transaction (idle_session_timeout stays 0), the lock and unlock statements never wait, and the in-lock credentials write is cut by its own 2 s bound before lock_timeout.

The discard goroutine: the shape is right. With a panic inside database/sql's query, a synchronous discard blocks the caller for good, because Conn.close waits for a close lock the panicked query never gives back. Each such panic leaves one blocked goroutine that pins one lock pool connection database/sql never frees. So there are at most lockConns per Store; after that no lock statement runs. A probe of 16 driver panics gave 16 goroutines, and the 17th lock waited for a connection. The hook-level panic (bunotel) closes the connection at once. The goroutine has no shutdown, and none is possible here. What is missing is a test: see the inline finding.

New findings

  • [Should fix, test-only] credential_lock.go:270: go discard against a synchronous discard is untested (inline).
  • [Nit] credential_lock.go:234: the error-path discard survives its removal; this is behaviour moved from before, not new (inline).

// the only one left blocked then; any other panic closes the connection at once.
func discardOnPanic(conn bun.Conn, answered *bool) {
if !*answered {
go discard(conn)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Should fix, test-only] Nothing tests the goroutine. If go discard(conn) becomes discard(conn), both panic tests still pass, because their seam panics in bun's query hook, before database/sql takes the Conn's close lock. A panic inside the driver (after grabConn's closemu.RLock) is the case the goroutine exists for. There a synchronous discard blocks the caller for good: Conn.close takes closemu.Lock, and queryDC never releases the read lock on a panic.

Fix: a seam whose Deadline panics once armed. pgdriver reads it in Conn.deadline, inside the driver. Then a test that the panic reaches the caller within a deadline:

type panicsOnDeadline struct {
	context.Context
	armed *atomic.Bool
}

func (c panicsOnDeadline) Deadline() (time.Time, bool) {
	if c.armed.Load() {
		panic("context deadline")
	}
	return c.Context.Deadline()
}

func (s *StoreSuite) TestALockWhoseDriverPanicsInTheLockStatementStillPanicsToItsCaller() {
	router := s.router()
	connection := s.connection("acme-app", nil)
	s.Require().NoError(router.ConnectorConnections.WithLocked(s.ctx, "acme-app", connection.ID,
		func(*ConnectorConnection, func() error) (bool, error) { return false, nil }))
	armed := new(atomic.Bool)
	armed.Store(true)
	panicked := make(chan any, 1)
	go func() {
		defer func() { panicked <- recover() }()
		_ = router.ConnectorConnections.WithLocked(panicsOnDeadline{s.ctx, armed}, "acme-app", connection.ID,
			func(*ConnectorConnection, func() error) (bool, error) { return false, nil })
	}()
	select {
	case p := <-panicked:
		s.Equal("context deadline", p, "the driver's panic reaches the caller")
	case <-time.After(5 * time.Second):
		s.FailNow("a panic inside database/sql's query leaves the caller blocked closing its connection")
	}
	s.Zero(router.lockSlots.callersOf("acme-app"), "a panic inside the driver gives the slot back")
}

Checked in both suites: it passes on this head and fails under the synchronous mutant (stuck at 5 s). Optional: the comment could state the bound. Each such goroutine pins a lock pool connection database/sql never frees, so there are at most lockConns per Store.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 2176cec: TestADriverPanicInTheLockStatementReachesTheCallerWhoseSlotIsGivenBack (a context whose Deadline panics inside the driver). With the discard made synchronous it fails in TestStoreSuite and TestShardedStoreSuite after its own 5 s deadline; on this head it passes (-count=10).

var locked bool
err := conn.QueryRowContext(ctx, "SELECT pg_try_advisory_lock(?::integer, ?::integer)", namespace, key).Scan(&locked)
answered = true
if err != nil {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Nit] Removing this error-path discard(conn) fails no test (lock, waiter, deadline and cancel tests all pass). The behaviour was the same before this refactor, so it is not new here. It is fine to leave it, or to pin it later.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Not fixed in this PR, to be a ticket. I tried the existing seam (a deadline already past, test TestALockCutByItsDeadlineBeforeTheContextSaysSoFailsWithTheDeadline plus the connection-gone assertion): with the discard on the failed lock statement removed it still passes, because pgdriver marks a connection bad after a timeout and database/sql drops it anyway. A test that fails needs an error that leaves the connection healthy (a server-side error on the lock statement), which is a new seam.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: GO

Delta review round 6: 2176cec (one test added, plus a merge of origin/main with no conflicts). Reviewed merged onto origin/main c78b8e8.

Prior findings

  • R5.1 (the driver-panic test must fail when the discard is synchronous): fixed. TestADriverPanicInTheLockStatementReachesTheCallerWhoseSlotIsGivenBack passes on head in TestStoreSuite and TestShardedStoreSuite: 5 runs each, and 50 runs each with -cpu 1. Mutant M3 (go discard(conn) made synchronous, credential_lock.go:270) fails it in both suites at the test's own 5 s deadline, with no hung suite. Restored; the file is identical to head.
  • R5.2 (a failing lock statement leaves no lock and no connection; M4 survives): ticket, accepted (Nit, not blocking). The fixer's reason holds for the timeout path: pgdriver v1.2.18 checkBadConn closes the connection on a timeout (error.go:48-73, driver.go:377-382), so a timed-out statement cannot show the discard. A server-side error that keeps the connection healthy is not checked.

New findings in the delta: none.

Suites

  • TestStoreSuite and TestShardedStoreSuite, whole, -p 1, on head merged onto c78b8e8: all pass except TestEveryHotTableIsReadByIndex (EXPLAIN plan checks, Postgres 16 locally). The same test fails on origin/main without this PR. Not counted.
  • CI when checked: integration (store), (agent), (rest), (routers) pass; go and integration (router) pending.
  • integration (api) fails on main itself: internal/api/scheduled_unpaid_test.go:1200 assigns scheduledPhoneWindow and scheduledCallLimit, which main declares as constants (internal/api/scheduled_delivery.go:55, :60). This PR changes no file under internal/api.
  • Both Analyze jobs fail on a GitHub IP allow-list error, not on code.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@kanat

kanat commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

Merged main into the branch. Two conflicts: store/shards.go (kept the lock pool in OpenShards next to main's new lost and polls fields) and pgsealed/AGENTS.md (kept the lock pool rule, took main's ConnectorConnections.SaveAtRevision rename). credential_lock.go and store.go merged cleanly; the lock pool still uses connect, so it gets main's primary-only connector. Vet and the store suites pass; only TestEveryHotTableIsReadByIndex fails, as on main locally.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: GO

Delta round 7, head 542fe30 (one merge of origin/main), earlier head 2176cec was GO in round 6.

  • Conflict resolution: OpenShards keeps the lock pool (connect(options.DSN, lockConns), locks:, closing the serving pool when the lock pool fails to open) and takes main's lost and polls. pgsealed/AGENTS.md keeps the lock-pool bullet and main's ConnectorConnections.SaveAtRevision name.
  • The lock pool needs nothing more from main's changes. It is opened by connect(), so it gets main's primary-only connector; a lock statement that fails already discards its connection, which ends the session and drops the lock. lost and polls serve only forgetLater on detachedWrite, which runs on the serving pool, never on a lock connection. Close still closes s.locks after the retry wait. Main did not change the statement bounds (sessionDefaults), which the lock pool shares.
  • git diff 2176cec5a 542fe30f1 on credential_lock.go, store.go, shards.go shows only main's changes; no PR line is reverted.
  • go vet -tags integration ./... is clean. TestStoreSuite and TestShardedStoreSuite with the lock, credential, waiter, panic and slot tests pass on the merged head, and so does TestResolverSuite Stalled.
  • The PR body states the final head's behaviour.

All earlier findings stay fixed. No new findings. CI was still running when I looked.

@kanat
kanat merged commit a48bdbe into main Nov 25, 2026
13 checks passed
@kanat
kanat deleted the fix/ai-3542-credential-lock-pool branch November 25, 2026 03:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant