Repository navigation
Reap a tenant connection pool only once no thread is using it - #378
cole-robertson wants to merge 2 commits into
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
The lookup path unnecessarily copies all tenant-pool keys even below the limit, and the connection test does not exercise the intended rescue/retry path.
2 open issues
What changed in this PR
This PR protects active tenant transactions by skipping connection pools that are still in use, rather than forcibly disconnecting them to enforce max_connection_pools.
Changes:
- Reaps idle pools with coordinated locking, allowing temporary overflow of the pool limit.
- Adds bounded retries for model connection and schema-cache access when a pool is reaped before use.
- Adds regression tests and documents deferred cleanup and retry limitations.
[!TIP]
If you aren't ready for review, convert to a draft PR.
Click "Convert to draft" or rungh pr ready --undo.
Click "Ready for review" or rungh pr readyto reengage.
| File | Description |
|---|---|
test/unit/tenant_test.rb |
Adds coverage for busy pools, retries, schema-cache isolation, and discarded pools. |
lib/active_record/tenanted/tenant.rb |
Implements idle-pool reaping and retry handling. |
lib/active_record/tenanted/subtenant.rb |
Delegates connection and schema-cache access to the tenant class. |
lib/active_record/tenanted/lru.rb |
Adds deletion of specific pool entries. |
GUIDE.md |
Explains temporary pool-limit overflow and lookup-triggered cleanup. |
CHANGELOG.md |
Records the transaction-safety fix and retry limitations. |
Review effort: Balanced
| # pool that a thread is using, or whose locks are held, is skipped and reaped by a later call, | ||
| # so the limit can be exceeded meanwhile. The caller's own pool is kept. | ||
| def reap_connection_pools(keep:) | ||
| tenanted_connection_pools.keys.each do |shard, role| |
There was a problem hiding this comment.
Fixed in dd5cc27: the cleanup now returns before copying the pool list unless the process is over the limit.
| stale_first = ->(**kwargs) { (lookups += 1) == 1 ? reaped : connection_pool.call(**kwargs) } | ||
| User.stub(:connection_pool, stale_first) do | ||
| assert_equal(1, TenantedApplicationRecord.with_tenant("one") { User.connection.select_value("SELECT COUNT(*) FROM users") }) | ||
| end | ||
| assert_equal(2, lookups) |
There was a problem hiding this comment.
This refers to the earlier commit; the current test fails if connection doesn't retry.
Reaping a pool to stay under max_connection_pools went through remove_connection_pool, which takes connections away from the threads using them, even in the middle of a transaction, leaving it half-written. A pool is now emptied with ConnectionPool#disconnect, which raises instead, and removed only while its locks are held and only if the connection handler still has that same pool. A pool in use is skipped and reaped by a later lookup once it is idle. A model's with_connection, lease_connection, connection and schema_cache retry with the tenant's new pool when their pool is reaped before checkout, for up to checkout_timeout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4e6339c to
73db9b9
Compare
reap_connection_pools runs on every pool lookup, so return before snapshotting the LRU keys unless the pool count is over the limit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>


When a process has more than
max_connection_poolstenant pools, the least recently used one is reaped withremove_connection_pool. That callsPoolConfig#disconnect!, which after twice the checkout timeout takes connections away from the threads that have them checked out, even in the middle of a transaction. With SQLite this can leave a transaction half-written: some of its rows are kept and the rest are not.Reproduction
One thread runs a two-row transaction while another touches three other tenants, with
max_connection_pools: 2. Save asrepro.rband runruby repro.rb, orTENANTED_PATH=path/to/this/branch ruby repro.rbfor this change.repro.rb
On 0.9.0:
With this change:
It also happens at the default limit of 50. With 60 tenants and 5 or 8 threads, each of 8 runs on 0.9.0 left 5–10 transactions half-written and took 51–111 seconds; with this change none, in 2–3 seconds. With a limit of 2 and 3 threads, 0.9.0 can also stall: two of three runs had not finished after 120 seconds.
Change
ConnectionPool#disconnect, which raises rather than take a connection, and removed only while its locks are held and only if the connection handler still has that same pool. A pool in use is skipped and reaped by a later lookup once it is idle, somax_connection_poolscan be exceeded meanwhile.with_connection,lease_connection,connectionandschema_cacheretry with the tenant's new pool when their pool is reaped before checkout, for up tocheckout_timeout. A block that has started is never run again.Not covered
A pool object held directly, as in
Model.connection_pool.with_connection, can still raiseActiveRecord::ConnectionNotEstablishedif it is reaped; the gem can't point it at the new pool. The same goes for a schema cache kept and used after its tenant's pool is reaped, and for a retry that runs out of time. In each case the block or query has not run, and 0.9.0 raises there too.This uses
ConnectionPool#reaper_lock,#discarded?and the pool config's monitor, which are:nodoc:. They work the same way in 8.1.2.1, 8.1.4.1 and main.Testing