Skip to content

Fire an every at a wall-clock time in the record's own zone - #102

Merged
C-Sinclair merged 4 commits into
mainfrom
feat/every-at-timezone
Nov 12, 2026
Merged

C-Sinclair merged 4 commits into
mainfrom
feat/every-at-timezone

Conversation

@C-Sinclair

@C-Sinclair C-Sinclair commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #98.

  • Adds at, on and time_zone to every, so a recurring action can fire at a wall-clock time in each record's own zone instead of measuring interval from its last fire.
  • Adds AshWorkflow.WallClock, which computes occurrences in Elixir for AshWorkflow.Scheduler.Precise and AshWorkflow.Calculations.PendingDeadlines. AshWorkflow.Transformers.AddScheduler asks the same question in SQL for the Oban trigger.
  • Adds AshWorkflow.Verifiers.ValidateEvery rules for the new options, and exempts a wall-clock every from AshWorkflow.Verifiers.ValidateTimeoutPrecision.
  • AshWorkflow.Charts.Format.every/1 labels a wall-clock every as "every 14 days at 09:00 on mon in candidate_time_zone", so the Mermaid, DOT and JSON charts show its schedule. AshWorkflow.Clarity.Timeline lists it with the moments not timed from entry, since its first fire depends on the local time the record entered the step.
every :daily_digest do
  at ~T[09:00:00]
  on [:mon, :tue, :wed, :thu, :fri]
  time_zone :candidate_time_zone
  action :send_digest
end

Why the zone comes out of the row

interval {1, :days} fires a day after whatever time the record entered the step, and polling lag compounds the drift. A daily digest is not that. It goes out at 09:00 where the recipient is.

A global cron can send every digest at one instant. It cannot send each record's digest at 09:00 in that record's own zone. Two records in the same step, one in Australia/Sydney and one in Europe/London, are due nine to eleven hours apart depending on the season.

time_zone takes three things:

Form Example
Literal time_zone "Australia/Sydney"
Attribute time_zone :candidate_time_zone
Expression calculation calculate :candidate_time_zone, :string, expr(candidate.time_zone)

The calculation covers a zone living on a related record. There is no path syntax for relationships, because an expression calculation already is one and it composes. ValidateEvery rejects a module calculation, the same check and the same reasoning AshWorkflow.Verifiers.ValidateTimeoutFields applies to a timeout's field: the zone is read from the trigger's filter, which the data layer evaluates.

Two readers, one schedule

flowchart TD
    DSL["every :daily_digest<br/>at / on / time_zone"] --> AS[AshWorkflow.Transformers.AddScheduler]
    AS -->|Work.match| OB["AshWorkflow.Scheduler.Oban<br/>is this record due now?"]
    AS -->|Work.deadline| PR["AshWorkflow.Scheduler.Precise<br/>when is this record next due?"]
    OB --> SQL["AT TIME ZONE fragment,<br/>evaluated per row"]
    PR --> WC[AshWorkflow.WallClock]
    PD[AshWorkflow.Calculations.PendingDeadlines] --> WC
Loading

Work.match becomes a Postgres fragment, since the zone is per row, so at under AshWorkflow.Scheduler.Oban needs a SQL data layer. Work.deadline carries the schedule itself, and AshWorkflow.Scheduler.due_at/2 resolves it through WallClock.next_occurrence/3, so AshWorkflow.Scheduler.Precise runs on any data layer. Timeline.recheck_filter/1 and Timeline.due_now?/2 are what keep it off the fragment.

interval alongside at is a stride

on says which days carry an occurrence. It cannot say every other Monday, because it is a set of weekdays. An interval beside an at says that instead, and the two compose:

every :fortnightly_digest do
  interval {14, :days}
  at ~T[09:00:00]
  on [:mon]
  time_zone :candidate_time_zone
  action :send_digest
end

A stride counts local dates rather than elapsed duration, and ValidateEvery rejects any unit but :days beside an at. Both follow from one fact: firing at 09:00 writes the last-fired column microseconds after 09:00.

Stride read as Occurrence 14 days after a fire at 09:00:00.000001
Duration, last_fire + 14 days Ineligible by one microsecond, so the digest slips a week
Local dates, Date.diff/2 Eligible, and no daylight saving exposure

Daylight saving and missed occurrences

A local time daylight saving skipped still fires that day, at the instant the clock jumped to. ~T[02:30:00] on a day whose clocks go 02:00 to 03:00 fires at 03:00 local. Skipping the day instead would mean a digest missing one day a year, in whichever zones the rows happen to name. A local time that happens twice fires on the first of its two instants, and the second is then no longer after the last fire.

A missed occurrence fires late rather than being skipped, on that day or a later one, and once however many were missed. The Oban fragment finds the most recent occurrence among the last seven local dates in the row's zone. on is never empty, so the most recent occurrence is always one of those seven. A stride compares that occurrence's local date with the last fire's, not today's date.

Why no cron option

A cron "0 9 * * 1-5" option would add three things at, on and a stride cannot express: several times a day, minute-level patterns such as */15 9-17 * * 1-5, and day-of-month rules such as 0 9 1 * *. This PR leaves it out.

  • The Oban trigger decides due-ness in SQL, per row, in the row's own zone. at needs only a seven-day generate_series. A general cron expression would need a cron evaluator in SQL or a scan at minute resolution.
  • AshWorkflow.Scheduler.Precise could compute the next cron run in Elixir, but at has to work under both schedulers.
  • Durations cannot express business days or calendar months #79 proposes resolving a deadline in Elixir and writing it to an owned column, which the trigger then compares like a fire_at. If an every stored its next fire instant after each run, cron, at, business days and calendar months would all reduce to computing the next instant in Elixir, with no per-row SQL. That design has its own costs: a record whose time_zone changes needs its column recomputed, and a schedule change in the DSL needs a backfill for records already in the step.

Cron belongs with that stored-next-fire design, decided once alongside #79, rather than added to the fragment approach here.

What #79 will need

#79 adds business-day and calendar-month durations, and both issues ask for one time_zone option. This PR puts time_zone on every only. Its value is a literal zone string, or an atom naming an attribute or an expression calculation. A business-day timeout can take the same value unchanged.

  • time_zone on timeout, validated the same way as Every.validate_time_zone/1. That function lives on AshWorkflow.Entities.Every, and AshWorkflow.WallClock.time_zone_for/2 takes a WallClock struct. Durations cannot express business days or calendar months #79 should move the validation and the record lookup to a module both entities share.
  • A workflow-level default zone, if Durations cannot express business days or calendar months #79 adds one beside its calendar. ValidateEvery requires time_zone alongside at. A default only relaxes that rule, so it is an additive change.
  • ValidateEvery rejects a module calculation for time_zone, because the Oban trigger reads the zone in SQL. Durations cannot express business days or calendar months #79 resolves a business-day deadline in Elixir when the record enters the step, so it does not need that restriction. Keeping the same rule on both entities keeps one meaning for the option.

Notes for the reviewer

  • AshWorkflowTest.Postgres.RelatedZoneObanTest is the only place the calculation has to inline into SQL and join.
  • A wall-clock every writes its last_fired_field on each fire, like an interval one. It has no Work.fired_field, so AshWorkflow.Scheduler.Work.not_fired/1 is always true for it, as for any every.
  • AshWorkflow.Clarity.Diagram.step_timeline/2 replaced every : with a space, because a Mermaid timeline splits on it. It now writes a colon between two digits as U+2236 RATIO, so "09:00" does not render as "09 00".
  • at needs an IANA database in the host application, so tz is added as a dev and test dependency and config/config.exs sets :time_zone_database. ValidateEvery checks a literal time_zone against it at compile time.
  • The fragment lifts state_entered_at and the last-fired column with an explicit AT TIME ZONE 'UTC' before shifting into the row's zone. Both are stored as naive timestamps holding UTC, and leaving the conversion implicit would resolve against the session TimeZone setting.
  • mix spark.formatter added at, on, time_zone and the previously missing last_fired_field to .formatter.exs, which reformatted one line in AshWorkflowTest.EveryUntilWorkflow.
  • The three migrations are hand-trimmed to the tables they add. The generator wanted to sweep in unrelated snapshot drift for no_index_workflows, own_index_workflows and four index renames, none of which belongs here. Index names match their snapshots.

@C-Sinclair
C-Sinclair force-pushed the feat/every-at-timezone branch from b4cd6d4 to 7a49470 Compare October 22, 2026 11:27
@C-Sinclair
C-Sinclair marked this pull request as ready for review November 6, 2026 11:14
`every` measures `interval` from its last fire, so `interval {1, :days}`
drifts to whatever time the record entered the step. `at` names a local
time instead, `on` names the days, and `time_zone` places it:

    every :daily_digest do
      at ~T[09:00:00]
      on [:mon, :tue, :wed, :thu, :fri]
      time_zone :candidate_time_zone
      action :send_digest
    end

`time_zone` takes a literal, an attribute, or an expression calculation,
which is how a record reads its zone off a related one. A per-record zone
is the case a global cron cannot express, so the Oban trigger's `where`
clause reads the zone out of each row with an `AT TIME ZONE` fragment.
`AshWorkflow.Scheduler.Precise` asks when a record is next due instead,
and computes the same occurrence in Elixir through `AshWorkflow.WallClock`.

An `interval` declared alongside `at` is a stride: how many local days
must separate two fires, so `interval {14, :days}` with `on [:mon]` is
09:00 every second Monday. The stride counts local dates rather than
elapsed duration, since firing writes the last-fired column microseconds
after 09:00 and a duration comparison would slip the next fire a week.

A local time daylight saving skipped still fires that day, at the instant
the clock jumped to. One that happens twice fires on the first of the two.
A missed occurrence fires late rather than being skipped.

`AshWorkflow.Charts.Format.every/1` labels a wall-clock `every` by its schedule, and `AshWorkflow.Clarity.Timeline` lists it with the moments not timed from entry. `AshWorkflow.Scheduler.Work.deadline/0` gains the optional `wall_clock` key. `AshWorkflowTest.DataCase.set_field/3` shifts a zoned `DateTime` to UTC before writing it.

Resolves #98
Precise's wall-clock sweep and recheck now apply max_fires, which they
previously ignored. The Oban trigger's AT TIME ZONE fragment skips a row
whose zone Postgres does not know rather than failing the whole query.
WallClock.time_zone_for/2 unwraps a ci_string zone attribute.
The Oban trigger now looks back eight local dates, so a single-day on
whose last occurrence fell a week ago fires as soon as polling resumes,
as Precise already does. The Every and WallClock docs now describe the
stride's first fire and the daylight saving difference between Postgres
and WallClock. ValidateEvery explains a too-short until on a stride.
A last fire from an earlier visit to the step made the record due as
soon as it re-entered. Both schedulers and pending_deadlines now measure
from whichever of the last fire and state_entered_at is later, as the
fire count already does. The Oban fragment checks pg_timezone_names only
for a zone read from the row, since a literal zone is checked at compile
time. The topic doc shows the SQL the transformer now generates.
@C-Sinclair
C-Sinclair force-pushed the feat/every-at-timezone branch from 576fbdc to 6cb94bf Compare November 10, 2026 14:46
@C-Sinclair
C-Sinclair merged commit c04e8d4 into main Nov 12, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

every cannot fire at a wall-clock time in the record's time zone

1 participant