From 11c6de493c2630f9911315cbfaf213fa39b33469 Mon Sep 17 00:00:00 2001 From: Lucas Carlson Date: Tue, 1 Dec 2026 16:17:02 -0800 Subject: [PATCH 1/2] fix: prune messages with NOT EXISTS and keyset paging MessagePruner#prunable guarded each message with six NOT IN subqueries. The effects (status != 'completed') and broadcasts (status != 'delivered') lists cannot use an index, so SQLite scanned both tables for every batch, and #prune_relation re-ran the whole query for every batch, including the final empty one. Rewrite the six guards as correlated NOT EXISTS, which probe the existing message_id indexes, and page by id so each batch resumes after the last. A batch shorter than batch_size ends the loop without another query. Tests compare against the previous NOT IN query for every combination of guards, cover batch boundaries and the query count, and assert on SQLite that effects and broadcasts are searched by message_id. --- CHANGELOG.md | 10 + lib/solid_objects/message_pruner.rb | 51 ++-- .../lib/solid_objects/message_pruner.rbs | 14 ++ test/integration/message_pruner_test.rb | 237 ++++++++++++++++++ 4 files changed, 293 insertions(+), 19 deletions(-) create mode 100644 test/integration/message_pruner_test.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index c032226..ac93d3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- Make `SolidObjects::MessagePruner#prune` fast on large tables. The guards + that keep a message alive (ready, claimed, dead-lettered, retried, unfinished + effects and undelivered broadcasts) are now correlated `NOT EXISTS` + subqueries instead of `NOT IN` lists. The `status != 'completed'` and + `status != 'delivered'` lists could not use an index, so SQLite scanned the + whole effects and broadcasts tables for every batch. Each batch now also + resumes after the last id of the previous one, and pruning stops after a + short batch instead of running one more full query. The same messages are + pruned on every database. No migration is needed. + ## 1.0.6 - 2026-11-08 - Add `docs/compare/temporal.md`, a comparison with the Temporal Ruby SDK. diff --git a/lib/solid_objects/message_pruner.rb b/lib/solid_objects/message_pruner.rb index 927fd8c..4851520 100644 --- a/lib/solid_objects/message_pruner.rb +++ b/lib/solid_objects/message_pruner.rb @@ -41,38 +41,51 @@ def policy_relations relations << default_relation end + # Messages with no live reference. Each guard is a correlated NOT EXISTS + # rather than NOT IN: the planner can answer it with an index probe on the + # referencing table's message_id, even when the guard filters on a + # non-indexed column such as status, and a NULL in the referencing column + # cannot make the whole predicate unknown. + # # @rbs () -> ActiveRecord::Relation[Message] def prunable - Message - .where.not(id: ReadyMessage.select(:message_id)) - .where.not(id: ClaimedMessage.select(:message_id)) - .where.not(id: DeadLetter.select(:message_id)) - .where.not( - id: DeadLetter - .where.not(retried_message_id: nil) - .select(:retried_message_id) - ) - .where.not( - id: Effect - .where.not(status: "completed") - .select(:message_id) - ) - .where.not( - id: Broadcast - .where.not(status: "delivered") - .select(:message_id) + reference_guards.reduce(Message.all) do |messages, (references, column)| + messages.where.not( + references.where(references.arel_table[column].eq(Message.arel_table[:id])).select(1).arel.exists ) + end end + # Rows that keep a message alive, and the column that points at it. + # + # @rbs () -> Array[[ActiveRecord::Relation[untyped], Symbol]] + def reference_guards + [ + [ ReadyMessage.all, :message_id ], + [ ClaimedMessage.all, :message_id ], + [ DeadLetter.all, :message_id ], + [ DeadLetter.where.not(retried_message_id: nil), :retried_message_id ], + [ Effect.where.not(status: "completed"), :message_id ], + [ Broadcast.where.not(status: "delivered"), :message_id ] + ] + end + + # Pages by primary key so each batch resumes after the previous one instead + # of re-walking rows that are still protected. A short page is the last one. + # # @rbs (ActiveRecord::Relation[Message]) -> Integer def prune_relation(relation) deleted = 0 + last_id = 0 loop do - message_ids = relation.limit(batch_size).pluck(:id) + message_ids = relation.where(id: (last_id + 1)..).order(:id).limit(batch_size).pluck(:id) break if message_ids.empty? deleted += Message.where(id: message_ids).delete_all + break if message_ids.size < batch_size + + last_id = message_ids.last end deleted diff --git a/sig/generated/lib/solid_objects/message_pruner.rbs b/sig/generated/lib/solid_objects/message_pruner.rbs index 44b4b2f..e9147a6 100644 --- a/sig/generated/lib/solid_objects/message_pruner.rbs +++ b/sig/generated/lib/solid_objects/message_pruner.rbs @@ -24,9 +24,23 @@ module SolidObjects # @rbs () -> Array[ActiveRecord::Relation[Message]] def policy_relations: () -> Array[ActiveRecord::Relation[Message]] + # Messages with no live reference. Each guard is a correlated NOT EXISTS + # rather than NOT IN: the planner can answer it with an index probe on the + # referencing table's message_id, even when the guard filters on a + # non-indexed column such as status, and a NULL in the referencing column + # cannot make the whole predicate unknown. + # # @rbs () -> ActiveRecord::Relation[Message] def prunable: () -> ActiveRecord::Relation[Message] + # Rows that keep a message alive, and the column that points at it. + # + # @rbs () -> Array[[ActiveRecord::Relation[untyped], Symbol]] + def reference_guards: () -> Array[[ ActiveRecord::Relation[untyped], Symbol ]] + + # Pages by primary key so each batch resumes after the previous one instead + # of re-walking rows that are still protected. A short page is the last one. + # # @rbs (ActiveRecord::Relation[Message]) -> Integer def prune_relation: (ActiveRecord::Relation[Message]) -> Integer diff --git a/test/integration/message_pruner_test.rb b/test/integration/message_pruner_test.rb new file mode 100644 index 0000000..d6f862a --- /dev/null +++ b/test/integration/message_pruner_test.rb @@ -0,0 +1,237 @@ +# frozen_string_literal: true + +require "database_test_helper" + +class MessagePrunerTest < ActiveSupport::TestCase + # Every way a message can be kept alive. A message is protected when any one + # of these rows points at it. + GUARDS = %i[ + ready + claimed + dead_letter + retried + unfinished_effect + undelivered_broadcast + ].freeze + + setup do + @now = Time.current + end + + test "prunes exactly the messages that no guard protects, for every combination of guards" do + messages = (0...(2**GUARDS.size)).to_h do |mask| + guards = GUARDS.each_with_index.select { |_guard, bit| mask[bit] == 1 }.map(&:first) + [ create_message(guards:), guards ] + end + recent = create_message(completed_at: @now - 1.day) + unguarded = messages.select { |_message, guards| guards.empty? }.keys.map(&:id) + expected = legacy_prunable_ids + + assert_equal unguarded, expected, "the legacy query must agree with the guard matrix" + total = SolidObjects::Message.count + assert_equal expected.size, pruner.preview + assert_equal expected.size, pruner.prune + assert_equal total - expected.size, SolidObjects::Message.count + assert_empty SolidObjects::Message.where(id: expected) + assert SolidObjects::Message.exists?(recent.id) + end + + test "an effect or broadcast only protects a message until it finishes" do + effect_states = %w[pending processing completed dead] + broadcast_states = %w[pending processing delivered dead] + effects = effect_states.to_h { |status| [ status, create_message(effects: [ status ]) ] } + broadcasts = broadcast_states.to_h { |status| [ status, create_message(broadcasts: [ status ]) ] } + mixed = create_message(effects: %w[completed completed pending], broadcasts: %w[delivered delivered]) + create_message(effects: %w[completed completed], broadcasts: %w[delivered delivered]) + + assert_equal 3, pruner.prune + + protected_messages = effects.values_at("pending", "processing", "dead") + + broadcasts.values_at("pending", "processing", "dead") + [ mixed ] + assert_equal protected_messages.map(&:id).sort, SolidObjects::Message.order(:id).pluck(:id) + end + + test "a dead letter protects the message it was retried as" do + original = create_message(guards: [ :dead_letter ]) + retry_message = create_message + original.dead_letter.update!(retried_message_id: retry_message.id) + other = create_message + + assert_equal [ other.id ], legacy_prunable_ids + assert_equal 1, pruner.prune + assert SolidObjects::Message.exists?(original.id) + assert SolidObjects::Message.exists?(retry_message.id) + refute SolidObjects::Message.exists?(other.id) + end + + test "paging deletes every prunable message across batch boundaries" do + [ 0, 1, 2, 3, 4, 5, 6, 7 ].each do |prunable_count| + SolidObjects::Message.delete_all + kept = [] + # Protected messages sit before, between and after the prunable ones. + kept << create_message(guards: [ :ready ]) + prunable_count.times do |index| + create_message + kept << create_message(guards: [ GUARDS[index % GUARDS.size] ]) if index.even? + end + kept << create_message(guards: [ :unfinished_effect ]) + kept << create_message(completed_at: @now - 1.day) + + assert_equal prunable_count, pruner(batch_size: 3).prune, "#{prunable_count} prunable messages" + assert_equal kept.map(&:id).sort, SolidObjects::Message.order(:id).pluck(:id), "#{prunable_count} prunable messages" + assert_equal 0, pruner(batch_size: 3).prune + end + end + + test "a short batch ends pruning without another query" do + 5.times { create_message } + + assert_equal 2, message_selects { assert_equal 5, pruner(batch_size: 3).prune } + assert_equal 1, message_selects { assert_equal 0, pruner(batch_size: 3).prune } + + 2.times { create_message } + assert_equal 1, message_selects { assert_equal 2, pruner(batch_size: 3).prune } + end + + test "a full final batch is followed by one query that finds nothing" do + 6.times { create_message } + + assert_equal 3, message_selects { assert_equal 6, pruner(batch_size: 3).prune } + end + + test "each batch resumes after the last id of the previous one" do + 4.times { create_message(guards: [ :ready ]) } + deletable = Array.new(5) { create_message } + lower_bounds = [] + subscription = ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload| + next unless payload[:sql].include?("NOT (EXISTS") + + binds = payload[:type_casted_binds] + binds = binds.call if binds.respond_to?(:call) + lower_bounds << binds[-2] + end + + assert_equal 5, pruner(batch_size: 2).prune + + assert_equal [ 1, deletable[1].id + 1, deletable[3].id + 1 ], lower_bounds + ensure + ActiveSupport::Notifications.unsubscribe(subscription) + end + + test "per actor retention still applies when pruning in batches" do + short = Array.new(3) { create_message(actor_type: "short") } + long = Array.new(3) { create_message(actor_type: "long") } + SolidObjects.configuration.message_retention_by_actor_type = { "short" => 1.day } + short.each { |message| message.update!(completed_at: @now - 2.days) } + long.each { |message| message.update!(completed_at: @now - 2.days) } + + assert_equal 3, pruner(batch_size: 2).prune + assert_equal long.map(&:id), SolidObjects::Message.order(:id).pluck(:id) + end + + test "SQLite looks effects and broadcasts up by message id instead of scanning them" do + skip "requires a SQLite query plan" unless database_family == :sqlite + + sql = pruner.send(:policy_relations).last.where(id: 1..).order(:id).limit(1_000).to_sql + plan = SolidObjects::Record.connection.select_all("EXPLAIN QUERY PLAN #{sql}").map { |row| row["detail"] } + + [ SolidObjects::Effect, SolidObjects::Broadcast ].each do |model| + assert plan.any? { |step| step.match?(/\ASEARCH #{model.table_name} USING (COVERING )?INDEX \S+ \(message_id=\?\)/) }, plan.join("\n") + assert plan.none? { |step| step.match?(/\ASCAN #{model.table_name}/) }, plan.join("\n") + end + end + + private + + def pruner(batch_size: 1_000) + SolidObjects::MessagePruner.new(now: @now, batch_size:) + end + + # The query the pruner used before it switched to NOT EXISTS, kept here as the + # oracle that the rewrite selects the same rows. + def legacy_prunable_ids + SolidObjects::Message + .where.not(id: SolidObjects::ReadyMessage.select(:message_id)) + .where.not(id: SolidObjects::ClaimedMessage.select(:message_id)) + .where.not(id: SolidObjects::DeadLetter.select(:message_id)) + .where.not(id: SolidObjects::DeadLetter.where.not(retried_message_id: nil).select(:retried_message_id)) + .where.not(id: SolidObjects::Effect.where.not(status: "completed").select(:message_id)) + .where.not(id: SolidObjects::Broadcast.where.not(status: "delivered").select(:message_id)) + .where(completed_at: ...(@now - SolidObjects.configuration.message_retention)) + .order(:id) + .pluck(:id) + end + + def message_selects + selects = 0 + subscription = ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload| + selects += 1 if payload[:sql].start_with?("SELECT") && payload[:sql].include?("NOT (EXISTS") + end + yield + selects + ensure + ActiveSupport::Notifications.unsubscribe(subscription) + end + + def create_message(guards: [], effects: [], broadcasts: [], actor_type: "pruner", completed_at: nil) + completed_at ||= @now - SolidObjects.configuration.message_retention - 1.day + instance = SolidObjects::Instance.create!(actor_type:, actor_id: SecureRandom.uuid, state: {}) + message = SolidObjects::Message.create!( + instance:, actor_type:, actor_id: instance.actor_id, operation: "run", delivery_mode: "async", + arguments: {}, sequence: 1, max_attempts: 3, request_id: SecureRandom.uuid, + enqueued_at: completed_at, available_at: completed_at, completed_at: + ) + attach_guards(message, guards) + effects.each { |status| create_effect(message, status) } + broadcasts.each { |status| create_broadcast(message, status) } + message + end + + def attach_guards(message, guards) + guards.each do |guard| + case guard + when :ready + SolidObjects::ReadyMessage.create!(message:, instance: message.instance, sequence: message.sequence, + available_at: @now, created_at: @now) + when :claimed + SolidObjects::ClaimedMessage.create!(message:, instance: message.instance, activation_generation: 1, claimed_at: @now) + when :dead_letter + create_dead_letter(message) + when :retried + retry_of = create_message + SolidObjects::DeadLetter.where(message_id: retry_of.id).delete_all + create_dead_letter(retry_of, retried_message_id: message.id) + when :unfinished_effect + create_effect(message, "pending") + when :undelivered_broadcast + create_broadcast(message, "pending") + end + end + end + + def create_dead_letter(message, retried_message_id: nil) + SolidObjects::DeadLetter.create!( + message:, instance: message.instance, actor_type: message.actor_type, actor_id: message.actor_id, + operation: message.operation, arguments: {}, attempts: 1, exception_class: "RuntimeError", + exception_message: "boom", backtrace: [], first_failed_at: @now, last_failed_at: @now, + retried_message_id: + ) + end + + def create_effect(message, status) + SolidObjects::Effect.create!( + message:, instance: message.instance, effect_id: SecureRandom.uuid, name: "work", arguments: {}, + status:, max_attempts: 3, available_at: @now, + completed_at: (@now if status == "completed") + ) + end + + def create_broadcast(message, status) + SolidObjects::Broadcast.create!( + message:, instance: message.instance, broadcast_id: SecureRandom.uuid, + observable_name: "obs-#{SecureRandom.hex(4)}", value: {}, state_version: 1, + activation_generation: 1, status:, available_at: @now, + delivered_at: (@now if status == "delivered") + ) + end +end From ecbea5acf903aaca858eae78bf715c3f47ef5899 Mon Sep 17 00:00:00 2001 From: Lucas Carlson Date: Tue, 1 Dec 2026 16:23:32 -0800 Subject: [PATCH 2/2] test: make the pruner plan and cursor checks hold across databases The SQLite plan assertion depended on whatever statistics earlier tests left behind. Seed 3,000 effects and broadcasts and ANALYZE inside restoring_sqlite_statistics, like the effect recovery plan test. MySQL clients inline the id cursor instead of binding it, so read it from the SQL when there are no binds. Inline the guard list in MessagePruner#prunable. --- lib/solid_objects/message_pruner.rb | 27 ++++------- .../lib/solid_objects/message_pruner.rbs | 15 ++---- test/integration/message_pruner_test.rb | 46 +++++++++++++++---- 3 files changed, 53 insertions(+), 35 deletions(-) diff --git a/lib/solid_objects/message_pruner.rb b/lib/solid_objects/message_pruner.rb index 4851520..cc19a19 100644 --- a/lib/solid_objects/message_pruner.rb +++ b/lib/solid_objects/message_pruner.rb @@ -41,25 +41,14 @@ def policy_relations relations << default_relation end - # Messages with no live reference. Each guard is a correlated NOT EXISTS - # rather than NOT IN: the planner can answer it with an index probe on the - # referencing table's message_id, even when the guard filters on a - # non-indexed column such as status, and a NULL in the referencing column - # cannot make the whole predicate unknown. + # Messages that no live row points at. Each guard is a correlated NOT EXISTS + # rather than NOT IN, so the database can answer it with an index probe on + # the referencing table, even for the `status !=` guards that NOT IN could + # only answer by scanning, and a NULL in the referencing column cannot make + # the predicate unknown. # # @rbs () -> ActiveRecord::Relation[Message] def prunable - reference_guards.reduce(Message.all) do |messages, (references, column)| - messages.where.not( - references.where(references.arel_table[column].eq(Message.arel_table[:id])).select(1).arel.exists - ) - end - end - - # Rows that keep a message alive, and the column that points at it. - # - # @rbs () -> Array[[ActiveRecord::Relation[untyped], Symbol]] - def reference_guards [ [ ReadyMessage.all, :message_id ], [ ClaimedMessage.all, :message_id ], @@ -67,7 +56,11 @@ def reference_guards [ DeadLetter.where.not(retried_message_id: nil), :retried_message_id ], [ Effect.where.not(status: "completed"), :message_id ], [ Broadcast.where.not(status: "delivered"), :message_id ] - ] + ].reduce(Message.all) do |messages, (references, column)| + messages.where.not( + references.where(references.arel_table[column].eq(Message.arel_table[:id])).select(1).arel.exists + ) + end end # Pages by primary key so each batch resumes after the previous one instead diff --git a/sig/generated/lib/solid_objects/message_pruner.rbs b/sig/generated/lib/solid_objects/message_pruner.rbs index e9147a6..40f8249 100644 --- a/sig/generated/lib/solid_objects/message_pruner.rbs +++ b/sig/generated/lib/solid_objects/message_pruner.rbs @@ -24,20 +24,15 @@ module SolidObjects # @rbs () -> Array[ActiveRecord::Relation[Message]] def policy_relations: () -> Array[ActiveRecord::Relation[Message]] - # Messages with no live reference. Each guard is a correlated NOT EXISTS - # rather than NOT IN: the planner can answer it with an index probe on the - # referencing table's message_id, even when the guard filters on a - # non-indexed column such as status, and a NULL in the referencing column - # cannot make the whole predicate unknown. + # Messages that no live row points at. Each guard is a correlated NOT EXISTS + # rather than NOT IN, so the database can answer it with an index probe on + # the referencing table, even for the `status !=` guards that NOT IN could + # only answer by scanning, and a NULL in the referencing column cannot make + # the predicate unknown. # # @rbs () -> ActiveRecord::Relation[Message] def prunable: () -> ActiveRecord::Relation[Message] - # Rows that keep a message alive, and the column that points at it. - # - # @rbs () -> Array[[ActiveRecord::Relation[untyped], Symbol]] - def reference_guards: () -> Array[[ ActiveRecord::Relation[untyped], Symbol ]] - # Pages by primary key so each batch resumes after the previous one instead # of re-walking rows that are still protected. A short page is the last one. # diff --git a/test/integration/message_pruner_test.rb b/test/integration/message_pruner_test.rb index d6f862a..b739dc3 100644 --- a/test/integration/message_pruner_test.rb +++ b/test/integration/message_pruner_test.rb @@ -106,9 +106,7 @@ class MessagePrunerTest < ActiveSupport::TestCase subscription = ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload| next unless payload[:sql].include?("NOT (EXISTS") - binds = payload[:type_casted_binds] - binds = binds.call if binds.respond_to?(:call) - lower_bounds << binds[-2] + lower_bounds << cursor_of(payload) end assert_equal 5, pruner(batch_size: 2).prune @@ -132,12 +130,21 @@ class MessagePrunerTest < ActiveSupport::TestCase test "SQLite looks effects and broadcasts up by message id instead of scanning them" do skip "requires a SQLite query plan" unless database_family == :sqlite - sql = pruner.send(:policy_relations).last.where(id: 1..).order(:id).limit(1_000).to_sql - plan = SolidObjects::Record.connection.select_all("EXPLAIN QUERY PLAN #{sql}").map { |row| row["detail"] } + connection = SolidObjects::Record.connection + restoring_sqlite_statistics(connection) do + # The planner only prefers the message_id index once statistics say the + # tables are large and each message owns a few rows. + messages = Array.new(300) { create_message } + seed_effects_and_broadcasts(messages, per_message: 10) + connection.execute("ANALYZE") - [ SolidObjects::Effect, SolidObjects::Broadcast ].each do |model| - assert plan.any? { |step| step.match?(/\ASEARCH #{model.table_name} USING (COVERING )?INDEX \S+ \(message_id=\?\)/) }, plan.join("\n") - assert plan.none? { |step| step.match?(/\ASCAN #{model.table_name}/) }, plan.join("\n") + sql = pruner.send(:policy_relations).last.where(id: 1..).order(:id).limit(1_000).to_sql + plan = connection.select_all("EXPLAIN QUERY PLAN #{sql}").map { |row| row["detail"] } + + [ SolidObjects::Effect, SolidObjects::Broadcast ].each do |model| + assert plan.any? { |step| step.match?(/\ASEARCH #{model.table_name} USING (COVERING )?INDEX \S+ \(message_id=\?\)/) }, plan.join("\n") + assert plan.none? { |step| step.match?(/\ASCAN #{model.table_name}/) }, plan.join("\n") + end end end @@ -162,6 +169,29 @@ def legacy_prunable_ids .pluck(:id) end + # Postgres and SQLite send the cursor as a bind; the MySQL clients inline it. + def cursor_of(payload) + binds = payload[:type_casted_binds] + binds = binds.call if binds.respond_to?(:call) + return binds[-2] if binds.present? + + payload[:sql][/\bid[`"]? >= (\d+)/, 1].to_i + end + + def seed_effects_and_broadcasts(messages, per_message:) + now = Time.current + rows = messages.flat_map { |message| Array.new(per_message) { |index| [ message, index ] } } + SolidObjects::Effect.insert_all!(rows.map { |message, _index| + { message_id: message.id, instance_id: message.instance_id, effect_id: SecureRandom.uuid, name: "work", arguments: {}, + status: "completed", max_attempts: 3, available_at: now, completed_at: now, created_at: now, updated_at: now } + }) + SolidObjects::Broadcast.insert_all!(rows.map { |message, index| + { message_id: message.id, instance_id: message.instance_id, broadcast_id: SecureRandom.uuid, + observable_name: "obs#{index}", value: {}, state_version: 1, activation_generation: 1, status: "delivered", + available_at: now, delivered_at: now, created_at: now, updated_at: now } + }) + end + def message_selects selects = 0 subscription = ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload|