Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: catch up missed daily backup slots after a restart (#8456)

[._.]/ Adam Eivyed3a5e7472c8
diff --git a/server/services/backupScheduler.js b/server/services/backupScheduler.js
index a9ff2fc725..d263c28130 100644
--- a/server/services/backupScheduler.js
+++ b/server/services/backupScheduler.js
@@ -8,10 +8,10 @@
* disabling backups cancels it.
*/
-import { schedule, cancel } from './eventScheduler.js';
+import { schedule, cancel, parseCronToPrevRun } from './eventScheduler.js';
import { getSettings, getSettingsWithStatus, settingsEvents } from './settings.js';
-import { runBackup } from './backup.js';
-import { getUserTimezone } from './userTimezone.js';
+import { runBackup, getState } from './backup.js';
+import { getUserTimezone, getTimezoneUpdatedAt } from './userTimezone.js';
import { resolveBackupConfig } from '../lib/backupConfig.js';
const EVENT_ID = 'backup-daily';
@@ -22,6 +22,11 @@ const EVENT_ID = 'backup-daily';
// well inside a normal session.
const CORRUPT_SETTINGS_RETRY_MS = 60_000;
+// Boot delay before a detected missed-slot catch-up actually runs (#8456) —
+// long enough that it never piles onto boot-time migrations and store
+// warm-up, short enough that it still runs well inside a normal session.
+const CATCHUP_BOOT_DELAY_MS = 5 * 60_000;
+
// Only confirmed disabled or runnable configurations are cached.
// null means stopped or failed, so identical inputs can retry.
let reconciliationState = null;
@@ -30,6 +35,15 @@ let reconciliationState = null;
// stays unreadable across several syncBackupSchedule() calls.
let corruptRetryTimer = null;
+// At most one missed-slot catch-up attempt per process boot (#8456) — set the
+// moment a catch-up is EVALUATED (whether or not one is actually scheduled),
+// so a settings save right after boot can't re-arm a second attempt.
+let catchUpEvaluated = false;
+
+// The pending catch-up timer, so stopBackupScheduler() (used between tests,
+// and by anything that tears the scheduler down) can cancel it.
+let catchUpTimer = null;
+
/**
* The registration-affecting slice of settings: `null` when backup scheduling
* should be inactive (explicitly disabled, or no destination configured).
@@ -40,15 +54,89 @@ function registrationInputs(settings) {
return { cron: effective.cronExpression };
}
+/**
+ * Re-read settings and run a backup if it is still wanted — the cron handler
+ * body, shared with the missed-slot catch-up (#8456) so both paths respect a
+ * disable/destPath-clear that happened after registration/detection.
+ * @param {string} logReason - what triggered this run, for the log line
+ */
+async function runScheduledBackup(logReason) {
+ const fresh = await getSettings();
+ const effective = resolveBackupConfig(fresh.backup);
+ if (!effective.enabled) {
+ console.log('💾 Backup scheduler: disabled since registration — skipping run');
+ return;
+ }
+ if (!effective.destPath) {
+ console.log('💾 Backup scheduler: destPath cleared since registration — skipping run');
+ return;
+ }
+ const excludePaths = fresh.backup?.excludePaths || [];
+ const disabledDefaultExcludes = fresh.backup?.disabledDefaultExcludes || [];
+ console.log(`💾 Backup scheduler: running ${logReason} backup`);
+ await runBackup(effective.destPath, null, { excludePaths, disabledDefaultExcludes, retentionCount: effective.retentionCount });
+}
+
+/**
+ * If the most recent cron slot elapsed without a backup — the server was down
+ * or crash-looping across it (#8456) — schedule a one-time catch-up run after
+ * a fixed boot delay. At most one evaluation per process boot: `catchUpEvaluated`
+ * is set here regardless of outcome, so a settings save immediately after boot
+ * can't re-arm a second attempt for a slot this same boot already judged.
+ *
+ * Skipped when the registration-affecting config (cron/enabled/destPath) OR
+ * the global timezone changed AFTER the missed slot — `backupConfigUpdatedAt`
+ * / `timezoneUpdatedAt` are stamped by settings.js's `save()` only when those
+ * fields actually change, so an install that never touched them keeps the
+ * plain catch-up (sentinel `0` never gates), mirroring
+ * `dailyReminderScheduler.js`'s two `updatedAt` floors.
+ */
+async function maybeCatchUpMissedSlot(inputs, timezone, settings) {
+ if (catchUpEvaluated) return;
+ catchUpEvaluated = true;
+ try {
+ const prevRun = parseCronToPrevRun(inputs.cron, new Date(), timezone);
+ if (!prevRun) return;
+ const prevRunMs = prevRun.getTime();
+
+ const state = await getState().catch(() => null);
+ const lastRunMs = state?.lastRun ? new Date(state.lastRun).getTime() : NaN;
+ if (Number.isFinite(lastRunMs) && lastRunMs >= prevRunMs) return; // not missed
+
+ const configUpdatedAt = Number(settings?.backupConfigUpdatedAt) || 0;
+ const timezoneUpdatedAt = (await getTimezoneUpdatedAt().catch(() => null)) || 0;
+ const cutoff = Math.max(configUpdatedAt, timezoneUpdatedAt);
+ if (cutoff && prevRunMs < cutoff) {
+ console.log(`💾 Backup scheduler: missed slot (${prevRun.toISOString()}) predates last config/timezone change — skipping catch-up`);
+ return;
+ }
+
+ console.log(`💾 Backup scheduler: missed slot ${prevRun.toISOString()} — catching up in ${Math.round(CATCHUP_BOOT_DELAY_MS / 60_000)}m`);
+ catchUpTimer = setTimeout(() => {
+ catchUpTimer = null;
+ runScheduledBackup('missed-slot catch-up').catch(err =>
+ console.error(`❌ Backup scheduler: catch-up run failed: ${err.message}`));
+ }, CATCHUP_BOOT_DELAY_MS);
+ catchUpTimer.unref?.();
+ } catch (err) {
+ console.error(`❌ Backup scheduler: missed-slot check failed: ${err.message}`);
+ }
+}
+
/**
* (Re)synchronize the backup cron to match the given settings snapshot.
* Idempotent — safe to call at boot and after every settings save. Registering
* a cron fires nothing until its expression elapses, so this never triggers a
* backup by itself.
* @param {object} [settings] - a settings snapshot; re-read when omitted
+ * @param {object} [options]
+ * @param {boolean} [options.catchUpMissedSlot] - Check for and schedule a
+ * catch-up for a slot that already elapsed (server-restart recovery). Only
+ * the boot-time call (`startBackupScheduler`) sets this; a reschedule from a
+ * settings/timezone save must not replay a slot the user did not miss.
* @returns {Promise<boolean>} whether a cron is registered after the sync
*/
-export async function syncBackupSchedule(settings) {
+export async function syncBackupSchedule(settings, { catchUpMissedSlot = false } = {}) {
if (!settings) {
// No explicit snapshot: this is the boot path (or a corrupt-read retry),
// so read through the strict status so an unreadable/malformed
@@ -63,10 +151,10 @@ export async function syncBackupSchedule(settings) {
// (settings:invalidated, or the boot retry below) must re-evaluate
// rather than treating this as a confirmed disabled state.
reconciliationState = null;
- scheduleCorruptRetry();
+ scheduleCorruptRetry(catchUpMissedSlot);
return wasScheduled;
}
- return syncBackupSchedule(read);
+ return syncBackupSchedule(read, { catchUpMissedSlot });
}
const current = settings;
const inputs = registrationInputs(current);
@@ -75,7 +163,10 @@ export async function syncBackupSchedule(settings) {
// Only `cron` + `timezone` + active/inactive are baked into the registration;
// destPath and the exclude lists are re-read by the handler on every run.
const signature = JSON.stringify({ active: Boolean(inputs), cron: inputs?.cron ?? null, tz: timezone });
- if (signature === reconciliationState?.signature) return reconciliationState.kind === 'scheduled';
+ if (signature === reconciliationState?.signature) {
+ if (inputs && catchUpMissedSlot) await maybeCatchUpMissedSlot(inputs, timezone, current);
+ return reconciliationState.kind === 'scheduled';
+ }
if (!inputs) {
if (reconciliationState?.kind === 'scheduled') {
@@ -89,6 +180,9 @@ export async function syncBackupSchedule(settings) {
}
reconciliationState = attemptRegistration(inputs, timezone, signature);
+ if (reconciliationState?.kind === 'scheduled' && catchUpMissedSlot) {
+ await maybeCatchUpMissedSlot(inputs, timezone, current);
+ }
return reconciliationState?.kind === 'scheduled';
}
@@ -108,22 +202,7 @@ function attemptRegistration(inputs, timezone, signature) {
type: 'cron',
cron: inputs.cron,
timezone,
- handler: async () => {
- const fresh = await getSettings();
- const effective = resolveBackupConfig(fresh.backup);
- if (!effective.enabled) {
- console.log('💾 Backup scheduler: disabled since registration — skipping run');
- return;
- }
- if (!effective.destPath) {
- console.log('💾 Backup scheduler: destPath cleared since registration — skipping run');
- return;
- }
- const excludePaths = fresh.backup?.excludePaths || [];
- const disabledDefaultExcludes = fresh.backup?.disabledDefaultExcludes || [];
- console.log('💾 Backup scheduler: running scheduled backup');
- await runBackup(effective.destPath, null, { excludePaths, disabledDefaultExcludes, retentionCount: effective.retentionCount });
- },
+ handler: () => runScheduledBackup('scheduled'),
metadata: { source: 'backupScheduler' }
});
} catch (err) {
@@ -150,11 +229,11 @@ function attemptRegistration(inputs, timezone, signature) {
* save. Runs outside the request lifecycle — the process-boundary try/catch
* convention applies, not the route error-bubbling one.
*/
-function scheduleCorruptRetry() {
+function scheduleCorruptRetry(catchUpMissedSlot = false) {
if (corruptRetryTimer) return;
corruptRetryTimer = setTimeout(() => {
corruptRetryTimer = null;
- syncBackupSchedule().catch(err =>
+ syncBackupSchedule(undefined, { catchUpMissedSlot }).catch(err =>
console.error(`❌ Backup scheduler: corrupt-settings retry failed: ${err.message}`));
}, CORRUPT_SETTINGS_RETRY_MS);
corruptRetryTimer.unref?.();
@@ -178,11 +257,13 @@ settingsEvents.on('settings:invalidated', () => {
/**
* Boot entry point — registers the cron once at startup if backup is
- * configured. Later enable/disable/cron edits are picked up by the
- * `settings:updated` subscription above.
+ * configured, then checks for a missed slot (#8456) — the daemon being down
+ * or crash-looping across the scheduled time. Later enable/disable/cron edits
+ * are picked up by the `settings:updated` subscription above, which never
+ * re-arms a catch-up.
*/
export async function startBackupScheduler() {
- return syncBackupSchedule();
+ return syncBackupSchedule(undefined, { catchUpMissedSlot: true });
}
/**
@@ -195,5 +276,10 @@ export function stopBackupScheduler() {
clearTimeout(corruptRetryTimer);
corruptRetryTimer = null;
}
+ if (catchUpTimer) {
+ clearTimeout(catchUpTimer);
+ catchUpTimer = null;
+ }
+ catchUpEvaluated = false;
console.log('💾 Backup scheduler: stopped');
}
diff --git a/server/services/backupScheduler.test.js b/server/services/backupScheduler.test.js
index 31fb979649..b721a3ca62 100644
--- a/server/services/backupScheduler.test.js
+++ b/server/services/backupScheduler.test.js
@@ -18,7 +18,10 @@ vi.mock('./eventScheduler.js', () => ({
// null nextRunAt as a failed registration, so the default mock returns a
// firing one.
schedule: vi.fn(() => ({ id: 'backup-daily', nextRunAt: Date.now() + 60_000 })),
- cancel: vi.fn()
+ cancel: vi.fn(),
+ // Defaults to "no missed slot" so every pre-existing test above stays
+ // unaffected by the #8456 catch-up check that now runs on every boot.
+ parseCronToPrevRun: vi.fn(() => null)
}));
// The scheduler subscribes to `settings:updated` at module load, so the mock
@@ -45,16 +48,21 @@ vi.mock('./settings.js', () => {
});
vi.mock('./backup.js', () => ({
- runBackup: vi.fn().mockResolvedValue({ success: true })
+ runBackup: vi.fn().mockResolvedValue({ success: true }),
+ // "never run" — matches backup.js's own DEFAULT_STATE, so a test that
+ // doesn't override this sees the same "no prior run" starting point.
+ getState: vi.fn().mockResolvedValue({ lastRun: null })
}));
vi.mock('./userTimezone.js', () => ({
getUserTimezone: vi.fn().mockResolvedValue('UTC'),
+ getTimezoneUpdatedAt: vi.fn().mockResolvedValue(null)
}));
-import { schedule, cancel } from './eventScheduler.js';
+import { schedule, cancel, parseCronToPrevRun } from './eventScheduler.js';
import { getSettings, getSettingsWithStatus } from './settings.js';
-import { runBackup } from './backup.js';
+import { runBackup, getState } from './backup.js';
+import { getTimezoneUpdatedAt } from './userTimezone.js';
import { startBackupScheduler, stopBackupScheduler, syncBackupSchedule } from './backupScheduler.js';
describe('startBackupScheduler', () => {
@@ -388,3 +396,135 @@ describe('corrupt settings read at boot (#8428)', () => {
expect(schedule.mock.calls[0][0]).toMatchObject({ cron: '0 3 * * *' });
});
});
+
+/**
+ * #8456: the daily backup cron fires nothing until its expression elapses, so
+ * an install where the daemon was down (or crash-looping) across the
+ * scheduled time gets zero backups that day, and — if the machine is
+ * consistently off at that time — ever. Boot now checks whether the most
+ * recent slot elapsed without a backup and, if so, runs a one-time catch-up
+ * after a fixed delay so it never piles onto boot-time migrations/warm-up.
+ */
+describe('missed-slot catch-up at boot (#8456)', () => {
+ const SETTINGS = { backup: { enabled: true, destPath: '/dest', cronExpression: '0 0 * * *' } };
+ const MISSED_SLOT = new Date('2026-01-02T00:00:00.000Z');
+
+ beforeEach(() => {
+ stopBackupScheduler();
+ vi.clearAllMocks();
+ parseCronToPrevRun.mockReturnValue(null);
+ getState.mockResolvedValue({ lastRun: null });
+ getTimezoneUpdatedAt.mockResolvedValue(null);
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('runs a catch-up backup after the boot delay when the last run predates the missed slot', async () => {
+ getSettings.mockResolvedValue(SETTINGS);
+ parseCronToPrevRun.mockReturnValue(MISSED_SLOT);
+ getState.mockResolvedValue({ lastRun: '2026-01-01T00:00:00.000Z' }); // yesterday's slot only
+
+ await startBackupScheduler();
+ expect(runBackup).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+
+ expect(runBackup).toHaveBeenCalledWith('/dest', null, {
+ excludePaths: [], disabledDefaultExcludes: [], retentionCount: null
+ });
+ });
+
+ it('does not catch up when the last run is at or after the most recent slot', async () => {
+ getSettings.mockResolvedValue(SETTINGS);
+ parseCronToPrevRun.mockReturnValue(MISSED_SLOT);
+ getState.mockResolvedValue({ lastRun: MISSED_SLOT.toISOString() });
+
+ await startBackupScheduler();
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+
+ expect(runBackup).not.toHaveBeenCalled();
+ });
+
+ it('suppresses catch-up when the backup config changed after the missed slot', async () => {
+ getSettings.mockResolvedValue({ ...SETTINGS, backupConfigUpdatedAt: MISSED_SLOT.getTime() + 60_000 });
+ parseCronToPrevRun.mockReturnValue(MISSED_SLOT);
+ getState.mockResolvedValue({ lastRun: '2026-01-01T00:00:00.000Z' });
+
+ await startBackupScheduler();
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+
+ expect(runBackup).not.toHaveBeenCalled();
+ });
+
+ it('suppresses catch-up when the timezone changed after the missed slot', async () => {
+ getSettings.mockResolvedValue(SETTINGS);
+ parseCronToPrevRun.mockReturnValue(MISSED_SLOT);
+ getState.mockResolvedValue({ lastRun: '2026-01-01T00:00:00.000Z' });
+ getTimezoneUpdatedAt.mockResolvedValue(MISSED_SLOT.getTime() + 60_000);
+
+ await startBackupScheduler();
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+
+ expect(runBackup).not.toHaveBeenCalled();
+ });
+
+ it('never catches up when backup is disabled', async () => {
+ getSettings.mockResolvedValue({ backup: { enabled: false, destPath: '/dest' } });
+ parseCronToPrevRun.mockReturnValue(MISSED_SLOT);
+ getState.mockResolvedValue({ lastRun: '2026-01-01T00:00:00.000Z' });
+
+ await startBackupScheduler();
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+
+ expect(runBackup).not.toHaveBeenCalled();
+ expect(parseCronToPrevRun).not.toHaveBeenCalled(); // never scheduled, so nothing to catch up
+ });
+
+ it('never catches up when destPath is missing', async () => {
+ getSettings.mockResolvedValue({ backup: { enabled: true } });
+ parseCronToPrevRun.mockReturnValue(MISSED_SLOT);
+ getState.mockResolvedValue({ lastRun: '2026-01-01T00:00:00.000Z' });
+
+ await startBackupScheduler();
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+
+ expect(runBackup).not.toHaveBeenCalled();
+ expect(parseCronToPrevRun).not.toHaveBeenCalled();
+ });
+
+ it('attempts at most one catch-up per boot, even if a settings save re-syncs immediately after', async () => {
+ getSettings.mockResolvedValue(SETTINGS);
+ parseCronToPrevRun.mockReturnValue(MISSED_SLOT);
+ getState.mockResolvedValue({ lastRun: '2026-01-01T00:00:00.000Z' });
+
+ await startBackupScheduler();
+ expect(parseCronToPrevRun).toHaveBeenCalledTimes(1);
+
+ // A same-signature re-sync (e.g. an unrelated settings save) must not
+ // re-evaluate the missed slot a second time this boot.
+ await syncBackupSchedule(SETTINGS, { catchUpMissedSlot: true });
+ expect(parseCronToPrevRun).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+ expect(runBackup).toHaveBeenCalledTimes(1);
+ });
+
+ it('a settings:updated re-sync does not itself trigger a catch-up', async () => {
+ getSettings.mockResolvedValue({ backup: { enabled: false } });
+ await startBackupScheduler();
+ expect(schedule).not.toHaveBeenCalled();
+
+ parseCronToPrevRun.mockReturnValue(MISSED_SLOT);
+ getState.mockResolvedValue({ lastRun: '2026-01-01T00:00:00.000Z' });
+ settingsEvents.emit('settings:updated', SETTINGS);
+ // The listener is async (it awaits getUserTimezone) — advance by 0 to let
+ // it settle without relying on `setImmediate`, which fake timers also fake.
+ await vi.advanceTimersByTimeAsync(0);
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
+
+ expect(runBackup).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/settings.js b/server/services/settings.js
index d3f1c3b457..7c3d96f35d 100644
--- a/server/services/settings.js
+++ b/server/services/settings.js
@@ -254,6 +254,22 @@ const save = async (settings, { actor = 'system', skipUserAction = false } = {})
if (isPlainObject(prev) && cleaned.timezone !== prev.timezone) {
cleaned.timezoneUpdatedAt = Date.now();
}
+ // Stamp `backupConfigUpdatedAt` whenever a registration-affecting backup
+ // field actually changes (cron expression, enabled, or destination) — the
+ // same shape as `timezoneUpdatedAt` above — so backupScheduler.js's
+ // missed-slot catch-up (#8456) can tell "this config produced the missed
+ // slot" from "the config was edited after the slot was missed" and skip a
+ // catch-up the current settings never scheduled.
+ if (isPlainObject(prev)) {
+ const prevBackup = isPlainObject(prev.backup) ? prev.backup : {};
+ const nextBackup = isPlainObject(cleaned.backup) ? cleaned.backup : {};
+ const backupScheduleChanged = prevBackup.cronExpression !== nextBackup.cronExpression
+ || prevBackup.enabled !== nextBackup.enabled
+ || (prevBackup.destPath || null) !== (nextBackup.destPath || null);
+ if (backupScheduleChanged) {
+ cleaned.backupConfigUpdatedAt = Date.now();
+ }
+ }
// atomicWrite (temp-file + rename) so a mid-write crash never truncates
// settings.json. Pass a pre-stringified string to preserve the trailing
// newline; atomicWrite's own JSON.stringify omits it.
diff --git a/server/services/settings.test.js b/server/services/settings.test.js
index 55ecc9ae8f..6ccadb8e6d 100644
--- a/server/services/settings.test.js
+++ b/server/services/settings.test.js
@@ -402,6 +402,64 @@ describe('settings.js', () => {
});
});
+ // backupScheduler.js's missed-slot catch-up (#8456) needs to tell "this
+ // config produced the missed slot" from "the config was edited after the
+ // slot was missed" — the same shape as timezoneUpdatedAt above.
+ describe('backupConfigUpdatedAt stamping (#8456)', () => {
+ it('stamps when the cron expression changes', async () => {
+ tryReadFile.mockResolvedValue(JSON.stringify({ backup: { enabled: true, destPath: '/dest', cronExpression: '0 0 * * *' } }));
+
+ const before = Date.now();
+ const result = await updateSettings({ backup: { enabled: true, destPath: '/dest', cronExpression: '0 3 * * *' } });
+
+ expect(typeof result.backupConfigUpdatedAt).toBe('number');
+ expect(result.backupConfigUpdatedAt).toBeGreaterThanOrEqual(before);
+ });
+
+ it('stamps when enabled toggles', async () => {
+ tryReadFile.mockResolvedValue(JSON.stringify({ backup: { enabled: true, destPath: '/dest' } }));
+
+ const result = await updateSettings({ backup: { enabled: false, destPath: '/dest' } });
+
+ expect(typeof result.backupConfigUpdatedAt).toBe('number');
+ });
+
+ it('stamps when destPath changes', async () => {
+ tryReadFile.mockResolvedValue(JSON.stringify({ backup: { enabled: true, destPath: '/dest-a' } }));
+
+ const result = await updateSettings({ backup: { enabled: true, destPath: '/dest-b' } });
+
+ expect(typeof result.backupConfigUpdatedAt).toBe('number');
+ });
+
+ it('does NOT stamp when an unrelated backup field changes (excludePaths)', async () => {
+ tryReadFile.mockResolvedValue(JSON.stringify({ backup: { enabled: true, destPath: '/dest', excludePaths: [] } }));
+
+ const result = await updateSettings({ backup: { enabled: true, destPath: '/dest', excludePaths: ['/scratch'] } });
+
+ expect(result.backupConfigUpdatedAt).toBeUndefined();
+ });
+
+ it('does NOT stamp when an unrelated top-level setting is saved', async () => {
+ tryReadFile.mockResolvedValue(JSON.stringify({ backup: { enabled: true, destPath: '/dest' }, theme: 'dark' }));
+
+ const result = await updateSettings({ theme: 'light' });
+
+ expect(result.backupConfigUpdatedAt).toBeUndefined();
+ });
+
+ it('preserves an existing backupConfigUpdatedAt across an unrelated save', async () => {
+ tryReadFile.mockResolvedValue(JSON.stringify({
+ backup: { enabled: true, destPath: '/dest' },
+ backupConfigUpdatedAt: 1234567890
+ }));
+
+ const result = await updateSettings({ theme: 'dark' });
+
+ expect(result.backupConfigUpdatedAt).toBe(1234567890);
+ });
+ });
+
describe('MortalLoom store key pollution guard', () => {
it('strips MortalLoom-store top-level keys on read', async () => {
// Simulates the historical corruption: settings.json contains both