Skip to content

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

fix(data): keep source columns distinct from reduction columns

Afloat7586b70b8564
diff --git a/server/data/chart-compiler.test.ts b/server/data/chart-compiler.test.ts
index c75052e798..d1e15e2ae4 100644
--- a/server/data/chart-compiler.test.ts
+++ b/server/data/chart-compiler.test.ts
@@ -67,9 +67,9 @@ describe("compileChart: reductions per chart type and column class", () => {
spec: { type: "bar", x: "region", y: "amount" },
method: "topN",
sql: [
- 'kept AS ( SELECT CAST("region" AS VARCHAR) AS x FROM src GROUP BY ALL ORDER BY sum("amount") DESC NULLS LAST, x LIMIT 20 )',
- `CASE WHEN CAST("region" AS VARCHAR) IN (SELECT x FROM kept) THEN CAST("region" AS VARCHAR) ELSE (SELECT label FROM other_bucket) END AS x`,
- 'sum("amount") AS y FROM src GROUP BY ALL ORDER BY x',
+ 'kept AS ( SELECT CAST(src."region" AS VARCHAR) AS x FROM src GROUP BY ALL ORDER BY sum(src."amount") DESC NULLS LAST, x LIMIT 20 )',
+ `CASE WHEN CAST(src."region" AS VARCHAR) IN (SELECT x FROM kept) THEN CAST(src."region" AS VARCHAR) ELSE (SELECT label FROM other_bucket) END AS x`,
+ 'sum(src."amount") AS y FROM src GROUP BY ALL ORDER BY x',
],
check: (vl) => {
expect(mark(vl)).toBe("bar");
@@ -82,14 +82,14 @@ describe("compileChart: reductions per chart type and column class", () => {
name: "bar over a boolean folds too, counting rows by default",
spec: { type: "bar", x: "paid" },
method: "topN",
- sql: ['CAST("paid" AS VARCHAR)', "count(*) AS y", "ORDER BY count(*) DESC NULLS LAST, x LIMIT 20"],
+ sql: ['CAST(src."paid" AS VARCHAR)', "count(*) AS y", "ORDER BY count(*) DESC NULLS LAST, x LIMIT 20"],
check: (vl) => expect(enc(vl).y).toMatchObject({ title: "count" }),
},
{
name: "bar with a series groups by colour as well",
spec: { type: "bar", x: "region", y: "amount", color: "channel" },
method: "topN",
- sql: ['CAST("channel" AS VARCHAR) AS color, sum("amount") AS y FROM src GROUP BY ALL'],
+ sql: ['CAST(src."channel" AS VARCHAR) AS color, sum(src."amount") AS y FROM src GROUP BY ALL'],
check: (vl) => {
expect(enc(vl).color).toMatchObject({ field: "color", type: "nominal", title: "channel" });
expect(enc(vl).y.stack).toBeUndefined();
@@ -100,10 +100,10 @@ describe("compileChart: reductions per chart type and column class", () => {
spec: { type: "bar", x: "amount", y: "qty" },
method: "bins",
sql: [
- 'bins_x AS ( SELECT min(CAST("amount" AS DOUBLE)) AS lo, CASE WHEN max(CAST("amount" AS DOUBLE)) = min(CAST("amount" AS DOUBLE)) THEN 1 ELSE (max(CAST("amount" AS DOUBLE)) - min(CAST("amount" AS DOUBLE))) / 30 END AS width FROM src )',
- 'bins_x.lo + least(floor((CAST("amount" AS DOUBLE) - bins_x.lo) / bins_x.width), 29) * bins_x.width AS x',
+ 'bins_x AS ( SELECT min(CAST(src."amount" AS DOUBLE)) AS lo, CASE WHEN max(CAST(src."amount" AS DOUBLE)) = min(CAST(src."amount" AS DOUBLE)) THEN 1 ELSE (max(CAST(src."amount" AS DOUBLE)) - min(CAST(src."amount" AS DOUBLE))) / 30 END AS width FROM src )',
+ 'bins_x.lo + least(floor((CAST(src."amount" AS DOUBLE) - bins_x.lo) / bins_x.width), 29) * bins_x.width AS x',
"+ 1) * bins_x.width AS x2",
- 'sum("qty") AS y FROM src, bins_x GROUP BY ALL ORDER BY x',
+ 'sum(src."qty") AS y FROM src, bins_x GROUP BY ALL ORDER BY x',
],
check: (vl) => {
expect(enc(vl).x).toMatchObject({ field: "x", type: "quantitative", bin: "binned", title: "amount" });
@@ -121,8 +121,8 @@ describe("compileChart: reductions per chart type and column class", () => {
"WHEN span <= 1314900000 AND step < 7689600 THEN INTERVAL 1 MONTH",
"WHEN span <= 3944700000 AND step < 31536000 THEN INTERVAL 3 MONTH ELSE INTERVAL 1 YEAR END AS unit",
'SELECT epoch(max(v) - min(v)) AS span, coalesce(min(gap), 0) AS step',
- 'SELECT v, epoch(v - lag(v) OVER (ORDER BY v)) AS gap FROM (SELECT DISTINCT CAST("ts" AS TIMESTAMP) AS v FROM src WHERE "ts" IS NOT NULL)',
- 'time_bucket(span_x.unit, "ts") AS x, time_bucket(span_x.unit, "ts") + span_x.unit AS x2, count(*) AS y FROM src, span_x GROUP BY ALL',
+ 'SELECT v, epoch(v - lag(v) OVER (ORDER BY v)) AS gap FROM (SELECT DISTINCT CAST(src."ts" AS TIMESTAMP) AS v FROM src WHERE src."ts" IS NOT NULL)',
+ 'time_bucket(span_x.unit, src."ts") AS x, time_bucket(span_x.unit, src."ts") + span_x.unit AS x2, count(*) AS y FROM src, span_x GROUP BY ALL',
],
check: (vl) => {
expect(enc(vl).x).toMatchObject({ field: "x", type: "temporal", title: "ts", axis: { formatType: "time" } });
@@ -142,7 +142,7 @@ describe("compileChart: reductions per chart type and column class", () => {
name: "a named timeUnit is a literal interval and needs no range",
spec: { type: "bar", x: "ts", timeUnit: "week" },
method: "timeBucket",
- sql: ['time_bucket(INTERVAL 1 WEEK, "ts") AS x, time_bucket(INTERVAL 1 WEEK, "ts") + INTERVAL 1 WEEK AS x2'],
+ sql: ['time_bucket(INTERVAL 1 WEEK, src."ts") AS x, time_bucket(INTERVAL 1 WEEK, src."ts") + INTERVAL 1 WEEK AS x2'],
notSql: ["span_x"],
check: (vl) => expect(enc(vl).x.type).toBe("temporal"),
},
@@ -150,14 +150,14 @@ describe("compileChart: reductions per chart type and column class", () => {
name: "quarter is three months",
spec: { type: "line", x: "d", y: "amount", timeUnit: "quarter" },
method: "timeBucket",
- sql: ['time_bucket(INTERVAL 3 MONTH, "d") AS x, sum("amount") AS y'],
+ sql: ['time_bucket(INTERVAL 3 MONTH, src."d") AS x, sum(src."amount") AS y'],
check: (vl) => expect(mark(vl)).toBe("line"),
},
{
name: "line of an aggregate over time buckets without a band end",
spec: { type: "line", x: "ts", y: "amount", agg: "avg", color: "channel" },
method: "timeBucket",
- sql: ['time_bucket(span_x.unit, "ts") AS x, CAST("channel" AS VARCHAR) AS color, avg("amount") AS y'],
+ sql: ['time_bucket(span_x.unit, src."ts") AS x, CAST(src."channel" AS VARCHAR) AS color, avg(src."amount") AS y'],
notSql: ["AS x2"],
check: (vl) => {
expect(mark(vl)).toBe("line");
@@ -170,8 +170,8 @@ describe("compileChart: reductions per chart type and column class", () => {
spec: { type: "line", x: "ts", y: "amount" },
method: "m4",
sql: [
- 'span AS ( SELECT min(epoch_ms(CAST("ts" AS TIMESTAMP))) AS t0, max(epoch_ms(CAST("ts" AS TIMESTAMP))) AS t1 FROM src WHERE "ts" IS NOT NULL AND "amount" IS NOT NULL )',
- 'least(floor(800 * (epoch_ms(CAST("ts" AS TIMESTAMP)) - span.t0) / greatest(span.t1 - span.t0, 1)), 799) AS px',
+ 'span AS ( SELECT min(epoch_ms(CAST(src."ts" AS TIMESTAMP))) AS t0, max(epoch_ms(CAST(src."ts" AS TIMESTAMP))) AS t1 FROM src WHERE src."ts" IS NOT NULL AND src."amount" IS NOT NULL )',
+ 'least(floor(800 * (epoch_ms(CAST(src."ts" AS TIMESTAMP)) - span.t0) / greatest(span.t1 - span.t0, 1)), 799) AS px',
"QUALIFY row_number() OVER (PARTITION BY px ORDER BY x) = 1 OR row_number() OVER (PARTITION BY px ORDER BY x DESC) = 1 OR row_number() OVER (PARTITION BY px ORDER BY y, x) = 1 OR row_number() OVER (PARTITION BY px ORDER BY y DESC, x) = 1 ORDER BY x",
],
notSql: ["GROUP BY"],
@@ -224,14 +224,14 @@ describe("compileChart: reductions per chart type and column class", () => {
name: "histogram honours bins and an aggregate",
spec: { type: "histogram", x: "amount", y: "qty", agg: "avg", bins: 10 },
method: "bins",
- sql: ["/ 10 END AS width", ", 9) * bins_x.width AS x", 'avg("qty") AS y'],
+ sql: ["/ 10 END AS width", ", 9) * bins_x.width AS x", 'avg(src."qty") AS y'],
check: (vl) => expect(enc(vl).y.title).toBe("avg(qty)"),
},
{
name: "scatter samples a repeatable reservoir",
spec: { type: "scatter", x: "qty", y: "amount", color: "channel", size: 'we"ird' },
method: "sample",
- sql: [`SELECT "qty" AS x, "amount" AS y, "channel" AS color, "we""ird" AS size FROM src USING SAMPLE reservoir(${DATA_LIMITS.chartMaxMarks} ROWS) REPEATABLE (42)`],
+ sql: [`SELECT src."qty" AS x, src."amount" AS y, src."channel" AS color, src."we""ird" AS size FROM src USING SAMPLE reservoir(${DATA_LIMITS.chartMaxMarks} ROWS) REPEATABLE (42)`],
notSql: ["GROUP BY"],
check: (vl) => {
expect(mark(vl)).toBe("point");
@@ -251,7 +251,7 @@ describe("compileChart: reductions per chart type and column class", () => {
name: "pie slices are the top N categories by the measure",
spec: { type: "pie", x: "channel", y: "amount" },
method: "topN",
- sql: ["LIMIT 20 )", "ELSE (SELECT label FROM other_bucket) END AS x", 'sum("amount") AS y FROM src GROUP BY ALL ORDER BY y DESC'],
+ sql: ["LIMIT 20 )", "ELSE (SELECT label FROM other_bucket) END AS x", 'sum(src."amount") AS y FROM src GROUP BY ALL ORDER BY y DESC'],
check: (vl) => {
expect(mark(vl)).toBe("arc");
expect(enc(vl).theta).toMatchObject({ field: "y", type: "quantitative" });
@@ -262,14 +262,14 @@ describe("compileChart: reductions per chart type and column class", () => {
name: "pie treats a numeric x as categories",
spec: { type: "pie", x: "qty" },
method: "topN",
- sql: ['CAST("qty" AS VARCHAR)'],
+ sql: ['CAST(src."qty" AS VARCHAR)'],
check: (vl) => expect(mark(vl)).toBe("arc"),
},
{
name: "heatmap groups two categories and colours by the measure",
spec: { type: "heatmap", x: "region", color: "channel" },
method: "group",
- sql: ['SELECT CAST("region" AS VARCHAR) AS x, CAST("channel" AS VARCHAR) AS y, count(*) AS color FROM src GROUP BY ALL ORDER BY x, y'],
+ sql: ['SELECT CAST(src."region" AS VARCHAR) AS x, CAST(src."channel" AS VARCHAR) AS y, count(*) AS color FROM src GROUP BY ALL ORDER BY x, y'],
notSql: ["kept"],
check: (vl) => {
expect(mark(vl)).toBe("rect");
@@ -282,7 +282,7 @@ describe("compileChart: reductions per chart type and column class", () => {
name: "heatmap bins both numeric axes and buckets a date axis",
spec: { type: "heatmap", x: "amount", color: "d", y: "qty", agg: "avg", bins: 5 },
method: "group",
- sql: ["bins_x AS (", "span_y AS (", 'time_bucket(span_y.unit, "d") AS y, time_bucket(span_y.unit, "d") + span_y.unit AS y2, avg("qty") AS color FROM src, bins_x, span_y'],
+ sql: ["bins_x AS (", "span_y AS (", 'time_bucket(span_y.unit, src."d") AS y, time_bucket(span_y.unit, src."d") + span_y.unit AS y2, avg(src."qty") AS color FROM src, bins_x, span_y'],
check: (vl) => {
expect(enc(vl).x).toMatchObject({ bin: "binned" });
expect(enc(vl).x2).toEqual({ field: "x2" });
@@ -329,13 +329,13 @@ describe("compileChart: reductions per chart type and column class", () => {
describe("compileChart: top-N folding", () => {
it("keeps the spec's limit", () => {
const { sql, reduction } = compile({ type: "bar", x: "region", y: "amount", limit: 5 });
- expect(norm(sql)).toContain("ORDER BY sum(\"amount\") DESC NULLS LAST, x LIMIT 5 )");
+ expect(norm(sql)).toContain("ORDER BY sum(src.\"amount\") DESC NULLS LAST, x LIMIT 5 )");
expect(reduction.note).toContain("top 5 of region");
});
it("ranks categories by the chart's own measure", () => {
const { sql } = compile({ type: "bar", x: "region", y: "amount", agg: "max" });
- expect(norm(sql)).toContain('ORDER BY max("amount") DESC NULLS LAST, x LIMIT 20 )');
+ expect(norm(sql)).toContain('ORDER BY max(src."amount") DESC NULLS LAST, x LIMIT 20 )');
});
it("does not fold numbers or dates", () => {
@@ -361,7 +361,7 @@ describe("compileChart: bars that span a range", () => {
it("bins whole numbers in whole steps and labels them without decimals", () => {
const { sql, vegaLite } = compile({ type: "bar", x: "qty", y: "amount" });
- expect(norm(sql)).toContain('greatest(1, ceil((max(CAST("qty" AS DOUBLE)) - min(CAST("qty" AS DOUBLE)) + 1) / 30)) AS width');
+ expect(norm(sql)).toContain('greatest(1, ceil((max(CAST(src."qty" AS DOUBLE)) - min(CAST(src."qty" AS DOUBLE)) + 1) / 30)) AS width');
expect(enc(vegaLite).x).toMatchObject({ bin: "binned", axis: { format: "d" } });
expect(enc(compile({ type: "bar", x: "amount" }).vegaLite).x.axis).toBeUndefined();
});
@@ -392,8 +392,8 @@ describe("compileChart: identifiers and the source", () => {
expect(quoteIdentifier("order")).toBe('"order"');
expect(quoteIdentifier('we"ird')).toBe('"we""ird"');
const { sql, vegaLite } = compile({ type: "bar", x: "order", y: 'we"ird' });
- expect(sql).toContain('CAST("order" AS VARCHAR)');
- expect(sql).toContain('sum("we""ird") AS y');
+ expect(sql).toContain('CAST(src."order" AS VARCHAR)');
+ expect(sql).toContain('sum(src."we""ird") AS y');
expect(enc(vegaLite).x.title).toBe("order");
expect(enc(vegaLite).y.title).toBe('sum(we"ird)');
});
@@ -444,7 +444,7 @@ describe("compileChart: spec_invalid", () => {
it("allows min/max of a date and types y as temporal", () => {
const { sql, vegaLite } = compile({ type: "bar", x: "region", y: "ts", agg: "max" });
- expect(sql).toContain('max("ts") AS y');
+ expect(sql).toContain('max(src."ts") AS y');
expect(enc(vegaLite).y).toMatchObject({ type: "temporal", title: "max(ts)" });
});
});
diff --git a/server/data/chart-compiler.ts b/server/data/chart-compiler.ts
index 4063c0349c..578f5bd4f1 100644
--- a/server/data/chart-compiler.ts
+++ b/server/data/chart-compiler.ts
@@ -68,7 +68,7 @@ function resolve(role: string, name: unknown, columns: DataColumn[]): Resolved {
candidates,
});
}
- return { column, cls: columnClass(column.type), id: quoteIdentifier(column.name) };
+ return { column, cls: columnClass(column.type), id: `src.${quoteIdentifier(column.name)}` };
}
type Encoding = Record<string, unknown>;
diff --git a/server/data/chart-source-columns.test.ts b/server/data/chart-source-columns.test.ts
new file mode 100644
index 0000000000..f8ece04d89
--- /dev/null
+++ b/server/data/chart-source-columns.test.ts
@@ -0,0 +1,86 @@
+import { DuckDBInstance, type DuckDBConnection } from "@duckdb/node-api";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import type { OmbChartSpec } from "./types.ts";
+import { compileChart } from "./chart-compiler.ts";
+
+let instance: DuckDBInstance;
+let connection: DuckDBConnection;
+
+beforeAll(async () => {
+ instance = await DuckDBInstance.create(":memory:");
+ connection = await instance.connect();
+});
+afterAll(() => {
+ connection?.closeSync();
+ instance?.closeSync();
+});
+
+async function chartRows(sql: string, spec: OmbChartSpec) {
+ const source = `(${sql})`;
+ const described = await connection.run(`SELECT * FROM ${source} LIMIT 0`);
+ const columns = Array.from({ length: described.columnCount }, (_, i) => ({
+ name: described.columnName(i), type: described.columnType(i).toString(),
+ }));
+ const compiled = compileChart(spec, columns, source);
+ const result = await connection.runAndReadAll(compiled.sql);
+ return result.getRowsJson();
+}
+
+describe("chart source columns alongside reduction columns", () => {
+ it.each(["lo", "width", "LO", "Width"])("bins a source axis named %s", async (name) => {
+ const rows = await chartRows(`SELECT * FROM (VALUES (1, 3), (2, 5)) t("${name}", amount)`, {
+ type: "bar", x: name, y: "amount", bins: 2,
+ });
+ expect(rows.map(([x, x2, y]) => [x, x2, Number(y)])).toEqual([[1, 2, 3], [2, 3, 5]]);
+ });
+
+ it.each(["lo", "width"])("aggregates a source measure named %s", async (name) => {
+ const rows = await chartRows(`SELECT * FROM (VALUES (1, 3), (2, 5)) t(position, "${name}")`, {
+ type: "bar", x: "position", y: name, bins: 2,
+ });
+ expect(rows.map(([x, x2, y]) => [x, x2, Number(y)])).toEqual([[1, 2, 3], [2, 3, 5]]);
+ });
+
+ it("keeps a source color named width separate from the bin width", async () => {
+ const rows = await chartRows("SELECT * FROM (VALUES (1, 'small', 3), (2, 'large', 5)) t(position, width, amount)", {
+ type: "bar", x: "position", color: "width", y: "amount", bins: 2,
+ });
+ expect(rows.map(([x, x2, color, y]) => [x, x2, color, Number(y)])).toEqual([[1, 2, "small", 3], [2, 3, "large", 5]]);
+ });
+
+ it("buckets source dates named unit", async () => {
+ const rows = await chartRows("SELECT * FROM (VALUES (DATE '2026-01-01', 3), (DATE '2026-01-02', 5)) t(unit, amount)", {
+ type: "bar", x: "unit", y: "amount",
+ });
+ expect(rows.map(([x, , y]) => [String(x).slice(0, 10), Number(y)])).toEqual([["2026-01-01", 3], ["2026-01-02", 5]]);
+ });
+
+ it("reduces source timestamps named t0 without confusing them with the range", async () => {
+ const rows = await chartRows("SELECT * FROM (VALUES (TIMESTAMP '2026-01-01', 3), (TIMESTAMP '2026-01-02', 5)) t(t0, amount)", {
+ type: "line", x: "t0", y: "amount",
+ });
+ expect(rows.map(([x, y]) => [String(x).slice(0, 10), Number(y)])).toEqual([["2026-01-01", 3], ["2026-01-02", 5]]);
+ });
+
+ it("reduces a source measure named t1 without confusing it with the range", async () => {
+ const rows = await chartRows("SELECT * FROM (VALUES (TIMESTAMP '2026-01-01', 3), (TIMESTAMP '2026-01-02', 5)) t(moment, t1)", {
+ type: "line", x: "moment", y: "t1",
+ });
+ expect(rows.map(([x, y]) => [String(x).slice(0, 10), Number(y)])).toEqual([["2026-01-01", 3], ["2026-01-02", 5]]);
+ });
+
+ it("bins both heatmap axes when each shares a reduction column name", async () => {
+ const rows = await chartRows("SELECT * FROM (VALUES (1, 3, 7), (2, 4, 11)) t(lo, width, amount)", {
+ type: "heatmap", x: "lo", color: "width", y: "amount", bins: 2,
+ });
+ expect(rows.map(([x, x2, y, y2, color]) => [x, x2, y, y2, Number(color)])).toEqual([[1, 2, 3, 4, 7], [2, 3, 4, 5, 11]]);
+ });
+
+ it("preserves ordinary axis and measure columns", async () => {
+ const rows = await chartRows("SELECT * FROM (VALUES (1, 3), (2, 5)) t(position, amount)", {
+ type: "bar", x: "position", y: "amount", bins: 2,
+ });
+ expect(rows.map(([x, x2, y]) => [x, x2, Number(y)])).toEqual([[1, 2, 3], [2, 3, 5]]);
+ });
+});
diff --git a/server/data/engine.ts b/server/data/engine.ts
index 07daaf901e..1eeda496ad 100644
--- a/server/data/engine.ts
+++ b/server/data/engine.ts
@@ -579,10 +579,11 @@ class BotDb implements BotDatabase {
const result: DataHistogram = { table: this.displayName(entry), column: found.name, bins: [] };
if (numeric || temporal) {
- const value = numeric ? `CAST(${id} AS DOUBLE)` : `epoch(CAST(${id} AS TIMESTAMP))`;
- const sql = `WITH omb_range AS (SELECT min(${value}) AS lo, max(${value}) AS hi FROM ${from} WHERE ${id} IS NOT NULL)
+ const sourceId = `omb_source.${id}`;
+ const value = numeric ? `CAST(${sourceId} AS DOUBLE)` : `epoch(CAST(${sourceId} AS TIMESTAMP))`;
+ const sql = `WITH omb_range AS (SELECT min(${value}) AS lo, max(${value}) AS hi FROM ${from} AS omb_source WHERE ${sourceId} IS NOT NULL)
SELECT LEAST(coalesce(floor((${value} - omb_range.lo) / nullif(omb_range.hi - omb_range.lo, 0) * ${bins}), 0), ${bins - 1})::INTEGER AS bin, count(*) AS n, min(omb_range.lo), min(omb_range.hi)
-FROM ${from}, omb_range WHERE ${id} IS NOT NULL GROUP BY bin ORDER BY bin`;
+FROM ${from} AS omb_source, omb_range WHERE ${sourceId} IS NOT NULL GROUP BY bin ORDER BY bin`;
const rows = (await this.statement("panel", sql, options, (o, conn) => this.read(o, conn, sql))).rows;
if (!rows.length) return result;
const lo = Number(rows[0][2]);
diff --git a/server/data/histogram-source-columns.test.ts b/server/data/histogram-source-columns.test.ts
new file mode 100644
index 0000000000..27bafca701
--- /dev/null
+++ b/server/data/histogram-source-columns.test.ts
@@ -0,0 +1,44 @@
+import { mkdtempSync } from "node:fs";
+import { rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+
+import { createDataEngine } from "./engine.ts";
+
+const root = mkdtempSync(join(tmpdir(), "omb-histogram-columns-"));
+const engine = createDataEngine({ botFolder: (id) => join(root, id), dataDir: join(root, "data") });
+const connection = "bot" as const;
+
+afterAll(async () => {
+ await engine.closeAll();
+ await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+});
+
+describe("histogram source columns alongside range columns", () => {
+ it.each([
+ ["lo", "lower-lo"], ["hi", "lower-hi"], ["LO", "upper-lo"], ["Hi", "mixed-hi"],
+ ])("counts numeric source values named %s", async (name, botId) => {
+ const db = await engine.forBot(botId);
+ await db.run(`CREATE TABLE measurements AS SELECT range AS "${name}" FROM range(5)`, { connection });
+ expect((await db.histogram("measurements", name, { bins: 2 })).bins).toEqual([
+ { label: "0 – 2", count: 2 }, { label: "2 – 4", count: 3 },
+ ]);
+ });
+
+ it.each(["lo", "hi"])("counts temporal source values named %s", async (name) => {
+ const db = await engine.forBot(`temporal-${name}`);
+ await db.run(`CREATE TABLE measurements AS SELECT DATE '2026-01-01' + range::INTEGER AS "${name}" FROM range(5)`, { connection });
+ expect((await db.histogram("measurements", name, { bins: 2 })).bins).toEqual([
+ { label: "2026-01-01", count: 2 }, { label: "2026-01-03", count: 3 },
+ ]);
+ });
+
+ it("preserves categorical values named lo", async () => {
+ const db = await engine.forBot("categorical");
+ await db.run("CREATE TABLE measurements AS SELECT * FROM (VALUES ('small'), ('large'), ('large')) t(lo)", { connection });
+ expect((await db.histogram("measurements", "lo", { bins: 2 })).bins).toEqual([
+ { label: "large", count: 2 }, { label: "small", count: 1 },
+ ]);
+ });
+});