Skip to content

Reap a tenant connection pool only once no thread is using it - #378

Open
cole-robertson wants to merge 2 commits into
basecamp:mainfrom
cole-robertson:reap-idle-pools
Open

cole-robertson wants to merge 2 commits into
basecamp:mainfrom
cole-robertson:reap-idle-pools

Conversation

@cole-robertson

@cole-robertson cole-robertson commented Nov 21, 2026 •

Copy link
Copy Markdown

When a process has more than max_connection_pools tenant pools, the least recently used one is reaped with remove_connection_pool. That calls PoolConfig#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 as repro.rb and run ruby repro.rb, or TENANTED_PATH=path/to/this/branch ruby repro.rb for this change.

repro.rb
# frozen_string_literal: true

# One thread runs a two-row transaction on tenant "victim". While it runs, another thread
# touches three other tenants, which takes the process over max_connection_pools: 2.
# Prints the rows "victim" ended up with: both rows, or neither, is correct.
#
#   ruby repro.rb                      # activerecord-tenanted 0.9.0
#   TENANTED_PATH=path/to/checkout ruby repro.rb

ENV["RAILS_ENV"] = "production"
require "bundler/inline"

gemfile(true, quiet: true) do
  source "https://rubygems.org"
  gem "rails", "~> 8.1.2"
  gem "sqlite3"
  if ENV["TENANTED_PATH"]
    gem "activerecord-tenanted", path: ENV["TENANTED_PATH"]
  else
    gem "activerecord-tenanted", "0.9.0"
  end
end

require "logger"
require "tmpdir"
require "rails"
require "active_record/railtie"
require "active_storage/engine"
require "activerecord-tenanted"

dir = Dir.mktmpdir
FileUtils.mkdir_p(%w[config tenants db/tenant_migrate storage].map { File.join(dir, _1) })
File.write(File.join(dir, "config/database.yml"), <<~YAML)
  production:
    primary:
      adapter: sqlite3
      database: #{dir}/primary.sqlite3
    tenant:
      adapter: sqlite3
      database: "#{dir}/tenants/%{tenant}.sqlite3"
      tenanted: true
      checkout_timeout: 1
      max_connection_pools: 2
      migrations_paths: #{dir}/db/tenant_migrate
YAML

class ReproApp < Rails::Application
  config.load_defaults 8.1
  config.eager_load = false
  config.logger = ActiveSupport::TaggedLogging.new(Logger.new(nil))
  config.secret_key_base = "x" * 32
  config.active_record_tenanted.connection_class = "TenantRecord"
end
ReproApp.config.root = dir
ReproApp.config.active_storage.service = :local
ReproApp.config.active_storage.service_configurations = { "local" => { "service" => "Disk", "root" => "#{dir}/storage" } }
ReproApp.initialize!

class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class
end

class TenantRecord < ApplicationRecord
  self.abstract_class = true
  tenanted "tenant"
end

class Item < TenantRecord
  self.table_name = "items"
end

tenants = %w[victim t1 t2 t3]
tenants.each do |name|
  SQLite3::Database.new("#{dir}/tenants/#{name}.sqlite3") do |db|
    db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, v TEXT)")
  end
end

error = nil
victim = Thread.new do
  Rails.application.executor.wrap do
    TenantRecord.with_tenant("victim") do
      Item.transaction do
        Item.create!(v: "first")
        sleep 1.5
        Item.create!(v: "second")
      end
    end
  end
rescue => e
  error = e
end

sleep 0.3
Thread.new do
  Rails.application.executor.wrap do
    %w[t1 t2 t3].each { |name| TenantRecord.with_tenant(name) { Item.count } }
  end
end.join
victim.join

rows = SQLite3::Database.new("#{dir}/tenants/victim.sqlite3").execute("SELECT v FROM items ORDER BY id").flatten
puts "activerecord-tenanted #{ENV["TENANTED_PATH"] || Gem.loaded_specs["activerecord-tenanted"].version}, Rails #{Rails.version}"
puts "transaction raised: #{error ? "#{error.class}: #{error.message.lines.first.strip}" : "nothing"}"
puts "rows in victim: #{rows.inspect}"
puts(rows.size == 1 ? "HALF-WRITTEN: one of the transaction's two rows was kept" : "OK")

On 0.9.0:

transaction raised: ActiveRecord::StatementInvalid: SQLite3::SQLException: cannot rollback - no transaction is active
rows in victim: ["second"]
HALF-WRITTEN: one of the transaction's two rows was kept

With this change:

transaction raised: nothing
rows in victim: ["first", "second"]
OK

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

  • A pool is emptied with 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, so max_connection_pools can be exceeded meanwhile.
  • The reaper lock is taken first, as Rails' reaper takes it; the other locks are only tried, so reaping backs off rather than deadlocks.
  • 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. 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 raise ActiveRecord::ConnectionNotEstablished if 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

  • Unit tests pass on Rails 8.1.2.1, 8.1.4.1 and main, including new ones for skipping a busy pool, the retry and its timeout, not re-running a started block, and a pool discarded after a fork.
  • The reproduction above, and a threaded workload on MRI, TruffleRuby 40 and JRuby 10, leave transactions half-written on 0.9.0 and none with this change.

Copilot AI balanced review requested due to automatic review settings November 21, 2026 18:50

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 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 run gh pr ready --undo.
Click "Ready for review" or run gh pr ready to 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|

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in dd5cc27: the cleanup now returns before copying the pool list unless the process is over the limit.

Comment thread test/unit/tenant_test.rb Outdated
Comment on lines +1283 to +1287
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)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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>
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>
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.

2 participants