feat(dict): stable lemma ids — a card names its word, not a build position

Cards point at lemmas by id, and an id was the entry's position in the
sorted build. One word added near the top of the dictionary would have
moved every card below it onto a different word — silently, because loaded
bands were recorded by number and a rebuilt dictionary never reached an
existing install anyway. A custom word took max(id)+1 on whichever device
added it, so the same id meant different words on a phone and a laptop.

An id is now lemmaId(headword, pos), a 53-bit hash defined once in
shared/ and used by the build, the loader, custom words and the migration.
The build asserts all 30,520 entries are collision-free, and a test pins the
function itself, since changing it re-keys every card.

Band files are format 2: they carry no ids at all. The loader derives each
id from the word, and a surface names its lemma by row index in the same
file. Writing hashed ids out cost 0.5 MB of incompressible digits; leaving
them out makes the files smaller than before (1.1 MB -> 1.0 MB).

The loaded dictionary is now versioned by its band hashes, so a rebuild
reloads on the next boot — safe only now that a reload cannot move a card.

Migration 6 re-keys an existing install without stamping anything: cards
and their tombstones move through the lemma rows still loaded, custom words
become custom_word rows (the learner's data, which can travel) carrying the
time their card was made, and the dictionary is dropped to reload.

Sync is paused until the protocol that replaces it lands: the server still
holds rows under the old ids, and exchanging them would plant cards that
name no word.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-09-16 19:59:14 +02:00
parent 04a0900a2c
commit f8183d786f
24 changed files with 595 additions and 60 deletions

View File

@@ -23,7 +23,7 @@ import {
import { newCard, grade, GOOD } from "@lib/srs.js";
/** Every table that carries user data, and therefore a write timestamp. */
const SYNCABLE = ["card", "progress", "chat", "meta", "study_log", "peek"] as const;
const SYNCABLE = ["card", "progress", "chat", "meta", "study_log", "peek", "custom_word"] as const;
export function conformanceSuite(name: string, open: () => Promise<Db>): void {
describe(`Db conformance — ${name}`, () => {

62
test/db/lemma-id.test.ts Normal file
View File

@@ -0,0 +1,62 @@
/* A lemma's id is a hash of the word, not its position in the build.
Cards point at lemmas by id. When ids were positions, adding one entry near
the top of the dictionary moved every card below it onto a different word,
and a custom word's id meant different words on different devices. */
import { describe, it, expect } from "vitest";
import { readFileSync } from "node:fs";
import { gunzipSync } from "node:zlib";
import { lemmaId } from "@shared/lemma-id.mjs";
describe("lemmaId", () => {
/* PINNED. Changing the hash re-keys every card on every device; if this
test has to change, a migration has to move the cards with it. */
it("is exactly this function", () => {
expect(lemmaId("밥", "noun")).toBe(55855054575946);
expect(lemmaId("가다", "verb")).toBe(1434356355562999);
});
it("depends on the part of speech as well as the headword", () => {
expect(lemmaId("밥", "noun")).not.toBe(lemmaId("밥", "verb"));
});
it("is a positive safe integer, which SQLite stores as INTEGER PRIMARY KEY", () => {
for (const [h, p] of [["밥", "noun"], ["", ""], ["신경 쓰다", "verb"], ["x".repeat(500), "noun"]]) {
const id = lemmaId(h!, p!);
expect(Number.isSafeInteger(id)).toBe(true);
expect(id).toBeGreaterThan(0);
}
});
});
describe("the shipped dictionary", () => {
const manifest = JSON.parse(
readFileSync(new URL("../../app/public/dict/manifest.json", import.meta.url), "utf8"),
) as { format: number; totals: { lemmas: number }; bands: { file: string }[] };
it("is format 2 — no ids in the files, derived as they load", () => {
expect(manifest.format).toBe(2);
});
it("gives every (headword, pos) its own id", () => {
const owner = new Map<number, string>();
let n = 0;
for (const band of manifest.bands) {
const data = JSON.parse(
gunzipSync(readFileSync(new URL(`../../app/public/dict/${band.file}`, import.meta.url))).toString("utf8"),
) as { format: number; columns: { lemma: string[] }; lemmas: unknown[][] };
expect(data.format).toBe(2);
const hw = data.columns.lemma.indexOf("headword");
const pos = data.columns.lemma.indexOf("pos");
for (const row of data.lemmas) {
const key = `${row[hw]}/${row[pos]}`;
const id = lemmaId(row[hw] as string, row[pos] as string);
expect(owner.get(id) ?? key, `${key} collides`).toBe(key);
owner.set(id, key);
n++;
}
}
expect(n).toBe(manifest.totals.lemmas);
});
});

View File

@@ -0,0 +1,89 @@
/* Migration 6 — cards move to stable lemma ids.
A database as the previous build left it: positional lemma ids, a custom
word at the old reserved offset, a tombstone naming a card by its old id.
After the migration every reference names the same word under its hashed
id, and nothing has been stamped — the rows are the same rows, renamed. */
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { SqliteWasmDb } from "@app/db/sqlite-wasm-core.js";
import { migrate } from "@app/db/migrate.js";
import { lemmaId } from "@shared/lemma-id.mjs";
import type { Db } from "@app/db/types.js";
let db: Db;
beforeEach(async () => {
db = await SqliteWasmDb.open({ memory: true });
await migrate(db, 5);
await db.exec(`
INSERT INTO lemma (id, headword, pos, gloss_en, unit_band, source) VALUES
(1, '물', 'noun', 'water', 0, 'curated'),
(2, '밥', 'noun', 'rice', 0, 'curated'),
(3, '책', 'noun', 'book', 0, 'curated'),
(10000000, '던전', 'noun', 'dungeon', 0, 'custom');
INSERT INTO surface (form, lemma_id, analysis) VALUES
('밥', 2, 'headword, noun'),
('던전', 10000000, 'headword, custom');
INSERT INTO card (lemma_id, state, interval, due, reps, updated_at) VALUES
(2, 2, 21, 100, 5, 111),
(10000000, 1, 1, 90, 1, 222),
(424242, 1, 1, 90, 1, 250);
INSERT INTO tombstone (tbl, pk, updated_at) VALUES ('card', '3', 333);
INSERT INTO meta (k, v, updated_at) VALUES ('dict.loadedBands', '[0]', 0);
`);
await migrate(db);
});
afterEach(async () => {
await db.close();
});
describe("migration 6", () => {
it("moves each card to its word's stable id, keeping its schedule and stamp", async () => {
const rice = await db.get<{ interval: number; reps: number; updated_at: number }>(
"SELECT interval, reps, updated_at FROM card WHERE lemma_id = ?",
[lemmaId("밥", "noun")],
);
expect(rice).toEqual({ interval: 21, reps: 5, updated_at: 111 });
expect(await db.get("SELECT 1 FROM card WHERE lemma_id = 2")).toBeUndefined();
});
it("leaves a card it cannot name exactly as it was", async () => {
expect(await db.get<{ updated_at: number }>("SELECT updated_at FROM card WHERE lemma_id = 424242")).toEqual({
updated_at: 250,
});
});
it("renames a card's tombstone with it", async () => {
const graves = await db.all<{ pk: string; updated_at: number }>(
"SELECT pk, updated_at FROM tombstone WHERE tbl = 'card'",
);
expect(graves).toEqual([{ pk: String(lemmaId("책", "noun")), updated_at: 333 }]);
});
it("turns a custom lemma into a custom_word, stamped when its card was made", async () => {
expect(await db.all("SELECT headword, pos, gloss, updated_at FROM custom_word")).toEqual([
{ headword: "던전", pos: "noun", gloss: "dungeon", updated_at: 222 },
]);
const id = lemmaId("던전", "noun");
expect(await db.get("SELECT headword, source FROM lemma WHERE id = ?", [id])).toEqual({
headword: "던전",
source: "custom",
});
expect(await db.get("SELECT form FROM surface WHERE lemma_id = ?", [id])).toEqual({ form: "던전" });
expect(await db.get<{ updated_at: number }>("SELECT updated_at FROM card WHERE lemma_id = ?", [id])).toEqual({
updated_at: 222,
});
});
it("drops the shipped dictionary, so the bands reload under the new ids", async () => {
expect(await db.all("SELECT headword FROM lemma WHERE source <> 'custom'")).toEqual([]);
expect(await db.get("SELECT v FROM meta WHERE k = 'dict.loadedBands'")).toBeUndefined();
});
it("stamps nothing", async () => {
for (const tbl of ["card", "custom_word", "tombstone", "meta"]) {
const row = await db.get<{ top: number | null }>(`SELECT max(updated_at) AS top FROM ${tbl}`);
expect(row?.top ?? 0, tbl).toBeLessThanOrEqual(333);
}
});
});