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
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
Original file line number Diff line number Diff line change
@@ -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
3 changes: 2 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
52 changes: 49 additions & 3 deletions docs/reminders.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Docs conventions: "the JS PRD" is not used anywhere else in the docs; the repository writes "JavaScript".

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

Expand Down Expand Up @@ -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
Expand Down
44 changes: 31 additions & 13 deletions lib/solid_objects/actor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -338,27 +339,37 @@ 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,
next_run_at: row.next_run_at,
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
Expand All @@ -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,
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
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:,
Expand All @@ -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

Expand Down
2 changes: 1 addition & 1 deletion lib/solid_objects/doctor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions lib/solid_objects/executor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
)
Expand Down
47 changes: 44 additions & 3 deletions lib/solid_objects/reminder_scheduler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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:)
Expand All @@ -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,
Expand All @@ -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(
Expand All @@ -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
Expand All @@ -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
Expand Down
Loading