diff --git a/benchmarks/collection-session.perf.ts b/benchmarks/collection-session.perf.ts new file mode 100644 index 00000000..acc16970 --- /dev/null +++ b/benchmarks/collection-session.perf.ts @@ -0,0 +1,186 @@ +import { cpus } from "node:os"; +import { setTimeout as delay } from "node:timers/promises"; +import { expect, it } from "vitest"; +import { + applyBulkEdits, + planTaskChange, +} from "../src/application/bulk-task-edit"; +import { taskOccurrencesBetween } from "../src/domain/task-occurrence"; +import { TaskNotesTaskModel } from "../src/domain/tasknotes-model"; +import { emptyViewDraft } from "../src/domain/view-document"; +import { groupTaskViewRows } from "../src/domain/view-grouping"; +import { tasksForViewDraft } from "../src/domain/view-preview"; +import { + nextTaskFixture, + seedRecord, + taskQueryWhere, +} from "../src/test/next-task-fixture"; + +const fields = ["effort", "client", "team", "area"].map((key) => ({ + id: key, + key, + displayName: key, + type: "text" as const, +})); +const records = Array.from({ length: 10_000 }, (_, i) => ({ + path: `Tasks/T${i}.md`, + types: ["task"], + frontmatter: { + id: `task-${i}`, + type: "task", + title: `Review ${10_000 - i}`, + status: "open", + priority: "normal", + tags: [i % 5 ? "work" : "home"], + projects: [`P${i % 80}`], + scheduled: `2026-10-${String((i % 28) + 1).padStart(2, "0")}`, + ...(i % 4 === 0 + ? { recurrence: i % 8 ? "FREQ=WEEKLY" : "FREQ=DAILY" } + : {}), + Effort: "medium", + client: "A", + team: "B", + area: "C", + dateCreated: "2026-10-01T10:00:00Z", + dateModified: "2026-10-17T11:00:00Z", + }, + body: "Task detail. ".repeat(80), +})); + +// Opt in separately from the ordinary collections benchmark. +it.runIf(process.env.TASKNOTES_BENCH_SESSION === "1")( + "profiles a 10k collection session", + async () => { + const samples: Record = {}; + for (let round = 0; round < 5; round++) { + const fixture = await nextTaskFixture( + { where: taskQueryWhere, confirmDelayMs: null }, + false, + { userFields: fields }, + ); + const { repository, replica, client } = fixture; + try { + records.forEach((record) => seedRecord(replica, record)); + const model = new TaskNotesTaskModel({ userFields: fields }); + for (const mode of ["cold", "warm"] as const) { + const time = async (name: string, run: () => T | Promise) => { + const start = performance.now(); + const value = await run(); + (samples[`${name}.${mode}`] ??= []).push(performance.now() - start); + return value; + }; + const tasks = await time("decode", () => + records.map((record) => model.readSummary(record)), + ); + expect(tasks[0]?.customProperties.effort).toBe("medium"); + const count = await time("index", async () => { + if (mode === "cold") await repository.initialize(); + return (await repository.stats()).total; + }); + expect(count).toBe(10_000); + const matches = await time("filterSort", () => + tasksForViewDraft( + { + ...emptyViewDraft("obsidian-bases"), + filter: 'note.tags.contains("work")', + sort: [{ property: "title", direction: "asc" }], + }, + tasks, + )!, + ); + expect(matches).toHaveLength(8000); + const rows = matches.map((task) => ({ + task, + values: { project: task.projects[0] }, + })); + const groups = Array.from( + new Set(rows.map((row) => row.values.project)), + (project) => ({ + values: { project }, + count: 125, + summaries: {}, + }), + ); + const grouped = await time("group", () => + groupTaskViewRows({ groups, rows }), + ); + expect(grouped.every((group) => group.rows.length === 125)).toBe( + true, + ); + const end = `2026-11-${20 + round}`; + const occurrences = await time("recurrence", () => + tasks.reduce( + (n, t) => n + taskOccurrencesBetween(t, "2026-11-01", end).length, + 0, + ), + ); + expect(occurrences).toBeGreaterThan(20_000); + const selection = await Promise.all( + tasks.slice(0, 32).map((t) => repository.getSummary(t.id)), + ); + const change = { + kind: "tag" as const, + value: "reviewed", + remove: mode === "warm", + }; + const edits = await time("bulkCapture32", () => + applyBulkEdits( + selection.map((t) => t!), + (task) => planTaskChange(task, change), + { + getSummary: (id) => repository.getSummary(id), + updateTask: (id, input) => repository.update(id, input), + setTaskArchived: (id, v) => repository.setArchived(id, v), + }, + "Task changed", + ), + ); + expect(edits.failures).toEqual([]); + expect(edits.receipts).toHaveLength(32); + expect(await client.pendingWrites()).toHaveLength(32); + const pending = await time("pendingTitles32", () => + repository.unconfirmedTaskTitles(), + ); + expect(pending).toHaveLength(32); + await time("ack32", async () => { + replica.confirmAll(); + const deadline = performance.now() + 10_000; + while ( + repository.unconfirmedTaskTitles() !== undefined || + client.ledger.getSnapshot().saveState !== "saved" + ) { + if (performance.now() > deadline) + throw Error("Pending acknowledgements did not drain"); + await delay(1); + } + }); + expect( + (await repository.getSummary("task-31"))?.tags.includes("reviewed"), + ).toBe(!change.remove); + // Let collection-wide readers receive the trailing change notification + // before the next round times an already hydrated index. + await repository.stats(); + } + } finally { + fixture.close(); + } + } + const metrics = Object.fromEntries( + Object.entries(samples).map(([key, values]) => { + const sorted = [...values].sort((a, b) => a - b); + return [ + key, + { + median: +sorted[2]!.toFixed(2), + p95: +sorted[4]!.toFixed(2), + samples: values.map((v) => +v.toFixed(2)), + }, + ]; + }), + ); + console.log( + JSON.stringify({ node: process.version, cpu: cpus()[0]?.model, metrics }), + ); + }, + 300_000, +); diff --git a/package.json b/package.json index 9b2b2163..924d66b6 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,8 @@ "format:check": "prettier --check .", "cap:sync": "pnpm build && cap sync", "android": "pnpm cap:sync && cap run android", - "store:screenshots": "node scripts/store-screenshots.mjs" + "store:screenshots": "node scripts/store-screenshots.mjs", + "bench:collection-session": "tsc -p benchmarks/tsconfig.json && TASKNOTES_BENCH_SESSION=1 vitest run --config benchmarks/vitest.config.ts benchmarks/collection-session.perf.ts" }, "dependencies": { "@capacitor-community/in-app-review": "8.0.0", diff --git a/scripts/bench-first-paint.mjs b/scripts/bench-first-paint.mjs new file mode 100644 index 00000000..9ce5e6f3 --- /dev/null +++ b/scripts/bench-first-paint.mjs @@ -0,0 +1,76 @@ +/* global window, requestAnimationFrame */ +// First usable task row in the local SDK protocol fixture. +import { chromium } from "@playwright/test"; +import assert from "node:assert/strict"; + +const origins = ( + process.argv.length > 2 ? process.argv.slice(2) : ["http://127.0.0.1:4173"] +).map((url) => new URL(url)); +for (const origin of origins) + assert.ok(["localhost", "127.0.0.1"].includes(origin.hostname)); +const browser = await chromium.launch(); +const results = Object.fromEntries( + origins.map(({ origin }) => [origin, { cold: [], warm: [] }]), +); + +async function openCollection(origin) { + const samples = results[origin.origin]; + const context = await browser.newContext({ + timezoneId: "UTC", + serviceWorkers: "block", + viewport: { width: 1280, height: 800 }, + }); + const page = await context.newPage(); + page.setDefaultTimeout(60_000); + await page.addInitScript(() => { + window.__TASKNOTES_NEXT_SMOKE__ = { + records: Array.from({ length: 10_000 }, (_, index) => ({ + path: `Tasks/T${index}.md`, + frontmatter: { + type: "task", + id: `task-${index}`, + title: `Task ${index}`, + tags: ["task"], + status: "open", + projects: [`P${index % 80}`], + scheduled: "2026-11-04", + }, + body: "Task detail. ".repeat(80), + })), + }; + }); + for (const mode of ["cold", "warm"]) { + await page.goto(origin.href); + const open = page.getByRole("button", { + name: "Open synced fixture collection", + }); + await open.waitFor(); + // Include seeding, SDK open, React commit and a paint opportunity. + await open.evaluate((button) => { + performance.mark("fixture-open"); + button.click(); + }); + await page.locator(".task-row-title").first().waitFor(); + samples[mode].push( + await page.evaluate(async () => { + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(resolve)), + ); + return Math.round( + performance.measure("first task", "fixture-open").duration, + ); + }), + ); + } + await context.close(); +} +try { + for (let round = 0; round < 5; round++) { + for (const origin of round % 2 ? [...origins].reverse() : origins) + await openCollection(origin); + console.log(JSON.stringify({ round, results })); + } + console.log(JSON.stringify({ chromium: browser.version(), results })); +} finally { + await browser.close(); +} diff --git a/src/domain/task-occurrence.ts b/src/domain/task-occurrence.ts index 1800b3d8..d7d9aa1c 100644 --- a/src/domain/task-occurrence.ts +++ b/src/domain/task-occurrence.ts @@ -77,9 +77,6 @@ function recurringDatesBetween( start: string, end: string, ): readonly string[] { - const startDate = utcStorageDate(start); - const endDate = utcStorageDate(end); - if (!startDate || !endDate || startDate > endDate) return []; const key = JSON.stringify([ task.recurrence, normalizeTaskDateTime(task.scheduled ?? task.createdAt, task.timezone), @@ -92,6 +89,9 @@ function recurringDatesBetween( recurrenceDateCache.set(key, cached); return cached; } + const startDate = utcStorageDate(start); + const endDate = utcStorageDate(end); + if (!startDate || !endDate || startDate > endDate) return []; startDate.setUTCDate(startDate.getUTCDate() - 1); endDate.setUTCDate(endDate.getUTCDate() + 1); const dates = generateRecurringInstances( diff --git a/src/domain/tasknotes-model.test.ts b/src/domain/tasknotes-model.test.ts index 6c185952..1a48b926 100644 --- a/src/domain/tasknotes-model.test.ts +++ b/src/domain/tasknotes-model.test.ts @@ -32,6 +32,27 @@ describe("TaskNotes task model app boundary", () => { ], }); + it("preserves custom field alias precedence and removes legacy spellings only on write", () => { + const frontmatter = { + title: "Legacy", + status: "todo", + Energy: 1, + ENERGY: 3, + Client: "Legacy", + client: "Canonical", + }; + const input = { path: "tasks/legacy.md", body: "", frontmatter }; + expect(model.readSummary(input).customProperties).toMatchObject({ + energy: 1, + client: "Canonical", + }); + const saved = model.update(model.read(input), { title: "Edited" }); + expect(saved.frontmatter).toMatchObject({ energy: 1, client: "Canonical" }); + for (const alias of ["Energy", "ENERGY", "Client"]) + expect(saved.frontmatter).not.toHaveProperty(alias); + expect(frontmatter.Energy).toBe(1); + }); + it("merges an editor property change or clear into the latest record", () => { const peer = model.create( { diff --git a/src/domain/tasknotes-model.ts b/src/domain/tasknotes-model.ts index 34e6cc49..32a3924a 100644 --- a/src/domain/tasknotes-model.ts +++ b/src/domain/tasknotes-model.ts @@ -148,6 +148,8 @@ export interface MaterializedOccurrenceTransition { export class TaskNotesTaskModel { readonly config: TaskCollectionConfiguration; + private readonly fieldAliases: { canonical: string; aliases: string[] }[]; + private readonly customFieldAliases: { key: string; lower: string }[]; private readonly recordsFolder: string; private readonly pathPattern?: string; @@ -175,6 +177,21 @@ export class TaskNotesTaskModel { linkWriteFormat: config.linkWriteFormat ?? "wikilink", timezone: config.timezone, }; + const mapping = this.config.fieldMapping; + this.fieldAliases = Object.entries(READ_ALIASES).flatMap( + ([role, aliases]) => { + const canonical = mapping[role as keyof typeof mapping]; + return canonical ? [{ canonical, aliases }] : []; + }, + ); + const reserved = new Set( + [...Object.values(mapping), "id", "tags", "type", "types"].map((name) => + name.toLocaleLowerCase(), + ), + ); + this.customFieldAliases = this.config.userFields + .map(({ key }) => ({ key, lower: key.toLocaleLowerCase() })) + .filter(({ lower }) => !reserved.has(lower)); this.recordsFolder = options.recordsFolder ?? "tasks"; this.pathPattern = options.pathPattern; } @@ -1070,12 +1087,7 @@ export class TaskNotesTaskModel { removeAliases: boolean, ): Record { const result = { ...source }; - for (const [role, aliases] of Object.entries(READ_ALIASES) as [ - keyof TaskNotesModelConfig["fieldMapping"], - string[], - ][]) { - const canonical = this.config.fieldMapping[role]; - if (!canonical) continue; + for (const { canonical, aliases } of this.fieldAliases) { if (!Object.prototype.hasOwnProperty.call(result, canonical)) { const alias = aliases.find((candidate) => Object.prototype.hasOwnProperty.call(result, candidate), @@ -1087,27 +1099,17 @@ export class TaskNotesTaskModel { if (alias !== canonical) delete result[alias]; } } - if (this.config.userFields.length) { - const reserved = new Set( - [ - ...Object.values(this.config.fieldMapping), - "id", - "tags", - "type", - "types", - ].map((name) => name.toLocaleLowerCase()), - ); + if (this.customFieldAliases.length) { const existingKeys = Object.keys(result); - for (const field of this.config.userFields) { - const lower = field.key.toLocaleLowerCase(); - if (reserved.has(lower)) continue; + for (const { key, lower } of this.customFieldAliases) { + if (!removeAliases && Object.hasOwn(result, key)) continue; const matches = existingKeys.filter( (candidate) => - candidate !== field.key && candidate.toLocaleLowerCase() === lower, + candidate !== key && candidate.toLocaleLowerCase() === lower, ); if (!matches.length) continue; - if (!Object.prototype.hasOwnProperty.call(result, field.key)) { - result[field.key] = result[matches[0]!]; + if (!Object.prototype.hasOwnProperty.call(result, key)) { + result[key] = result[matches[0]!]; } if (removeAliases) { for (const alias of matches) delete result[alias]; diff --git a/src/domain/view-grouping.ts b/src/domain/view-grouping.ts index 4328f806..6979d37f 100644 --- a/src/domain/view-grouping.ts +++ b/src/domain/view-grouping.ts @@ -25,9 +25,10 @@ export function groupTaskViewRows( lookup = { fields, indices: new Map() }; byFields.set(signature, lookup); } - const key = JSON.stringify( - fields.map((field) => valueKey(group.values[field])), - ); + const key = + fields.length === 1 + ? valueKey(group.values[fields[0]!]) + : JSON.stringify(fields.map((field) => valueKey(group.values[field]))); if (!lookup.indices.has(key)) lookup.indices.set(key, groups.length); groups.push({ key: `${sourceIndex}:${valueKey(group.values)}`, @@ -43,9 +44,12 @@ export function groupTaskViewRows( execution.rows.forEach((row, rowIndex) => { let first = assigned.get(row.task.id)?.groupIndex ?? Infinity; for (const { fields, indices } of byFields.values()) { - const key = JSON.stringify( - fields.map((field) => valueKey(rowGroupValue(row, field))), - ); + const key = + fields.length === 1 + ? valueKey(rowGroupValue(row, fields[0]!)) + : JSON.stringify( + fields.map((field) => valueKey(rowGroupValue(row, field))), + ); const groupIndex = indices.get(key); if (groupIndex === undefined || groupIndex >= first) continue; first = groupIndex; diff --git a/src/storage/next-change-feed-index.test.ts b/src/storage/next-change-feed-index.test.ts index 366b9987..cad91925 100644 --- a/src/storage/next-change-feed-index.test.ts +++ b/src/storage/next-change-feed-index.test.ts @@ -11,6 +11,7 @@ import { seedTaskView, taskQueryWhere, } from "../test/next-task-fixture"; +import { CollectionChangeWindow } from "./collection-change-window"; import { deferred } from "../test/deferred"; import { rememberTaskEdit } from "../app/task-edit-undo"; import { takeUndo } from "../app/undo-history"; @@ -693,6 +694,25 @@ it("does not archive with settings retired during the task read", async () => { ).toMatch(/^New\//); }); +it("reads the latest task and captures edits while a UI notification is pending", async () => { + const f = await fixture(false, true); + await f.repository.initialize(); + f.replica.editElsewhere(f.id, { frontmatter: { title: "Peer edit" } }); + f.push([f.change]); + const quiet = vi.spyOn(CollectionChangeWindow.prototype, "quiet"); + const id = String(f.record.frontmatter.id); + expect(await f.repository.getSummary(id)).toMatchObject({ + title: "Peer edit", + }); + expect(await f.repository.update(id, { priority: "high" })).toMatchObject({ + title: "Peer edit", + priority: "high", + }); + expect(quiet).not.toHaveBeenCalled(); + expect(await f.client.pendingWrites()).toHaveLength(1); + f.replica.confirmAll(); +}); + it("allows a prepared task edit across a refresh that verifies the same model", async () => { const f = await fixture(); await f.repository.initialize(); diff --git a/src/storage/next-repository.ts b/src/storage/next-repository.ts index 4522d086..c80a13a8 100644 --- a/src/storage/next-repository.ts +++ b/src/storage/next-repository.ts @@ -914,15 +914,18 @@ export class NextTaskRepository implements TaskRepository { signal: AbortSignal, fence: "modelGeneration" | "viewGeneration" | "dataRevision", read: () => Promise, - waitForQuiet = true, + pacing: "quiet" | "notification" | "on-conflict" = "quiet", ): Promise { // A lifetime-owned READ has no overall deadline, so refusals that no // local change explains are bounded here as they were by the deadline. let unexplainedSince: number | null = null; + // Exact reads keep every generation and record check. Only a retired read + // needs to wait for coalescing before trying again. + let coalesce = pacing !== "on-conflict"; for (;;) { signal.throwIfAborted(); - if (this.changeWindow.unsettled) - await this.changeWindow.quiet(signal, waitForQuiet); + if (coalesce && this.changeWindow.unsettled) + await this.changeWindow.quiet(signal, pacing !== "notification"); const generation = this[fence]; try { const result = await read(); @@ -940,6 +943,7 @@ export class NextTaskRepository implements TaskRepository { reason.reason !== "view_discovery_stale") ) throw reason; + coalesce = true; // A currentness refusal is a retired READ, not a failed collection. // When a local change event retired it, the new generation already // exists: reread at once (a coalesced native change still waits for @@ -1036,21 +1040,26 @@ export class NextTaskRepository implements TaskRepository { * the repository lifetime and each page keeps its own foreground deadline: * on a relayed collection one deadline over the whole pass refused every * caller once the collection was large enough or the link slow (#512). */ - private async ensureIndex(): Promise { + private async ensureIndex( + pacing: "notification" | "on-conflict" = "notification", + ): Promise { const signal = this.lifetimeSignal(); await this.readCurrentGeneration( signal, "modelGeneration", () => this.loadIndex(signal), - false, + pacing, ); } /** The task model alone: a fixed number of requests, one deadline. */ private async ensureModel(): Promise { const signal = this.lifetimeSignal(); - await this.readCurrentGeneration(signal, "modelGeneration", () => - this.initializeModel(this.requestSignal(signal)), + await this.readCurrentGeneration( + signal, + "modelGeneration", + () => this.initializeModel(this.requestSignal(signal)), + "on-conflict", ); } @@ -1059,6 +1068,7 @@ export class NextTaskRepository implements TaskRepository { signal, "modelGeneration", () => this.initializeModel(signal), + "on-conflict", ); return () => { if (this.modelGeneration !== generation) throw collectionChanged(); @@ -2662,7 +2672,7 @@ export class NextTaskRepository implements TaskRepository { async getSummary(id: string): Promise { const owner = this.lifetimeSignal(); - await this.ensureIndex(); + await this.ensureIndex("on-conflict"); const signal = this.requestSignal(owner); signal.throwIfAborted(); const entry = this.cache.get(id);