@skyphusion/create-prism 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,269 @@
1
+ // prism#258: cost_usd on the D1 chat row and on the stream `done` event, end to
2
+ // end through the real fetch handler (workerd, local D1), with upstream fetch
3
+ // stubbed. Covers: BYOK non-stream, BYOK stream, an unpriced/no-usage turn
4
+ // (null, not 0), and the control-plane path where cost comes from the plane
5
+ // header and NOT from the playground catalog (ernst S1-2). Also proves the
6
+ // migration lands where CI applies it (S1-1).
7
+
8
+ import { env, SELF } from "cloudflare:test";
9
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
10
+ import { MODELS } from "../src/models";
11
+ import schemaSql from "../schema.sql?raw";
12
+
13
+ const migrationFiles = import.meta.glob("../migrations/*.sql", { query: "?raw", import: "default", eager: true }) as Record<string, string>;
14
+
15
+ function statementsOf(sql: string): string[] {
16
+ return sql
17
+ .split("\n")
18
+ .map((line) => line.replace(/--.*$/, ""))
19
+ .join("\n")
20
+ .split(";")
21
+ .map((s) => s.trim())
22
+ .filter((s) => s.length > 0);
23
+ }
24
+
25
+ async function applyAll(db: D1Database, sql: string): Promise<void> {
26
+ for (const stmt of statementsOf(sql)) {
27
+ try {
28
+ await db.prepare(stmt).run();
29
+ } catch (e) {
30
+ const msg = String((e as { message?: string })?.message ?? e);
31
+ if (/duplicate column name|already exists/i.test(msg)) continue;
32
+ throw e;
33
+ }
34
+ }
35
+ }
36
+
37
+ const anyEnv = env as unknown as { AUTH_MODE?: string };
38
+ const USER_ACCT = "0123456789abcdef0123456789abcdef";
39
+ const PCP_KEY = `pcp_${"0123456789abcdef"}_${"A".repeat(43)}`;
40
+ const SONNET = "anthropic/claude-sonnet-4-6"; // legacy gateway path, priced $3 in / $15 out
41
+ const realFetch = globalThis.fetch;
42
+
43
+ function cookieFrom(res: Response): string {
44
+ return res.headers.get("set-cookie")!.split(";")[0];
45
+ }
46
+
47
+ function req(path: string, opts: { method?: string; body?: unknown; cookie?: string } = {}): Promise<Response> {
48
+ const headers = new Headers();
49
+ if (opts.body !== undefined) headers.set("content-type", "application/json");
50
+ if (opts.cookie) headers.set("cookie", opts.cookie);
51
+ headers.set("cf-connecting-ip", "203.0.113.9");
52
+ return SELF.fetch(`https://prism.test${path}`, {
53
+ method: opts.method ?? "GET",
54
+ headers,
55
+ body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
56
+ });
57
+ }
58
+
59
+ async function signupAndConfigure(username: string, prefs: Record<string, unknown>): Promise<string> {
60
+ const res = await req("/api/auth/signup", { method: "POST", body: { username, password: "password123" } });
61
+ expect(res.status).toBe(201);
62
+ const cookie = cookieFrom(res);
63
+ const p = await req("/api/prefs", { method: "PATCH", cookie, body: prefs });
64
+ expect(p.status).toBe(200);
65
+ return cookie;
66
+ }
67
+
68
+ const BYOK = { account_id: USER_ACCT, gateway_id: "gw", cf_aig_token: "tok" };
69
+
70
+ interface UpstreamCall { url: string }
71
+ let calls: UpstreamCall[];
72
+ let upstream: (url: string) => Response | null;
73
+
74
+ beforeEach(async () => {
75
+ await applyAll(env.DB, schemaSql);
76
+ for (const t of ["chats", "user_prefs", "users", "sessions", "auth_attempts", "conversation_compact"]) {
77
+ await env.DB.prepare(`DELETE FROM ${t}`).run();
78
+ }
79
+ anyEnv.AUTH_MODE = "public";
80
+ calls = [];
81
+ upstream = () => null;
82
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
83
+ const url = input instanceof Request ? input.url : String(input);
84
+ const r = upstream(url);
85
+ if (r) {
86
+ calls.push({ url });
87
+ return r;
88
+ }
89
+ return realFetch(input, init);
90
+ }) as typeof fetch;
91
+ });
92
+
93
+ afterEach(() => {
94
+ globalThis.fetch = realFetch;
95
+ delete anyEnv.AUTH_MODE;
96
+ });
97
+
98
+ function anthropicJson(usage: unknown, url = "https://api.cloudflare.com/"): Response {
99
+ const message = {
100
+ id: "msg_1", type: "message", role: "assistant", model: "stub",
101
+ content: [{ type: "text", text: "hello" }], stop_reason: "end_turn", usage,
102
+ };
103
+ // The REST (account-scoped) door wraps the message; the gateway door does not.
104
+ const wrapped = url.startsWith("https://api.cloudflare.com/") ? { success: true, errors: [], result: message } : message;
105
+ return new Response(JSON.stringify(wrapped), { headers: { "content-type": "application/json" } });
106
+ }
107
+
108
+ function anthropicSse(inTok: unknown, outTok: unknown): Response {
109
+ const frames = [
110
+ ["message_start", { type: "message_start", message: { id: "m", role: "assistant", usage: { input_tokens: inTok, output_tokens: 1 } } }],
111
+ ["content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "hi" } }],
112
+ ["message_delta", { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: outTok } }],
113
+ ["message_stop", { type: "message_stop" }],
114
+ ];
115
+ const body = frames.map(([ev, d]) => `event: ${ev}\ndata: ${JSON.stringify(d)}\n\n`).join("");
116
+ return new Response(body, { headers: { "content-type": "text/event-stream" } });
117
+ }
118
+
119
+ async function sseEvents(res: Response): Promise<Array<Record<string, unknown>>> {
120
+ const text = await res.text();
121
+ return text
122
+ .split("\n")
123
+ .filter((l) => l.startsWith("data: "))
124
+ .map((l) => JSON.parse(l.slice(6)) as Record<string, unknown>);
125
+ }
126
+
127
+ async function lastRow(): Promise<{ cost_usd: number | null; tokens_in: number | null; tokens_out: number | null; model: string }> {
128
+ const r = await env.DB.prepare(`SELECT cost_usd, tokens_in, tokens_out, model FROM chats ORDER BY id DESC LIMIT 1`).first();
129
+ return r as never;
130
+ }
131
+
132
+ describe("migration location (S1-1)", () => {
133
+ it("the column ships as a numbered file in migrations/ (where CI applies it) and in schema.sql", async () => {
134
+ const names = Object.keys(migrationFiles).sort();
135
+ expect(names.some((n) => n.endsWith("0006_chat_cost.sql"))).toBe(true);
136
+ // CI applies only migrations/. Assert the file there adds exactly the column
137
+ // the Worker binds, nullable with no default.
138
+ const m = names.find((n) => n.endsWith("0006_chat_cost.sql"))!;
139
+ expect(statementsOf(migrationFiles[m])).toEqual(["ALTER TABLE chats ADD COLUMN cost_usd REAL"]);
140
+ // schema.sql (fresh DB) carries the same column.
141
+ const cols = (await env.DB.prepare(`PRAGMA table_info(chats)`).all()).results as Array<{ name: string; notnull: number; dflt_value: unknown }>;
142
+ const c = cols.find((x) => x.name === "cost_usd")!;
143
+ expect(c).toBeDefined();
144
+ expect(c.notnull).toBe(0);
145
+ expect(c.dflt_value).toBeNull();
146
+ });
147
+ });
148
+
149
+ describe("BYOK non-stream /api/chat", () => {
150
+ it("a priced chat model: the D1 row and the response carry cost_usd", async () => {
151
+ upstream = (u) => (u.startsWith("https://gateway.ai.cloudflare.com/") || u.startsWith("https://api.cloudflare.com/") ? anthropicJson({ input_tokens: 1000, output_tokens: 500 }, u) : null);
152
+ const cookie = await signupAndConfigure("cora", BYOK);
153
+ const res = await req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
154
+ expect(res.status).toBe(200);
155
+ const body = (await res.json()) as { cost_usd: number | null };
156
+ expect(body.cost_usd).toBe(0.0105); // 1000 * $3/M + 500 * $15/M
157
+ const row = await lastRow();
158
+ expect(row).toMatchObject({ model: SONNET, tokens_in: 1000, tokens_out: 500, cost_usd: 0.0105 });
159
+ });
160
+
161
+ it("a missing or unsafe token count stores null, not 0, and the chat still succeeds", async () => {
162
+ upstream = (u) => anthropicJson({ input_tokens: "lots", output_tokens: -4 }, u);
163
+ const cookie = await signupAndConfigure("dax", BYOK);
164
+ const res = await req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
165
+ expect(res.status).toBe(200);
166
+ expect(((await res.json()) as { cost_usd: unknown }).cost_usd).toBeNull();
167
+ expect((await lastRow()).cost_usd).toBeNull();
168
+ // No usage object at all.
169
+ upstream = (u) => anthropicJson(undefined, u);
170
+ const res2 = await req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "again" } });
171
+ expect(res2.status).toBe(200);
172
+ expect((await lastRow()).cost_usd).toBeNull();
173
+ });
174
+ });
175
+
176
+ describe("BYOK stream /api/chat/stream", () => {
177
+ it("the done event and the D1 row both carry cost_usd", async () => {
178
+ upstream = (u) => (u.startsWith("https://gateway.ai.cloudflare.com/") || u.startsWith("https://api.cloudflare.com/") ? anthropicSse(2000, 1000) : null);
179
+ const cookie = await signupAndConfigure("eli", BYOK);
180
+ const res = await req("/api/chat/stream", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
181
+ expect(res.status).toBe(200);
182
+ const done = (await sseEvents(res)).find((e) => e.type === "done")!;
183
+ expect(done).toBeDefined();
184
+ expect(done.tokens_in).toBe(2000);
185
+ expect(done.tokens_out).toBe(1000);
186
+ expect(done.cost_usd).toBe(0.021); // 2000 * $3/M + 1000 * $15/M = 6000 + 15000 micro
187
+ expect((await lastRow()).cost_usd).toBe(0.021);
188
+ });
189
+
190
+ it("no usage in the stream: done carries null (not 0) and so does the row", async () => {
191
+ upstream = () => new Response(`event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "x" } })}\n\n`, { headers: { "content-type": "text/event-stream" } });
192
+ const cookie = await signupAndConfigure("fay", BYOK);
193
+ const res = await req("/api/chat/stream", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
194
+ const done = (await sseEvents(res)).find((e) => e.type === "done")!;
195
+ expect(done).toBeDefined();
196
+ expect(done.cost_usd).toBeNull();
197
+ expect((await lastRow()).cost_usd).toBeNull();
198
+ });
199
+ });
200
+
201
+ describe("control-plane path: the plane's charge, not the catalog (S1-2)", () => {
202
+ const PLANE = "https://play-proxy.skyphusion.org/v1/chat/completions";
203
+ function plane(headers: Record<string, string>, usage: unknown = { prompt_tokens: 1000, completion_tokens: 500 }) {
204
+ return (u: string) =>
205
+ u === PLANE
206
+ ? new Response(JSON.stringify({ model: SONNET, choices: [{ message: { role: "assistant", content: "from plane" } }], usage }), {
207
+ headers: { "content-type": "application/json", "prism-request-id": "req_1", ...headers },
208
+ })
209
+ : null;
210
+ }
211
+ const CATALOG_PRICE = 0.0105; // what the playground list price would give for 1000 in + 500 out
212
+
213
+ it("non-stream: cost_usd is the header figure, which differs from the catalog price", async () => {
214
+ upstream = plane({ "prism-metered": "true", "prism-usage-micro-usd": "123456" });
215
+ const cookie = await signupAndConfigure("gus", { control_plane_key: PCP_KEY });
216
+ const res = await req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
217
+ expect(res.status).toBe(200);
218
+ expect(calls.map((c) => c.url)).toEqual([PLANE]);
219
+ const body = (await res.json()) as { cost_usd: number | null };
220
+ expect(body.cost_usd).toBe(0.123456);
221
+ expect(body.cost_usd).not.toBe(CATALOG_PRICE);
222
+ expect((await lastRow()).cost_usd).toBe(0.123456);
223
+ });
224
+
225
+ it("stream: the done event carries the same plane figure", async () => {
226
+ upstream = plane({ "prism-metered": "true", "prism-usage-micro-usd": "777" });
227
+ const cookie = await signupAndConfigure("hal", { control_plane_key: PCP_KEY });
228
+ const res = await req("/api/chat/stream", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
229
+ const done = (await sseEvents(res)).find((e) => e.type === "done")!;
230
+ expect(done.cost_usd).toBe(0.000777);
231
+ expect((await lastRow()).cost_usd).toBe(0.000777);
232
+ });
233
+
234
+ it("header absent: null on the row and on done, even though the catalog could price it", async () => {
235
+ upstream = plane({});
236
+ const cookie = await signupAndConfigure("ivy", { control_plane_key: PCP_KEY });
237
+ const res = await req("/api/chat/stream", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
238
+ const done = (await sseEvents(res)).find((e) => e.type === "done")!;
239
+ expect(done.cost_usd).toBeNull();
240
+ expect((await lastRow()).cost_usd).toBeNull();
241
+ });
242
+
243
+ it("prism-metered false: null, not the header's 0", async () => {
244
+ upstream = plane({ "prism-metered": "false", "prism-usage-micro-usd": "0" });
245
+ const cookie = await signupAndConfigure("jon", { control_plane_key: PCP_KEY });
246
+ const res = await req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
247
+ expect(((await res.json()) as { cost_usd: unknown }).cost_usd).toBeNull();
248
+ expect((await lastRow()).cost_usd).toBeNull();
249
+ });
250
+ });
251
+
252
+ describe("a pricing fault never fails the chat write", () => {
253
+ it("a model with corrupt pricing still persists the row, with null cost", async () => {
254
+ const m = MODELS.find((x) => x.id === SONNET)!;
255
+ const saved = m.pricing;
256
+ m.pricing = { in_micro_per_mtok: Number.NaN, out_micro_per_mtok: 1, priced_at: "2026-12-04" };
257
+ try {
258
+ upstream = (u) => anthropicJson({ input_tokens: 10, output_tokens: 10 }, u);
259
+ const cookie = await signupAndConfigure("kit", BYOK);
260
+ const res = await req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
261
+ expect(res.status).toBe(200);
262
+ const row = await lastRow();
263
+ expect(row.tokens_in).toBe(10);
264
+ expect(row.cost_usd).toBeNull();
265
+ } finally {
266
+ m.pricing = saved;
267
+ }
268
+ });
269
+ });
@@ -0,0 +1,318 @@
1
+ // prism#259: funnel counters in D1, end to end through the real handler (workerd,
2
+ // local D1, upstream fetch stubbed). Covers the ernst S1-8 / S1-9 controls:
3
+ // count a signup only after the insert, first output once and only for a done
4
+ // row, a counter fault never fails a signup or a chat, account deletion leaves
5
+ // no row naming the account, and the DOCUMENTED operator queries (read from
6
+ // docs/funnel-metrics.md) return the 7-day median on a seeded local D1, with a
7
+ // valid zero-row baseline alongside.
8
+
9
+ import { env, SELF } from "cloudflare:test";
10
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
11
+ import schemaSql from "../schema.sql?raw";
12
+ import docSql from "../docs/funnel-metrics.md?raw";
13
+ import { recordFirstOutput } from "../src/funnel";
14
+ import { persistChat } from "../src/routes/chat";
15
+
16
+ async function applySchema(db: D1Database): Promise<void> {
17
+ const statements = schemaSql
18
+ .split("\n")
19
+ .map((line) => line.replace(/--.*$/, ""))
20
+ .join("\n")
21
+ .split(";")
22
+ .map((s) => s.trim())
23
+ .filter((s) => s.length > 0);
24
+ for (const stmt of statements) {
25
+ try {
26
+ await db.prepare(stmt).run();
27
+ } catch (e) {
28
+ const msg = String((e as { message?: string })?.message ?? e);
29
+ if (/duplicate column name|already exists/i.test(msg)) continue;
30
+ throw e;
31
+ }
32
+ }
33
+ }
34
+
35
+ const anyEnv = env as unknown as { AUTH_MODE?: string };
36
+ const USER_ACCT = "0123456789abcdef0123456789abcdef";
37
+ const SONNET = "anthropic/claude-sonnet-4-6";
38
+ const realFetch = globalThis.fetch;
39
+
40
+ beforeEach(async () => {
41
+ await applySchema(env.DB);
42
+ for (const t of ["chats", "user_prefs", "users", "sessions", "auth_attempts", "conversation_compact", "funnel_daily"]) {
43
+ await env.DB.prepare(`DELETE FROM ${t}`).run();
44
+ }
45
+ anyEnv.AUTH_MODE = "public";
46
+ let n = 0;
47
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
48
+ const url = input instanceof Request ? input.url : String(input);
49
+ if (url.startsWith("https://gateway.ai.cloudflare.com/") || url.startsWith("https://api.cloudflare.com/")) {
50
+ n += 1;
51
+ const message = {
52
+ id: `msg_${n}`, type: "message", role: "assistant", model: "stub",
53
+ content: [{ type: "text", text: "hello" }], stop_reason: "end_turn", usage: { input_tokens: 3, output_tokens: 5 },
54
+ };
55
+ const payload = url.startsWith("https://api.cloudflare.com/") ? { success: true, errors: [], result: message } : message;
56
+ return new Response(JSON.stringify(payload), { headers: { "content-type": "application/json" } });
57
+ }
58
+ return realFetch(input, init);
59
+ }) as typeof fetch;
60
+ });
61
+
62
+ afterEach(() => {
63
+ globalThis.fetch = realFetch;
64
+ delete anyEnv.AUTH_MODE;
65
+ });
66
+
67
+ function req(path: string, opts: { method?: string; body?: unknown; cookie?: string; ip?: string } = {}): Promise<Response> {
68
+ const headers = new Headers();
69
+ if (opts.body !== undefined) headers.set("content-type", "application/json");
70
+ if (opts.cookie) headers.set("cookie", opts.cookie);
71
+ headers.set("cf-connecting-ip", opts.ip ?? "203.0.113.20");
72
+ return SELF.fetch(`https://prism.test${path}`, {
73
+ method: opts.method ?? "GET",
74
+ headers,
75
+ body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
76
+ });
77
+ }
78
+
79
+ async function signup(username: string): Promise<{ cookie: string; id: string }> {
80
+ const res = await req("/api/auth/signup", { method: "POST", body: { username, password: "password123" }, ip: `198.51.100.${Math.floor(Math.random() * 200) + 1}` });
81
+ expect(res.status).toBe(201);
82
+ const cookie = res.headers.get("set-cookie")!.split(";")[0];
83
+ const u = await env.DB.prepare(`SELECT id FROM users WHERE username_lc = ?`).bind(username).first<{ id: string }>();
84
+ return { cookie, id: u!.id };
85
+ }
86
+
87
+ async function configure(cookie: string): Promise<void> {
88
+ const r = await req("/api/prefs", { method: "PATCH", cookie, body: { account_id: USER_ACCT, gateway_id: "gw", cf_aig_token: "tok" } });
89
+ expect(r.status).toBe(200);
90
+ }
91
+
92
+ async function chat(cookie: string): Promise<Response> {
93
+ return req("/api/chat", { method: "POST", cookie, body: { model: SONNET, user_input: "hi" } });
94
+ }
95
+
96
+ interface Daily {
97
+ signups: number; first_outputs: number;
98
+ ttfo_lt_1m: number; ttfo_1_5m: number; ttfo_5_30m: number; ttfo_30m_24h: number; ttfo_ge_24h: number;
99
+ }
100
+ async function daily(): Promise<Daily> {
101
+ const r = await env.DB.prepare(
102
+ `SELECT COALESCE(SUM(signups),0) signups, COALESCE(SUM(first_outputs),0) first_outputs,
103
+ COALESCE(SUM(ttfo_lt_1m),0) ttfo_lt_1m, COALESCE(SUM(ttfo_1_5m),0) ttfo_1_5m,
104
+ COALESCE(SUM(ttfo_5_30m),0) ttfo_5_30m, COALESCE(SUM(ttfo_30m_24h),0) ttfo_30m_24h,
105
+ COALESCE(SUM(ttfo_ge_24h),0) ttfo_ge_24h FROM funnel_daily`,
106
+ ).first<Daily>();
107
+ return r!;
108
+ }
109
+
110
+ describe("signup counting (S1-9)", () => {
111
+ it("counts a signup after the insert succeeds, once per account", async () => {
112
+ expect((await daily()).signups).toBe(0);
113
+ await signup("amy");
114
+ await signup("ben");
115
+ expect((await daily()).signups).toBe(2);
116
+ });
117
+
118
+ it("a refused signup (taken username, bad input) is not counted", async () => {
119
+ await signup("cat");
120
+ const dup = await req("/api/auth/signup", { method: "POST", body: { username: "cat", password: "password123" }, ip: "198.51.100.150" });
121
+ expect(dup.status).toBe(409);
122
+ const bad = await req("/api/auth/signup", { method: "POST", body: { username: "x", password: "1" }, ip: "198.51.100.151" });
123
+ expect(bad.status).toBeGreaterThanOrEqual(400);
124
+ expect((await daily()).signups).toBe(1);
125
+ });
126
+ });
127
+
128
+ describe("first output (S1-9)", () => {
129
+ it("sets first_output_at once, counts once, and buckets the time from signup", async () => {
130
+ const { cookie, id } = await signup("dee");
131
+ await configure(cookie);
132
+ // Age the account so the signup-to-first-output time is about 3 minutes.
133
+ await env.DB.prepare(`UPDATE users SET created_at = datetime('now', '-3 minutes') WHERE id = ?`).bind(id).run();
134
+
135
+ expect((await chat(cookie)).status).toBe(200);
136
+ const u1 = await env.DB.prepare(`SELECT first_output_at FROM users WHERE id = ?`).bind(id).first<{ first_output_at: string | null }>();
137
+ expect(u1!.first_output_at).not.toBeNull();
138
+ let d = await daily();
139
+ expect(d.first_outputs).toBe(1);
140
+ expect(d.ttfo_1_5m).toBe(1);
141
+
142
+ // A second and third output change nothing.
143
+ expect((await chat(cookie)).status).toBe(200);
144
+ expect((await chat(cookie)).status).toBe(200);
145
+ const u2 = await env.DB.prepare(`SELECT first_output_at FROM users WHERE id = ?`).bind(id).first<{ first_output_at: string | null }>();
146
+ expect(u2!.first_output_at).toBe(u1!.first_output_at);
147
+ d = await daily();
148
+ expect(d.first_outputs).toBe(1);
149
+ expect(d.ttfo_1_5m + d.ttfo_lt_1m + d.ttfo_5_30m + d.ttfo_30m_24h + d.ttfo_ge_24h).toBe(1);
150
+ });
151
+
152
+ it("a concurrent burst of outputs still counts the account once", async () => {
153
+ const { id } = await signup("eve");
154
+ await Promise.all(Array.from({ length: 8 }, () => recordFirstOutput(env as never, id)));
155
+ expect((await daily()).first_outputs).toBe(1);
156
+ });
157
+
158
+ it("a failed turn is not a first output", async () => {
159
+ const { cookie, id } = await signup("fox");
160
+ await configure(cookie);
161
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
162
+ const url = input instanceof Request ? input.url : String(input);
163
+ if (url.startsWith("https://gateway.ai.cloudflare.com/") || url.startsWith("https://api.cloudflare.com/")) {
164
+ return new Response(JSON.stringify({ error: "boom" }), { status: 500 });
165
+ }
166
+ return realFetch(input, init);
167
+ }) as typeof fetch;
168
+ const res = await chat(cookie);
169
+ expect(res.status).toBeGreaterThanOrEqual(400);
170
+ const u = await env.DB.prepare(`SELECT first_output_at FROM users WHERE id = ?`).bind(id).first<{ first_output_at: string | null }>();
171
+ expect(u!.first_output_at).toBeNull();
172
+ expect((await daily()).first_outputs).toBe(0);
173
+ });
174
+
175
+ it("only a done row with output counts: pending and failed rows do not", async () => {
176
+ const { id } = await signup("gil");
177
+ const base = {
178
+ userEmail: id, model: "m", model_type: "video" as const, system_prompt: null, user_input: "x",
179
+ output: "", output_artifact: null, attachments: [], tokens_in: null, tokens_out: null,
180
+ latency_ms: 0, ai_gateway_log_id: null,
181
+ };
182
+ await persistChat(env as never, { ...base, status: "pending" });
183
+ await persistChat(env as never, { ...base, status: "failed", output: "partial" });
184
+ expect((await daily()).first_outputs).toBe(0);
185
+ await persistChat(env as never, { ...base, status: "done", output: "real output" });
186
+ expect((await daily()).first_outputs).toBe(1);
187
+ });
188
+
189
+ it("no users row (access mode): nothing is counted and nothing throws", async () => {
190
+ await recordFirstOutput(env as never, "someone@example.com");
191
+ expect((await daily()).first_outputs).toBe(0);
192
+ });
193
+ });
194
+
195
+ describe("a counter fault never fails a signup or a chat (S1-9)", () => {
196
+ it("with funnel_daily gone, signup still 201 and chat still 200 and the row still persists", async () => {
197
+ await env.DB.prepare(`ALTER TABLE funnel_daily RENAME TO funnel_daily_off`).run();
198
+ try {
199
+ const { cookie } = await signup("gus");
200
+ await configure(cookie);
201
+ const res = await chat(cookie);
202
+ expect(res.status).toBe(200);
203
+ const n = await env.DB.prepare(`SELECT COUNT(*) AS n FROM chats`).first<{ n: number }>();
204
+ expect(n!.n).toBe(1);
205
+ } finally {
206
+ await env.DB.prepare(`ALTER TABLE funnel_daily_off RENAME TO funnel_daily`).run();
207
+ }
208
+ });
209
+ });
210
+
211
+ describe("account deletion leaves nothing that names the account (S1-8)", () => {
212
+ async function tablesNaming(id: string): Promise<string[]> {
213
+ const tables = (await env.DB.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_cf_%'`).all<{ name: string }>()).results ?? [];
214
+ const hits: string[] = [];
215
+ for (const t of tables) {
216
+ const rows = (await env.DB.prepare(`SELECT * FROM "${t.name}"`).all()).results ?? [];
217
+ if (JSON.stringify(rows).includes(id)) hits.push(t.name);
218
+ }
219
+ return hits;
220
+ }
221
+
222
+ it("deleting the account removes first_output_at with it; funnel_daily keeps the anonymous counts", async () => {
223
+ const { cookie, id } = await signup("hal");
224
+ await configure(cookie);
225
+ expect((await chat(cookie)).status).toBe(200);
226
+
227
+ // Precondition: the instrument can see the account id where it lives.
228
+ const before = await tablesNaming(id);
229
+ expect(before).toContain("users");
230
+ expect(before).toContain("chats");
231
+ const u = await env.DB.prepare(`SELECT first_output_at FROM users WHERE id = ?`).bind(id).first<{ first_output_at: string | null }>();
232
+ expect(u!.first_output_at).not.toBeNull();
233
+ const dayRow = JSON.stringify((await env.DB.prepare(`SELECT * FROM funnel_daily`).all()).results);
234
+ expect(dayRow).not.toContain(id); // the durable table never held it
235
+
236
+ const del = await req("/api/account", { method: "DELETE", cookie, body: { password: "password123" } });
237
+ expect(del.status).toBe(200);
238
+
239
+ expect(await tablesNaming(id)).toEqual([]);
240
+ const gone = await env.DB.prepare(`SELECT COUNT(*) AS n FROM users WHERE id = ?`).bind(id).first<{ n: number }>();
241
+ expect(gone!.n).toBe(0);
242
+ // Positive control: the aggregates survived (the table was not wiped with the account).
243
+ const d = await daily();
244
+ expect(d.signups).toBe(1);
245
+ expect(d.first_outputs).toBe(1);
246
+ });
247
+
248
+ it("funnel_daily has no column that could hold an identity", async () => {
249
+ const cols = ((await env.DB.prepare(`PRAGMA table_info(funnel_daily)`).all<{ name: string }>()).results ?? []).map((c) => c.name).sort();
250
+ expect(cols).toEqual(["day", "first_outputs", "signups", "ttfo_30m_24h", "ttfo_5_30m", "ttfo_1_5m", "ttfo_ge_24h", "ttfo_lt_1m"].sort());
251
+ });
252
+ });
253
+
254
+ // The operator queries are the ones in docs/funnel-metrics.md, extracted from
255
+ // the doc text so the test cannot drift from what the operator copies.
256
+ function documentedQuery(name: string): string {
257
+ const m = docSql.match(new RegExp(`<!-- query:${name} -->\\s*\`\`\`sql\\n([\\s\\S]*?)\`\`\``));
258
+ if (!m) throw new Error(`documented query ${name} not found in docs/funnel-metrics.md`);
259
+ return m[1];
260
+ }
261
+
262
+ describe("documented operator queries (the Done-when)", () => {
263
+ it("harness control: the three documented queries are found in the doc", () => {
264
+ for (const q of ["median-exact", "median-bucket", "totals"]) expect(documentedQuery(q).length).toBeGreaterThan(20);
265
+ });
266
+
267
+ it("0-row baseline: no accounts gives samples 0 and a null median, not an error and not 0", async () => {
268
+ const exact = await env.DB.prepare(documentedQuery("median-exact")).first<{ samples: number; median_seconds: number | null }>();
269
+ expect(exact).toEqual({ samples: 0, median_seconds: null });
270
+ const bucket = await env.DB.prepare(documentedQuery("median-bucket")).first<{ first_outputs: number; median_bucket: string | null }>();
271
+ expect(bucket).toEqual({ first_outputs: 0, median_bucket: null });
272
+ const totals = await env.DB.prepare(documentedQuery("totals")).first();
273
+ expect(totals).toEqual({ signups: 0, first_outputs: 0 });
274
+ });
275
+
276
+ async function seedUser(name: string, createdAgo: string, firstOutputAgo: string | null): Promise<void> {
277
+ await env.DB.prepare(
278
+ `INSERT INTO users (id, username, username_lc, password_hash, created_at, first_output_at)
279
+ VALUES (?, ?, ?, 'x', datetime('now', ?), ${firstOutputAgo ? "datetime('now', ?)" : "NULL"})`,
280
+ ).bind(...[`usr_${name}`, name, name, createdAgo, ...(firstOutputAgo ? [firstOutputAgo] : [])]).run();
281
+ }
282
+
283
+ it("seeded: the 7-day median is returned, excluding old and not-yet-output accounts", async () => {
284
+ // Time to first output: 30 s, 120 s, 600 s, 7200 s -> median (120 + 600) / 2 = 360.
285
+ await seedUser("a", "-1 hours", "-3570 seconds");
286
+ await seedUser("b", "-1 hours", "-3480 seconds");
287
+ await seedUser("c", "-2 hours", "-6600 seconds");
288
+ await seedUser("d", "-5 hours", "-3 hours");
289
+ // Excluded: first output 10 days ago (5 s), and an account with no output yet.
290
+ await seedUser("old", "-10 days", "-9 days");
291
+ await env.DB.prepare(`UPDATE users SET first_output_at = datetime('now', '-10 days', '+5 seconds'), created_at = datetime('now', '-10 days') WHERE id = 'usr_old'`).run();
292
+ await seedUser("none", "-1 hours", null);
293
+
294
+ const exact = await env.DB.prepare(documentedQuery("median-exact")).first<{ samples: number; median_seconds: number | null }>();
295
+ expect(exact).toEqual({ samples: 4, median_seconds: 360 });
296
+
297
+ // Durable daily rows: today 4 outputs spread across buckets, plus an old day that must be excluded.
298
+ await env.DB.prepare(
299
+ `INSERT INTO funnel_daily (day, signups, first_outputs, ttfo_lt_1m, ttfo_1_5m, ttfo_5_30m, ttfo_30m_24h)
300
+ VALUES (date('now'), 6, 4, 1, 1, 1, 1)`,
301
+ ).run();
302
+ await env.DB.prepare(
303
+ `INSERT INTO funnel_daily (day, signups, first_outputs, ttfo_ge_24h) VALUES (date('now', '-20 days'), 99, 99, 99)`,
304
+ ).run();
305
+ const bucket = await env.DB.prepare(documentedQuery("median-bucket")).first();
306
+ expect(bucket).toEqual({ first_outputs: 4, median_bucket: "1 to 5 min" });
307
+ const totals = await env.DB.prepare(documentedQuery("totals")).first();
308
+ expect(totals).toEqual({ signups: 6, first_outputs: 4 });
309
+ });
310
+
311
+ it("odd sample count: the median is the middle value", async () => {
312
+ await seedUser("p", "-1 hours", "-3570 seconds"); // 30 s
313
+ await seedUser("q", "-1 hours", "-3300 seconds"); // 300 s
314
+ await seedUser("r", "-1 hours", "-2400 seconds"); // 1200 s
315
+ const exact = await env.DB.prepare(documentedQuery("median-exact")).first();
316
+ expect(exact).toEqual({ samples: 3, median_seconds: 300 });
317
+ });
318
+ });