Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

39.7 KB
Raw Blame
// Loaded the way the packaged app loads it: from a tree outside node_modules named by OMB_DUCKDB_DIR.
import { cpSync, existsSync, mkdirSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs";
import { rm } from "node:fs/promises";
import { createRequire } from "node:module";
import { availableParallelism, tmpdir } from "node:os";
import { join } from "node:path";
import { gzipSync } from "node:zlib";
import type { DuckDBConnection } from "@duckdb/node-api";
import { afterAll, describe, expect, it, vi } from "vitest";

import { DATA_LIMITS, DATA_RESULTS_SCHEMA } from "../../shared/data-surface.ts";
import { CLOSE_DRAIN_MS, EXTENSION_INSTALL_TIMEOUT_MS, Lane, closeNames, createDataEngine, dataEngine, drainLanes, duckdbDirectory, instanceSettings, levenshtein, likePattern, loadExtensions, quoteIdentifier, type DataEngineOptions } from "./engine.ts";
import { DataFailure, type BotDatabase, type DataEngine } from "./types.ts";
import { DataSheetStore } from "./sheet.ts";
import { planLoad } from "./tools.ts";

const root = mkdtempSync(join(tmpdir(), "omb-data-engine-"));
const outOfTree = join(root, "duckdb-resources");
const nodeApi = realpathSync(join(process.cwd(), "node_modules", "@duckdb", "node-api"));
const bindings = realpathSync(join(nodeApi, "..", "node-bindings"));
const platform = realpathSync(join(bindings, "..", `node-bindings-${process.platform}-${process.arch}`));
for (const [name, source] of [["node-api", nodeApi], ["node-bindings", bindings], [`node-bindings-${process.platform}-${process.arch}`, platform]]) {
  cpSync(source, join(outOfTree, "node_modules", "@duckdb", name), { recursive: true, dereference: true });
}

const LONG_QUERY = "SELECT count(*) FROM range(100000000) x, range(100000000) y";
const engines: DataEngine[] = [];

function engine(overrides: Partial<DataEngineOptions> = {}): DataEngine {
  const created = createDataEngine({
    botFolder: (botId) => join(root, "bots", botId),
    dataDir: join(root, "data"),
    env: { ...process.env, OMB_DUCKDB_DIR: outOfTree, OMB_RESOURCES_PATH: undefined },
    ...overrides,
  });
  engines.push(created);
  return created;
}

async function failure(promise: Promise<unknown>): Promise<DataFailure> {
  try {
    await promise;
  } catch (error) {
    if (error instanceof DataFailure) return error;
    throw error;
  }
  throw new Error("expected a DataFailure");
}

const bot = { connection: "bot" as const };
const panel = { connection: "panel" as const };

afterAll(async () => {
  // On Windows CI DuckDB's native close blocks the worker thread here; the process exit reclaims the handles.
  if (process.platform === "win32") {
    console.warn("engine.test: leaving the databases to the process on Windows (native close blocks the thread)");
    return;
  }
  // A close gives up on a stuck statement after CLOSE_DRAIN_MS; the hook must outlast that.
  const closing = Promise.all(engines.map((e) => e.closeAll()));
  const gaveUp = new Promise<"gave-up">((resolve) => setTimeout(() => resolve("gave-up"), CLOSE_DRAIN_MS * 2).unref());
  if (await Promise.race([closing.then(() => "closed" as const), gaveUp]) === "gave-up") throw new Error("closeAll did not finish");
  // Windows keeps a just-closed database busy (EPERM on rm); 10 × 100 ms of linear retry stays inside the hook timeout.
  await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
}, CLOSE_DRAIN_MS * 4);

describe("closing", () => {
  it("drains idle lanes at once, and gives up on one that never finishes", async () => {
    const idle = { run: async <T,>(_sql: string, _options: object, work: () => Promise<T>) => work() };
    expect(await drainLanes([idle, idle], 1_000)).toBe(true);
    const stuck = { run: <T,>() => new Promise<T>(() => undefined) };
    const started = Date.now();
    expect(await drainLanes([idle, stuck], 50)).toBe(false);
    expect(Date.now() - started).toBeLessThan(1_000);
  });
});

describe("loading the binding", () => {
  it("prefers OMB_DUCKDB_DIR, then a staged resources tree, then node_modules", () => {
    const staged = join(root, "resources");
    mkdirSync(join(staged, "duckdb"), { recursive: true });
    expect(duckdbDirectory({ OMB_DUCKDB_DIR: "/x", OMB_RESOURCES_PATH: staged })).toBe("/x");
    expect(duckdbDirectory({ OMB_RESOURCES_PATH: staged })).toBe(join(staged, "duckdb"));
    expect(duckdbDirectory({ OMB_RESOURCES_PATH: join(root, "nowhere") })).toBeNull();
    expect(duckdbDirectory({})).toBeNull();
  });

  it("loads from the copied out-of-tree directory", async () => {
    const e = engine();
    expect(e.unavailable()).toBeNull();
    const db = await e.forBot("loader");
    const result = await db.run("SELECT 1 AS one", bot);
    expect(result.rows).toEqual([[1]]);
    const loaded = Object.keys(createRequire(import.meta.url).cache).filter((file) => file.startsWith(realpathSync(outOfTree)));
    expect(loaded.some((file) => file.endsWith("duckdb.node"))).toBe(true);
  });

  it("names the directory and an action when the binding is missing, in one line, without throwing", async () => {
    const missing = join(root, "no-binding-here");
    const e = engine({ env: { ...process.env, OMB_DUCKDB_DIR: missing } });
    const reason = e.unavailable();
    expect(reason).toContain(missing);
    expect(reason).toMatch(/OMB_DUCKDB_DIR/);
    expect(reason).not.toContain("\n");
    const error = await failure(e.forBot("x"));
    expect(error.error.code).toBe("engine_unavailable");
    expect(error.error.message).toBe(reason);
  });

  it("answers a status read from the binding's files, loading nothing, then confirms by loading", async () => {
    const loadedFrom = (dir: string) => Object.keys(createRequire(import.meta.url).cache).filter((file) => file.startsWith(realpathSync(dir)));
    const fresh = join(root, "duckdb-status");
    cpSync(outOfTree, fresh, { recursive: true });
    const changed = vi.fn();
    const e = engine({ env: { ...process.env, OMB_DUCKDB_DIR: fresh }, confirmInstalledMs: 0 });
    e.onInstalledChange(changed);
    expect(e.installed()).toBe(true);
    expect(loadedFrom(fresh)).toEqual([]);
    await vi.waitFor(() => expect(loadedFrom(fresh).some((file) => file.endsWith("duckdb.node"))).toBe(true));
    expect(e.installed()).toBe(true);
    expect(changed).not.toHaveBeenCalled();
    expect(engine({ env: { ...process.env, OMB_DUCKDB_DIR: join(root, "no-binding-here") } }).installed()).toBe(false);
  });

  it("tells its listeners when files that looked right do not load", async () => {
    const broken = join(root, "duckdb-broken");
    cpSync(outOfTree, broken, { recursive: true });
    writeFileSync(join(broken, "node_modules", "@duckdb", `node-bindings-${process.platform}-${process.arch}`, "duckdb.node"), "not a library");
    const changed = vi.fn();
    const e = engine({ env: { ...process.env, OMB_DUCKDB_DIR: broken }, confirmInstalledMs: 0 });
    e.onInstalledChange(changed);
    expect(e.installed()).toBe(true);
    await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(1));
    expect(e.installed()).toBe(false);
    expect(e.unavailable()).toContain(broken);
  });

  it("tells its listeners when a binding whose files were not found loads after all", async () => {
    const changed = vi.fn();
    const e = engine({ confirmInstalledMs: 0, filesFound: () => false });
    e.onInstalledChange(changed);
    expect(e.installed()).toBe(false);
    await vi.waitFor(() => expect(changed).toHaveBeenCalledTimes(1));
    expect(e.installed()).toBe(true);
  });

  it("ships a default engine that loads nothing until asked", () => {
    expect(typeof dataEngine.forBot).toBe("function");
    expect(dataEngine.unavailable()).toBeNull();
  });

  it("refuses a bot id that is not a folder name", async () => {
    const e = engine();
    expect((await failure(e.forBot("../escape"))).error.code).toBe("invalid_input");
    expect((await failure(e.forBot(""))).error.code).toBe("invalid_input");
  });
});

describe("instance settings", () => {
  it("caps memory at a quarter of RAM or 2 GB, threads at four, and keeps extensions per version", () => {
    const settings = instanceSettings("/bots/b", "/data", "v1.5.6", {}, { cpus: 10, memoryBytes: 64 * 1024 ** 3 });
    expect(settings.memory_limit).toBe("2048MiB");
    expect(settings.threads).toBe("4");
    expect(settings.temp_directory).toBe(join("/bots/b", "data-tmp"));
    expect(settings.extension_directory).toBe(join("/data", "duckdb-extensions", "v1.5.6"));
    expect(settings.max_temp_directory_size).toBe("20GB");
    expect(settings.allow_persistent_secrets).toBe("false");
    expect(settings.autoinstall_known_extensions).toBe("false");
    expect(settings.autoload_known_extensions).toBe("true");
    expect(settings.preserve_insertion_order).toBe("false");
    expect(instanceSettings("/b", "/d", "v1", { OMB_DUCKDB_MEMORY_LIMIT: "3GB", OMB_DUCKDB_MAX_TEMP_SIZE: "1GB" })).toMatchObject({ memory_limit: "3GB", max_temp_directory_size: "1GB" });
  });

  it("sizes threads and memory from the container's limits, not the host's", () => {
    const limited = instanceSettings("/b", "/d", "v1", {}, { cpus: 2, memoryBytes: 2 * 1024 ** 3 });
    expect(limited.threads).toBe("2");
    expect(limited.memory_limit).toBe("512MiB");
    expect(instanceSettings("/b", "/d", "v1", {}, { cpus: 0.5, memoryBytes: 512 * 1024 ** 2 })).toMatchObject({ threads: "1", memory_limit: "256MiB" });
  });

  it("applies them to the opened database", async () => {
    const e = engine({ env: { ...process.env, OMB_DUCKDB_DIR: outOfTree, OMB_DUCKDB_MEMORY_LIMIT: "300MiB" } });
    const db = await e.forBot("settings");
    const names = ["memory_limit", "threads", "temp_directory", "extension_directory", "allow_persistent_secrets", "preserve_insertion_order", "autoinstall_known_extensions", "autoload_known_extensions"];
    const result = await db.run(`SELECT ${names.map((name) => `current_setting('${name}')`).join(", ")}`, bot);
    const [memory, threads, temp, extensions, secrets, order, autoinstall, autoload] = result.rows[0];
    expect(memory).toBe("300.0 MiB");
    expect(threads).toBe(String(Math.min(4, availableParallelism())));
    expect(temp).toBe(join(root, "bots", "settings", "data-tmp"));
    expect(String(extensions).startsWith(join(root, "data", "duckdb-extensions"))).toBe(true);
    expect(String(extensions)).toMatch(/v\d+\.\d+\.\d+$/);
    expect([secrets, order, autoinstall, autoload]).toEqual([false, false, false, true]);
    expect(existsSync(join(root, "bots", "settings", "data.duckdb"))).toBe(true);
  });
});

describe("extensions", () => {
  it("installs supported extensions from the official core repository before loading them", async () => {
    const run = vi.fn<DuckDBConnection["run"]>();
    await loadExtensions({ run }, ["httpfs", "excel"]);
    expect(run.mock.calls.map(([sql]) => sql)).toEqual([
      "INSTALL httpfs FROM core", "LOAD httpfs",
      "INSTALL excel FROM core", "LOAD excel",
    ]);
  });

  it("keeps an offline failure actionable and does not proceed to load", async () => {
    const run = vi.fn<DuckDBConnection["run"]>().mockRejectedValue(new Error("Could not connect"));
    const error = await failure(loadExtensions({ run }, ["excel"]));
    expect(error.error).toMatchObject({ code: "sql_error", message: "Could not connect", retryable: true, hint: expect.stringContaining("excel extension") });
    expect(error.error.hint).toContain("http://extensions.duckdb.org");
    expect(run).toHaveBeenCalledTimes(1);
  });

  function fakeBinding(installMs: number) {
    const statements: string[] = [];
    const fake = { statements, installError: null as Error | null, interrupts: 0 };
    const result = (select: boolean) => ({
      statementType: select ? 1 : 0, rowCount: select ? 1 : 0, columnCount: select ? 1 : 0, chunkCount: select ? 1 : 0,
      columnName: () => "one", columnType: () => ({ toString: () => "INTEGER" }),
      getChunk: () => ({ convertRows: (convert: (value: unknown, type: unknown) => unknown) => [[convert(1, { typeId: 0 })]] }),
    });
    const connection = () => {
      let abandon: (() => void) | null = null;
      return {
        async run(sql: string) {
          statements.push(sql);
          if (sql.startsWith("INSTALL")) {
            if (fake.installError) throw fake.installError;
            await new Promise<void>((resolve, reject) => {
              const timer = setTimeout(resolve, installMs);
              abandon = () => { clearTimeout(timer); reject(new Error("INTERRUPT Error: Interrupted!")); };
            });
          }
          return result(sql.startsWith("SELECT"));
        },
        runAndReadAll: async () => ({ getRowsJson: () => [] }),
        interrupt() { fake.interrupts++; abandon?.(); },
        closeSync() {},
      };
    };
    const binding = {
      version: () => "fake",
      DuckDBInstance: { create: async () => ({ connect: async () => connection(), closeSync() {} }) },
      StatementType: { SELECT: 1, EXPLAIN: 2 },
      DuckDBTypeId: { BLOB: 99 },
      JsonDuckDBValueConverter: (value: unknown) => value,
    };
    return Object.assign(fake, { connection, binding: binding as unknown as NonNullable<DataEngineOptions["binding"]> });
  }

  it("installs on its own budget ahead of the statement, so a download outlasting the statement timeout still runs it", async () => {
    const fake = fakeBinding(300);
    const db = await engine({ binding: fake.binding }).forBot("extensions");
    const started = Date.now();
    const seen = await db.run("SELECT 1", { ...bot, timeoutMs: 100, extensions: ["excel"] });
    expect(Date.now() - started).toBeGreaterThanOrEqual(250);
    expect(seen.rows).toEqual([[1]]);
    expect(fake.interrupts).toBe(0);
    expect(fake.statements.slice(1)).toEqual(["INSTALL excel FROM core", "LOAD excel", "SELECT 1"]);
    expect(EXTENSION_INSTALL_TIMEOUT_MS).toBe(5 * 60_000);
    fake.installError = new Error("Could not connect");
    const offline = await failure(db.run("SELECT 1", { ...bot, extensions: ["excel"] }));
    expect(offline.error).toMatchObject({ code: "sql_error", message: "Could not connect", retryable: true });
    expect(offline.error.hint).toContain("http://extensions.duckdb.org");
  });

  it("keeps the extension hint when the install itself is cut off, instead of calling it a slow query", async () => {
    const fake = fakeBinding(300);
    const lane = new Lane(fake.connection() as never);
    const cut = await failure(lane.run("INSTALL excel FROM core", { timeoutMs: 100 }, (conn) => loadExtensions(conn, ["excel"])));
    expect(fake.interrupts).toBe(1);
    expect(cut.error).toMatchObject({ code: "sql_error", message: "INTERRUPT Error: Interrupted!", retryable: true });
    expect(cut.error.hint).toContain("http://extensions.duckdb.org");
    expect(cut.error.hint).not.toContain("Narrow the query");
  });
});

describe("a bot's database", () => {
  const e = engine();
  let db: BotDatabase;
  const ready = (async () => {
    db = await e.forBot("alpha");
    await db.run("CREATE OR REPLACE TABLE sales AS SELECT range AS id, 'n' || range AS name, (range % 7)::DECIMAL(10,2) AS amt, DATE '2024-01-01' + INTERVAL (range) DAY AS day, CASE WHEN range % 4 = 0 THEN NULL ELSE 'v' || (range % 5) END AS v FROM range(100)", bot);
  })();

  it("runs a statement, bounds the rows and keeps the exact count", async () => {
    await ready;
    const all = await db.run("SELECT id FROM sales ORDER BY id", bot);
    expect(all.rowCount).toBe(100);
    expect(all.rows.length).toBe(100);
    expect(all.truncated).toBe(false);
    expect(all.columns).toEqual([{ name: "id", type: "BIGINT" }]);
    expect(typeof all.elapsedMs).toBe("number");
    const some = await db.run("SELECT id FROM sales ORDER BY id", { ...bot, maxRows: 3 });
    expect(some.rows).toEqual([["0"], ["1"], ["2"]]);
    expect(some.rowCount).toBe(100);
    expect(some.truncated).toBe(true);
  });

  it.each([
    { label: "compressed files", names: ["one.csv.gz", "nested/two.csv.gz"] },
    { label: "uppercase extensions", names: ["one.CSV", "nested/two.CSV"] },
    { label: "mixed names", names: ["one.csv", "two.CSV", "nested/three.csv.gz"] },
  ])("loads every discovered CSV in a folder with $label", async ({ names }) => {
    await ready;
    const source = mkdtempSync(join(root, "load-folder-"));
    mkdirSync(join(source, "nested"));
    for (const [index, name] of names.entries()) {
      const csv = `amount\n${index + 1}\n`;
      writeFileSync(join(source, name), name.endsWith(".gz") ? gzipSync(csv) : csv);
    }
    const plans = planLoad({ source, kind: "folder" });
    expect(plans).toHaveLength(1);
    const result = await db.run(`SELECT count(*)::INTEGER, sum(amount)::INTEGER FROM ${plans[0]!.reader}`, bot);
    expect(result.rows).toEqual([[names.length, names.length * (names.length + 1) / 2]]);
  });

  it("returns JSON cells: big numbers and decimals as text, dates as DuckDB prints them, blobs by size, nested values as JSON text", async () => {
    await ready;
    const result = await db.run(`SELECT 1::BIGINT AS big, 1.25::DECIMAL(10,2) AS dec, DATE '2024-01-02' AS d, TIMESTAMP '2024-01-02 03:04:05' AS ts, 'ab'::BLOB AS bl, [1,2] AS l, {'x':1} AS st, INTERVAL 1 DAY AS iv, 1::HUGEINT AS hu, 1.5::DOUBLE AS dbl, true AS bo, NULL::INTEGER AS nul, MAP {'k':1} AS mp, 'x' AS v`, bot);
    expect(result.columns.map((c) => c.type)).toEqual(["BIGINT", "DECIMAL(10,2)", "DATE", "TIMESTAMP", "BLOB", "INTEGER[]", 'STRUCT("x" INTEGER)', "INTERVAL", "HUGEINT", "DOUBLE", "BOOLEAN", "INTEGER", "MAP(VARCHAR, INTEGER)", "VARCHAR"]);
    expect(result.rows[0]).toEqual(["1", "1.25", "2024-01-02", "2024-01-02 03:04:05", "<blob 2 bytes>", "[1,2]", '{"x":1}', '{"months":0,"days":1,"micros":"0"}', "1", 1.5, true, null, '[{"key":"k","value":1}]', "x"]);
  });

  it("materialises a result in the results schema, where the panel's connection sees it", async () => {
    await ready;
    const made = await db.materialise("SELECT id, amt FROM sales WHERE id < 10;", "q1", bot);
    expect(made).toMatchObject({ table: `${DATA_RESULTS_SCHEMA}.q1`, rowCount: 10, columns: [{ name: "id", type: "BIGINT" }, { name: "amt", type: "DECIMAL(10,2)" }] });
    const seen = await db.run(`SELECT count(*) FROM ${DATA_RESULTS_SCHEMA}.q1`, panel);
    expect(seen.rows).toEqual([["10"]]);
    // The reason the schema exists: a temp table is the bot connection's alone.
    await db.run("CREATE TEMP TABLE scratch AS SELECT 1 AS x", bot);
    expect((await failure(db.run("SELECT * FROM scratch", panel))).error.code).toBe("table_not_found");
    expect((await failure(db.materialise("SELECT 1", "bad name", bot))).error.code).toBe("invalid_input");
  });

  it("drops a result, and a missing one is not an error", async () => {
    await ready;
    await db.materialise("SELECT 1 AS one", "gone", bot);
    await db.dropResult("gone");
    await db.dropResult("gone");
    expect((await failure(db.run(`SELECT * FROM ${DATA_RESULTS_SCHEMA}.gone`, bot))).error.code).toBe("table_not_found");
  });

  it("keeps an earlier query result when the sheet reopens before the next query", async () => {
    const database = await engine().forBot("result-names");
    const options = { botId: "result-names", dir: join(root, "bots", "result-names") };
    const first = new DataSheetStore(options).nextResultName();
    await database.materialise("SELECT 11 AS value", first, bot);
    const second = new DataSheetStore(options).nextResultName();
    await database.materialise("SELECT 22 AS value", second, bot);
    expect((await database.run(`SELECT * FROM ${DATA_RESULTS_SCHEMA}.${first}`, panel)).rows).toEqual([[11]]);
    expect((await database.run(`SELECT * FROM ${DATA_RESULTS_SCHEMA}.${second}`, panel)).rows).toEqual([[22]]);
  });

  it("drops a result on the panel's connection without waiting behind the bot's statement", async () => {
    await ready;
    await db.materialise("SELECT 1 AS one", "aside", bot);
    const long = db.run(LONG_QUERY, bot);
    const started = Date.now();
    await db.dropResult("aside", "panel");
    expect(Date.now() - started).toBeLessThan(2_000);
    db.interrupt("bot");
    expect((await failure(long)).error.code).toBe("cancelled");
    expect((await failure(db.run(`SELECT * FROM ${DATA_RESULTS_SCHEMA}.aside`, panel))).error.code).toBe("table_not_found");
  });

  it("pages with a stable order, sorts, and filters by text across every column", async () => {
    await ready;
    const asc = await db.page("sales", { offset: 10, limit: 5, sort: { column: "id", direction: "asc" } });
    expect(asc.rows.map((row) => row[0])).toEqual(["10", "11", "12", "13", "14"]);
    expect(asc).toMatchObject({ rowCount: 100, offset: 10 });
    expect(asc.columns.map((c) => c.name)).toEqual(["id", "name", "amt", "day", "v"]);
    const desc = await db.page("sales", { offset: 0, limit: 2, sort: { column: "ID", direction: "desc" } });
    expect(desc.rows.map((row) => row[0])).toEqual(["99", "98"]);

    const seen = new Set<string>();
    for (let offset = 0; offset < 100; offset += 30) {
      for (const row of (await db.page("sales", { offset, limit: 30 })).rows) seen.add(String(row[0]));
    }
    expect(seen.size).toBe(100);

    const filtered = await db.page("sales", { offset: 0, limit: 50, filter: "N1" });
    expect(filtered.rowCount).toBe(11);
    expect(filtered.rows.every((row) => String(row[1]).toLowerCase().includes("n1"))).toBe(true);
    const literal = await db.page("sales", { offset: 0, limit: 50, filter: "n%" });
    expect(literal.rowCount).toBe(0);
    const injected = await db.page("sales", { offset: 0, limit: 50, filter: "'; DROP TABLE sales; --" });
    expect(injected.rowCount).toBe(0);
    expect((await db.run("SELECT count(*) FROM sales", bot)).rows).toEqual([["100"]]);

    const bad = await failure(db.page("sales", { offset: 0, limit: 5, sort: { column: "nope", direction: "asc" } }));
    expect(bad.error.code).toBe("invalid_input");
  });

  it("filters only the exact selected column before counting, sorting and paging", async () => {
    const database = await e.forBot("column-filter");
    await database.run(`CREATE TABLE entries AS SELECT range AS "order.id", CASE WHEN range % 2 = 0 THEN 'needle' ELSE 'other' END AS "customer ""label""", CASE WHEN range % 2 = 1 THEN 'needle' ELSE 'other' END AS notes FROM range(100)`, bot);
    const query = { offset: 20, limit: 3, filter: "NEEDLE", sort: { column: "order.id", direction: "desc" as const } };
    expect((await database.page("entries", query)).rowCount).toBe(100);
    const scoped = await database.page("entries", { ...query, filterColumn: 'customer "label"' });
    expect(scoped).toMatchObject({ rowCount: 50, offset: 20 });
    expect(scoped.rows.map(row => row[0])).toEqual(["58", "56", "54"]);
    const numeric = await database.page("entries", { offset: 9, limit: 3, filter: "9", filterColumn: "order.id", sort: { column: "order.id", direction: "asc" } });
    expect(numeric.rowCount).toBe(19);
    expect(numeric.rows.map(row => row[0])).toEqual(["90", "91", "92"]);
    expect((await database.page("entries", { ...query, filterColumn: "notes", filter: "" })).rowCount).toBe(100);
    for (const filter of [undefined, "", "needle"]) {
      for (const filterColumn of ["missing", "NOTES", 'notes" OR true --']) {
        expect((await failure(database.page("entries", { offset: 0, limit: 1, filter, filterColumn }))).error.code).toBe("invalid_input");
      }
    }
  });

  it("treats wildcards, backslashes and quotes literally within a selected column", async () => {
    const database = await e.forBot("literal-column-filter");
    await database.run(`CREATE TABLE entries AS SELECT * FROM (VALUES (1, '100%_done\\file''s'), (2, '100xxdone/fileXs'), (3, NULL)) AS t(id, "odd.column")`, bot);
    for (const filter of ["%_", "\\file", "'s"]) {
      expect(await database.page("entries", { offset: 0, limit: 5, filterColumn: "odd.column", filter })).toMatchObject({ rowCount: 1, rows: [[1, "100%_done\\file's"]] });
    }
    expect((await database.page("entries", { offset: 0, limit: 5, filterColumn: "odd.column", filter: "'; DROP TABLE entries; --" })).rowCount).toBe(0);
    expect((await database.page("entries", { offset: 0, limit: 5 })).rowCount).toBe(3);
  });

  it("describes a table or a query: types, null %, approx distinct, min/max as text, three samples", async () => {
    await ready;
    const described = await db.describe("sales", bot);
    expect(described.rowCount).toBe(100);
    const v = described.columns.find((c) => c.name === "v")!;
    expect(v).toMatchObject({ type: "VARCHAR", nullPct: 25, approxUnique: 5, min: "v0", max: "v4" });
    expect(v.sample!.length).toBe(DATA_LIMITS.sampleValues);
    expect(v.sample!.every((s) => /^v[0-4]$/.test(s))).toBe(true);
    const id = described.columns.find((c) => c.name === "id")!;
    expect(id).toMatchObject({ nullPct: 0, min: "0", max: "99" });
    expect(id.approxUnique).toBeGreaterThan(90);
    const day = described.columns.find((c) => c.name === "day")!;
    expect(day.min).toBe("2024-01-01 00:00:00");

    const query = await db.describe("SELECT id FROM sales WHERE id < 10", bot);
    expect(query.rowCount).toBe(10);
    expect(query.columns[0]).toMatchObject({ name: "id", max: "9" });
  });

  it.each(["分析", "report/2026", 'Revenue "USD"', "select from report", " padded "])("describes a quoted table named %j without treating its name as SQL", async (name) => {
    await ready;
    await db.run(`CREATE TABLE ${quoteIdentifier(name)} AS SELECT 17 AS amount`, bot);
    const described = await db.describe(`main . ${quoteIdentifier(name)}`, bot);
    expect(described).toMatchObject({ rowCount: 1, columns: [{ name: "amount", min: "17", max: "17" }] });
  });

  it("still describes an existing unquoted display name with spaces", async () => {
    await ready;
    await db.run('CREATE TABLE "Old display name" AS SELECT 19 AS amount', bot);
    expect(await db.describe("Old display name", bot)).toMatchObject({ rowCount: 1, columns: [{ name: "amount", min: "19" }] });
  });

  it("profiles at most describeColumnsMax columns and lists the rest by type only", async () => {
    await ready;
    const wide = Array.from({ length: DATA_LIMITS.describeColumnsMax + 5 }, (_, i) => `${i} AS c${i}`).join(", ");
    const described = await db.describe(`SELECT ${wide}`, bot);
    expect(described.columns.length).toBe(DATA_LIMITS.describeColumnsMax + 5);
    expect(described.columns[0].nullPct).toBe(0);
    expect(described.columns[DATA_LIMITS.describeColumnsMax - 1].sample).toEqual([String(DATA_LIMITS.describeColumnsMax - 1)]);
    expect(described.columns[DATA_LIMITS.describeColumnsMax]).toEqual({ name: `c${DATA_LIMITS.describeColumnsMax}`, type: "INTEGER" });
  });

  it("caches column stats until a write, including a same-size replacement or update", async () => {
    await ready;
    await db.run("CREATE OR REPLACE TABLE counted AS SELECT range AS n FROM range(10)", bot);
    const first = await db.stats("counted");
    expect(first).toMatchObject({ table: "counted", rowCount: 10 });
    expect(first.columns[0]).toMatchObject({ name: "n", nullPct: 0, min: "0", max: "9" });
    expect(await db.stats("counted")).toBe(first);
    await db.run("INSERT INTO counted VALUES (10)", bot);
    const second = await db.stats("counted");
    expect(second).not.toBe(first);
    expect(second.rowCount).toBe(11);
    expect(second.columns[0].max).toBe("10");
    await db.run("CREATE OR REPLACE TABLE counted AS SELECT (range + 100)::INTEGER AS replacement FROM range(11)", bot);
    const replaced = await db.stats("counted");
    expect(replaced).not.toBe(second);
    expect(replaced.columns[0]).toMatchObject({ name: "replacement", type: "INTEGER", min: "100", max: "110" });
    await db.run("UPDATE counted SET replacement = 9", panel);
    expect((await db.stats("counted")).columns[0]).toMatchObject({ min: "9", max: "9", approxUnique: 1 });
    await db.materialise("SELECT 1 AS before", "cached", bot);
    await db.stats("omb_results.cached");
    await db.materialise("SELECT 2 AS after", "cached", bot);
    expect((await db.stats("omb_results.cached")).columns[0]).toMatchObject({ name: "after", min: "2", max: "2" });
  });

  it("bins numbers and dates into twenty equal widths and counts the top text values", async () => {
    await ready;
    const ids = await db.histogram("sales", "id");
    expect(ids.bins.length).toBe(20);
    expect(ids.bins.every((bin) => bin.count === 5)).toBe(true);
    expect(ids.bins[0].label).toBe("0 – 4.95");
    const days = await db.histogram("sales", "day");
    expect(days.bins.length).toBe(20);
    expect(days.bins[0].label).toBe("2024-01-01 00:00");
    expect(days.bins.reduce((sum, bin) => sum + bin.count, 0)).toBe(100);
    const dates = await db.histogram("sales", "day", { bins: 4 });
    expect(dates.bins.map((bin) => bin.count)).toEqual([25, 25, 25, 25]);
    const text = await db.histogram("sales", "v");
    expect(text.bins.length).toBe(5);
    expect(text.bins[0].count).toBeGreaterThanOrEqual(text.bins[1].count);
    expect(text.bins.reduce((sum, bin) => sum + bin.count, 0)).toBe(75);
    const constant = await db.histogram("SELECT 1", "x").catch((error) => error);
    expect(constant).toBeInstanceOf(DataFailure);
    expect((await failure(db.histogram("sales", "nope"))).error.code).toBe("invalid_input");
  });

  it("lists tables and views with counts and columns, never the results schema", async () => {
    await ready;
    await db.run("CREATE OR REPLACE VIEW big_sales AS SELECT * FROM sales WHERE amt > 3", bot);
    await db.materialise("SELECT 1", "hidden", bot);
    const tables = await db.listTables();
    const names = tables.map((table) => table.name);
    expect(names).toContain("sales");
    expect(names).toContain("big_sales");
    expect(names.some((name) => name.includes(DATA_RESULTS_SCHEMA))).toBe(false);
    const sales = tables.find((table) => table.name === "sales")!;
    expect(sales.rowCount).toBe(100);
    expect(sales.columns.map((c) => c.name)).toEqual(["id", "name", "amt", "day", "v"]);
    expect(sales.columns[2].type).toBe("DECIMAL(10,2)");
    const viewCount = Number((await db.run("SELECT count(*) FROM big_sales", bot)).rows[0][0]);
    expect(tables.find((table) => table.name === "big_sales")!.rowCount).toBe(viewCount);
  });

  it("resolves names case-insensitively, bare or qualified, quoting only what needs it", async () => {
    await ready;
    await db.run('CREATE OR REPLACE TABLE "order" (x INT)', bot);
    await db.run('CREATE OR REPLACE TABLE "My Table" (x INT)', bot);
    expect(await db.resolveTable("SALES")).toBe("main.sales");
    expect(await db.resolveTable("main.sales")).toBe("main.sales");
    expect(await db.resolveTable('"Main"."Sales"')).toBe("main.sales");
    expect(await db.resolveTable("q1")).toBe(`${DATA_RESULTS_SCHEMA}.q1`);
    expect(await db.resolveTable(`${DATA_RESULTS_SCHEMA}.Q1`)).toBe(`${DATA_RESULTS_SCHEMA}.q1`);
    expect(await db.resolveTable("order")).toBe('main."order"');
    expect(await db.resolveTable("my table")).toBe('main."My Table"');
    const missing = await failure(db.resolveTable("salez"));
    expect(missing.error.code).toBe("table_not_found");
    expect(missing.error.candidates).toContain("sales");
    expect(missing.error.candidates!.length).toBeLessThanOrEqual(5);
  });

  it("supplies query-ready table names without changing catalog identities", async () => {
    const names = await engine().forBot("query-names");
    await names.run('CREATE TABLE "order" AS SELECT 1 AS n', bot);
    await names.run('CREATE TABLE "My Table" AS SELECT 2 AS n', bot);
    await names.run('CREATE TABLE "has.dot" AS SELECT 3 AS n', bot);
    await names.run('CREATE SCHEMA "Other Schema"', bot);
    await names.run('CREATE TABLE "Other Schema"."select" AS SELECT 4 AS n', bot);
    const tables = await names.listTables();
    expect(tables.map(({ name, sqlName }) => ({ name, sqlName }))).toEqual([
      { name: "Other Schema.select", sqlName: '"Other Schema"."select"' },
      { name: "My Table", sqlName: '"My Table"' },
      { name: "has.dot", sqlName: '"has.dot"' },
      { name: "order", sqlName: '"order"' },
    ]);
    for (const table of tables) {
      expect((await names.run(`SELECT * FROM ${table.sqlName}`, panel)).rowCount).toBe(1);
    }
  });

  it("maps DuckDB errors to codes without rewording them", async () => {
    await ready;
    const parse = await failure(db.run("SELEC 1", bot));
    expect(parse.error).toMatchObject({ code: "sql_error", sql: "SELEC 1", line: 1 });
    expect(parse.error.message).toContain('syntax error at or near "SELEC"');
    const missing = await failure(db.run("SELECT *\nFROM salez", bot));
    expect(missing.error).toMatchObject({ code: "table_not_found", line: 2 });
    expect(missing.error.message).toContain("Table with name salez does not exist");
    expect(missing.error.candidates).toContain("sales");
    const binder = await failure(db.run("SELECT nope FROM sales", bot));
    expect(binder.error.code).toBe("sql_error");
    expect(binder.error.message).toMatch(/^Binder Error/);
  });
});

describe("cancellation", () => {
  it("maps a timeout to `timeout` (retryable) and leaves the connection usable", async () => {
    const db = await engine().forBot("slow");
    const started = Date.now();
    const error = await failure(db.run(LONG_QUERY, { ...bot, timeoutMs: 150 }));
    expect(Date.now() - started).toBeLessThan(5_000);
    expect(error.error).toMatchObject({ code: "timeout", retryable: true, sql: LONG_QUERY });
    expect(error.error.message).toMatch(/interrupt/i);
    expect(error.error.hint).toContain("150 ms");
    expect((await db.run("SELECT 42", bot)).rows).toEqual([[42]]);
  });

  it("maps an aborted signal to `cancelled`", async () => {
    const db = await engine().forBot("aborted");
    const controller = new AbortController();
    setTimeout(() => controller.abort(), 100);
    const error = await failure(db.run(LONG_QUERY, { ...bot, signal: controller.signal }));
    expect(error.error.code).toBe("cancelled");
    // A slow runner may see the signal before the statement starts, which is cancelled all the same.
    expect(error.error.message).toMatch(/interrupt|cancelled before it ran/i);
    const early = new AbortController();
    early.abort();
    expect((await failure(db.run("SELECT 1", { ...bot, signal: early.signal }))).error.code).toBe("cancelled");
  });

  /** A lane whose statement reaches the connection only on `dispatch()`; an interrupt before that is lost, as DuckDB's is,
   * and one that is never delivered after it lets the statement finish half a second later. */
  function undispatched(signal?: AbortSignal) {
    const seen = { dispatched: false, delivered: 0 };
    let abandon: (() => void) | undefined;
    const lane = new Lane({
      run: () => {
        seen.dispatched = true;
        return new Promise<unknown>((resolve, reject) => {
          const finish = setTimeout(() => resolve("finished without an interrupt"), 500);
          abandon = () => { clearTimeout(finish); reject(new Error("INTERRUPT Error: Interrupted!")); };
        });
      },
      interrupt: () => {
        seen.delivered++;
        abandon?.();
      },
    } as never);
    let parked!: () => void;
    const atWork = new Promise<void>((done) => { parked = done; });
    let dispatch!: () => void;
    const gate = new Promise<void>((done) => { dispatch = done; });
    const running = lane.run("SELECT 1", { signal, timeoutMs: 30_000 }, async (conn) => {
      parked();
      await gate;
      return conn.run("SELECT 1");
    });
    return { seen, lane, atWork, dispatch, running };
  }

  it("cancels a statement whose abort landed before it dispatched", async () => {
    const controller = new AbortController();
    const statement = undispatched(controller.signal);
    await statement.atWork;
    controller.abort();
    statement.dispatch();
    const error = await failure(statement.running);
    expect(statement.seen.dispatched).toBe(true);
    expect(error.error.code).toBe("cancelled");
    expect(statement.seen.delivered).toBeGreaterThan(1);
  });

  it("cancels a statement whose interrupt landed before it dispatched", async () => {
    const statement = undispatched();
    await statement.atWork;
    statement.lane.interrupt();
    statement.dispatch();
    const error = await failure(statement.running);
    expect(statement.seen.dispatched).toBe(true);
    expect(error.error.code).toBe("cancelled");
    expect(statement.seen.delivered).toBeGreaterThan(1);
  });

  it("interrupts one connection while the other keeps working, and queued statements still run", async () => {
    const db = await engine().forBot("two-lanes");
    const long = db.run(LONG_QUERY, panel);
    const queued = db.run("SELECT 7", panel);
    const other = await db.run("SELECT 'bot side'", bot);
    expect(other.rows).toEqual([["bot side"]]);
    db.interrupt("panel");
    expect((await failure(long)).error.code).toBe("cancelled");
    expect((await queued).rows).toEqual([[7]]);
    db.interrupt("bot");
    expect((await db.run("SELECT 8", bot)).rows).toEqual([[8]]);
  });
});

describe("lifecycle", () => {
  it("closes an idle database and reopens it on the next use with its data intact", async () => {
    const e = engine({ idleMs: 250 });
    const db = await e.forBot("idle");
    await db.run("CREATE TABLE kept AS SELECT 1 AS x", bot);
    const inner = db as unknown as { isOpen: boolean };
    expect(inner.isOpen).toBe(true);
    await new Promise((resolve) => setTimeout(resolve, 700));
    expect(inner.isOpen).toBe(false);
    expect((await db.run("SELECT count(*) FROM kept", panel)).rows).toEqual([["1"]]);
    expect(inner.isOpen).toBe(true);
    await db.close();
    expect(inner.isOpen).toBe(false);
    expect((await db.run("SELECT x FROM kept", bot)).rows).toEqual([[1]]);
  });

  it("does not close under a statement that outlives the idle window", async () => {
    const e = engine({ idleMs: 200 });
    const db = await e.forBot("busy");
    const controller = new AbortController();
    const long = db.run(LONG_QUERY, { ...bot, signal: controller.signal });
    await new Promise((resolve) => setTimeout(resolve, 600));
    expect((db as unknown as { isOpen: boolean }).isOpen).toBe(true);
    controller.abort();
    expect((await failure(long)).error.code).toBe("cancelled");
  });

  it("deletes a bot's database, its WAL and its spill directory", async () => {
    const e = engine();
    const db = await e.forBot("doomed");
    await db.run("CREATE TABLE t AS SELECT 1", bot);
    const folder = join(root, "bots", "doomed");
    // Written once the database is closed: Windows refuses to open the WAL while DuckDB holds it.
    await db.close();
    mkdirSync(join(folder, "data-tmp"), { recursive: true });
    writeFileSync(join(folder, "data-tmp", "spill.tmp"), "x");
    writeFileSync(join(folder, "data.duckdb.wal"), "x");
    writeFileSync(join(folder, "SOUL.md"), "keep me");
    await e.deleteBot("doomed");
    expect(existsSync(join(folder, "data.duckdb"))).toBe(false);
    expect(existsSync(join(folder, "data.duckdb.wal"))).toBe(false);
    expect(existsSync(join(folder, "data-tmp"))).toBe(false);
    expect(existsSync(join(folder, "SOUL.md"))).toBe(true);
    const again = await e.forBot("doomed");
    expect((await failure(again.run("SELECT * FROM t", bot))).error.code).toBe("table_not_found");
  });

  it("closeAll closes every open database", async () => {
    const e = engine();
    const a = await e.forBot("ca");
    const b = await e.forBot("cb");
    await Promise.all([a.run("SELECT 1", bot), b.run("SELECT 1", bot)]);
    await e.closeAll();
    expect((a as unknown as { isOpen: boolean }).isOpen).toBe(false);
    expect((b as unknown as { isOpen: boolean }).isOpen).toBe(false);
  });
});

describe("helpers", () => {
  it("escapes LIKE wildcards in a person's filter text", () => {
    expect(likePattern("a%b_c\\d")).toBe("%a\\%b\\_c\\\\d%");
  });

  it("measures edit distance and offers the nearest names first", () => {
    expect(levenshtein("kitten", "sitting")).toBe(3);
    expect(levenshtein("", "abc")).toBe(3);
    expect(closeNames("salez", ["sales", "orders", "sale_items", "zzz"])).toEqual(["sales"]);
    expect(closeNames("sale", ["sales", "orders", "sale_items", "zzz"])).toEqual(["sales", "sale_items"]);
    expect(closeNames("ord", ["orders", "sales", "words"])).toEqual(["orders", "words"]);
    expect(closeNames("x", Array.from({ length: 10 }, (_, i) => `x${i}`)).length).toBe(5);
  });
});