Skip to content

fix(automations): advance cron and hourly schedules past a DST fall-back hour - #20179

Merged
nwparker merged 1 commit into
stablyai:mainfrom
eatmoreduck:fix/automation-dst-fallback-rerun
Oct 26, 2026
Merged

nwparker merged 1 commit into
stablyai:mainfrom
eatmoreduck:fix/automation-dst-fallback-rerun

Conversation

@eatmoreduck

@eatmoreduck eatmoreduck commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When clocks "fall back" in autumn, the hour from 1:00 to 2:00 happens twice. During the second pass of that hour, Orca's scheduler mixed it up with the first pass. A run meant for the second 1:30 could start 30 minutes late, or be marked as missed. An hourly run at the second 1:00 could be dropped entirely. The scheduler also kept re-checking and re-saving the schedule about once a minute for that whole hour. This fix rounds times in a way that can never move them backwards, so each pass of the repeated hour runs once, on time.

What Changed

Before: inside the repeated fall-back hour, nextAutomationOccurrenceAfter could return after itself (breaking its strictly-after contract), and latestAutomationOccurrenceAtOrBefore could return the first pass's instant while the clock was in the second pass.

After: every next run is strictly later than after, and cron and FREQ=HOURLY schedules fire once per pass of a repeated minute, on time.

Mechanism:

  • src/shared/automation-cron-occurrence.ts: floorToMinute now uses epoch arithmetic (Math.floor(ts / 60_000) * 60_000) instead of date.setSeconds(0, 0). Rebuilding from local wall-clock fields makes an ambiguous minute resolve to the earlier offset, up to an hour before the input.
  • src/shared/automation-schedule-occurrences.ts: cron and HOURLY, both next and latest, now share one absolute-minute walk (nextMatchingMinute / latestMatchingMinute, which take a matcher). This replaces the HOURLY setMinutes + HOUR_MS logic, which had the same rewind problem.
  • src/shared/automation-cron-input-validation.test.ts: the assertion that pinned the buggy result ("Pin existing DST ambiguity (Automation scheduler can re-fire every tick through a DST fall-back hour #20154)") now expects the next day's run. Added an hourly regression covering first pass -> second pass -> next hour, plus latest inside the second pass.

Why

Runs are deduped by (automationId, scheduledFor), so main never launched the same run twice. The second pass was still handled wrong, though. Simulating the scheduler's evaluate/createRun/advance loop with 60s ticks in America/New_York on 2026-11-01:

  • 30 1 * * *: the 01:30 EST run started at 02:00 EST, 30 minutes late (or became skipped_missed past its grace window). 32 evaluations in the window.
  • FREQ=HOURLY;BYMINUTE=0: the 01:00 EST run was dropped. 63 evaluations.
  • With the fix: 2 / 4 evaluations, every run on time, none dropped.

Epoch flooring is always <= its input and within 60s of it. Every modern offset is a whole number of minutes (including :30 and :45 zones), so a UTC minute boundary is also a local one. Sharing one minute walk across cron and HOURLY keeps a single source of truth, so the two paths can't drift apart again.

Linked Issue

Fixes #20154

Visual Proof

N/A. This is scheduler time arithmetic with no UI or interaction change. The behavioral before/after is the probe output under Testing.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

On macOS (arm64):

  • Repro on main: with main's sources, the two updated assertions fail (expected 1793514600000 to be 1793601000000 and expected 1793514600000 to be 1793518200000). With this branch they pass.
  • Probe: a simulated scheduler with a 67s tick over 48h windows, 8 expressions (30 1 * * *, 30 * * * *, FREQ=HOURLY;BYMINUTE=30, */15 1 * * *, 45 1 * * 0, 0 2 * * *, FREQ=DAILY;BYHOUR=1;BYMINUTE=30, 15 0 * * *), across 5 DST windows (New York fall-back and spring-forward, London fall-back, both Lord Howe 30-minute transitions). Main: 14 of 40 cases fail. Branch: 40 of 40 pass. Daily 30 1 fires twice on fall-back day, matching the existing "fires both repeats" policy, and spring-forward still skips the nonexistent 02:00.
  • pnpm test src/shared/automation src/main/persistence/scheduling-automations src/main/automations: 50 files, 451 tests pass.
  • oxlint and oxfmt --check are clean on the touched files.

The DST suite uses vi.stubEnv('TZ', ...) and is skipped on win32, where Node ignores runtime TZ changes. The change itself is platform-independent epoch arithmetic. It has no remote/SSH, mobile, folder-workspace, wire, or persistence-format impact.

Original fix by @eatmoreduck in #20179 (author preserved on the commit).

Review

  • Behavior note: cron and HOURLY fire once per pass of the repeated hour. DAILY/WEEKLY RRULE presets still fire once and are unchanged.
  • In 30-minute-DST zones (Lord Howe), HOURLY follows the local wall-clock :MM, so a skipped minute moves to the next real :MM.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Checked for security, cross-platform (pure epoch arithmetic), remote SSH and mixed versions (no RPC or persistence change), mobile (N/A), backwards compatibility, and performance (the HOURLY walk is bounded at about 60 iterations per call). No issues found.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

No actionable comments were generated in the recent review.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: d13195e0-7e7f-4f6c-9328-007503c0b1f7

📥 Commits

Reviewing files that changed from the base of the PR and between 73eb8aa450c98f744c55455681c15104ea62d16a and b0a879fd9df7570bc84366cd94a756349d13d894.

📒 Files selected for processing (2)
  • src/shared/automation-cron-occurrence.ts
  • src/shared/automation-schedule-occurrences.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Walkthrough

nextAutomationOccurrenceAfter and latestAutomationOccurrenceAtOrBefore now scan hourly occurrences by absolute minutes instead of recomposing local time fields. The searches use bounded forward and backward scans. floorToMinute now uses UTC arithmetic and documents pre-epoch and DST behavior. Tests cover DST fall-back repeats, strictly later results, latest occurrence lookup, and skipped spring-forward times. Test setup restores the original TZ environment state.

Priority: Normal

Severity of issue fixed: Medium

Merge Risk: Minimal · up to b0a87

The DST occurrence changes have targeted regression coverage, with no active merge-blocking risk identified.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Issue #20154 requires each occurrence to be strictly later than after and requires correct handling of repeated fall-back times. floorToMinute now uses UTC epoch-minute flooring, including mathema…
Out of Scope Changes check Passed The changes stay within issue #20154. They modify minute flooring, hourly occurrence scanning, and supporting regression-test timezone handling. The pre-epoch flooring correction supports the same tim…
Title check Passed The title names the main change: it fixes cron and hourly automation schedules so they advance correctly past a DST fall-back hour. It is short, specific, and matches the changeset, which changes floo…
Description check Passed The description follows the repository template and fills in every required section. It has a clear ELI5, a before and after with the mechanism, a rationale with alternatives, a linked issue (Fixes #2…
Full details: Linked Issues check

Explanation

Issue #20154 requires each occurrence to be strictly later than after and requires correct handling of repeated fall-back times. floorToMinute now uses UTC epoch-minute flooring, including mathematical flooring for pre-epoch timestamps. Hourly occurrence searches now scan absolute minutes. Regression tests cover both fall-back occurrences, strict advancement, spring-forward skipping, and normal-time behavior.

Full details: Out of Scope Changes check

Explanation

The changes stay within issue #20154. They modify minute flooring, hourly occurrence scanning, and supporting regression-test timezone handling. The pre-epoch flooring correction supports the same timestamp-flooring behavior and does not add unrelated functionality.

Full details: Title check

Explanation

The title names the main change: it fixes cron and hourly automation schedules so they advance correctly past a DST fall-back hour. It is short, specific, and matches the changeset, which changes floorToMinute and the cron and hourly occurrence logic for the repeated hour.

Full details: Description check

Explanation

The description follows the repository template and fills in every required section. It has a clear ELI5, a before and after with the mechanism, a rationale with alternatives, a linked issue (Fixes #20154), testing evidence, an N/A visual proof with reason, the agent skill boundary, and the checklist. The Review and Notes sections are complete. The AI Disclosure section is left blank, which the template allows for internal contributors.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 7ffaed2c-af35-4d24-b62c-94bbc4c0af99

📥 Commits

Reviewing files that changed from the base of the PR and between 6252f81 and f6ac69320416fbced509741a2b54ce8ea4da2d50.

📒 Files selected for processing (2)
  • src/shared/automation-cron-occurrence.ts
  • src/shared/automation-schedule-occurrences.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The cron fix is correct and the regression tests are real, but the FREQ=HOURLY RRULE path reproduces the same non-advancing nextRunAt loop, so #20154 is only half closed. Please extend the fix or explicitly scope the hourly path out.

Reviewed changes

  • UTC floor in floorToMinute: now floors with timestamp - (timestamp % 60_000) instead of recomposing local wall-clock fields, so an ambiguous fall-back minute can no longer resolve to the earlier (EDT) offset and move backwards in absolute time.
  • DST regression suite: a new America/New_York suite pins both repeats of the fall-back minute, the strictly-after contract across the repeated hour, and the skipped spring-forward minute.

⚠️ The FREQ=HOURLY branch still returns a nextRunAt at or before now through fall-back

nextAutomationOccurrenceAfter's hourly branch uses the same local-field recomposition the cron fix just removed, so an hourly automation still stays due and re-dispatches every tick for the rest of the repeated hour — the exact blast radius #20154 describes. This PR closes that issue, so either the hourly path needs the symmetric fix or the residual scope should be called out.

Technical details
# `FREQ=HOURLY` keeps `nextRunAt` non-advancing through the repeated hour

## Affected sites
- `src/shared/automation-schedule-occurrences.ts:110-119` — the `FREQ=HOURLY` branch calls `base.setMinutes(rule.byMinute, 0, 0)`. On an ambiguous fall-back minute V8 resolves that local time to the earlier (EDT) offset, so `candidate` lands an hour *before* `after`; the single `candidate += HOUR_MS` then returns the same wall-clock minute, i.e. `candidate <= after`.
- `src/shared/automation-schedule-occurrences.ts:146-153` — `latestAutomationOccurrenceAtOrBefore`'s hourly branch has the mirrored defect: `base.setMinutes(...)` resolves to the earlier offset and reports the first-pass occurrence for a second-pass `now`.
- `src/main/automations/service.ts:236` — `evaluateDueRuns` only skips when `nextRunAt > now`, and `src/main/persistence/scheduling-automations/automation-definition-operations.ts:111` defaults `missedRunGraceMinutes` to 720, so the hourly run proceeds to dispatch each tick.

## Evidence
Driving the real hourly branch with `TZ=America/New_York`, `BYMINUTE=30`, `after` inside the second `01:xx` pass (epoch 06:30Z–06:59Z):

```
after 2026-11-01T06:30:00.000Z -> next 2026-11-01T06:30:00.000Z (not strictly after)
after 2026-11-01T06:30:30.000Z -> next 2026-11-01T06:30:00.000Z
after 2026-11-01T06:31:00.000Z -> next 2026-11-01T06:30:00.000Z
after 2026-11-01T06:35:00.000Z -> next 2026-11-01T06:30:00.000Z
```

The cron tests in this PR do not exercise this branch; `automation-schedules.test.ts` has no hourly fall-back case.

## Required outcome
- `nextAutomationOccurrenceAfter` returns a value strictly greater than `after` for `FREQ=HOURLY` schedules through the fall-back hour, or the hourly residual is explicitly scoped out of #20154.

## Suggested approach (optional)
- Fix the hourly branch symmetrically (absolute-time arithmetic, or enforce the `> after` postcondition after computing the candidate as #20154 originally suggested), and add a `FREQ=HOURLY` fall-back case to the new suite.

## Open questions for the human (optional)
- Is `FREQ=HOURLY` intentionally out of scope for this fix? If so, #20154 should stay open or note the residual.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@eatmoreduck

Copy link
Copy Markdown
Contributor Author

Good catch on the TZ restore — fixed in 0dec56f7: the original process.env.TZ is now captured before the override (the previous code read the already-overwritten value) and restored in afterAll, deleted when it was originally unset. The skipIf probe also runs after the override so a POSIX host in any timezone enables the suite correctly. Verified under both the default TZ and TZ=Asia/Shanghai. Converted the touched functions' comments to doc comments for the docstring-coverage check as well.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

0dec56f resolves the TZ-capture nit and adds docstrings, but the prior review's blocking concern is still open: this PR closes #20154 while the FREQ=HOURLY (hourly preset) path keeps the same non-advancing nextRunAt behavior through a fall-back hour.

Reviewed changes

  • Restored the process timezone correctly in the DST suite: process.env.TZ is now captured before the override and restored in afterAll, deleting it when it was originally unset, so later tests in a shared worker run under their own timezone.
  • Documented the touched functions: floorToMinute's inline // Why: note became a JSDoc block (same explanation), and the test helpers gained docstrings.

⚠️ The FREQ=HOURLY path still returns nextRunAt <= now through fall-back

The hourly preset is a first-class automation option, and nextAutomationOccurrenceAfter's hourly branch still uses the local-field recomposition this PR just removed from floorToMinute. Through the second pass of a repeated hour, candidate resolves an hour earlier, the single += HOUR_MS lands back on after, and advanceAutomationNextRun writes a non-advancing nextRunAt — so an hourly automation still re-dispatches every tick, the exact blast radius #20154 describes. Either fix this branch symmetrically or explicitly scope it out of this PR.

Technical details
# `FREQ=HOURLY` keeps `nextRunAt` non-advancing through the repeated hour

## Affected sites
- `src/shared/automation-schedule-occurrences.ts:110-119` — the `FREQ=HOURLY` branch calls `base.setMinutes(rule.byMinute, 0, 0)`. On an ambiguous fall-back minute V8 resolves that local time to the earlier (EDT) offset, so `candidate` lands an hour before `after`; the single `candidate += HOUR_MS` returns `after` itself.
- `src/shared/automation-schedule-occurrences.ts:146-153` — `latestAutomationOccurrenceAtOrBefore`'s hourly branch has the mirrored defect.
- `src/renderer/src/components/automations/automation-orca-save.ts:71-79` — the hourly preset is persisted via `buildAutomationRrule`, which emits `FREQ=HOURLY;BYMINUTE=…`, so this branch is the production path for `preset: 'hourly'` (e.g. the `maintenance-hourly` template).
- `src/main/automations/service.ts:236` — `evaluateDueRuns` only skips when `nextRunAt > now`, so the non-advancing value re-dispatches each tick.

## Evidence
Reproduced this run with `TZ=America/New_York`, `after = 2026-11-01T06:30:00Z` (second EST pass):
`base.setMinutes(30, 0, 0)` → `2026-11-01T05:30:00Z`; `candidate <= after` → `+HOUR_MS` → `2026-11-01T06:30:00Z`, i.e. equal to `after`, not strictly greater.

## Required outcome
- `nextAutomationOccurrenceAfter` returns a value strictly greater than `after` for `FREQ=HOURLY` schedules through the fall-back hour, or the hourly residual is explicitly scoped out of this PR/#20154.

Pullfrog  | Fix it ➔ | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@eatmoreduck

Copy link
Copy Markdown
Contributor Author

Valid catch — fixed symmetrically in 73eb8aa4. Both FREQ=HOURLY branches now scan absolute minutes like the cron branch does (floorToMinute + ±1-minute steps, never recomposing local fields), so through the fall-back hour both repeats of the scheduled minute fire once each and next is strictly greater than after. Normal-time behavior is preserved, including firing at a dtstart that lands exactly on the scheduled minute; covered by 3 new regression tests alongside the existing hourly ones. The daily/weekly scanDayCandidates path still uses local-field recomposition in atLocalTime, which only matters for zones whose transition crosses midnight — left out of scope here.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Changes since the prior pullfrog review (0dec56f) — commit 73eb8aa:

  • Fixed the FREQ=HOURLY branches to walk absolute minutes: both nextAutomationOccurrenceAfter (src/shared/automation-schedule-occurrences.ts:109-124) and latestAutomationOccurrenceAtOrBefore (:151-162) now anchor on floorToMinute and step minute-by-minute matching getMinutes() === rule.byMinute, replacing the ambiguous setMinutes(rule.byMinute, 0, 0) recomposition that could return after itself (or the earlier pass) through a fall-back hour. This closes the blocking concern from the prior review.
  • Added three hourly DST regression tests: both repeats of an hourly minute fire, nextAutomationOccurrenceAfter advances past the repeated hour rather than returning after, and latestAutomationOccurrenceAtOrBefore returns the EST-pass minute. All assert exact instants, so they fail against the previous implementation.
  • Documented the walk rationale: inline // Why: notes on both branches referencing #20154, plus the floorToMinute JSDoc.

Verified the full suite passes under TZ=America/New_York (vitest run src/shared/automation-schedule-occurrences.test.ts src/shared/automation-schedules.test.ts — 31 passed), and traced the boundary cases (exact-minute after, dtstart off-minute and after after, strict-after contract) by hand; the walk preserves the pre-existing non-DST behavior and now advances correctly in both DST directions.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@eatmoreduck

Copy link
Copy Markdown
Contributor Author

One more hardening from the CodeRabbit inline suggestion (it landed on #20579's snapshot but belongs to this PR): floorToMinute now uses Math.floor(timestamp / 60_000) * 60_000 instead of timestamp - (timestamp % 60_000) — JS % keeps the sign of the dividend, so pre-epoch inputs (negative timestamps) were floored forward in absolute time (-15_000 → 0 instead of -60_000). Identical behavior for the realistic post-epoch domain; pinned by a new floorToMinute describe block that runs on all platforms (b0a879fd).

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Changes since the prior pullfrog review (73eb8aa) — commit b0a879f:

  • Made floorToMinute floor toward negative infinity: replaced timestamp - (timestamp % 60_000) with Math.floor(timestamp / 60_000) * 60_000, so pre-epoch inputs round down rather than toward zero. For the actual input domain (positive epoch ms) the result is identical.
  • Added floorToMinute unit tests: positive-minute flooring (including the exact-minute 0) and pre-epoch cases (-15_000, -1, -60_000), all of which fail against the sign-preserving % form.
  • Documented the sign rationale: the JSDoc now explains why Math.floor is used instead of %.

Verified TZ=America/New_York vitest run src/shared/automation-schedule-occurrences.test.ts src/shared/automation-schedules.test.ts — 33 passed. Traced Math.floor(timestamp / 60_000): the division is exact for multiples of 60 000 and correctly-rounded otherwise, and for Date-range magnitudes the 1/60 000 fractional step exceeds the half-ULP, so rounding can never cross an integer boundary and change the floor. All previous review concerns are addressed; the only prior inline thread is already resolved.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the fix/automation-dst-fallback-rerun branch from b0a879f to 8bfa301 Compare October 26, 2026 09:49
@nwparker nwparker changed the title fix(automations): advance cron schedules past a DST fall-back hour fix(automations): advance cron and hourly schedules past a DST fall-back hour Oct 26, 2026
floorToMinute recomposed local wall-clock fields via setSeconds(0, 0), and
the FREQ=HOURLY branches used setMinutes. Inside a repeated fall-back hour
both resolve to the earlier offset, so nextAutomationOccurrenceAfter could
return `after` itself and latestAutomationOccurrenceAtOrBefore could return
the first pass's instant.

Run dedupe by scheduledFor prevents duplicate launches, but the second pass
was mishandled: a `30 1 * * *` cron's second run started 30 minutes late (or
was recorded as skipped_missed past its grace window), the 01:00 EST run of
`FREQ=HOURLY;BYMINUTE=0` was dropped, and the scheduler re-evaluated and
flushed state on roughly every tick for the hour because nextRunAt stayed
in the past.

Floor with epoch arithmetic and route cron and hourly schedules through one
absolute-minute walk, so each pass of a repeated minute fires once, on time.

Fixes stablyai#20154

Co-authored-by: Neil <[email protected]>
@nwparker
nwparker force-pushed the fix/automation-dst-fallback-rerun branch from 8bfa301 to c09efed Compare October 26, 2026 11:15
@nwparker
nwparker merged commit 1ac1d40 into stablyai:main Oct 26, 2026
64 of 66 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.

Automation scheduler can re-fire every tick through a DST fall-back hour

2 participants