diff --git a/CHANGELOG.md b/CHANGELOG.md index ac93d3c..552a193 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,27 @@ ## Unreleased +- `schedule` accepts `missed: :skip`, which drops missed occurrences of a + recurring reminder and waits for the next scheduled time. An occurrence that + is late but still before the next scheduled time runs. Once a later + scheduled time has passed, the scheduler enqueues nothing and advances to + the first scheduled time after now. `:latest` and `:all` are unchanged. +- `ReminderStatus` reports `last_run_at`, the scheduler's now when it last + enqueued the reminder, and `error_class`, the error that paused it. + Scheduling a name that already exists keeps `last_run_at` and `occurrence` + and clears `error_class`. +- A reminder whose operation the actor no longer declares is paused when it + comes due, with `error_class` `"SolidObjects::UnknownMessage"`, instead of + staying scheduled. The scheduler no longer raises on it, and no longer + claims it again on every pass. Scheduling the same name again arms it. +- `docs/reminders.md` documents the three missed policies and when a reminder + fires. +- Add `db/migrate/20261130000000_add_solid_objects_reminder_run_history.rb`, + which adds `reminders.last_run_at` and `reminders.error_class` and allows + `skip` in the `missed_policy` check. An application installs it with + `bin/rails solid_objects:install:migrations` and runs it before it upgrades a + scheduler, because the scheduler writes `last_run_at` on every enqueue. The + doctor now reports the columns as missing when they are not installed. - 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` diff --git a/db/migrate/20261130000000_add_solid_objects_reminder_run_history.rb b/db/migrate/20261130000000_add_solid_objects_reminder_run_history.rb new file mode 100644 index 0000000..8028c8e --- /dev/null +++ b/db/migrate/20261130000000_add_solid_objects_reminder_run_history.rb @@ -0,0 +1,30 @@ +# rbs_inline: enabled + +class AddSolidObjectsReminderRunHistory < ActiveRecord::Migration[7.1] + # @rbs () -> void + def up + add_column reminders_table, :last_run_at, :datetime, precision: 6 + add_column reminders_table, :error_class, :string, limit: 191 + remove_check_constraint reminders_table, name: "chk_so_reminders_missed" + add_check_constraint reminders_table, + "missed_policy IN ('latest', 'all', 'skip')", + name: "chk_so_reminders_missed" + end + + # @rbs () -> void + def down + remove_check_constraint reminders_table, name: "chk_so_reminders_missed" + add_check_constraint reminders_table, + "missed_policy IN ('latest', 'all')", + name: "chk_so_reminders_missed" + remove_column reminders_table, :error_class + remove_column reminders_table, :last_run_at + end + + private + + # @rbs () -> String + def reminders_table + SolidObjects.table_name(:reminders) + end +end diff --git a/docs/architecture.md b/docs/architecture.md index ea8540b..729a429 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -611,10 +611,11 @@ row with an idempotency key derived from reminder ID and occurrence. The mailbox insert and reminder advancement commit atomically. The mailbox provides sequential processing and ordinary retry behavior. -Solid Objects persists each occurrence by its mailbox row. Unlike Orleans reminders, an outage does not intentionally discard a due occurrence. Recurring catch-up is configurable: +Solid Objects persists each occurrence by its mailbox row. Unlike Orleans reminders, an outage does not intentionally discard a due occurrence unless the reminder opts into `:skip`. Recurring catch-up is configurable: - `:latest` enqueues the current occurrence and advances beyond the current time. - `:all` enqueues one occurrence per scheduler pass and advances one interval, allowing bounded catch-up through ordinary scheduler work. +- `:skip` enqueues an occurrence only while no later aligned time has passed. Otherwise it enqueues nothing and advances beyond the current time, dropping the missed occurrences. ### Schedule reconciliation diff --git a/docs/reminders.md b/docs/reminders.md index 6d47814..d3a5496 100644 --- a/docs/reminders.md +++ b/docs/reminders.md @@ -13,8 +13,42 @@ def schedule_evaluation end ``` -Use `missed: :latest` to coalesce missed occurrences or `missed: :all` to -enqueue each one. +A recurring reminder that comes due late, for example after an outage, uses +its `missed:` policy. The default is `:latest`. The policy can be a symbol or +a string. + +- `missed: :latest` coalesces missed occurrences (the JS PRD's `run_once`). The + scheduler enqueues one occurrence and advances to the first scheduled time + after now. +- `missed: :all` enqueues each missed occurrence (the JS PRD's `catch_up`). The + scheduler advances one interval at a time, even into the past, so each + missed occurrence becomes its own message on a later scheduler pass. +- `missed: :skip` drops missed occurrences and waits for the next scheduled + time. An occurrence that is late but still before the next scheduled time + runs. Once a later scheduled time has also passed, the scheduler enqueues + nothing and advances to the first scheduled time after now. + +A one-shot reminder has no next scheduled time, so it fires once when it is +due under every policy. + +## When a reminder fires + +`schedule(at:)` stores `at` as the reminder's `next_run_at`. The scheduler +treats a reminder as due when `next_run_at` is on or before now. Now is the +time passed to `run_due_reminders(now:)` in a test, and otherwise the database +clock, which the scheduler reads and converts to UTC. A due reminder becomes an +ordinary internal mailbox message, so retry and retention of a fired reminder +follow that message. Time zone and clock skew are not a documented guarantee. + +A fired reminder is an internal message, so `authorize_message` is not called +for it. An external enqueue of the same operation still is. + +If the actor no longer declares the reminder's operation when it comes due, +the scheduler enqueues nothing and pauses the reminder. Its status becomes +`"paused"` and its `error_class` is `"SolidObjects::UnknownMessage"`. A paused +reminder is not claimed again. Scheduling the same name again arms it. A +failure of an occurrence that was already enqueued does not pause the +reminder: retries and dead letters stay on that message. ## A schedule call needs an operation @@ -157,7 +191,19 @@ of an actor removes its reminders. `reminder` returns the status of one reminder, or `nil`. `reminders` lists every key of one operation. Both include the changes that the current turn -staged. +staged. A status reports `next_run_at`, `interval_seconds`, `missed_policy`, +and `status`, and the run history of the reminder: + +- `occurrence` counts the times the scheduler enqueued the reminder. It starts + at 0. A window that `:skip` drops and a retry of an enqueued message do not + count. +- `last_run_at` is the scheduler's now when it last enqueued the reminder, or + `nil` if it never has. It is not when the operation finished. +- `error_class` names the error that paused the reminder, or is `nil`. + +Scheduling a name that already exists, including a one-shot that already +fired, keeps `occurrence` and `last_run_at`, clears `error_class`, and sets the +status to `"scheduled"`. The read in the same turn shows the same history. Self-scheduling actors should also have a low-frequency application reconciler. It may read `SolidObjects::Instance.states_for`, `.without_pending_work`, and diff --git a/lib/solid_objects/actor.rb b/lib/solid_objects/actor.rb index bf64c62..29264dd 100644 --- a/lib/solid_objects/actor.rb +++ b/lib/solid_objects/actor.rb @@ -17,7 +17,8 @@ class Actor UnscheduleIntent = Data.define(:name) UnscheduleAllIntent = Data.define(:operation) ReminderStatus = Data.define(:name, :operation, :key, :next_run_at, :interval_seconds, - :missed_policy, :occurrence, :status, :handle) + :missed_policy, :occurrence, :status, :handle, :last_run_at, :error_class) + MISSED_POLICIES = %w[latest all skip].freeze OutboundMessageIntent = Data.define(:actor_type, :actor_id, :operation, :arguments, :available_at, :idempotency_key) class << self @@ -256,8 +257,8 @@ def schedule(at:, every: nil, missed: :latest, key: nil) raise ArgumentError, "reminder interval must be positive" end missed_policy = missed.to_s - unless %w[all latest].include?(missed_policy) - raise ArgumentError, "missed reminder policy must be all or latest" + unless MISSED_POLICIES.include?(missed_policy) + raise ArgumentError, "missed reminder policy must be latest, all, or skip" end reminder_key = validated_reminder_key(key) call = ScheduleCall.new(at:, key: reminder_key) @@ -338,19 +339,27 @@ def handle_name(handle, key:) end # The view is the committed schedule with this turn's staged intents applied - # in order, so a read agrees with what the commit will leave behind. + # in order, so a read agrees with what the commit will leave behind. A + # completed one-shot is not reported, but one this turn schedules again is in + # the view until the intents are applied, because the commit reuses its row + # and keeps its run history. # @rbs () -> Hash[String, ReminderStatus] def reminder_view - reminder_intents.each_with_object(committed_reminders) do |intent, view| - apply_reminder_intent(view, intent) + view = reminder_intents.each_with_object(committed_reminders) do |intent, staged| + apply_reminder_intent(staged, intent) end + view.delete_if { |_name, status| status.status == "completed" } end # @rbs () -> Hash[String, ReminderStatus] def committed_reminders return {} unless instance_id - Reminder.where(instance_id:).where.not(status: "completed").each_with_object({}) do |row, view| + # Completed rows only matter for names this turn schedules again, and an + # actor that keys a one-shot per item accumulates them. + rearmed = reminder_intents.filter_map { |intent| intent.name if intent.is_a?(ReminderIntent) } + rows = Reminder.where(instance_id:) + rows.where.not(status: "completed").or(rows.where(name: rearmed)).each_with_object({}) do |row, view| view[row.name] = reminder_status( name: row.name, operation: row.operation, @@ -358,7 +367,9 @@ def committed_reminders interval_seconds: row.interval_seconds, missed_policy: row.missed_policy, occurrence: row.occurrence, - status: row.status + status: row.status, + last_run_at: row.last_run_at, + error_class: row.error_class ) end end @@ -368,19 +379,24 @@ def apply_reminder_intent(view, intent) return view.delete_if { |_name, status| status.operation == intent.operation } if intent.is_a?(UnscheduleAllIntent) return view.delete(intent.name) if intent.is_a?(UnscheduleIntent) + # A replace moves the alarm but keeps its run history, and clears the + # error that paused it, as the commit will. + existing = view[intent.name] view[intent.name] = reminder_status( name: intent.name, operation: intent.operation, next_run_at: intent.at, interval_seconds: intent.interval_seconds, missed_policy: intent.missed_policy, - occurrence: view[intent.name]&.occurrence || 0, - status: "scheduled" + occurrence: existing&.occurrence || 0, + status: "scheduled", + last_run_at: existing&.last_run_at, + error_class: nil ) end - # @rbs (name: String, operation: String, next_run_at: Time?, interval_seconds: untyped, missed_policy: String, occurrence: Integer, status: String) -> ReminderStatus - def reminder_status(name:, operation:, next_run_at:, interval_seconds:, missed_policy:, occurrence:, status:) + # @rbs (name: String, operation: String, next_run_at: Time?, interval_seconds: untyped, missed_policy: String, occurrence: Integer, status: String, last_run_at: Time?, error_class: String?) -> ReminderStatus + def reminder_status(name:, operation:, next_run_at:, interval_seconds:, missed_policy:, occurrence:, status:, last_run_at:, error_class:) ReminderStatus.new( name:, operation:, @@ -390,7 +406,9 @@ def reminder_status(name:, operation:, next_run_at:, interval_seconds:, missed_p missed_policy:, occurrence:, status:, - handle: { REMINDER_HANDLE_KEY => name } + handle: { REMINDER_HANDLE_KEY => name }, + last_run_at:, + error_class: ) end diff --git a/lib/solid_objects/doctor.rb b/lib/solid_objects/doctor.rb index 0610c35..c449882 100644 --- a/lib/solid_objects/doctor.rb +++ b/lib/solid_objects/doctor.rb @@ -76,7 +76,7 @@ def to_s id message_id instance_id process_id activation_token activation_generation claimed_at ], - reminders: %w[id instance_id operation next_run_at status], + reminders: %w[id instance_id operation next_run_at status last_run_at error_class], effects: %w[ id message_id instance_id effect_id status available_at success_operation failure_operation diff --git a/lib/solid_objects/executor.rb b/lib/solid_objects/executor.rb index fcfcb0e..b29910e 100644 --- a/lib/solid_objects/executor.rb +++ b/lib/solid_objects/executor.rb @@ -293,6 +293,9 @@ def schedule_reminders(instance, intents) reminder = Reminder.find_or_initialize_by(instance:, name: intent.name) previous_run_at = reminder.next_run_at + # A move keeps occurrence and last_run_at, which are the alarm's run + # history, and clears error_class, which explained a pause the move + # ends. reminder.assign_attributes( actor_type: instance.actor_type, actor_id: instance.actor_id, @@ -302,6 +305,7 @@ def schedule_reminders(instance, intents) interval_seconds: intent.interval_seconds, missed_policy: intent.missed_policy, status: "scheduled", + error_class: nil, claimed_by: nil, claimed_at: nil ) diff --git a/lib/solid_objects/reminder_scheduler.rb b/lib/solid_objects/reminder_scheduler.rb index dddd7dd..ef97bf5 100644 --- a/lib/solid_objects/reminder_scheduler.rb +++ b/lib/solid_objects/reminder_scheduler.rb @@ -127,11 +127,14 @@ def claim_next(now:) end end - # @rbs (Reminder, now: Time?) -> MessageReference? + # Returns the enqueued message, :skipped when a skip reminder dropped a + # missed window, :paused when its operation is unknown, or nil when the + # reminder or its actor is gone. Anything but nil is scheduler work. + # @rbs (Reminder, now: Time?) -> (MessageReference | :skipped | :paused)? def enqueue(reminder, now:) actor_class = SolidObjects.registry.fetch(reminder.actor_type) unless actor_class.definition.messages.key?(reminder.operation.to_sym) - raise UnknownMessage, "unknown reminder operation #{reminder.operation.inspect}" + return pause(reminder, UnknownMessage.new("unknown reminder operation #{reminder.operation.inspect}")) end mailbox = Mailbox.new(database_adapter:) @@ -143,6 +146,8 @@ def enqueue(reminder, now:) next unless locked_reminder verify_claim!(locked_reminder) schedule_now = now || database_adapter.database_now + next skip_missed_window(locked_reminder, schedule_now) if missed_window?(locked_reminder, schedule_now) + message = mailbox.enqueue_in_transaction( reference: Reference.new(actor_type: instance.actor_type, actor_id: instance.actor_id), operation: locked_reminder.operation, @@ -155,13 +160,14 @@ def enqueue(reminder, now:) locked_reminder.update!( status: recurring ? "scheduled" : "completed", occurrence: locked_reminder.occurrence + 1, + last_run_at: schedule_now, next_run_at: recurring ? next_run_at(locked_reminder, schedule_now) : locked_reminder.next_run_at, claimed_by: nil, claimed_at: nil ) message end - return unless message + return message unless message.is_a?(Message) mailbox.announce(message) SolidObjects.instrument( @@ -179,6 +185,39 @@ def enqueue(reminder, now:) MessageReference.from_message(message) end + # A skip reminder runs an occurrence that is late inside its own slot, but + # once a later aligned time has also passed, every occurrence up to now is + # missed: none is enqueued, and the reminder waits for the next aligned + # time after now. One-shots have no next time, so they always fire. + # @rbs (Reminder, Time) -> bool + def missed_window?(reminder, now) + return false unless reminder.missed_policy == "skip" && reminder.interval_seconds.present? + + now >= reminder.next_run_at + reminder.interval_seconds.to_f + end + + # @rbs (Reminder, Time) -> :skipped + def skip_missed_window(reminder, now) + reminder.update!(next_run_at: next_run_at(reminder, now), claimed_by: nil, claimed_at: nil) + :skipped + end + + # A reminder whose operation is unknown cannot become a message, so it is + # paused with the error recorded rather than left scheduled, where every + # scheduler pass would claim it and fail again. Only a new schedule of the + # same name arms it again. + # @rbs (Reminder, StandardError) -> (:paused | nil) + def pause(reminder, error) + database_adapter.transaction do + locked_reminder = Reminder.lock.find_by(id: reminder.id) + next unless locked_reminder + verify_claim!(locked_reminder) + + locked_reminder.update!(status: "paused", error_class: error.class.name, claimed_by: nil, claimed_at: nil) + :paused + end + end + # @rbs (Reminder) -> void def release(reminder) Reminder @@ -193,6 +232,8 @@ def verify_claim!(reminder) raise LostActivation, "reminder claim changed" end + # latest and skip advance to the first aligned time after now; all advances + # one interval, even into the past, so each missed occurrence is enqueued. # @rbs (Reminder, Time) -> Time def next_run_at(reminder, now) interval = reminder.interval_seconds.to_f diff --git a/sig/generated/lib/solid_objects/actor.rbs b/sig/generated/lib/solid_objects/actor.rbs index 6b4b459..dcaa5be 100644 --- a/sig/generated/lib/solid_objects/actor.rbs +++ b/sig/generated/lib/solid_objects/actor.rbs @@ -135,14 +135,20 @@ module SolidObjects attr_reader handle(): untyped - def self.new: (untyped name, untyped operation, untyped key, untyped next_run_at, untyped interval_seconds, untyped missed_policy, untyped occurrence, untyped status, untyped handle) -> instance - | (name: untyped, operation: untyped, key: untyped, next_run_at: untyped, interval_seconds: untyped, missed_policy: untyped, occurrence: untyped, status: untyped, handle: untyped) -> instance + attr_reader last_run_at(): untyped - def self.members: () -> [ :name, :operation, :key, :next_run_at, :interval_seconds, :missed_policy, :occurrence, :status, :handle ] + attr_reader error_class(): untyped - def members: () -> [ :name, :operation, :key, :next_run_at, :interval_seconds, :missed_policy, :occurrence, :status, :handle ] + def self.new: (untyped name, untyped operation, untyped key, untyped next_run_at, untyped interval_seconds, untyped missed_policy, untyped occurrence, untyped status, untyped handle, untyped last_run_at, untyped error_class) -> instance + | (name: untyped, operation: untyped, key: untyped, next_run_at: untyped, interval_seconds: untyped, missed_policy: untyped, occurrence: untyped, status: untyped, handle: untyped, last_run_at: untyped, error_class: untyped) -> instance + + def self.members: () -> [ :name, :operation, :key, :next_run_at, :interval_seconds, :missed_policy, :occurrence, :status, :handle, :last_run_at, :error_class ] + + def members: () -> [ :name, :operation, :key, :next_run_at, :interval_seconds, :missed_policy, :occurrence, :status, :handle, :last_run_at, :error_class ] end + MISSED_POLICIES: untyped + class OutboundMessageIntent < Data attr_reader actor_type(): untyped @@ -291,7 +297,10 @@ module SolidObjects def handle_name: (reminder_handle, key: untyped) -> String # The view is the committed schedule with this turn's staged intents applied - # in order, so a read agrees with what the commit will leave behind. + # in order, so a read agrees with what the commit will leave behind. A + # completed one-shot is not reported, but one this turn schedules again is in + # the view until the intents are applied, because the commit reuses its row + # and keeps its run history. # @rbs () -> Hash[String, ReminderStatus] def reminder_view: () -> Hash[String, ReminderStatus] @@ -301,8 +310,8 @@ module SolidObjects # @rbs (Hash[String, ReminderStatus], untyped) -> void def apply_reminder_intent: (Hash[String, ReminderStatus], untyped) -> void - # @rbs (name: String, operation: String, next_run_at: Time?, interval_seconds: untyped, missed_policy: String, occurrence: Integer, status: String) -> ReminderStatus - def reminder_status: (name: String, operation: String, next_run_at: Time?, interval_seconds: untyped, missed_policy: String, occurrence: Integer, status: String) -> ReminderStatus + # @rbs (name: String, operation: String, next_run_at: Time?, interval_seconds: untyped, missed_policy: String, occurrence: Integer, status: String, last_run_at: Time?, error_class: String?) -> ReminderStatus + def reminder_status: (name: String, operation: String, next_run_at: Time?, interval_seconds: untyped, missed_policy: String, occurrence: Integer, status: String, last_run_at: Time?, error_class: String?) -> ReminderStatus # @rbs (name: String, operation: String) -> String? def reminder_key_of: (name: String, operation: String) -> String? diff --git a/sig/generated/lib/solid_objects/reminder_scheduler.rbs b/sig/generated/lib/solid_objects/reminder_scheduler.rbs index 7200313..e1704b5 100644 --- a/sig/generated/lib/solid_objects/reminder_scheduler.rbs +++ b/sig/generated/lib/solid_objects/reminder_scheduler.rbs @@ -47,8 +47,28 @@ module SolidObjects # @rbs (now: Time?) -> Reminder? def claim_next: (now: Time?) -> Reminder? - # @rbs (Reminder, now: Time?) -> MessageReference? - def enqueue: (Reminder, now: Time?) -> MessageReference? + # Returns the enqueued message, :skipped when a skip reminder dropped a + # missed window, :paused when its operation is unknown, or nil when the + # reminder or its actor is gone. Anything but nil is scheduler work. + # @rbs (Reminder, now: Time?) -> (MessageReference | :skipped | :paused)? + def enqueue: (Reminder, now: Time?) -> (MessageReference | :skipped | :paused)? + + # A skip reminder runs an occurrence that is late inside its own slot, but + # once a later aligned time has also passed, every occurrence up to now is + # missed: none is enqueued, and the reminder waits for the next aligned + # time after now. One-shots have no next time, so they always fire. + # @rbs (Reminder, Time) -> bool + def missed_window?: (Reminder, Time) -> bool + + # @rbs (Reminder, Time) -> :skipped + def skip_missed_window: (Reminder, Time) -> :skipped + + # A reminder whose operation is unknown cannot become a message, so it is + # paused with the error recorded rather than left scheduled, where every + # scheduler pass would claim it and fail again. Only a new schedule of the + # same name arms it again. + # @rbs (Reminder, StandardError) -> (:paused | nil) + def pause: (Reminder, StandardError) -> (:paused | nil) # @rbs (Reminder) -> void def release: (Reminder) -> void @@ -56,6 +76,8 @@ module SolidObjects # @rbs (Reminder) -> void def verify_claim!: (Reminder) -> void + # latest and skip advance to the first aligned time after now; all advances + # one interval, even into the past, so each missed occurrence is enqueued. # @rbs (Reminder, Time) -> Time def next_run_at: (Reminder, Time) -> Time diff --git a/test/integration/reminder_missed_policy_test.rb b/test/integration/reminder_missed_policy_test.rb new file mode 100644 index 0000000..181501f --- /dev/null +++ b/test/integration/reminder_missed_policy_test.rb @@ -0,0 +1,362 @@ +# frozen_string_literal: true + +require "database_test_helper" + +# Covers the skip missed-run policy, the run history on ReminderStatus, and +# the pause of a reminder whose operation is unknown when it fires. Each test +# passes the scheduler an explicit now, so the lateness of an occurrence is +# exact rather than a race with the wall clock. +class ReminderMissedPolicyTest < ActiveSupport::TestCase + SCHEDULED_AT = Time.utc(2030, 1, 1, 12) + INTERVAL = 60 + + class TickActor < SolidObjects::Actor + actor_type "reminder-tick" + + attribute :ticks, default: 0 + attribute :seen, default: nil + + def arm(at:, every: INTERVAL, missed: "latest", key: nil) + schedule(at: Time.at(at).utc, every:, missed:, key:).tick + end + + def arm_explode(at:) + schedule(at: Time.at(at).utc, every: INTERVAL).explode + end + + def rearm_and_read(at:) + schedule(at: Time.at(at).utc, every: INTERVAL, missed: "skip").tick + read + end + + def read(key: nil) + self.seen = describe(reminder(:tick, key:)) + end + + def tick + self.ticks += 1 + end + + def explode + raise "the operation failed" + end + + private + + def describe(status) + return unless status + + { + "missed_policy" => status.missed_policy, + "next_run_at" => status.next_run_at.to_i, + "occurrence" => status.occurrence, + "last_run_at" => status.last_run_at&.to_i, + "error_class" => status.error_class, + "status" => status.status + } + end + end + + def at(offset) + SCHEDULED_AT + offset + end + + def drain + worker = SolidObjects::Worker.new + worker.run_until_idle + ensure + worker&.stop + end + + def fire(now) + scheduler = SolidObjects::ReminderScheduler.new + scheduler.run_once(now:) + ensure + scheduler&.stop + end + + def arm(missed: "latest", every: INTERVAL, key: nil, actor_id: "one") + TickActor.ref(actor_id).async.arm(at: SCHEDULED_AT.to_i, every:, missed:, key:) + drain + SolidObjects::Reminder.find_by!(actor_type: "reminder-tick", actor_id:, name: key ? "tick:#{key}" : "tick") + end + + def seen(actor_id: "one") + TickActor.ref(actor_id).async.read + drain + SolidObjects::Instance.find_by!(actor_type: "reminder-tick", actor_id:).state.fetch("seen") + end + + # Reminder occurrences only, not the turns that armed or read them. + def messages + SolidObjects::Message.where(actor_type: "reminder-tick", delivery_mode: "internal") + end + + def direct_actor + TickActor.new(actor_id: "direct", state: SolidObjects::State.new(TickActor.definition.state_definition)) + end + + # 1. Create + + test "missed defaults to latest and accepts skip as a symbol or a string" do + actor = direct_actor + actor.schedule(at: SCHEDULED_AT).tick + actor.schedule(at: SCHEDULED_AT, every: INTERVAL, missed: :skip, key: "symbol").tick + actor.schedule(at: SCHEDULED_AT, every: INTERVAL, missed: "skip", key: "string").tick + + assert_equal "latest", actor.reminder(:tick).missed_policy + assert_equal "skip", actor.reminder(:tick, key: "symbol").missed_policy + assert_equal "skip", actor.reminder(:tick, key: "string").missed_policy + end + + test "each missed policy persists and round-trips on the reminder status" do + %w[latest all skip].each { |policy| arm(missed: policy, key: policy) } + + assert_equal %w[all latest skip], + SolidObjects::Reminder.where(actor_type: "reminder-tick").order(:missed_policy).pluck(:missed_policy) + %w[latest all skip].each do |policy| + TickActor.ref("one").async.read(key: policy) + drain + assert_equal policy, + SolidObjects::Instance.find_by!(actor_type: "reminder-tick").state.fetch("seen").fetch("missed_policy") + end + end + + test "an unknown missed policy and a non-positive interval are still refused" do + actor = direct_actor + + error = assert_raises(ArgumentError) { actor.schedule(at: SCHEDULED_AT, missed: :never) } + assert_match(/skip/, error.message) + assert_raises(ArgumentError) { actor.schedule(at: SCHEDULED_AT, every: 0) } + end + + test "the database refuses a missed policy the runtime does not know" do + reminder = arm + + assert_raises(ActiveRecord::StatementInvalid) { reminder.update_column(:missed_policy, "never") } + end + + # 6. Run history before any enqueue + + test "a first schedule reports no run history" do + arm(missed: "skip") + + seen = seen() + assert_nil seen.fetch("last_run_at") + assert_equal 0, seen.fetch("occurrence") + assert_nil seen.fetch("error_class") + assert_equal "scheduled", seen.fetch("status") + end + + # 5. Missed-run policies + + test "skip enqueues an occurrence that is late inside its own slot" do + reminder = arm(missed: "skip") + + assert fire(at(30)) + + assert_equal 1, messages.count + reminder.reload + assert_equal 1, reminder.occurrence + assert_equal at(30).to_i, reminder.last_run_at.to_i + assert_equal at(INTERVAL).to_i, reminder.next_run_at.to_i + assert_equal "scheduled", reminder.status + assert_nil reminder.claimed_by + seen = seen() + assert_equal at(30).to_i, seen.fetch("last_run_at") + assert_equal 1, seen.fetch("occurrence") + end + + test "skip drops a missed window and waits for the next scheduled time" do + reminder = arm(missed: "skip") + now = at(INTERVAL * 2.5) + + assert fire(now), "a skipped window is still scheduler work" + + assert_empty messages + reminder.reload + assert_equal 0, reminder.occurrence + assert_nil reminder.last_run_at + assert_equal at(INTERVAL * 3).to_i, reminder.next_run_at.to_i + assert_operator reminder.next_run_at, :>, now + assert_equal "scheduled", reminder.status + assert_nil reminder.claimed_by + assert_not fire(now), "the reminder must not stay due in the past" + + assert fire(at(INTERVAL * 3 + 5)) + assert_equal 1, messages.count + assert_equal at(INTERVAL * 4).to_i, reminder.reload.next_run_at.to_i + end + + test "skip treats the next aligned time itself as missed" do + reminder = arm(missed: "skip") + + assert fire(at(INTERVAL)) + + assert_empty messages + assert_equal at(INTERVAL * 2).to_i, reminder.reload.next_run_at.to_i + end + + test "a one-shot skip reminder still fires and completes" do + reminder = arm(missed: "skip", every: nil) + + assert fire(at(INTERVAL * 10)) + + assert_equal 1, messages.count + reminder.reload + assert_equal "completed", reminder.status + assert_equal SCHEDULED_AT.to_i, reminder.next_run_at.to_i + assert_nil seen + end + + test "latest enqueues a missed window once and jumps past now" do + reminder = arm(missed: "latest") + + assert fire(at(INTERVAL * 2.5)) + + assert_equal 1, messages.count + assert_equal 1, reminder.reload.occurrence + assert_equal at(INTERVAL * 3).to_i, reminder.next_run_at.to_i + end + + test "all enqueues every missed occurrence, one interval per pass" do + reminder = arm(missed: "all") + now = at(INTERVAL * 2.5) + + assert fire(now) + assert_equal at(INTERVAL).to_i, reminder.reload.next_run_at.to_i, + "all arms the next aligned time even when it is still in the past" + assert fire(now) + assert fire(now) + assert_not fire(now) + + assert_equal 3, reminder.reload.occurrence + assert_equal at(INTERVAL * 3).to_i, reminder.next_run_at.to_i + assert_equal (0..2).map { |occurrence| "reminder:#{reminder.id}:#{occurrence}" }, + messages.order(:id).pluck(:idempotency_key) + end + + # 6. Pause on an unknown operation at fire + + test "an unknown operation at fire pauses the reminder" do + reminder = arm + assert fire(at(10)) + reminder.reload.update!(operation: "vanished") + + assert fire(at(INTERVAL + 10)), "pausing is scheduler work, not an error that stops the loop" + + reminder.reload + assert_equal "paused", reminder.status + assert_equal "SolidObjects::UnknownMessage", reminder.error_class + assert_equal 1, reminder.occurrence + assert_equal at(10).to_i, reminder.last_run_at.to_i + assert_nil reminder.claimed_by + assert_equal 1, messages.count, "the paused attempt enqueues nothing" + assert_not fire(at(INTERVAL * 100)), "a paused reminder is not claimed again" + seen = seen() + assert_equal "paused", seen.fetch("status") + assert_equal "SolidObjects::UnknownMessage", seen.fetch("error_class") + end + + # 2. Replace + + test "a replace keeps the run history and clears the error" do + reminder = arm + assert fire(at(10)) + reminder.reload.update!(operation: "vanished") + fire(at(INTERVAL + 10)) + moved = at(INTERVAL * 10) + + TickActor.ref("one").async.rearm_and_read(at: moved.to_i) + drain + + in_turn = SolidObjects::Instance.find_by!(actor_type: "reminder-tick").state.fetch("seen") + committed = seen + [ in_turn, committed ].each do |status| + assert_equal "scheduled", status.fetch("status") + assert_nil status.fetch("error_class") + assert_equal 1, status.fetch("occurrence") + assert_equal at(10).to_i, status.fetch("last_run_at") + assert_equal moved.to_i, status.fetch("next_run_at") + assert_equal "skip", status.fetch("missed_policy") + end + assert_equal 1, SolidObjects::Reminder.where(actor_type: "reminder-tick").count + end + + # The row of a fired one-shot is reused when its name is scheduled again, so + # the in-turn read must show the history the commit will keep. + test "rearming a fired one-shot reads the same history in the turn and after it" do + arm(every: nil) + assert fire(at(10)) + assert_nil seen, "a completed one-shot is not reported" + moved = at(INTERVAL * 10) + + TickActor.ref("one").async.rearm_and_read(at: moved.to_i) + drain + + in_turn = SolidObjects::Instance.find_by!(actor_type: "reminder-tick").state.fetch("seen") + assert_equal seen, in_turn + assert_equal 1, in_turn.fetch("occurrence") + assert_equal at(10).to_i, in_turn.fetch("last_run_at") + assert_equal "scheduled", in_turn.fetch("status") + end + + test "a mailbox failure of an enqueued occurrence does not pause the reminder" do + SolidObjects.configuration.max_attempts = 1 + TickActor.ref("one").async.arm_explode(at: SCHEDULED_AT.to_i) + drain + + assert fire(at(10)) + drain + + assert_equal 1, SolidObjects::DeadLetter.where(actor_type: "reminder-tick").count + reminder = SolidObjects::Reminder.find_by!(actor_type: "reminder-tick") + assert_equal "scheduled", reminder.status + assert_nil reminder.error_class + assert_equal 1, reminder.occurrence + end + + # 7. Restart recovery + + test "a due reminder whose claim owner is gone still fires" do + reminder = arm + abandoned = SolidObjects::ReminderScheduler.new + assert abandoned.send(:claim_next, now: at(10)) + stale = SolidObjects.database_adapter.database_now - SolidObjects.configuration.process_alive_threshold - 1 + reminder.reload.update!(claimed_at: stale) + + assert fire(at(10)) + + assert_equal 1, messages.count + assert_equal 1, reminder.reload.occurrence + ensure + abandoned&.stop + end + + # 8. Fire authorization + + test "a fired reminder runs when authorize_message refuses external enqueues" do + arm + SolidObjects.configuration.authorize_message = ->(**) { false } + + assert fire(at(10)) + drain + + assert_equal 1, SolidObjects::Instance.find_by!(actor_type: "reminder-tick").state.fetch("ticks") + assert_raises(SolidObjects::Unauthorized) { TickActor.ref("one").async.tick } + assert_equal 1, messages.count + end + + # 9. Duplicate delivery + + test "an occurrence the scheduler sees twice is delivered once" do + reminder = arm + assert fire(at(10)) + reminder.reload.update!(occurrence: 0, next_run_at: SCHEDULED_AT) + + assert fire(at(10)) + + assert_equal 1, messages.count + assert_equal "reminder:#{reminder.id}:0", messages.sole.idempotency_key + end +end diff --git a/test/models/reminder_run_history_migration_test.rb b/test/models/reminder_run_history_migration_test.rb new file mode 100644 index 0000000..fda3da5 --- /dev/null +++ b/test/models/reminder_run_history_migration_test.rb @@ -0,0 +1,71 @@ +# frozen_string_literal: true + +require "database_test_helper" +require "tmpdir" + +class ReminderRunHistoryMigrationScratch < ActiveRecord::Base + self.abstract_class = true +end + +# The skip policy and the run history arrive in a migration of their own, so +# an installation that already has the earlier schema must be able to apply it +# without losing the reminders it already holds. +class ReminderRunHistoryMigrationTest < ActiveSupport::TestCase + MIGRATION_FILE = "20261130000000_add_solid_objects_reminder_run_history.rb" + + test "upgrades an installed schema and keeps its latest and all reminders" do + Dir.mktmpdir do |directory| + ReminderRunHistoryMigrationScratch.establish_connection( + adapter: "sqlite3", + database: File.join(directory, "upgrade.sqlite3") + ) + connection = ReminderRunHistoryMigrationScratch.connection + migrations = SolidObjects::SchemaBootstrap.migrations + index = migrations.index { |migration| migration.instance_method(:up).source_location.first.end_with?(MIGRATION_FILE) } + assert index, "#{MIGRATION_FILE} is not in db/migrate" + migrations.first(index).each { |migration| apply(migration, connection) } + instance_id = insert_instance(connection) + insert_reminder(connection, instance_id, "latest") + insert_reminder(connection, instance_id, "all") + assert_raises(ActiveRecord::StatementInvalid) { insert_reminder(connection, instance_id, "skip") } + + apply(migrations.fetch(index), connection) + + reminders = SolidObjects.table_name(:reminders) + assert_equal [ %w[all all], %w[latest latest] ], + connection.select_rows("SELECT name, missed_policy FROM #{reminders} ORDER BY name") + assert_equal [ [ nil, nil ] ] * 2, + connection.select_rows("SELECT last_run_at, error_class FROM #{reminders}") + insert_reminder(connection, instance_id, "skip") + assert_raises(ActiveRecord::StatementInvalid) { insert_reminder(connection, instance_id, "never") } + ensure + ReminderRunHistoryMigrationScratch.remove_connection + end + end + + private + + def apply(migration_class, connection) + migration = migration_class.new + migration.define_singleton_method(:connection) { connection } + migration.migrate(:up) + end + + def insert_instance(connection) + connection.insert(<<~SQL) + INSERT INTO #{SolidObjects.table_name(:instances)} + (actor_type, actor_id, state, state_version, created_at, updated_at) + VALUES ('upgrade', 'one', '{}', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) + SQL + end + + def insert_reminder(connection, instance_id, policy) + connection.insert(<<~SQL) + INSERT INTO #{SolidObjects.table_name(:reminders)} + (instance_id, actor_type, actor_id, name, operation, arguments, next_run_at, + interval_seconds, missed_policy, created_at, updated_at) + VALUES (#{instance_id}, 'upgrade', 'one', '#{policy}', 'tick', '{}', CURRENT_TIMESTAMP, + 60, '#{policy}', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) + SQL + end +end