A local-first personal finance app
[AI] Retry incomplete schedule advancement without blocking healthy schedules (#9386)
Tim479db6081b4a
diff --git a/packages/desktop-client/src/components/schedules/PostsOfflineNotification.tsx b/packages/desktop-client/src/components/schedules/PostsOfflineNotification.tsxindex b839d18622..7757d6a7da 100644--- a/packages/desktop-client/src/components/schedules/PostsOfflineNotification.tsx+++ b/packages/desktop-client/src/components/schedules/PostsOfflineNotification.tsx@@ -29,8 +29,13 @@ export function PostsOfflineNotification() {: [];async function onPost() {- await send('schedule/force-run-service');- dispatch(popModal());+ try {+ await send('schedule/force-run-service');+ dispatch(popModal());+ } catch (error) {+ // The connection also reports this through the global server-error notification.+ console.error('Failed to post scheduled transactions', error);+ }}const payeesList = payees.map(id => (diff --git a/packages/loot-core/src/server/schedules/app.test.ts b/packages/loot-core/src/server/schedules/app.test.tsindex 45c2fd6036..938fd8047b 100644--- a/packages/loot-core/src/server/schedules/app.test.ts+++ b/packages/loot-core/src/server/schedules/app.test.ts@@ -4,10 +4,13 @@ import MockDate from 'mockdate';import { aqlQuery } from '#server/aql';import * as db from '#server/db';import { loadMappings } from '#server/db/mappings';+import { app as mainApp } from '#server/main-app';+import { runMutator } from '#server/mutators';import * as prefs from '#server/prefs';import { loadRules, updateRule } from '#server/transactions/transaction-rules';import { q } from '#shared/query';import { getNextDate } from '#shared/schedules';+import type { ServerEvents } from '#types/server-events';import {advanceSchedulesService,@@ -1313,6 +1316,173 @@ describe('schedule app', () => {});});+ describe('schedule advancement failures', () => {+ let accountId: string;+ let syncErrors: number;+ const catchUpDates = ['2016-12-18', '2016-12-25', '2017-01-01'];+ const healthyDates = ['2016-12-25', '2017-01-01'];++ function forwardSync(event: ServerEvents['sync-event']) {+ if (event.type === 'error') {+ syncErrors++;+ }+ schedulesApp.events.emit('sync', event);+ }++ beforeEach(async () => {+ MockDate.set(new Date(2016, 11, 31, 12));+ schedulesApp.startServices();+ await prefs.loadPrefs();+ accountId = await db.insertAccount({ name: 'Checking', closed: 0 });+ syncErrors = 0;+ // Production also registers the schedule listener on the main app.+ mainApp.events.on('sync', forwardSync);+ });++ afterEach(async () => {+ // Detach before draining so a self-retry regression cannot leak work.+ mainApp.events.off('sync', forwardSync);+ await runMutator(() => Promise.resolve());+ db.runQuery('DROP TRIGGER IF EXISTS fail_schedule_advancement');+ prefs.unloadPrefs();+ MockDate.reset();+ await schedulesApp.stopServices();+ });++ function rewindSchedule(id: string, nextDate = 20161218) {+ db.runQuery(+ 'UPDATE schedules_next_date SET local_next_date = ?, base_next_date = ? WHERE schedule_id = ?',+ [nextDate, nextDate, id],+ );+ }++ async function createRecurringSchedule({+ postsTransaction = true,+ nextDate = 20161218,+ } = {}) {+ const id = await createSchedule({+ schedule: { posts_transaction: postsTransaction },+ conditions: [+ { op: 'is', field: 'account', value: accountId },+ {+ op: 'is',+ field: 'date',+ value: { start: '2016-12-18', frequency: 'weekly', patterns: [] },+ },+ ],+ });+ rewindSchedule(id, nextDate);+ if (!postsTransaction) {+ await db.insertTransaction({+ account: accountId,+ amount: 0,+ date: '2016-12-18',+ schedule: id,+ });+ }+ return id;+ }++ async function postedDates(id: string) {+ const { data } = await aqlQuery(+ q('transactions')+ .filter({ schedule: id })+ .select('date')+ .orderBy({ date: 'asc' }),+ );+ return data.map(row => row.date);+ }++ async function syncSuccessfully() {+ mainApp.events.emit('sync', { type: 'success', tables: [] });+ await runMutator(() => Promise.resolve());+ // Also drain a retry incorrectly enqueued by this run's own error.+ await runMutator(() => Promise.resolve());+ }++ it.each([+ { postsTransaction: true, ruleState: 'missing' },+ { postsTransaction: false, ruleState: 'corrupt' },+ ])(+ 'isolates a $ruleState rule and retries unexpected errors without duplicates (auto-post: $postsTransaction)',+ async ({ postsTransaction, ruleState }) => {+ const failedId = await createRecurringSchedule({ postsTransaction });+ const brokenId = await createRecurringSchedule({+ postsTransaction: false,+ });+ // The healthy schedule must sort after the failing ones.+ const healthyId = await createRecurringSchedule({ nextDate: 20161225 });+ const { data: ruleId } = await aqlQuery(+ q('schedules').filter({ id: brokenId }).calculate('rule'),+ );+ if (ruleState === 'missing') {+ db.runQuery('DELETE FROM rules WHERE id = ?', [ruleId]);+ } else {+ db.runQuery('UPDATE rules SET actions = ? WHERE id = ?', [+ JSON.stringify([{ op: 'invalid-action' }]),+ ruleId,+ ]);+ }+ await loadRules();+ // Exercise the real setNextDate write through each advancement path.+ db.runQuery(`+ CREATE TEMP TRIGGER fail_schedule_advancement+ BEFORE UPDATE OF local_next_date ON schedules_next_date+ WHEN OLD.schedule_id = '${failedId}'+ BEGIN SELECT RAISE(FAIL, 'schedule advancement write failed'); END+ `);++ await syncSuccessfully();+ expect.soft(syncErrors).toBe(1);+ expect.soft(prefs.getPrefs().lastScheduleRun).not.toBe('2017-01-01');+ expect(await postedDates(failedId)).toEqual(['2016-12-18']);+ expect(await postedDates(healthyId)).toEqual(healthyDates);++ db.runQuery('DROP TRIGGER fail_schedule_advancement');+ await syncSuccessfully();+ expect(await postedDates(failedId)).toEqual(+ postsTransaction ? catchUpDates : ['2016-12-18'],+ );+ expect(await postedDates(healthyId)).toEqual(healthyDates);+ const { data: nextDate } = await aqlQuery(+ q('schedules').filter({ id: failedId }).calculate('next_date'),+ );+ expect(nextDate).toBe('2017-01-01');+ expect(prefs.getPrefs().lastScheduleRun).toBe('2017-01-01');++ // Incoming old next-date data must not bypass the successful daily marker.+ rewindSchedule(healthyId);+ await syncSuccessfully();+ const { data: unchangedDate } = await aqlQuery(+ q('schedules').filter({ id: healthyId }).calculate('next_date'),+ );+ expect(unchangedDate).toBe('2016-12-18');+ },+ );++ it('does not retry its own clock-drift error', async () => {+ const id = await createSchedule({+ schedule: { posts_transaction: true },+ conditions: [+ { op: 'is', field: 'account', value: accountId },+ { op: 'is', field: 'date', value: '2016-12-18' },+ ],+ });+ // Completing this paid one-time schedule writes a new message.+ await db.insertTransaction({+ account: accountId,+ amount: 0,+ date: '2016-12-18',+ schedule: id,+ });+ // A backward clock correction leaves the clock over five minutes ahead.+ MockDate.set(new Date(2016, 11, 31, 11, 50));++ await syncSuccessfully();+ expect(syncErrors).toBe(1);+ });+ });+describe('auto-post service throttling', () => {const dateCondition = {op: 'is',diff --git a/packages/loot-core/src/server/schedules/app.ts b/packages/loot-core/src/server/schedules/app.tsindex e8304ee524..f3f9b7fe86 100644--- a/packages/loot-core/src/server/schedules/app.ts+++ b/packages/loot-core/src/server/schedules/app.ts@@ -9,6 +9,7 @@ import { addTransactions } from '#server/accounts/sync';import { createApp } from '#server/app';import { aqlQuery } from '#server/aql';import * as db from '#server/db';+import { RuleError } from '#server/errors';import { toDateRepr } from '#server/models';import { mutator, runMutator } from '#server/mutators';import * as prefs from '#server/prefs';@@ -239,7 +240,12 @@ export async function setNextDate({if (conditions == null) {const rule = await getRuleForSchedule(id);if (rule == null) {- throw new Error('No rule found for schedule');+ // Corrupt rules are dropped when the rule cache loads, so this also+ // covers them. A RuleError marks a rule problem, not an I/O failure.+ throw new RuleError(+ 'schedule-rule-not-found',+ 'No rule found for schedule',+ );}conditions = rule.serialize().conditions;}@@ -657,12 +663,7 @@ async function advanceRecurringScheduleFromNextDate(const previousNextDate = schedule.next_date;- try {- await setNextDate({ id: schedule.id, advance: true });- } catch {- // This might error if the rule is corrupted and it can't find the rule.- return null;- }+ await setNextDate({ id: schedule.id, advance: true });const updatedSchedule = await getSchedule(schedule.id);@@ -694,6 +695,7 @@ export async function advanceSchedulesService(syncSuccess) {);const failedToPost = [];+ const advancementErrors: Error[] = [];let didPost = false;const { data: upcomingLength } = await aqlQuery(@@ -703,33 +705,72 @@ export async function advanceSchedulesService(syncSuccess) {);for (const schedule of schedules) {- const status = getStatus(- schedule.next_date,- schedule.completed,- hasTrans.has(schedule.id),- schedule.custom_upcoming_length ??- upcomingLength[0]?.value ??- DEFAULT_UPCOMING_SCHEDULE_DAYS,- );+ try {+ const status = getStatus(+ schedule.next_date,+ schedule.completed,+ hasTrans.has(schedule.id),+ schedule.custom_upcoming_length ??+ upcomingLength[0]?.value ??+ DEFAULT_UPCOMING_SCHEDULE_DAYS,+ );- if (- schedule.posts_transaction &&- schedule._account &&- (status !== 'paid' || isRecurringSchedule(schedule)) &&- (status === 'paid' || status === 'due' || status === 'missed')- ) {- let currentSchedule = schedule;- let currentStatus = status;-- while (- currentSchedule.posts_transaction &&- currentSchedule._account &&- (currentStatus === 'paid' ||- currentStatus === 'due' ||- currentStatus === 'missed')+ if (+ schedule.posts_transaction &&+ schedule._account &&+ (status !== 'paid' || isRecurringSchedule(schedule)) &&+ (status === 'paid' || status === 'due' || status === 'missed')) {- if (currentStatus === 'paid') {- if (currentSchedule.next_date === currentDay()) {+ let currentSchedule = schedule;+ let currentStatus = status;++ while (+ currentSchedule.posts_transaction &&+ currentSchedule._account &&+ (currentStatus === 'paid' ||+ currentStatus === 'due' ||+ currentStatus === 'missed')+ ) {+ if (currentStatus === 'paid') {+ if (currentSchedule.next_date === currentDay()) {+ break;+ }++ const updatedSchedule =+ await advanceRecurringScheduleFromNextDate(currentSchedule);++ if (updatedSchedule == null) {+ break;+ }++ currentSchedule = updatedSchedule;+ currentStatus = getStatus(+ currentSchedule.next_date,+ currentSchedule.completed,+ await hasTransactionForSchedule(currentSchedule),+ currentSchedule.custom_upcoming_length ??+ upcomingLength[0]?.value ??+ DEFAULT_UPCOMING_SCHEDULE_DAYS,+ );+ continue;+ }++ // Automatically create a transaction for due schedules.+ if (syncSuccess) {+ await postTransactionForSchedule({ id: currentSchedule.id });++ didPost = true;+ } else {+ failedToPost.push(currentSchedule._payee);+ break;+ }++ // do not skip schedules due today+ if (currentStatus === 'due') {+ break;+ }++ if (!isRecurringSchedule(currentSchedule)) {break;}@@ -749,64 +790,35 @@ export async function advanceSchedulesService(syncSuccess) {upcomingLength[0]?.value ??DEFAULT_UPCOMING_SCHEDULE_DAYS,);- continue;- }-- // Automatically create a transaction for due schedules.- if (syncSuccess) {- await postTransactionForSchedule({ id: currentSchedule.id });-- didPost = true;- } else {- failedToPost.push(currentSchedule._payee);- break;- }-- // do not skip schedules due today- if (currentStatus === 'due') {- break;- }-- if (!isRecurringSchedule(currentSchedule)) {- break;- }-- const updatedSchedule =- await advanceRecurringScheduleFromNextDate(currentSchedule);-- if (updatedSchedule == null) {- break;}-- currentSchedule = updatedSchedule;- currentStatus = getStatus(- currentSchedule.next_date,- currentSchedule.completed,- await hasTransactionForSchedule(currentSchedule),- currentSchedule.custom_upcoming_length ??- upcomingLength[0]?.value ??- DEFAULT_UPCOMING_SCHEDULE_DAYS,- );- }- } else if (status === 'paid') {- if (schedule._date) {- // Move forward recurring schedules- if (isRecurringSchedule(schedule)) {- try {+ } else if (status === 'paid') {+ if (schedule._date) {+ // Move forward recurring schedules+ if (isRecurringSchedule(schedule)) {await setNextDate({ id: schedule.id });- } catch {- // This might error if the rule is corrupted and it can't- // find the rule- }- } else {- if (schedule._date < currentDay()) {- // Complete any single schedules- await updateSchedule({- schedule: { id: schedule.id, completed: true },- });+ } else {+ if (schedule._date < currentDay()) {+ // Complete any single schedules+ await updateSchedule({+ schedule: { id: schedule.id, completed: true },+ });+ }}}}+ } catch (error) {+ // A missing or corrupt rule is expected and should not block retries.+ if (error instanceof RuleError) {+ continue;+ }++ // Keep successful posts and next-date updates. A retry uses persisted+ // paid occurrences to resume without posting them a second time.+ advancementErrors.push(+ new Error(`Failed to advance schedule ${schedule.id}`, {+ cause: error,+ }),+ );}}@@ -823,6 +835,10 @@ export async function advanceSchedulesService(syncSuccess) {syncDisabled: false,});}++ if (advancementErrors.length > 0) {+ throw new AggregateError(advancementErrors, 'Failed to advance schedules');+ }}export type SchedulesHandlers = {@@ -858,7 +874,35 @@ app.method('schedule/get-upcoming-dates', getUpcomingDates);app.service(trackJSONPaths);+// Failed schedule writes emit sync errors too. While a run is active, ignore+// them so the retry waits for a later external sync instead of this run.+let advancingAfterSync = false;++async function advanceSchedulesAfterSync(syncSuccess: boolean) {+ const runDay = currentDay();+ // An earlier queued sync may have completed today's work already.+ if (prefs.getPrefs().lastScheduleRun === runDay) {+ return;+ }++ advancingAfterSync = true;+ try {+ await advanceSchedulesService(syncSuccess);++ // Rejected or offline runs must remain retryable on a later sync.+ if (syncSuccess) {+ await prefs.savePrefs({ lastScheduleRun: runDay });+ }+ } finally {+ advancingAfterSync = false;+ }+}+app.events.on('sync', ({ type }) => {+ if (advancingAfterSync) {+ return;+ }+const completeEvent =type === 'success' || type === 'error' || type === 'unauthorized';@@ -869,24 +913,11 @@ app.events.on('sync', ({ type }) => {}if (prefs.getPrefs().lastScheduleRun !== currentDay()) {- void runMutator(async () => {- const runDay = currentDay();- const { lastScheduleRun } = prefs.getPrefs();- // A run queued by an earlier sync may have already finished today- if (lastScheduleRun === runDay) {- return;- }-- await advanceSchedulesService(type === 'success');-- // Only mark the day as done when sync succeeded, so that- // schedule auto-posting is retried on subsequent successful syncs- if (type === 'success') {- await prefs.savePrefs({ lastScheduleRun: runDay });- }- }).catch(error => {- logger.error('Failed to run schedule service after sync', error);- });+ runMutator(() => advanceSchedulesAfterSync(type === 'success')).catch(+ error => {+ logger.error('Failed to run schedule service after sync', error);+ },+ );}}});diff --git a/upcoming-release-notes/retry-schedule-advancement.md b/upcoming-release-notes/retry-schedule-advancement.mdnew file mode 100644index 0000000000..d93c02233d--- /dev/null+++ b/upcoming-release-notes/retry-schedule-advancement.md@@ -0,0 +1,6 @@+---+category: Bugfix+authors: [tim-smart]+---++Fix scheduled transactions failing to catch up after a temporary error without duplicating transactions already posted