A local-first personal finance app
[AI] Batch sum-amount query on cold budget build (#8140)
Matiss Janis Aboltins044a4ad47a5f
diff --git a/packages/loot-core/src/server/budget/base.test.ts b/packages/loot-core/src/server/budget/base.test.tsindex 11686dcb24..72f47286bc 100644--- a/packages/loot-core/src/server/budget/base.test.ts+++ b/packages/loot-core/src/server/budget/base.test.ts@@ -337,4 +337,177 @@ describe('Base budget', () => {// Verify total spent includes both visible and hidden group amountsexpect(sheet.getCellValue(sheetName, 'total-spent')).toBe(-3000);});++ it('Seeds sum-amount across all months on a cold build (Envelope Budget)', async () => {+ await sheet.loadSpreadsheet(db);+ sheet.get().meta().budgetType = 'envelope';++ await db.insertCategoryGroup({ id: 'group1', name: 'Expenses' });+ await db.insertCategoryGroup({+ id: 'group2',+ name: 'Income',+ is_income: 1,+ });+ const foodId = await db.insertCategory({+ name: 'Food',+ cat_group: 'group1',+ });+ const rentId = await db.insertCategory({+ name: 'Rent',+ cat_group: 'group1',+ });++ await db.insertAccount({ id: 'account1', name: 'Account 1' });++ // Insert transactions across multiple months *before* building the+ // budgets, so the cold build seeds the sum-amount cells from the+ // batched query rather than per-cell queries.+ await db.insertTransaction({+ date: '2017-01-10',+ amount: -1000,+ account: 'account1',+ category: foodId,+ });+ await db.insertTransaction({+ date: '2017-01-20',+ amount: -500,+ account: 'account1',+ category: foodId,+ });+ await db.insertTransaction({+ date: '2017-02-15',+ amount: -2500,+ account: 'account1',+ category: foodId,+ });+ await db.insertTransaction({+ date: '2017-01-05',+ amount: -90000,+ account: 'account1',+ category: rentId,+ });+ await db.insertTransaction({+ date: '2017-03-01',+ amount: -90000,+ account: 'account1',+ category: rentId,+ });++ await createAllBudgets();+ await sheet.waitOnSpreadsheet();++ const jan = monthUtils.sheetForMonth('2017-01');+ const feb = monthUtils.sheetForMonth('2017-02');+ const mar = monthUtils.sheetForMonth('2017-03');++ // Per-category seeded sums+ expect(sheet.getCellValue(jan, `sum-amount-${foodId}`)).toBe(-1500);+ expect(sheet.getCellValue(feb, `sum-amount-${foodId}`)).toBe(-2500);+ expect(sheet.getCellValue(mar, `sum-amount-${foodId}`)).toBe(0);+ expect(sheet.getCellValue(jan, `sum-amount-${rentId}`)).toBe(-90000);+ // A category with no transactions in a month seeds to 0+ expect(sheet.getCellValue(feb, `sum-amount-${rentId}`)).toBe(0);+ expect(sheet.getCellValue(mar, `sum-amount-${rentId}`)).toBe(-90000);++ // Downstream cells read the seeded values correctly+ expect(sheet.getCellValue(jan, 'group-sum-amount-group1')).toBe(-91500);+ expect(sheet.getCellValue(feb, 'group-sum-amount-group1')).toBe(-2500);+ expect(sheet.getCellValue(jan, `leftover-${foodId}`)).toBe(-1500);+ });++ it('Seeds sum-amount across all months on a cold build (Tracking Budget)', async () => {+ await sheet.loadSpreadsheet(db);+ sheet.get().meta().budgetType = 'tracking';++ await db.insertCategoryGroup({ id: 'group1', name: 'Expenses' });+ await db.insertCategoryGroup({+ id: 'group2',+ name: 'Income',+ is_income: 1,+ });+ const foodId = await db.insertCategory({+ name: 'Food',+ cat_group: 'group1',+ });+ const rentId = await db.insertCategory({+ name: 'Rent',+ cat_group: 'group1',+ });++ await db.insertAccount({ id: 'account1', name: 'Account 1' });++ await db.insertTransaction({+ date: '2017-01-10',+ amount: -1500,+ account: 'account1',+ category: foodId,+ });+ await db.insertTransaction({+ date: '2017-01-05',+ amount: -90000,+ account: 'account1',+ category: rentId,+ });+ await db.insertTransaction({+ date: '2017-02-15',+ amount: -2500,+ account: 'account1',+ category: foodId,+ });++ await createAllBudgets();+ await sheet.waitOnSpreadsheet();++ const jan = monthUtils.sheetForMonth('2017-01');+ const feb = monthUtils.sheetForMonth('2017-02');++ expect(sheet.getCellValue(jan, `sum-amount-${foodId}`)).toBe(-1500);+ expect(sheet.getCellValue(jan, `sum-amount-${rentId}`)).toBe(-90000);+ expect(sheet.getCellValue(feb, `sum-amount-${foodId}`)).toBe(-2500);+ expect(sheet.getCellValue(jan, 'total-spent')).toBe(-91500);+ expect(sheet.getCellValue(feb, 'total-spent')).toBe(-2500);+ });++ it('Excludes off-budget account spending when seeding sum-amount', async () => {+ await sheet.loadSpreadsheet(db);+ sheet.get().meta().budgetType = 'envelope';++ await db.insertCategoryGroup({ id: 'group1', name: 'Expenses' });+ await db.insertCategoryGroup({+ id: 'group2',+ name: 'Income',+ is_income: 1,+ });+ const foodId = await db.insertCategory({+ name: 'Food',+ cat_group: 'group1',+ });++ await db.insertAccount({ id: 'onbudget', name: 'On budget' });+ await db.insertAccount({+ id: 'offbudget',+ name: 'Off budget',+ offbudget: 1,+ });++ await db.insertTransaction({+ date: '2017-01-10',+ amount: -1000,+ account: 'onbudget',+ category: foodId,+ });+ // Off-budget spending must not be counted, matching the per-cell query.+ await db.insertTransaction({+ date: '2017-01-12',+ amount: -5000,+ account: 'offbudget',+ category: foodId,+ });++ await createAllBudgets();+ await sheet.waitOnSpreadsheet();++ const jan = monthUtils.sheetForMonth('2017-01');+ expect(sheet.getCellValue(jan, `sum-amount-${foodId}`)).toBe(-1000);+ });});diff --git a/packages/loot-core/src/server/budget/base.ts b/packages/loot-core/src/server/budget/base.tsindex 21c3de20e4..4e10a6f8c1 100644--- a/packages/loot-core/src/server/budget/base.ts+++ b/packages/loot-core/src/server/budget/base.ts@@ -38,6 +38,38 @@ export function getBudgetRange(start: string, end: string) {return { start, end, range: monthUtils.rangeInclusive(start, end) };}+// Computes the spend total for every category in every month within the+// given day range using a single grouped query. This is used to seed the+// `sum-amount` cells on a cold build so we avoid running one+// `SELECT SUM(amount)` query per category per month (which scales as+// categories × months and dominates load time for budgets with many years+// of data). The filters must match the per-cell query in `createCategory`+// exactly so balances stay identical.+function getSumAmountsByMonth(+ rangeStart: number,+ rangeEnd: number,+): Map<string, number> {+ const rows = db.runQuery<{ month: number; category: string; amount: number }>(+ `SELECT t.category AS category,+ t.date / 100 AS month,+ SUM(t.amount) AS amount+ FROM v_transactions_internal_alive t+ LEFT JOIN accounts a ON a.id = t.account+ WHERE t.date >= ${rangeStart} AND t.date <= ${rangeEnd}+ AND t.category IS NOT NULL+ AND a.offbudget = 0+ GROUP BY t.category, t.date / 100`,+ [],+ true,+ );++ const sums = new Map<string, number>();+ for (const row of rows) {+ sums.set(`${row.month}-${row.category}`, row.amount || 0);+ }+ return sums;+}+export function createCategory(cat, sheetName, prevSheetName, start, end) {sheet.get().createDynamic(sheetName, 'sum-amount-' + cat.id, {initialValue: 0,@@ -249,42 +281,92 @@ export async function createBudget(months) {envelopeBudget.createBudget(meta, categories, months);}- months.forEach(month => {- if (!meta.createdMonths.has(month)) {- const prevMonth = monthUtils.prevMonth(month);- const { start, end } = monthUtils.bounds(month);- const sheetName = monthUtils.sheetForMonth(month);- const prevSheetName = monthUtils.sheetForMonth(prevMonth);-- categories.forEach(cat => {- createCategory(cat, sheetName, prevSheetName, start, end);- });- groups.forEach(group => {- if (budgetType === 'envelope') {- envelopeBudget.createCategoryGroup(group, sheetName);- } else {- trackingBudget.createCategoryGroup(group, sheetName);+ // Only months that don't already exist need to be created and seeded.+ const monthsToCreate = months.filter(month => !meta.createdMonths.has(month));++ // Spend totals for every category in the months being created, computed+ // once via a single grouped query and used to seed the `sum-amount` cells so+ // they don't each run their own query. Scoped to the uncached month span so+ // extending the budget horizon doesn't rescan the entire transaction+ // history, and loaded lazily so warm loads never touch the database here.+ let sumAmounts: Map<string, number> | null = null;+ const getSumAmounts = () => {+ if (!sumAmounts) {+ // `monthsToCreate` isn't guaranteed to be sorted, so find the span+ // explicitly ('YYYY-MM' strings compare chronologically).+ let firstMonth = monthsToCreate[0];+ let lastMonth = monthsToCreate[0];+ for (const month of monthsToCreate) {+ if (month < firstMonth) {+ firstMonth = month;}- });+ if (month > lastMonth) {+ lastMonth = month;+ }+ }+ sumAmounts = getSumAmountsByMonth(+ monthUtils.bounds(firstMonth).start,+ monthUtils.bounds(lastMonth).end,+ );+ }+ return sumAmounts;+ };+ const seededCells: string[] = [];+ monthsToCreate.forEach(month => {+ const prevMonth = monthUtils.prevMonth(month);+ const { start, end } = monthUtils.bounds(month);+ const sheetName = monthUtils.sheetForMonth(month);+ const prevSheetName = monthUtils.sheetForMonth(prevMonth);+ const dbMonth = parseInt(month.replace('-', ''));++ categories.forEach(cat => {+ // Seed the spend total before creating the dynamic cell so the cell+ // skips its per-category query. Only happens on a cold build, when+ // the value hasn't been restored from cache.+ const sumCell = `sum-amount-${cat.id}`;+ if (sheet.get().getCellValueLoose(sheetName, sumCell) == null) {+ const name = resolveName(sheetName, sumCell);+ sheet+ .get()+ .load(name, getSumAmounts().get(`${dbMonth}-${cat.id}`) || 0);+ seededCells.push(name);+ }+ createCategory(cat, sheetName, prevSheetName, start, end);+ });+ groups.forEach(group => {if (budgetType === 'envelope') {- envelopeBudget.createSummary(- groups,- categories,- prevSheetName,- sheetName,- );+ envelopeBudget.createCategoryGroup(group, sheetName);} else {- trackingBudget.createSummary(groups, sheetName);+ trackingBudget.createCategoryGroup(group, sheetName);}+ });- meta.createdMonths.add(month);+ if (budgetType === 'envelope') {+ envelopeBudget.createSummary(+ groups,+ categories,+ prevSheetName,+ sheetName,+ );+ } else {+ trackingBudget.createSummary(groups, sheetName);}++ meta.createdMonths.add(month);});sheet.get().setMeta(meta);sheet.endTransaction();+ // Persist the seeded spend totals to the cache. Because they were loaded+ // directly (rather than recomputed) they aren't part of the computation+ // queue that normally gets cached, so without this a warm load would have+ // to recompute them. The cells already hold their final values here.+ if (seededCells.length > 0) {+ sheet.get().saveCachedCells(seededCells);+ }+// Wait for the spreadsheet to finish computing. Normally this won't// do anything (as values are cached) but on first run this need to// show the loading screen while it initially sets up.diff --git a/packages/loot-core/src/server/spreadsheet/spreadsheet.ts b/packages/loot-core/src/server/spreadsheet/spreadsheet.tsindex 304daa0c31..e6a9389cea 100644--- a/packages/loot-core/src/server/spreadsheet/spreadsheet.ts+++ b/packages/loot-core/src/server/spreadsheet/spreadsheet.ts@@ -221,9 +221,7 @@ export class Spreadsheet {this.events.emit('change', { names: this.computeQueue });// Cache the updated cells- if (typeof this.saveCache === 'function') {- this.saveCache(this.computeQueue);- }+ this.saveCachedCells(this.computeQueue);this.markCacheSafe();this.running = false;@@ -231,6 +229,12 @@ export class Spreadsheet {}}+ saveCachedCells(names: string[]): void {+ if (typeof this.saveCache === 'function') {+ this.saveCache(names);+ }+ }+markCacheSafe() {if (!this.cacheBarrier) {if (this.setCacheStatus) {diff --git a/upcoming-release-notes/batch-budget-sum-amount-query.md b/upcoming-release-notes/batch-budget-sum-amount-query.mdnew file mode 100644index 0000000000..4896e1e050--- /dev/null+++ b/upcoming-release-notes/batch-budget-sum-amount-query.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [MatissJanis]+---++Improved budget loading speed for long-running budgets with many years of data