Files
RuneStone/tests/unit/features/pm/scan-performance.spec.ts
2026-11-16 04:21:21 -07:00

196 lines
7.2 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import { setTimeout as delay } from "node:timers/promises";
import { TaskStore } from "../../../../src/lib/features/pm/model/store.ts";
import { cardPath } from "../../../../src/lib/features/pm/storage/cards.ts";
import { newTask, editTask } from "../../../../src/lib/features/pm/storage/notes.ts";
import { newBoardSource, parseBoard } from "../../../../src/lib/features/pm/storage/board.ts";
import { cardsMarker, privateRulesPath } from "../../../../src/lib/features/pm/storage/persistence.ts";
import { mapConcurrent, scanConcurrency } from "../../../../src/lib/features/pm/storage/scan.ts";
import type { Workspace } from "../../../../src/lib/features/pm/model/model.ts";
test("native discovery avoids directory bridge calls and retains save conflicts", async () => {
const boardSource = newBoardSource();
const boardId = parseBoard(boardSource).id;
const id = crypto.randomUUID();
const taskPath = cardPath(id);
const original = newTask(id, {
title: "Latency card", status: "todo", tags: [], sessions: [], archived: false,
placements: { [boardId]: { listId: "todo" } },
}, "Original details", id).source;
const files = new Map([["Board.md", boardSource], [taskPath, original], [cardsMarker, "*\n"], [privateRulesPath, "*\n"]]);
let scans = 0, lists = 0, writes = 0;
let scanFailure = false;
const workspace: Workspace = {
async listMarkdown() {
scans++;
if (scanFailure) throw new Error("Directory unavailable");
return [...files.keys()].filter(path => !path.startsWith(".") && path.endsWith(".md"));
},
async list(path) {
lists++;
assert.equal(path, ".runestone/pm/cards", "Visible folders must use the native listing");
return [{ name: taskPath.split("/").at(-1)!, rel_path: taskPath, kind: "file" }];
},
async read(path) { const value = files.get(path); assert.notEqual(value, undefined); return value!; },
async readOptional(path) { return files.get(path) ?? null; },
async create() { throw new Error("Unexpected create"); },
async write(path, source, expected) { assert.equal(files.get(path), expected); writes++; files.set(path, source); },
};
const store = new TaskStore(workspace, { id: boardId, path: "Board.md" });
await store.reload();
await store.moveTask(store.tasks[0], "doing");
await store.save(store.tasks[0], { body: "Updated details" });
assert.equal(scans, 3);
assert.equal(lists, 3);
assert.equal(writes, 2);
const stale = store.tasks[0];
const external = editTask(stale, { body: "External details" });
files.set(taskPath, external);
await assert.rejects(store.save(stale, { body: "Stale details" }), /changed/);
const current = store.tasks[0];
files.set("Copy.md", current.source);
await assert.rejects(store.moveTask(current, "done"), /duplicate/);
files.delete("Copy.md");
await store.reload();
scanFailure = true;
await assert.rejects(store.save(store.tasks[0], { body: "Blocked details" }), /Directory unavailable/);
assert.equal(files.get(taskPath), external);
assert.equal(writes, 2);
});
test("load, move, and detail saves overlap bounded reads without weakening conflict checks", async (t) => {
const source = newBoardSource();
const boardId = parseBoard(source).id;
const files = new Map([
["Board.md", source],
[cardsMarker, "*\n"],
[privateRulesPath, "*\n"],
]);
for (let index = 0; index < 32; index++) {
files.set(`Notes${index % 4}/Note${index}.md`, "An ordinary note.");
const id = crypto.randomUUID();
files.set(
cardPath(id),
newTask(
id,
{
title: `Card ${index}`,
status: "todo",
tags: [],
sessions: [],
archived: false,
placements: { [boardId]: { listId: "todo" } },
},
"Original details",
id,
).source,
);
}
let active = 0,
peak = 0,
reads = 0;
const readDelay = 15;
const workspace: Workspace = {
async list(parent = "") {
const entries = new Map();
const prefix = parent ? `${parent}/` : "";
for (const path of files.keys()) {
if (!path.startsWith(prefix)) continue;
const parts = path.slice(prefix.length).split("/");
entries.set(parts[0], {
name: parts[0],
rel_path: prefix + parts[0],
kind: parts.length > 1 ? "folder" : "file",
});
}
return [...entries.values()];
},
async read(path) {
reads++;
peak = Math.max(peak, ++active);
try {
await delay(readDelay);
const value = files.get(path);
if (value === undefined) throw new Error("Missing note");
return value;
} finally {
active--;
}
},
async readOptional(path) {
return files.get(path) ?? null;
},
async write(path, source, expected) {
assert.equal(files.get(path), expected);
files.set(path, source);
},
async create(path, source) {
assert.equal(files.has(path), false);
files.set(path, source);
},
};
const store = new TaskStore(workspace, { id: boardId, path: "Board.md" });
for (const [name, action] of [
["load", () => store.reload()],
["move", () => store.moveTask(store.tasks[0], "doing")],
["edit", () => store.save(store.tasks[0], { body: "Updated details" })],
] as const) {
peak = reads = 0;
const started = performance.now();
await action();
const elapsed = performance.now() - started;
assert.equal(reads, 65);
assert.equal(peak, scanConcurrency);
assert.equal(active, 0);
// The serial delay alone is 975 ms. Keep generous headroom for busy runners.
assert.ok(elapsed < reads * readDelay * 0.75, `${name} took ${elapsed} ms`);
t.diagnostic(
`${name}: ${reads} reads, peak ${peak}, ${Math.round(elapsed)} ms (serial delay ${reads * readDelay} ms)`,
);
}
assert.equal(store.tasks[0].body, "Updated details");
assert.equal(store.tasks[0].status, "doing");
const cached = store.tasks[1];
await store.reload();
assert.equal(
store.tasks.find((task) => task.id === cached.id),
cached,
);
const stale = store.tasks[0];
const external = editTask(stale, { body: "External details" });
files.set(stale.path, external);
await assert.rejects(store.save(stale, { body: "Stale details" }), /changed/);
assert.equal(files.get(stale.path), external);
const current = store.tasks.find((task) => task.id === stale.id)!;
files.set("Notes0/Copied card.md", current.source);
await assert.rejects(store.moveTask(current, "done"), /duplicate/);
assert.equal(files.get(current.path), external);
});
test("parallel scanning retains input order and drains pending work on failure", async () => {
let active = 0;
await assert.rejects(
mapConcurrent([0, 1, 2, 3], async (value) => {
active++;
try {
await delay(value === 0 ? 1 : 20);
if (value === 0) throw new Error("Directory unavailable");
return value;
} finally {
active--;
}
}),
/Directory unavailable/,
);
assert.equal(active, 0);
assert.deepEqual(
await mapConcurrent([0, 1, 2, 3], async (value) => {
await delay(4 - value);
return value;
}),
[0, 1, 2, 3],
);
});