| 1 | import { readFileSync } from "node:fs"; |
| 2 | import { describe, expect, it } from "vitest"; |
| 3 | import { FUNNEL_COUNTER_FIELDS as INGEST_FUNNEL } from "../../telemetry-ingest/src/schema"; |
| 4 | import { allPlanSql, collectStats, FUNNEL_COUNTER_FIELDS } from "../src/queries"; |
| 5 | import { answer, fakeRunner, INSTALL_A } from "./support"; |
| 6 | |
| 7 | const FROM = new Date("2026-11-10T00:00:00Z"); |
| 8 | const TO = new Date("2026-11-12T00:00:00Z"); |
| 9 | |
| 10 | describe("queries", () => { |
| 11 | it("keeps the funnel counter list identical to the ingest schema", () => { |
| 12 | expect([...FUNNEL_COUNTER_FIELDS]).toEqual([...INGEST_FUNNEL]); |
| 13 | }); |
| 14 | |
| 15 | it("only ever uses index1 inside count(DISTINCT index1)", () => { |
| 16 | for (const source of ["binding", "rest"] as const) { |
| 17 | for (const sql of allPlanSql(source, FROM, TO)) { |
| 18 | expect(sql.replaceAll("count(DISTINCT index1)", "")).not.toMatch(/index1|install_id/); |
| 19 | } |
| 20 | } |
| 21 | }); |
| 22 | |
| 23 | it("uses the binding table without FORMAT or accountTag, and bare table for REST", () => { |
| 24 | const [binding] = allPlanSql("binding", FROM, TO); |
| 25 | expect(binding).toContain('events.analyticsEngine."codewhale_telemetry"'); |
| 26 | expect(binding).not.toMatch(/FORMAT|accountTag/); |
| 27 | expect(allPlanSql("rest", FROM, TO)[0]).toContain("FROM codewhale_telemetry WHERE"); |
| 28 | }); |
| 29 | |
| 30 | it("weights per dialect: automatic on the binding, by _sample_interval on the REST API", () => { |
| 31 | for (const sql of allPlanSql("binding", FROM, TO)) { |
| 32 | expect(sql).not.toMatch(/_sample_interval|sampleInterval|toString|toDate\(/); |
| 33 | expect(sql).toContain("toStartOfDay(timestamp)"); |
| 34 | expect(sql).toContain("timestamp >= '2026-11-10T00:00:00Z'"); |
| 35 | } |
| 36 | for (const sql of allPlanSql("rest", FROM, TO)) { |
| 37 | if (!sql.includes("count(DISTINCT index1)")) expect(sql).toContain("_sample_interval"); |
| 38 | expect(sql).toContain("toDateTime('2026-11-10 00:00:00')"); |
| 39 | expect(sql).not.toMatch(/toString|COUNT\(\*\)/); |
| 40 | } |
| 41 | const all = allPlanSql("binding", FROM, TO); |
| 42 | expect(all.some((sql) => sql.includes("COUNT(*)"))).toBe(true); |
| 43 | expect(all.some((sql) => sql.includes("SUM(double1)"))).toBe(true); |
| 44 | }); |
| 45 | |
| 46 | it("limits the native funnel to the six runtime surfaces", () => { |
| 47 | const native = allPlanSql("binding", FROM, TO).filter((sql) => sql.includes("'install_or_upgrade'") || sql.includes("double1 > 0")); |
| 48 | expect(native).toHaveLength(2); |
| 49 | for (const sql of native) expect(sql).toContain("blob2 IN ('tui', 'exec', 'cli', 'app-server', 'mcp-server', 'serve')"); |
| 50 | }); |
| 51 | |
| 52 | it("walks a long window in weekly chunks", async () => { |
| 53 | const { runner, seen } = fakeRunner(() => []); |
| 54 | await collectStats(runner, new Date("2026-08-14T00:00:00Z"), new Date("2026-11-12T00:00:00Z")); |
| 55 | expect(seen.length).toBe(13 * 10); |
| 56 | expect(seen.some((sql) => sql.includes("'2026-08-21T00:00:00Z'"))).toBe(true); |
| 57 | }); |
| 58 | |
| 59 | it("rejects an empty or inverted window", () => { |
| 60 | expect(() => allPlanSql("binding", TO, FROM)).toThrow(); |
| 61 | }); |
| 62 | |
| 63 | it("turns a fake Analytics Engine response into aggregate rows", async () => { |
| 64 | const { runner } = fakeRunner(answer); |
| 65 | const rows = await collectStats(runner, FROM, TO); |
| 66 | const pick = (metric: string, dim: string, key: string, day = "2026-11-10") => rows.find((r) => r.metric === metric && r.dim === dim && r.key === key && r.day === day)?.value; |
| 67 | expect(pick("active_installs", "all", "all")).toBe(4); |
| 68 | expect(pick("sessions", "version", "0.10.3")).toBe(10); |
| 69 | expect(pick("active_installs", "os", "macos", "2026-11-11")).toBe(5); |
| 70 | expect(pick("turns", "all", "all")).toBe(35); |
| 71 | expect(pick("tool_calls", "all", "all")).toBe(91); |
| 72 | expect(pick("tool_calls", "tool", "bash")).toBe(70); |
| 73 | expect(pick("model_turns_ok", "provider", "deepseek")).toBe(10); |
| 74 | expect(pick("model_turns_ok", "model", "deepseek/other")).toBe(8); |
| 75 | expect(pick("model_input_tokens", "model", "deepseek/deepseek-v4")).toBe(50); |
| 76 | expect(pick("native_installs_initialized", "funnel", "all")).toBe(3); |
| 77 | expect(pick("native_installs_with_successful_turn", "funnel", "all")).toBe(2); |
| 78 | expect(pick("website_funnel", "funnel", "home_view")).toBe(4 * 2 + 1); |
| 79 | expect(pick("website_funnel", "funnel", "install_view")).toBe(4); |
| 80 | }); |
| 81 | |
| 82 | it("sums rows whose keys collapse to other instead of overwriting them", async () => { |
| 83 | const { runner } = fakeRunner((sql) => |
| 84 | sql.includes("blob6 AS key") ? [{ day: "2026-11-10", key: "0.10.3 (weird)", installs: "4", sessions: "1" }, { day: "2026-11-10", key: "0.10.3 [dev]", installs: "6", sessions: "2" }] : [], |
| 85 | ); |
| 86 | const rows = await collectStats(runner, FROM, TO); |
| 87 | expect(rows.filter((r) => r.dim === "version" && r.metric === "active_installs")).toEqual([{ day: "2026-11-10", metric: "active_installs", dim: "version", key: "other", value: 10 }]); |
| 88 | }); |
| 89 | |
| 90 | it("rejects negative or non-numeric counts", async () => { |
| 91 | const { runner } = fakeRunner(() => [{ day: "2026-11-10", key: "all", installs: "-1", sessions: "1" }]); |
| 92 | await expect(collectStats(runner, FROM, TO)).rejects.toThrow(); |
| 93 | }); |
| 94 | |
| 95 | it("preserves every lowercased bundled catalog model id without folding to other", async () => { |
| 96 | const catalog = JSON.parse(readFileSync(new URL("../../crates/config/assets/models_dev.bundled.json", import.meta.url), "utf8")) as { |
| 97 | models?: Record<string, unknown>; |
| 98 | providers?: Record<string, { models?: Record<string, unknown> }>; |
| 99 | }; |
| 100 | const corrections = JSON.parse(readFileSync(new URL("../../crates/config/assets/catalog_corrections.json", import.meta.url), "utf8")) as { |
| 101 | reviewed?: { intrinsic?: Record<string, unknown> }; |
| 102 | }; |
| 103 | const ids = new Set<string>(); |
| 104 | for (const id of Object.keys(catalog.models ?? {})) ids.add(id.toLowerCase()); |
| 105 | for (const provider of Object.values(catalog.providers ?? {})) { |
| 106 | for (const id of Object.keys(provider.models ?? {})) ids.add(id.toLowerCase()); |
| 107 | } |
| 108 | for (const id of Object.keys(corrections.reviewed?.intrinsic ?? {})) ids.add(id.toLowerCase()); |
| 109 | expect(ids.size).toBeGreaterThan(0); |
| 110 | |
| 111 | const { runner } = fakeRunner((sql) => |
| 112 | sql.includes("blob1 = 'model_usage'") && !sql.includes("double1 > 0") |
| 113 | ? [...ids].map((model) => ({ |
| 114 | day: "2026-11-10", |
| 115 | provider: "openrouter", |
| 116 | model, |
| 117 | turns_ok: "1", |
| 118 | turns_failed: "0", |
| 119 | input_tokens: "10", |
| 120 | output_tokens: "5", |
| 121 | })) |
| 122 | : [], |
| 123 | ); |
| 124 | const rows = await collectStats(runner, FROM, TO); |
| 125 | const modelKeys = rows.filter((r) => r.dim === "model" && r.metric === "model_turns_ok").map((r) => r.key); |
| 126 | expect(modelKeys).not.toContain("openrouter/other"); |
| 127 | expect(modelKeys.sort()).toEqual([...ids].map((id) => `openrouter/${id}`).sort()); |
| 128 | }); |
| 129 | |
| 130 | it("skips funnel rows whose JSON counters parse to null or a non-object", async () => { |
| 131 | const { runner } = fakeRunner((sql) => |
| 132 | sql.includes("'funnel_usage'") |
| 133 | ? [ |
| 134 | { day: "2026-11-10", counters: "null", weight: "1" }, |
| 135 | { day: "2026-11-10", counters: "123", weight: "1" }, |
| 136 | { day: "2026-11-10", counters: "[]", weight: "1" }, |
| 137 | { day: "2026-11-10", counters: JSON.stringify({ home_view: 3 }), weight: "2" }, |
| 138 | ] |
| 139 | : [], |
| 140 | ); |
| 141 | const rows = await collectStats(runner, FROM, TO); |
| 142 | expect(rows.filter((r) => r.metric === "website_funnel")).toEqual([ |
| 143 | { day: "2026-11-10", metric: "website_funnel", dim: "funnel", key: "home_view", value: 6 }, |
| 144 | ]); |
| 145 | }); |
| 146 | }); |
| 147 | |
| 148 | describe("no install id leaves the stats layer", () => { |
| 149 | const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i; |
| 150 | |
| 151 | it("no field is an install id and no value looks like one, even when the source row carries one", async () => { |
| 152 | const { runner } = fakeRunner((sql) => { |
| 153 | const rows = answer(sql) as Record<string, unknown>[]; |
| 154 | return rows.map((row) => ({ ...row, index1: INSTALL_A, install_id: INSTALL_A, key: row.key ?? INSTALL_A })); |
| 155 | }); |
| 156 | const rows = await collectStats(runner, FROM, TO); |
| 157 | const text = JSON.stringify(rows); |
| 158 | expect(text).not.toMatch(UUID); |
| 159 | expect(text).not.toMatch(/install_id|index1/); |
| 160 | for (const row of rows) expect(Object.keys(row).sort()).toEqual(["day", "dim", "key", "metric", "value"]); |
| 161 | }); |
| 162 | |
| 163 | it("maps an id-shaped dimension value to other", async () => { |
| 164 | const { runner } = fakeRunner((sql) => (sql.includes("'tool_usage'") ? [{ day: "2026-11-10", tool: INSTALL_A, calls: "1", errors: "0" }] : [])); |
| 165 | const rows = await collectStats(runner, FROM, TO); |
| 166 | expect(rows.filter((r) => r.dim === "tool").map((r) => r.key)).toEqual(["other", "other"]); |
| 167 | }); |
| 168 | |
| 169 | it("maps unhyphenated ids, emails, paths and host:port to other", async () => { |
| 170 | for (const bad of ["3f2b1c4e5a6d4e7f8a9b0c1d2e3f4a5b", "alice@example.com", "/users/alice/x", "10.0.0.1:8080"]) { |
| 171 | const { runner } = fakeRunner((sql) => (sql.includes("blob6 AS key") ? [{ day: "2026-11-10", key: bad, installs: "1", sessions: "1" }] : [])); |
| 172 | const rows = await collectStats(runner, FROM, TO); |
| 173 | expect(rows.filter((r) => r.dim === "version").map((r) => r.key)).toEqual(["other", "other"]); |
| 174 | } |
| 175 | }); |
| 176 | }); |
| 177 |