Repository navigation
fix: prune messages with NOT EXISTS and keyset paging #113
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,267 @@ | ||
| # 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") | ||
|
|
||
| lower_bounds << cursor_of(payload) | ||
| 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 | ||
|
|
||
| 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") | ||
|
|
||
| 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 | ||
|
|
||
| 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 | ||
|
|
||
| # 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| | ||
| 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 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.