Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
186 changes: 186 additions & 0 deletions benchmarks/collection-session.perf.ts
Original file line number Diff line number Diff line change
@@ -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<string, number[]> = {};
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 <T>(name: string, run: () => T | Promise<T>) => {
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,
);
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
76 changes: 76 additions & 0 deletions scripts/bench-first-paint.mjs
Original file line number Diff line number Diff line change
@@ -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();
}
6 changes: 3 additions & 3 deletions src/domain/task-occurrence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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(
Expand Down
21 changes: 21 additions & 0 deletions src/domain/tasknotes-model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
{
Expand Down
Loading
Loading