Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,23 @@

## Unreleased

- Drop six indexes that a unique index already covers and index
`dead_letters.retried_message_id` (#115). Each of `ready_messages` and
`claimed_messages` repeated its `message_id` and `instance_id` unique
indexes, and `dead_letters` and `broadcasts` repeated their `message_id` ones,
so every insert and delete maintained two b-trees for one access path. The
foreign key `fk_so_dead_letters_retry` had no index on SQLite and PostgreSQL,
so each pruned message scanned `dead_letters`; the new index
`idx_so_dead_letters_retried_message` removes that scan, and MySQL keeps the
index it already created for the key. This is a minor-release change because
an existing installation has to run the migration. Install it with
`bin/rails solid_objects:install:migrations` and run your usual `db:migrate`
before you rely on the new indexes. Nothing in the gem reads the dropped
indexes by name, and the migration is reversible. A new installation reaches
the same index set. `index_solid_objects_messages_on_instance_id` and
`index_solid_objects_reminders_on_instance_id` repeat a unique index in the
same way and are left as they are.

## 1.1.0 - 2026-12-02

- Reminders (#110): `schedule` accepts `missed: :skip`, which drops missed
Expand Down
50 changes: 50 additions & 0 deletions db/migrate/20261202000000_drop_redundant_solid_objects_indexes.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# rbs_inline: enabled

class DropRedundantSolidObjectsIndexes < ActiveRecord::Migration[7.1]
# Plain indexes that a unique index on the same table already covers, by
# leading column. The unique index stays; the plain one only costs writes.
REDUNDANT_INDEXES = [
[ :ready_messages, :message_id ],
[ :claimed_messages, :message_id ],
[ :dead_letters, :message_id ],
[ :broadcasts, :message_id ],
[ :ready_messages, :instance_id ],
[ :claimed_messages, :instance_id ]
].freeze

RETRIED_MESSAGE_INDEX = "idx_so_dead_letters_retried_message"

# @rbs () -> void
def up
REDUNDANT_INDEXES.each do |table_name, column|
remove_index table(table_name), column, name: plain_index_name(table_name, column), if_exists: true
end
# MySQL indexes a foreign key on its own, so only add one when the column
# has none, whatever that index is called.
return if index_exists?(table(:dead_letters), :retried_message_id)

add_index table(:dead_letters), :retried_message_id, name: RETRIED_MESSAGE_INDEX
end

# @rbs () -> void
def down
# Restore the six indexes before dropping ours, so that no foreign key is
# ever left without a covering index.
REDUNDANT_INDEXES.each do |table_name, column|
add_index table(table_name), column, name: plain_index_name(table_name, column), if_not_exists: true
end
remove_index table(:dead_letters), :retried_message_id, name: RETRIED_MESSAGE_INDEX, if_exists: true
end

private

# @rbs (Symbol) -> String
def table(name)
SolidObjects.table_name(name)
end

# @rbs (Symbol, Symbol) -> String
def plain_index_name(table_name, column)
"index_#{table(table_name)}_on_#{column}"
end
end
224 changes: 224 additions & 0 deletions test/models/redundant_index_schema_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
# frozen_string_literal: true

require "database_test_helper"
require "tmpdir"

class RedundantIndexScratch < ActiveRecord::Base
self.abstract_class = true
end

class RedundantIndexFresh < ActiveRecord::Base
self.abstract_class = true
end

# A plain index whose leading columns already lead a unique index on the same
# table is a second b-tree for one access path, and every write maintains both.
class RedundantIndexSchemaTest < ActiveSupport::TestCase
MIGRATION_FILE = "20261202000000_drop_redundant_solid_objects_indexes.rb"

# Known duplicates that a possible follow-up may drop. They are allowlisted
# rather than dropped, and the test fails if one disappears so the list
# cannot go stale.
ALLOWLIST = {
"index_solid_objects_messages_on_instance_id" => "idx_so_messages_instance_sequence",
"index_solid_objects_reminders_on_instance_id" => "idx_so_reminders_name"
}.freeze

DROPPED = {
"ready_messages" => %w[message_id instance_id],
"claimed_messages" => %w[message_id instance_id],
"dead_letters" => %w[message_id],
"broadcasts" => %w[message_id]
}.freeze

KEPT_UNIQUE = %w[
idx_so_ready_message idx_so_claimed_message idx_so_dead_letters_message
idx_so_broadcasts_observable idx_so_ready_instance_sequence idx_so_claimed_instance
].freeze

test "no plain index repeats the leading columns of a unique index" do
offenders = redundant_indexes(connection).reject { |index| ALLOWLIST.key?(index.name) }

assert_empty offenders.map(&:name)
end

test "every allowlisted index still exists" do
names = all_indexes(connection).map(&:name)

assert_empty ALLOWLIST.keys - names
end

test "two unique indexes sharing a leading column are not redundant" do
names = indexes_of(connection, :messages).map(&:name)

assert_includes names, "idx_so_messages_instance_sequence"
assert_includes names, "idx_so_messages_idempotency"
refute_includes redundant_indexes(connection).map(&:name), "idx_so_messages_idempotency"
end

test "the detector flags a plain index covered by a unique index" do
Dir.mktmpdir do |directory|
RedundantIndexScratch.establish_connection(adapter: "sqlite3", database: File.join(directory, "d.sqlite3"))
scratch = RedundantIndexScratch.connection
scratch.create_table(:things) do |table|
table.integer :a
table.integer :b
end
scratch.add_index :things, :a, name: "plain_a"
scratch.add_index :things, [ :a, :b ], unique: true, name: "unique_ab"

assert_equal [ "plain_a" ], redundant_indexes(scratch, tables: [ "things" ]).map(&:name)
ensure
RedundantIndexScratch.remove_connection
end
end

test "the six covered indexes are gone, their unique indexes and the two required plain indexes stay" do
assert_final_index_set(connection)
end

test "dead_letters.retried_message_id has exactly one index" do
assert_equal 1, retried_message_indexes(connection).size
end

test "every message and instance foreign key still has a covering index" do
assert_empty uncovered_foreign_keys(connection, columns: %w[message_id instance_id])
end

# MySQL refuses a foreign key without a covering index, and creates one for
# a key that has none. SQLite and PostgreSQL leave a few keys (the claimed_by
# columns) unindexed outside this change, so the full check is MySQL's.
test "on MySQL every foreign key has a covering index" do
skip "only MySQL requires foreign key coverage" unless database_family == :mysql

assert_empty uncovered_foreign_keys(connection)
end

test "down restores the six indexes and removes the added one, and up reapplies" do
migration_class = migrations.fetch(migration_index)
apply(migration_class, connection, :down)
begin
DROPPED.each do |table, columns|
columns.each { |column| assert_includes index_names(connection, table), plain_name(table, column) }
end
assert_empty uncovered_foreign_keys(connection, columns: %w[message_id instance_id])
ensure
apply(migration_class, connection, :up)
end
assert_final_index_set(connection)
end

test "an upgrade of an installed schema ends in the same index set as a fresh install" do
Dir.mktmpdir do |directory|
RedundantIndexScratch.establish_connection(adapter: "sqlite3", database: File.join(directory, "u.sqlite3"))
scratch = RedundantIndexScratch.connection
migrations.first(migration_index).each { |migration| apply(migration, scratch, :up) }
DROPPED.each do |table, columns|
columns.each { |column| assert_includes index_names(scratch, table), plain_name(table, column) }
end
assert_empty retried_message_indexes(scratch)

apply(migrations.fetch(migration_index), scratch, :up)

assert_final_index_set(scratch)
assert_equal signature(fresh_sqlite_install(directory)), signature(scratch)
ensure
RedundantIndexScratch.remove_connection
RedundantIndexFresh.remove_connection
end
end

private

def connection
SolidObjects::Record.connection
end

def migrations
@migrations ||= SolidObjects::SchemaBootstrap.migrations
end

def migration_index
index = migrations.index { |migration| migration.instance_method(:up).source_location.first.end_with?(MIGRATION_FILE) }
assert index, "#{MIGRATION_FILE} is not in db/migrate"
index
end

def apply(migration_class, target, direction)
migration = migration_class.new
migration.define_singleton_method(:connection) { target }
migration.migrate(direction)
end

def table_names(target)
prefix = SolidObjects.table_name("")
target.tables.select { |name| name.start_with?(prefix) }
end

def indexes_of(target, table)
target.indexes(SolidObjects.table_name(table))
end

def index_names(target, table)
indexes_of(target, table).map(&:name)
end

def all_indexes(target, tables: table_names(target))
tables.flat_map { |table| target.indexes(table) }
end

def plain_name(table, column)
"index_#{SolidObjects.table_name(table)}_on_#{column}"
end

def redundant_indexes(target, tables: table_names(target))
tables.flat_map do |table|
indexes = target.indexes(table)
uniques = indexes.select(&:unique)
indexes.reject(&:unique).select do |index|
uniques.any? { |unique| unique.columns.first(index.columns.size) == index.columns }
end
end
end

def retried_message_indexes(target)
indexes_of(target, :dead_letters).select { |index| index.columns == [ "retried_message_id" ] }
end

def uncovered_foreign_keys(target, columns: nil)
table_names(target).flat_map do |table|
indexes = target.indexes(table)
keys = target.foreign_keys(table)
keys = keys.select { |foreign_key| columns.include?(foreign_key.column) } if columns
keys.reject do |foreign_key|
key_columns = Array(foreign_key.column)
indexes.any? { |index| index.columns.first(key_columns.size) == key_columns }
end.map { |foreign_key| "#{table}.#{foreign_key.column}" }
end
end

def assert_final_index_set(target)
DROPPED.each do |table, columns|
columns.each { |column| refute_includes index_names(target, table), plain_name(table, column) }
end
names = all_indexes(target).map(&:name)
KEPT_UNIQUE.each { |name| assert_includes names, name }
assert_includes names, plain_name(:effects, :message_id)
assert_includes names, plain_name(:dead_letters, :instance_id)
assert_equal 1, retried_message_indexes(target).size
assert_empty uncovered_foreign_keys(target, columns: %w[message_id instance_id])
end

# Both sides are SQLite: a MySQL database adds indexes for foreign keys that
# SQLite does not, so the live connection is not comparable with a scratch one.
def fresh_sqlite_install(directory)
RedundantIndexFresh.establish_connection(adapter: "sqlite3", database: File.join(directory, "f.sqlite3"))
fresh = RedundantIndexFresh.connection
SolidObjects::SchemaBootstrap.install(connection: fresh)
fresh
end

def signature(target)
all_indexes(target).map { |index| [ index.table, index.columns, index.unique ] }.sort_by(&:inspect)
end
end