返回 CodeWhale
queries.ts
根目录 / telemetry-stats / src / queries.ts
1 import { tableName } from "./sql";
2 import { ROW_LIMIT } from "./sql";
3 import type { SqlRunner, StatRow } from "./types";
4
5 export const FUNNEL_COUNTER_FIELDS = [
6 "home_view", "install_view", "quickstart_view", "contribute_view",
7 "install_intent", "install_confirmed", "star_exit", "issue_exit",
8 "help_wanted_exit", "guide_exit", "docs_search", "docs_search_empty",
9 "docs_search_result", "quickstart_confirmed",
10 ] as const;
11
12 const DAY_MS = 86_400_000;
13 const CHUNK_DAYS = 7;
14 const BATCH = 4;
15 const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
16 const HEX32 = /[0-9a-f]{32}/i;
17 const RUNTIME_SURFACES = "'tui', 'exec', 'cli', 'app-server', 'mcp-server', 'serve'";
18 const SURFACE_VALUES = new Set(["tui", "exec", "cli", "app-server", "mcp-server", "serve", "website", "web-app", "desktop", "control-plane", "vscode-extension"]);
19 const OS_VALUES = new Set(["linux", "macos", "windows", "freebsd", "android", "other"]);
20 const KEY_PATTERNS: Record<KeyKind, RegExp> = {
21 version: /^\d+\.\d+\.\d+(-[a-z]+(\.\d+)?)?$/,
22 provider: /^[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?$/,
23 model: /^[a-z0-9][a-z0-9._:/+-]{0,127}$/,
24 tool: /^[a-z][a-z0-9_]{0,39}$/,
25 surface: /^[a-z][a-z-]{0,19}$/,
26 os: /^[a-z]{3,10}$/,
27 all: /^all$/,
28 };
29
30 type KeyKind = "version" | "provider" | "model" | "tool" | "surface" | "os" | "all";
31
32 export const CAVEATS = [
33 "Observed active installs are distinct rotating anonymous ids with a session_start that UTC day. They are not people, accounts or total installs.",
34 "Sessions, turns, tool calls, tokens and funnel counters are weighted by sample interval, so they stay correct if Analytics Engine samples. Active installs and the native funnel are distinct counts and are not weighted.",
35 "The native funnel counts distinct ids from the six runtime surfaces that initialized or completed a successful turn that UTC day; ids that started from CI are not excluded.",
36 "Coverage is a lower bound: opted-out installs, older clients, offline shutdowns and dropped flushes are invisible. Funnel dates are received-batch dates.",
37 "Raw rows age out of Analytics Engine after three months; the daily totals kept beyond that hold counts only and no install ids.",
38 ];
39
40 export function utcDay(date: Date): string {
41 return date.toISOString().slice(0, 10);
42 }
43
44 export function startOfUtcDay(date: Date): Date {
45 return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
46 }
47
48 function sqlTime(date: Date): string {
49 return date.toISOString().slice(0, 19).replace("T", " ");
50 }
51
52 function windowClause(source: Source, from: Date, to: Date): string {
53 if (!(from < to)) throw new Error("from must precede to");
54 if (source === "binding") return `timestamp >= '${from.toISOString().slice(0, 19)}Z' AND timestamp < '${to.toISOString().slice(0, 19)}Z'`;
55 return `timestamp >= toDateTime('${sqlTime(from)}') AND timestamp < toDateTime('${sqlTime(to)}')`;
56 }
57
58 function weighted(source: Source, expr: string): string {
59 return source === "binding" ? `SUM(${expr})` : `sum(_sample_interval * ${expr})`;
60 }
61
62 function weightedCount(source: Source): string {
63 return source === "binding" ? "COUNT(*)" : "sum(_sample_interval)";
64 }
65
66 function safeDay(value: unknown): string {
67 const day = String(value).slice(0, 10);
68 if (!/^\d{4}-\d\d-\d\d$/.test(day)) throw new Error("invalid day in SQL response");
69 return day;
70 }
71
72 function safeKey(value: unknown, kind: KeyKind): string {
73 const key = String(value ?? "").trim();
74 if (key === "") return "unknown";
75 if (key.length > 80 || UUID.test(key) || HEX32.test(key) || !KEY_PATTERNS[kind].test(key)) return "other";
76 if (kind === "surface" && !SURFACE_VALUES.has(key)) return "other";
77 if (kind === "os" && !OS_VALUES.has(key)) return "other";
78 return key;
79 }
80
81 function safeValue(value: unknown): number {
82 const number = Number(value);
83 if (!Number.isFinite(number) || number < 0) throw new Error("invalid count in SQL response");
84 return number;
85 }
86
87 const DAY = "toStartOfDay(timestamp)";
88
89
90 type Row = Record<string, unknown>;
91 type Source = SqlRunner["source"];
92
93 function sumInto(rows: StatRow[]): StatRow[] {
94 const merged = new Map<string, StatRow>();
95 for (const row of rows) {
96 const id = `${row.day}\u0000${row.metric}\u0000${row.dim}\u0000${row.key}`;
97 const existing = merged.get(id);
98 if (existing) existing.value += row.value;
99 else merged.set(id, { ...row });
100 }
101 return [...merged.values()];
102 }
103
104 interface Plan {
105 sql: string;
106 parse(rows: Row[]): StatRow[];
107 }
108
109 function installDimension(source: Source, table: string, w: string, dim: string, column: string | null, kind: KeyKind): Plan {
110 const keyExpr = column ?? "'all'";
111 return {
112 sql: `SELECT ${DAY} AS day, ${keyExpr} AS key, count(DISTINCT index1) AS installs, ${weightedCount(source)} AS sessions FROM ${table} WHERE ${w} AND blob1 = 'session_start' GROUP BY day, key LIMIT ${ROW_LIMIT}`,
113 parse: (rows) =>
114 rows.flatMap((row) => [
115 { day: safeDay(row.day), metric: "active_installs", dim, key: safeKey(row.key, kind), value: safeValue(row.installs) },
116 { day: safeDay(row.day), metric: "sessions", dim, key: safeKey(row.key, kind), value: safeValue(row.sessions) },
117 ]),
118 };
119 }
120
121 export function buildPlans(source: Source, from: Date, to: Date): Plan[] {
122 const table = tableName(source);
123 const w = windowClause(source, from, to);
124 return [
125 installDimension(source, table, w, "all", null, "all"),
126 installDimension(source, table, w, "version", "blob6", "version"),
127 installDimension(source, table, w, "surface", "blob2", "surface"),
128 installDimension(source, table, w, "os", "blob3", "os"),
129 {
130 sql: `SELECT ${DAY} AS day, blob2 AS surface, ${weighted(source, "double1")} AS turns, ${weighted(source, "double2")} AS tool_calls FROM ${table} WHERE ${w} AND blob1 = 'session_end' GROUP BY day, surface LIMIT ${ROW_LIMIT}`,
131 parse: (rows) =>
132 rows.flatMap((row) =>
133 ["all", "surface"].flatMap((dim) =>
134 [["turns", row.turns], ["tool_calls", row.tool_calls]].map(([metric, value]) => ({
135 day: safeDay(row.day),
136 metric: String(metric),
137 dim,
138 key: dim === "all" ? "all" : safeKey(row.surface, "surface"),
139 value: safeValue(value),
140 })),
141 ),
142 ),
143 },
144 {
145 sql: `SELECT ${DAY} AS day, blob16 AS tool, ${weighted(source, "double1")} AS calls, ${weighted(source, "double2")} AS errors FROM ${table} WHERE ${w} AND blob1 = 'tool_usage' GROUP BY day, tool LIMIT ${ROW_LIMIT}`,
146 parse: (rows) =>
147 rows.flatMap((row) => [
148 { day: safeDay(row.day), metric: "tool_calls", dim: "tool", key: safeKey(row.tool, "tool"), value: safeValue(row.calls) },
149 { day: safeDay(row.day), metric: "tool_errors", dim: "tool", key: safeKey(row.tool, "tool"), value: safeValue(row.errors) },
150 ]),
151 },
152 {
153 sql: `SELECT ${DAY} AS day, blob15 AS provider, blob16 AS model, ${weighted(source, "double1")} AS turns_ok, ${weighted(source, "double2")} AS turns_failed, ${weighted(source, "double4")} AS input_tokens, ${weighted(source, "double5")} AS output_tokens FROM ${table} WHERE ${w} AND blob1 = 'model_usage' GROUP BY day, provider, model LIMIT ${ROW_LIMIT}`,
154 parse: (rows) =>
155 rows.flatMap((row) =>
156 (
157 [
158 ["model_turns_ok", row.turns_ok],
159 ["model_turns_failed", row.turns_failed],
160 ["model_input_tokens", row.input_tokens],
161 ["model_output_tokens", row.output_tokens],
162 ] as const
163 ).flatMap(([metric, value]) => [
164 { day: safeDay(row.day), metric, dim: "provider", key: safeKey(row.provider, "provider"), value: safeValue(value) },
165 { day: safeDay(row.day), metric, dim: "model", key: `${safeKey(row.provider, "provider")}/${safeKey(row.model, "model")}`, value: safeValue(value) },
166 ]),
167 ),
168 },
169 {
170 sql: `SELECT ${DAY} AS day, count(DISTINCT index1) AS installs FROM ${table} WHERE ${w} AND blob1 = 'install_or_upgrade' AND blob9 = 'install' AND blob2 IN (${RUNTIME_SURFACES}) GROUP BY day LIMIT ${ROW_LIMIT}`,
171 parse: (rows) =>
172 rows.map((row) => ({ day: safeDay(row.day), metric: "native_installs_initialized", dim: "funnel", key: "all", value: safeValue(row.installs) })),
173 },
174 {
175 sql: `SELECT ${DAY} AS day, count(DISTINCT index1) AS installs FROM ${table} WHERE ${w} AND blob1 = 'model_usage' AND double1 > 0 AND blob2 IN (${RUNTIME_SURFACES}) GROUP BY day LIMIT ${ROW_LIMIT}`,
176 parse: (rows) =>
177 rows.map((row) => ({ day: safeDay(row.day), metric: "native_installs_with_successful_turn", dim: "funnel", key: "all", value: safeValue(row.installs) })),
178 },
179 funnelPlan(source, from, to),
180 ];
181 }
182
183 export function funnelPlan(source: Source, from: Date, to: Date): Plan {
184 const table = tableName(source);
185 const w = windowClause(source, from, to);
186 return {
187 sql: `SELECT ${DAY} AS day, blob18 AS counters, ${weightedCount(source)} AS weight FROM ${table} WHERE ${w} AND blob1 = 'funnel_usage' AND blob2 = 'website' AND blob19 = '5' GROUP BY day, counters LIMIT ${ROW_LIMIT}`,
188 parse(rows) {
189 const out: StatRow[] = [];
190 for (const row of rows) {
191 let parsed: unknown;
192 try {
193 parsed = JSON.parse(String(row.counters));
194 } catch {
195 continue;
196 }
197 if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
198 const counters = parsed as Record<string, unknown>;
199 const weight = safeValue(row.weight);
200 for (const field of FUNNEL_COUNTER_FIELDS) {
201 const raw = counters[field];
202 if (raw === null || raw === undefined) continue;
203 const value = Number(raw);
204 if (!Number.isFinite(value) || value < 0) continue;
205 out.push({ day: safeDay(row.day), metric: "website_funnel", dim: "funnel", key: field, value: value * weight });
206 }
207 }
208 return out;
209 },
210 };
211 }
212
213 function order(rows: StatRow[]): StatRow[] {
214 return rows.sort((a, b) => a.day.localeCompare(b.day) || a.metric.localeCompare(b.metric) || a.dim.localeCompare(b.dim) || a.key.localeCompare(b.key));
215 }
216
217 export async function* statChunks(runner: SqlRunner, from: Date, to: Date): AsyncGenerator<StatRow[]> {
218 for (let start = from.getTime(); start < to.getTime(); start += CHUNK_DAYS * DAY_MS) {
219 const end = new Date(Math.min(start + CHUNK_DAYS * DAY_MS, to.getTime()));
220 const plans = buildPlans(runner.source, new Date(start), end);
221 const rows: StatRow[] = [];
222 for (let i = 0; i < plans.length; i += BATCH) {
223 const parsed = await Promise.all(plans.slice(i, i + BATCH).map(async (plan) => plan.parse((await runner.run(plan.sql)) as Row[])));
224 rows.push(...parsed.flat());
225 }
226 yield order(sumInto(rows));
227 }
228 }
229
230 export async function collectStats(runner: SqlRunner, from: Date, to: Date): Promise<StatRow[]> {
231 const rows: StatRow[] = [];
232 for await (const chunk of statChunks(runner, from, to)) rows.push(...chunk);
233 return rows;
234 }
235
236 export function allPlanSql(source: Source, from: Date, to: Date): string[] {
237 return buildPlans(source, from, to).map((plan) => plan.sql);
238 }
239
239 lines TYPESCRIPT