/** * THE BLIND INDEX ONE WAY (coordinator for the owner, 22 Nov 2026: his search index was 0.55 GB of `blind` and * 0.83 GB of `blind_rid`, 34.6 million tokens). An invented object laid out as his is (rows' tokens in `blind`, with * `blind_rid`, no row holding its own), its searches answered, then the move switched on and run alarm by alarm: * the same searches answer the same before, halfway and after; a row written mid-move and after keeps its tokens * right; `blind_rid` is gone at the end and the file is smaller. Small by default; `BIG_OBJECT=1` lays his 34.6 * million tokens. Invented records only. */ import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; import { BIG } from "./big_object.ts"; import { ADMIN, http, NOTES_OPEN, personalObject } from "./personal.ts"; import * as blind from "../src/blind.ts"; import { Store } from "../src/store.ts"; const SCALE = BIG ? 1 : 1 / 500; const TOKENS = Math.round(34_600_000 * SCALE); const PER_ROW = 120; const ROWS = Math.ceil(TOKENS / PER_ROW); const SPACE = 400_000; // distinct tokens: common words are in many rows const out: string[] = []; type Sql = SqlStorage; const searches = (sql: Sql, asks: string[][]): string[][] => { const store = new Store(sql, () => new Date()); return asks.map((tokens) => store.blindIds("email", tokens, null, 50)); }; describe("the blind index moved one way", () => { it("answers every search the same before, during and after the move, and drops blind_rid", async () => { const slug = "blind-oneway"; await personalObject(slug, { open: NOTES_OPEN.open }); const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug)); // His layout: the index by row, rows holding none of their own. await runInDurableObject(stub, (_i, s) => s.storage.sql.exec("CREATE INDEX IF NOT EXISTS blind_rid ON blind (rid)")); for (let done = 0; done < ROWS; done += 5_000) { const k = Math.min(5_000, ROWS - done); await runInDurableObject(stub, (_i, s) => { const sql = s.storage.sql; sql.exec( `WITH RECURSIVE c(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM c WHERE i < ${k}) INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) SELECT 'email', printf('e%09d', ? + i), json_object('_sealed', 'v1.x'), NULL, 1, 0, strftime('%Y-%m-%dT%H:%M:%fZ', 1700000000 + ? + i, 'unixepoch'), '2025-01-01T00:00:00.000Z' FROM c`, done, done, ); sql.exec(`INSERT INTO blind_row (table_id, id) SELECT 'email', id FROM rows WHERE table_id = 'email' AND id > printf('e%09d', ?) AND id <= printf('e%09d', ?)`, done, done + k); sql.exec( `WITH RECURSIVE t(j) AS (SELECT 1 UNION ALL SELECT j+1 FROM t WHERE j < ${PER_ROW}) INSERT OR IGNORE INTO blind (tok, rid) SELECT (abs(random()) % ${SPACE}) - ${SPACE / 2}, r.rid FROM blind_row r, t WHERE r.table_id = 'email' AND r.id > printf('e%09d', ?) AND r.id <= printf('e%09d', ?)`, done, done + k, ); }); } // Searches of one, two and three of a real row's tokens, and some of tokens nobody holds. const asks = await runInDurableObject(stub, (_i, s) => { const sql = s.storage.sql; const picks: string[][] = []; for (let q = 0; q < 60; q++) { const rid = Number(sql.exec<{ rid: number }>("SELECT rid FROM blind_row ORDER BY random() LIMIT 1").one().rid); const toks = sql.exec<{ tok: string }>("SELECT CAST(tok AS TEXT) AS tok FROM blind WHERE rid = ? ORDER BY random() LIMIT ?", rid, 1 + (q % 3)).toArray().map((r) => r.tok); picks.push(toks); } picks.push(["999999999999"], ["-1", "999999999998"]); return picks; }); const before = await runInDurableObject(stub, (_i, s) => searches(s.storage.sql, asks)); expect(before.filter((ids) => ids.length > 0).length).toBeGreaterThan(55); const fileBefore = await runInDurableObject(stub, (_i, s) => s.storage.sql.databaseSize); const built = await runInDurableObject(stub, (_i, s) => ({ tokens: Number(s.storage.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM blind").one().n), rows: Number(s.storage.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM blind_row").one().n) })); out.push(`built: ${built.rows} rows, ${built.tokens} tokens, file ${(fileBefore / 1e6).toFixed(0)} MB`); // Off until the account says so. await runInDurableObject(stub, async (instance) => (instance as unknown as { alarm(): Promise }).alarm()); expect(await runInDurableObject(stub, (_i, s) => blind.progress(s.storage.sql).left)).toBe(built.rows); expect((await http(slug, "PUT", "/v1/admin/business", { blind_oneway: "on" }, ADMIN)).status).toBe(200); let alarms = 0; let longest = 0; let halfway = false; const t0 = Date.now(); while (await runInDurableObject(stub, (_i, s) => blind.indexed(s.storage.sql))) { const took = await runInDurableObject(stub, async (instance, s) => { await s.storage.deleteAlarm(); const a = Date.now(); await (instance as unknown as { alarm(): Promise }).alarm(); const ms = Date.now() - a; await s.storage.deleteAlarm(); return ms; }); longest = Math.max(longest, took); alarms++; const p = await runInDurableObject(stub, (_i, s) => blind.progress(s.storage.sql)); if (!halfway && p.left > 0 && p.left < built.rows / 2) { halfway = true; // Halfway: the same answers, and a row rewritten now (moved or not) keeps exactly its new tokens. expect(await runInDurableObject(stub, (_i, s) => searches(s.storage.sql, asks))).toEqual(before); await runInDurableObject(stub, (_i, s) => { const store = new Store(s.storage.sql, () => new Date()); for (const id of ["e000000001", `e${String(built.rows).padStart(9, "0")}`]) { const was = store.blindOf("email", id); store.setBlind("email", id, was); expect(store.blindOf("email", id)).toEqual([...was].sort((a, b) => (BigInt(a) < BigInt(b) ? -1 : 1))); } }); } if (alarms > 2_000) break; } expect(halfway || built.rows <= blind.MOVE_ROWS).toBe(true); const after = await runInDurableObject(stub, (_i, s) => searches(s.storage.sql, asks)); expect(after, "every search answers the same").toEqual(before); const end = await runInDurableObject(stub, (_i, s) => { const sql = s.storage.sql; const store = new Store(sql, () => new Date()); // After: a row's tokens replaced, and cleared, along its own list. store.setBlind("email", "e000000002", ["1", "2", "3"]); const replaced = store.blindOf("email", "e000000002"); const found = store.blindIds("email", ["1", "2", "3"], null, 5); store.setBlind("email", "e000000002", []); return { replaced, found, cleared: store.blindOf("email", "e000000002"), progress: blind.progress(sql), file: sql.databaseSize, tokens: Number(sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM blind").one().n) }; }); expect(end.replaced).toEqual(["1", "2", "3"]); expect(end.found).toContain("e000000002"); expect(end.cleared).toEqual([]); expect(end.progress).toEqual({ left: 0, index: false }); out.push(`moved: ${alarms} alarms in ${((Date.now() - t0) / 1000).toFixed(0)} s, the longest ${longest} ms; ${asks.length} searches the same before, halfway and after`); out.push(`after: ${end.tokens} tokens, file ${(end.file / 1e6).toFixed(0)} MB (was ${(fileBefore / 1e6).toFixed(0)} MB)`); if (BIG) throw new Error(`RESULT\n${out.join("\n")}`); expect(end.file).toBeLessThan(fileBefore); }); });