Skip to content

A local-first personal finance app

[AI] Stop scanning every transaction once per rendered register row (#8663)

youngcw87e33e49eb4d
diff --git a/packages/desktop-client/src/components/transactions/useTransactionRowContextActions.ts b/packages/desktop-client/src/components/transactions/useTransactionRowContextActions.ts
index 65d302d4fe..a6447ac1a6 100644
--- a/packages/desktop-client/src/components/transactions/useTransactionRowContextActions.ts
+++ b/packages/desktop-client/src/components/transactions/useTransactionRowContextActions.ts
@@ -64,6 +64,9 @@ export function useTransactionRowContextActions({
}, [selectedIds]);
const scheduleQuery = useMemo(() => {
+ if (scheduleIds.length === 0) {
+ return undefined;
+ }
return q('schedules')
.filter({ id: { $oneof: scheduleIds } })
.select('*');
diff --git a/packages/desktop-client/src/hooks/useSchedules.test.ts b/packages/desktop-client/src/hooks/useSchedules.test.ts
new file mode 100644
index 0000000000..cb2df0566e
--- /dev/null
+++ b/packages/desktop-client/src/hooks/useSchedules.test.ts
@@ -0,0 +1,82 @@
+import { q } from '@actual-app/core/shared/query';
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { liveQuery } from '#queries/liveQuery';
+import type { LiveQuery } from '#queries/liveQuery';
+
+import { useSchedules } from './useSchedules';
+
+vi.mock('#queries/liveQuery', () => ({
+ liveQuery: vi.fn(),
+}));
+
+vi.mock('./useSyncedPref', () => ({
+ useSyncedPref: () => ['7', vi.fn()],
+}));
+
+type LiveQueryCall = {
+ onData: (data: unknown[], previousData: unknown[]) => void;
+ unsubscribe: ReturnType<typeof vi.fn>;
+};
+
+describe('useSchedules', () => {
+ let calls: LiveQueryCall[];
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ calls = [];
+
+ // `vi.mocked` keeps the mock bound to the real `liveQuery` signature, so a
+ // change to how the hook calls it still fails typecheck.
+ vi.mocked(liveQuery).mockImplementation((_query, { onData }) => {
+ const handle = {
+ onData: onData ?? vi.fn(),
+ unsubscribe: vi.fn(),
+ };
+ calls.push(handle);
+ // `LiveQuery` is a class with private state; only the subscription
+ // surface used by the hook is faked here.
+ return handle as unknown as LiveQuery<unknown>;
+ });
+ });
+
+ it('does not open any live query when no query is given', () => {
+ renderHook(() => useSchedules({}));
+
+ expect(liveQuery).not.toHaveBeenCalled();
+ });
+
+ it('unsubscribes the previous status query when schedules refresh', () => {
+ renderHook(() => useSchedules({ query: q('schedules').select('*') }));
+
+ // The schedules query is opened first; its onData opens the status query.
+ expect(calls).toHaveLength(1);
+ const schedulesQuery = calls[0];
+
+ schedulesQuery.onData([], []);
+ expect(calls).toHaveLength(2);
+ const firstStatusQuery = calls[1];
+ expect(firstStatusQuery.unsubscribe).not.toHaveBeenCalled();
+
+ // A refresh must tear down the previous status query rather than orphaning
+ // it — an orphan stays subscribed to sync events and keeps re-running.
+ schedulesQuery.onData([], []);
+ expect(firstStatusQuery.unsubscribe).toHaveBeenCalledTimes(1);
+ expect(calls).toHaveLength(3);
+ });
+
+ it('unsubscribes both queries on unmount', () => {
+ const { unmount } = renderHook(() =>
+ useSchedules({ query: q('schedules').select('*') }),
+ );
+
+ calls[0].onData([], []);
+ expect(calls).toHaveLength(2);
+
+ unmount();
+
+ expect(calls[0].unsubscribe).toHaveBeenCalled();
+ expect(calls[1].unsubscribe).toHaveBeenCalled();
+ });
+});
diff --git a/packages/desktop-client/src/hooks/useSchedules.ts b/packages/desktop-client/src/hooks/useSchedules.ts
index 6b6d1089d4..fb326f0580 100644
--- a/packages/desktop-client/src/hooks/useSchedules.ts
+++ b/packages/desktop-client/src/hooks/useSchedules.ts
@@ -106,6 +106,10 @@ export function useSchedules({
scheduleQueryRef.current = liveQuery<ScheduleEntity>(query, {
onData: async schedules => {
+ // `onData` fires again whenever the schedules change, so tear down the
+ // previous status query first. Otherwise each refresh orphans a live
+ // query that stays subscribed to sync events and keeps re-running.
+ statusQueryRef.current?.unsubscribe();
statusQueryRef.current = loadStatuses(
schedules,
(statuses: ScheduleStatuses) => {
diff --git a/packages/loot-core/src/shared/schedules.test.ts b/packages/loot-core/src/shared/schedules.test.ts
index ca1a0bf992..49165701c0 100644
--- a/packages/loot-core/src/shared/schedules.test.ts
+++ b/packages/loot-core/src/shared/schedules.test.ts
@@ -5,6 +5,7 @@ import type { RuleConditionEntity, ScheduleEntity } from '#types/models';
import * as monthUtils from './months';
import {
computeSchedulePreviewTransactions,
+ getHasTransactionsQuery,
getNextDate,
getScheduleOccurrenceMatchStartDate,
getStatus,
@@ -269,6 +270,35 @@ describe('schedules', () => {
});
});
+ describe('getHasTransactionsQuery', () => {
+ it('matches nothing when there are no schedules', () => {
+ // An empty `$or` compiles away to no constraint at all, which would make
+ // this scan every transaction in the budget. It must never do that.
+ const filters = getHasTransactionsQuery([]).serialize().filterExpressions;
+
+ expect(filters).toEqual([{ id: null }]);
+ expect(filters[0]).not.toHaveProperty('$or');
+ });
+
+ it('filters by schedule and date when schedules are given', () => {
+ const filters = getHasTransactionsQuery([
+ {
+ id: 'schedule-1',
+ next_date: '2024-03-10',
+ _conditions: [{ op: 'is', field: 'date', value: '2024-03-10' }],
+ },
+ ]).serialize().filterExpressions;
+
+ expect(filters).toEqual([
+ {
+ $or: [
+ { $and: { schedule: 'schedule-1', date: { $gte: '2024-03-10' } } },
+ ],
+ },
+ ]);
+ });
+ });
+
describe('getScheduleOccurrenceMatchStartDate', () => {
const occurrenceDate = '2024-03-10';
diff --git a/packages/loot-core/src/shared/schedules.ts b/packages/loot-core/src/shared/schedules.ts
index d2d98689df..034de54d4f 100644
--- a/packages/loot-core/src/shared/schedules.ts
+++ b/packages/loot-core/src/shared/schedules.ts
@@ -136,11 +136,19 @@ export function getHasTransactionsQuery(schedules) {
};
});
- return q('transactions')
+ const query = q('transactions')
.options({ splits: 'all' })
- .filter({ $or: filters })
.orderBy({ date: 'desc' })
.select(['schedule', 'date']);
+
+ // An empty `$or` compiles away to no constraint at all (`WHERE 1`), which
+ // would scan every transaction in the budget to answer a question about zero
+ // schedules. Match nothing instead — `id` is a primary key and never null.
+ if (filters.length === 0) {
+ return query.filter({ id: null });
+ }
+
+ return query.filter({ $or: filters });
}
type ScheduleRuleOptions = IRuleOptions & {
diff --git a/upcoming-release-notes/fix-per-row-schedule-fullscan.md b/upcoming-release-notes/fix-per-row-schedule-fullscan.md
new file mode 100644
index 0000000000..604743bf9f
--- /dev/null
+++ b/upcoming-release-notes/fix-per-row-schedule-fullscan.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [youngcw]
+---
+
+Fix the transaction list getting slower as a budget grows, especially when adding, clearing, or deleting transactions and when reconciling