Skip to content

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

fix: keep chart tail buckets distinct from real categories

Afloata9b2c7e15025
diff --git a/server/data/chart-compiler.test.ts b/server/data/chart-compiler.test.ts
index b34a6bebaf..c75052e798 100644
--- a/server/data/chart-compiler.test.ts
+++ b/server/data/chart-compiler.test.ts
@@ -68,7 +68,7 @@ describe("compileChart: reductions per chart type and column class", () => {
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 'other' END AS x`,
+ `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',
],
check: (vl) => {
@@ -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 'other' 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("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" });
diff --git a/server/data/chart-compiler.ts b/server/data/chart-compiler.ts
index da90689dd5..4063c0349c 100644
--- a/server/data/chart-compiler.ts
+++ b/server/data/chart-compiler.ts
@@ -271,6 +271,41 @@ function checkSpec(spec: OmbChartSpec): void {
if (spec.stack !== undefined && typeof spec.stack !== "boolean") fail("chart.stack must be true or false");
}
+function topNCtes(xExpr: string, measureExpr: string, n: number): Cte[] {
+ return [
+ {
+ name: "kept",
+ body: `
+ SELECT ${xExpr} AS x
+ FROM src
+ GROUP BY ALL
+ ORDER BY ${measureExpr} DESC NULLS LAST, x
+ LIMIT ${n}
+`,
+ },
+ {
+ name: "other_bucket",
+ // At most n labels are retained, so n + 1 candidates guarantee a free name.
+ // Keep the usual "other" label unless it would merge into a real category.
+ body: `
+ SELECT label
+ FROM (
+ SELECT i, CASE WHEN i = 0 THEN 'other' ELSE 'other (' || CAST(i + 1 AS VARCHAR) || ')' END AS label
+ FROM range(${n + 1}) candidates(i)
+ ) labels
+ WHERE NOT EXISTS (SELECT 1 FROM kept WHERE x = label)
+ ORDER BY i
+ LIMIT 1
+`,
+ },
+ ];
+}
+
+function foldToOther(xExpr: string): string {
+ // NULL retains the existing behavior of joining the folded tail.
+ return `CASE WHEN ${xExpr} IN (SELECT x FROM kept) THEN ${xExpr} ELSE (SELECT label FROM other_bucket) END`;
+}
+
function planCartesian(spec: OmbChartSpec, x: Resolved, y: Resolved | undefined, color: Resolved | undefined): Plan {
const bars = spec.type === "bar" || spec.type === "histogram";
const mark = bars ? "bar" : spec.type;
@@ -285,20 +320,10 @@ function planCartesian(spec: OmbChartSpec, x: Resolved, y: Resolved | undefined,
let xExpr = dim.expr;
let reduction = dim.reduction;
if (x.cls === "categorical" || x.cls === "boolean") {
- // `IN (subquery)` is NULL for a NULL category, so NULL lands in "other" with the tail.
const n = spec.limit ?? TOP_N_DEFAULT;
- ctes.push({
- name: "kept",
- body: `
- SELECT ${xExpr} AS x
- FROM src
- GROUP BY ALL
- ORDER BY ${m.expr} DESC NULLS LAST, x
- LIMIT ${n}
-`,
- });
- xExpr = `CASE WHEN ${xExpr} IN (SELECT x FROM kept) THEN ${xExpr} ELSE 'other' END`;
- reduction = { method: "topN", note: `top ${n} of ${x.column.name} by ${m.title}, the rest as "other"` };
+ ctes.push(...topNCtes(xExpr, m.expr, n));
+ xExpr = foldToOther(xExpr);
+ reduction = { method: "topN", note: `top ${n} of ${x.column.name} by ${m.title}, the rest grouped separately` };
}
const selects = [`${xExpr} AS x`];
@@ -381,19 +406,8 @@ function planPie(spec: OmbChartSpec, x: Resolved, y: Resolved | undefined): Plan
const m = measure(spec, y);
const n = spec.limit ?? TOP_N_DEFAULT;
const xExpr = `CAST(${x.id} AS VARCHAR)`;
- const ctes: Cte[] = [
- {
- name: "kept",
- body: `
- SELECT ${xExpr} AS x
- FROM src
- GROUP BY ALL
- ORDER BY ${m.expr} DESC NULLS LAST, x
- LIMIT ${n}
-`,
- },
- ];
- const folded = `CASE WHEN ${xExpr} IN (SELECT x FROM kept) THEN ${xExpr} ELSE 'other' END`;
+ const ctes = topNCtes(xExpr, m.expr, n);
+ const folded = foldToOther(xExpr);
const orderBy = spec.sort === "y" ? "y" : spec.sort === "-x" ? "x DESC" : spec.sort === "x" ? "x" : "y DESC";
const body = `SELECT ${folded} AS x,\n ${m.expr} AS y\nFROM src\nGROUP BY ALL\nORDER BY ${orderBy}`;
const encoding: Encoding = {
@@ -405,7 +419,7 @@ function planPie(spec: OmbChartSpec, x: Resolved, y: Resolved | undefined): Plan
{ field: "x", type: "nominal", title: x.column.name },
{ field: "y", type: "quantitative", title: m.title, format: money },
];
- return { ctes, body, vegaLite: vegaLiteSpec("arc", encoding, tooltip), reduction: { method: "topN", note: `top ${n} of ${x.column.name} by ${m.title}, the rest as "other"` } };
+ return { ctes, body, vegaLite: vegaLiteSpec("arc", encoding, tooltip), reduction: { method: "topN", note: `top ${n} of ${x.column.name} by ${m.title}, the rest grouped separately` } };
}
function planScatter(x: Resolved, y: Resolved | undefined, color: Resolved | undefined, size: Resolved | undefined): Plan {
diff --git a/server/data/charts.e2e.test.ts b/server/data/charts.e2e.test.ts
index 6116e0aa35..7e84de4889 100644
--- a/server/data/charts.e2e.test.ts
+++ b/server/data/charts.e2e.test.ts
@@ -80,6 +80,48 @@ describe("charts end to end on DuckDB", () => {
expect(new Set(reduced.rows.map((r) => r[1]))).toEqual(new Set(["web", "shop"]));
});
+ it.each(["bar", "pie"] as const)("%s: keeps a real other category separate from the folded tail", async (type) => {
+ const table = `other_${type}`;
+ await connection.run(`CREATE TABLE ${table} AS
+ SELECT * FROM (VALUES ('other', 100), ('alpha', 90), (NULL, 1)) t(category, amount)`);
+ const { compiled, reduced } = await chart({ type, x: "category", y: "amount", limit: 1, sort: "x" }, table);
+ expect(reduced.rows.map(([x, y]) => [x, Number(y)])).toEqual([["other", 100], ["other (2)", 91]]);
+ const svg = await chartRenderer.svg(compiled.vegaLite, reduced.rows, reduced.columns, { theme: "light" });
+ expect(svg).toContain("other (2)");
+ });
+
+ it("uses a tail label distinct from every retained category, including numbered other names", async () => {
+ await connection.run(`CREATE TABLE numbered_other AS
+ SELECT * FROM (VALUES ('other', 100), ('other (2)', 90), ('other (3)', 80), ('tail', 10)) t(category, amount)`);
+ const { reduced } = await chart({ type: "bar", x: "category", y: "amount", limit: 3, sort: "x" }, "numbered_other");
+ expect(reduced.rows.map(([x, y]) => [x, Number(y)])).toEqual([
+ ["other", 100], ["other (2)", 90], ["other (3)", 80], ["other (4)", 10],
+ ]);
+ });
+
+ it("uses the same distinct tail label for every color series", async () => {
+ await connection.run(`CREATE TABLE colored_other AS
+ SELECT * FROM (VALUES ('other', 'web', 100), ('other', 'shop', 90), ('tail', 'web', 1), ('tail', 'shop', 2)) t(category, channel, amount)`);
+ const { reduced } = await chart({ type: "bar", x: "category", y: "amount", color: "channel", limit: 1 }, "colored_other");
+ expect(reduced.rows.map(([x, color, y]) => [x, color, Number(y)])).toEqual(expect.arrayContaining([
+ ["other", "web", 100], ["other", "shop", 90], ["other (2)", "web", 1], ["other (2)", "shop", 2],
+ ]));
+ expect(reduced.rows).toHaveLength(4);
+ });
+
+ it("aggregates the raw tail rows after choosing a distinct label", async () => {
+ await connection.run(`CREATE TABLE averaged_other AS
+ SELECT * FROM (VALUES ('other', 100), ('a', 1), ('b', 3), ('b', 5)) t(category, amount)`);
+ const { reduced } = await chart({ type: "pie", x: "category", y: "amount", agg: "avg", limit: 1, sort: "x" }, "averaged_other");
+ expect(reduced.rows.map(([x, y]) => [x, Number(y)])).toEqual([["other", 100], ["other (2)", 3]]);
+ });
+
+ it("does not invent a tail when the only category is named other", async () => {
+ await connection.run(`CREATE TABLE only_other AS SELECT 'other' AS category, 100 AS amount`);
+ const { reduced } = await chart({ type: "pie", x: "category", y: "amount", limit: 1 }, "only_other");
+ expect(reduced.rows.map(([x, y]) => [x, Number(y)])).toEqual([["other", 100]]);
+ });
+
it("line: picks hour buckets for a 3.5-day range, day buckets for a 400-day one", async () => {
const hours = await chart({ type: "line", x: "ts", y: "amount", agg: "avg" }, "sales");
expect(hours.compiled.reduction.method).toBe("timeBucket");