cursedbelt-server 4.66.0 → 4.68.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,139 @@
1
+ /**
2
+ * The page's issue reports land in the app's D1 as one row each, redacted, bounded and purged
3
+ * (forge task 4500).
4
+ */
5
+ import { Database } from 'bun:sqlite';
6
+ import { describe, expect, test } from 'bun:test';
7
+ import { readFileSync } from 'node:fs';
8
+ import { createRequire } from 'node:module';
9
+ import { Hono } from 'hono';
10
+ import { createLocalD1 } from '../d1/local.js';
11
+ import {
12
+ CLIENT_ISSUES_DDL,
13
+ REDACTED_QUERY_KEY,
14
+ clientIssueDoor,
15
+ clientIssuesHandler,
16
+ createD1ClientIssuesRecorder,
17
+ issueStem,
18
+ redactQueryValues,
19
+ } from './d1.js';
20
+
21
+ const fresh = () => {
22
+ const sqlite = new Database(':memory:');
23
+ for (const ddl of CLIENT_ISSUES_DDL) sqlite.run(ddl);
24
+ return { sqlite, db: createLocalD1(sqlite) };
25
+ };
26
+
27
+ const report = (over: Record<string, unknown> = {}) => ({
28
+ v: 1,
29
+ app: 'collections',
30
+ build: 'abc1234',
31
+ change: 'raised',
32
+ id: 'video:42',
33
+ area: 'video',
34
+ tone: 'warning',
35
+ title: 'Video 42 is stuck loading',
36
+ outlook: 'Needs a code fix.',
37
+ occurrences: 2,
38
+ startedAt: 900,
39
+ page: '/watch/42?token=SECRET',
40
+ facts: [{ label: 'Segment', value: 'https://media.test/s.ts?sig=SIG&n=1' }],
41
+ report: 'Video 42 is stuck loading\n GET https://media.test/s.ts?exp=1&sig=SIG → 503',
42
+ ...over,
43
+ });
44
+
45
+ const post = (app: ReturnType<typeof createD1ClientIssuesRecorder>, body: unknown) =>
46
+ app.request('/', { method: 'POST', body: typeof body === 'string' ? body : JSON.stringify(body), headers: { 'user-agent': 'iPhone' } });
47
+
48
+ describe('🔴 a posted report is one redacted row (forge task 4500)', () => {
49
+ test('a raise and its end are two rows, nothing secret in either', async () => {
50
+ const { sqlite, db } = fresh();
51
+ let clock = 1_000;
52
+ const app = createD1ClientIssuesRecorder({ db, resolveUser: () => 'u1', now: () => clock });
53
+ expect((await post(app, report())).status).toBe(204);
54
+ clock = 2_000;
55
+ expect((await post(app, report({ change: 'resolved', endedAt: 1_900, resolution: 'Played' }))).status).toBe(204);
56
+ const rows = sqlite.query('SELECT * FROM client_issues ORDER BY id').all() as Record<string, unknown>[];
57
+ expect(rows.map((r) => r.change)).toEqual(['raised', 'resolved']);
58
+ expect(rows[0]).toMatchObject({ at: 1_000, issue_id: 'video:42', area: 'video', stem: 'video # is stuck loading', user_agent: 'iPhone', user_key: 'u1', build: 'abc1234', ended_at: null });
59
+ expect(rows[1]).toMatchObject({ ended_at: 1_900, resolution: 'Played' });
60
+ expect(JSON.stringify(rows)).not.toMatch(/SECRET|SIG/);
61
+ expect(rows[0]?.page).toBe('/watch/42?token=…');
62
+ });
63
+
64
+ test('a malformed body is a 400 and writes nothing', async () => {
65
+ const { sqlite, db } = fresh();
66
+ const app = createD1ClientIssuesRecorder({ db });
67
+ for (const body of ['not json', report({ v: 2 }), report({ change: 'updated' }), report({ title: '' })]) {
68
+ expect((await post(app, body)).status).toBe(400);
69
+ }
70
+ expect(sqlite.query('SELECT COUNT(*) AS n FROM client_issues').get()).toEqual({ n: 0 });
71
+ });
72
+
73
+ test('the account is the session’s, never the body’s, and every string is capped', () => {
74
+ const door = clientIssueDoor(report({ user_key: 'forged', title: 'x'.repeat(5_000), report: 'y'.repeat(50_000) }), { now: 1, userKey: null });
75
+ if ('error' in door) throw new Error(door.error);
76
+ expect(door.row.user_key).toBe('');
77
+ expect(door.row.title.length).toBe(240);
78
+ expect(door.row.report.length).toBe(12_000);
79
+ });
80
+ });
81
+
82
+ describe('clientIssuesHandler is the same door, for a literal route', () => {
83
+ test('app.post(path, handler) records the row', async () => {
84
+ const { sqlite, db } = fresh();
85
+ const app = new Hono().post('/api/client-issues', clientIssuesHandler({ db, now: () => 7 }));
86
+ const res = await app.request('/api/client-issues', { method: 'POST', body: JSON.stringify(report()) });
87
+ expect(res.status).toBe(204);
88
+ expect(sqlite.query('SELECT at FROM client_issues').all()).toEqual([{ at: 7 }]);
89
+ });
90
+ });
91
+
92
+ describe('🔴 the door is bounded whoever calls it', () => {
93
+ test('past maxRowsPerHour it answers 429 and writes nothing more', async () => {
94
+ const { sqlite, db } = fresh();
95
+ const app = createD1ClientIssuesRecorder({ db, maxRowsPerHour: 2, now: () => 5_000_000 });
96
+ expect((await post(app, report())).status).toBe(204);
97
+ expect((await post(app, report())).status).toBe(204);
98
+ expect((await post(app, report())).status).toBe(429);
99
+ expect(sqlite.query('SELECT COUNT(*) AS n FROM client_issues').get()).toEqual({ n: 2 });
100
+ });
101
+
102
+ test('a write purges the rows older than the retention', async () => {
103
+ const { sqlite, db } = fresh();
104
+ let clock = 1_000;
105
+ const app = createD1ClientIssuesRecorder({ db, retentionMs: 10_000, now: () => clock });
106
+ await post(app, report({ id: 'old' }));
107
+ clock = 20_000;
108
+ await post(app, report({ id: 'new' }));
109
+ expect(sqlite.query('SELECT issue_id FROM client_issues').all()).toEqual([{ issue_id: 'new' }]);
110
+ });
111
+ });
112
+
113
+ describe('issueStem groups what varies between occurrences', () => {
114
+ test('numbers, hashes, urls and quoted names drop out', () => {
115
+ expect(issueStem('Video 42 is stuck')).toBe(issueStem('Video 97 is stuck'));
116
+ expect(issueStem('“Holiday” failed: https://x.test/a/b')).toBe('<name> failed: <url>');
117
+ expect(issueStem('Chunk 3fa9c2d1e0 failed to load')).toBe('chunk # failed to load');
118
+ expect(issueStem('The server is failing (HTTP 503)')).toBe('the server is failing (http #)');
119
+ });
120
+ test('redactQueryValues leaves what is not a secret', () => {
121
+ expect(redactQueryValues('a?sig=1&n=2;exp=3')).toBe('a?sig=…&n=2;exp=…');
122
+ });
123
+ });
124
+
125
+ describe('🔴 the redaction is the page’s own rule, not a second copy that drifts', () => {
126
+ test('equals cursedbelt’s REDACTED_QUERY_KEY once the installed cursedbelt exports it', async () => {
127
+ const require = createRequire(import.meta.url);
128
+ const manifest = require.resolve('cursedbelt/package.json');
129
+ const version = (JSON.parse(readFileSync(manifest, 'utf8')) as { version: string }).version;
130
+ const belt = (await import('cursedbelt/react/notifications')) as { REDACTED_QUERY_KEY?: RegExp };
131
+ const [major = 0, minor = 0] = version.split('.').map(Number);
132
+ // 5.140.0 is the first cursedbelt with the export; the publish bumps this devDependency past it.
133
+ if (major > 5 || (major === 5 && minor >= 140)) expect(belt.REDACTED_QUERY_KEY).toBeDefined();
134
+ if (belt.REDACTED_QUERY_KEY) {
135
+ expect(REDACTED_QUERY_KEY.source).toBe(belt.REDACTED_QUERY_KEY.source);
136
+ expect(REDACTED_QUERY_KEY.flags).toBe(belt.REDACTED_QUERY_KEY.flags);
137
+ }
138
+ });
139
+ });
@@ -0,0 +1,221 @@
1
+ /**
2
+ * `cursedbelt-server/client-issues/d1` — the server half of the page's issue record (forge task 4500).
3
+ *
4
+ * `cursedbelt/react/notifications`' `installIssueReporter` beacons every `raised` and `resolved`
5
+ * problem a page sees (a stuck video, a failing API, an uncaught error) to {@link CLIENT_ISSUES_PATH};
6
+ * this door writes one row per report into the app's own D1 `client_issues`, and autopilot's watch
7
+ * reads that table to file the work. Before it, a problem reached a fix only when the owner copied
8
+ * a report off his phone by hand.
9
+ *
10
+ * ```ts
11
+ * import { CLIENT_ISSUES_DDL, createD1ClientIssuesRecorder } from "cursedbelt-server/client-issues/d1";
12
+ * app.route("/api/client-issues", createD1ClientIssuesRecorder({ db: (c) => c.env.DB, resolveUser }));
13
+ * // and CLIENT_ISSUES_DDL in the app's schema
14
+ * ```
15
+ *
16
+ * 🔴 The door trusts nothing it is sent: every string is capped, the app's own query-key redaction
17
+ * ({@link REDACTED_QUERY_KEY}, byte-identical to `cursedbelt`'s — the spec compares them) runs again
18
+ * here, and the account is the session's, never the body's. It may be mounted outside the session
19
+ * gate (a page that cannot sign in is exactly the page with a problem), so two bounds hold whoever
20
+ * calls it: at most {@link ClientIssuesOptions.maxRowsPerHour} rows an hour per app, and rows older
21
+ * than {@link ClientIssuesOptions.retentionMs} are purged on every write.
22
+ *
23
+ * 🔴 Worker-safe: nothing reachable from here at runtime imports `bun:*`.
24
+ */
25
+ import type { Context } from "hono";
26
+ import { Hono } from "hono";
27
+ import type { D1LikeDatabase } from "../d1/types.js";
28
+
29
+ export const CLIENT_ISSUES_PATH = "/api/client-issues";
30
+
31
+ /** The table and its index, as one-line DDL for the app's schema. */
32
+ export const CLIENT_ISSUES_DDL: readonly string[] = [
33
+ "CREATE TABLE IF NOT EXISTS client_issues ( id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, change TEXT NOT NULL, issue_id TEXT NOT NULL, area TEXT NOT NULL, stem TEXT NOT NULL, tone TEXT NOT NULL, outlook TEXT NOT NULL, title TEXT NOT NULL, occurrences INTEGER NOT NULL DEFAULT 1, started_at INTEGER NOT NULL, ended_at INTEGER, resolution TEXT NOT NULL DEFAULT '', page TEXT NOT NULL DEFAULT '', build TEXT NOT NULL DEFAULT '', user_agent TEXT NOT NULL DEFAULT '', user_key TEXT NOT NULL DEFAULT '', facts TEXT NOT NULL DEFAULT '[]', report TEXT NOT NULL DEFAULT '' )",
34
+ "CREATE INDEX IF NOT EXISTS idx_client_issues_at ON client_issues (at)",
35
+ ];
36
+
37
+ /** 🔴 Must equal `cursedbelt/react/notifications`' `REDACTED_QUERY_KEY` — `d1.spec.ts` compares them. */
38
+ export const REDACTED_QUERY_KEY = /token|sig|signature|key|secret|password|code|exp/i;
39
+
40
+ /** Every `key=value` whose key is a {@link REDACTED_QUERY_KEY}, its value replaced by `…`. */
41
+ export function redactQueryValues(text: string): string {
42
+ return text.replace(/([?&;]([^=&#\s]+)=)([^&#;\s]*)/g, (whole, head: string, key: string) =>
43
+ REDACTED_QUERY_KEY.test(key) ? `${head}…` : whole,
44
+ );
45
+ }
46
+
47
+ /**
48
+ * The words of a title with what varies between occurrences taken out — numbers, ids, hosts,
49
+ * quoted names — so "Video 42 is stuck" and "Video 97 is stuck" are one group for autopilot.
50
+ */
51
+ export function issueStem(title: string): string {
52
+ return title
53
+ .toLowerCase()
54
+ .replace(/https?:\/\/\S+/g, "<url>")
55
+ .replace(/["“'‘][^"”'’]*["”'’]/g, "<name>")
56
+ .replace(/\b[0-9a-f]{8,}\b/g, "#")
57
+ .replace(/\d+(?:[.,:]\d+)*/g, "#")
58
+ .replace(/\s+/g, " ")
59
+ .trim()
60
+ .slice(0, 160);
61
+ }
62
+
63
+ export interface ClientIssueRow {
64
+ at: number;
65
+ change: "raised" | "resolved";
66
+ issue_id: string;
67
+ area: string;
68
+ stem: string;
69
+ tone: string;
70
+ outlook: string;
71
+ title: string;
72
+ occurrences: number;
73
+ started_at: number;
74
+ ended_at: number | null;
75
+ resolution: string;
76
+ page: string;
77
+ build: string;
78
+ user_agent: string;
79
+ user_key: string;
80
+ facts: string;
81
+ report: string;
82
+ }
83
+
84
+ const cap = (value: unknown, max: number): string => (typeof value === "string" ? redactQueryValues(value).slice(0, max) : "");
85
+ const whole = (value: unknown): number | null =>
86
+ typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : null;
87
+
88
+ /** One posted report as the row it becomes, or why it is refused. Pure, so the door is tested without a server. */
89
+ export function clientIssueDoor(
90
+ body: unknown,
91
+ context: { now: number; userAgent?: string; userKey?: string | null },
92
+ ): { row: ClientIssueRow } | { error: string } {
93
+ if (!body || typeof body !== "object") return { error: "expected a json object" };
94
+ const b = body as Record<string, unknown>;
95
+ if (b.v !== 1) return { error: "unknown report version" };
96
+ if (b.change !== "raised" && b.change !== "resolved") return { error: "change must be raised or resolved" };
97
+ const issueId = cap(b.id, 160);
98
+ const title = cap(b.title, 240);
99
+ const area = cap(b.area, 40);
100
+ if (!issueId || !title || !area) return { error: "id, area and title are required" };
101
+ const startedAt = whole(b.startedAt) ?? context.now;
102
+ const facts = Array.isArray(b.facts)
103
+ ? b.facts
104
+ .slice(0, 20)
105
+ .filter((f): f is { label: unknown; value: unknown } => !!f && typeof f === "object")
106
+ .map((f) => ({ label: cap(f.label, 80), value: cap(f.value, 400) }))
107
+ : [];
108
+ return {
109
+ row: {
110
+ at: context.now,
111
+ change: b.change,
112
+ issue_id: issueId,
113
+ area,
114
+ stem: issueStem(title),
115
+ tone: cap(b.tone, 16) || "warning",
116
+ outlook: cap(b.outlook, 300),
117
+ title,
118
+ occurrences: Math.max(1, whole(b.occurrences) ?? 1),
119
+ started_at: startedAt,
120
+ ended_at: whole(b.endedAt),
121
+ resolution: cap(b.resolution, 300),
122
+ page: cap(b.page, 400),
123
+ build: cap(b.build, 80),
124
+ user_agent: cap(context.userAgent, 300),
125
+ user_key: context.userKey ?? "",
126
+ facts: JSON.stringify(facts),
127
+ report: cap(b.report, 12_000),
128
+ },
129
+ };
130
+ }
131
+
132
+ const COLUMNS = [
133
+ "at",
134
+ "change",
135
+ "issue_id",
136
+ "area",
137
+ "stem",
138
+ "tone",
139
+ "outlook",
140
+ "title",
141
+ "occurrences",
142
+ "started_at",
143
+ "ended_at",
144
+ "resolution",
145
+ "page",
146
+ "build",
147
+ "user_agent",
148
+ "user_key",
149
+ "facts",
150
+ "report",
151
+ ] as const satisfies readonly (keyof ClientIssueRow)[];
152
+
153
+ export interface ClientIssuesOptions {
154
+ /** The app's D1, or how to find it on the request. */
155
+ db: D1LikeDatabase | ((c: Context) => D1LikeDatabase);
156
+ /** The session's account, when there is one. Never read from the body. */
157
+ resolveUser?: (c: Context) => string | null;
158
+ /** Rows older than this are deleted on each write. Default 14 days. */
159
+ retentionMs?: number;
160
+ /** Reports past this many in the last hour are refused (429). Default 600. */
161
+ maxRowsPerHour?: number;
162
+ now?: () => number;
163
+ }
164
+
165
+ /** Write one row, purge the expired ones, refuse past the hourly bound. `"capped"` when refused. */
166
+ export async function recordClientIssueD1(
167
+ db: D1LikeDatabase,
168
+ row: ClientIssueRow,
169
+ bounds: { retentionMs: number; maxRowsPerHour: number },
170
+ ): Promise<"recorded" | "capped"> {
171
+ const recent = await db
172
+ .prepare("SELECT COUNT(*) AS n FROM client_issues WHERE at > ?")
173
+ .bind(row.at - 3_600_000)
174
+ .first<{ n: number }>();
175
+ if ((recent?.n ?? 0) >= bounds.maxRowsPerHour) return "capped";
176
+ await db.batch([
177
+ db
178
+ .prepare(`INSERT INTO client_issues (${COLUMNS.join(", ")}) VALUES (${COLUMNS.map(() => "?").join(", ")})`)
179
+ .bind(...COLUMNS.map((k) => row[k])),
180
+ db.prepare("DELETE FROM client_issues WHERE at < ?").bind(row.at - bounds.retentionMs),
181
+ ]);
182
+ return "recorded";
183
+ }
184
+
185
+ /**
186
+ * The one handler: take one posted report, answer 204 (400 malformed, 429 past the hourly bound).
187
+ * For an app that declares its routes as literals (`app.post("/api/client-issues", handler)`, so a
188
+ * route census can read them); {@link createD1ClientIssuesRecorder} is the same handler as a sub-app.
189
+ */
190
+ export function clientIssuesHandler(options: ClientIssuesOptions): (c: Context) => Promise<Response> {
191
+ const now = options.now ?? (() => Date.now());
192
+ const bounds = {
193
+ retentionMs: options.retentionMs ?? 14 * 24 * 3_600_000,
194
+ maxRowsPerHour: options.maxRowsPerHour ?? 600,
195
+ };
196
+ return async (c) => {
197
+ let body: unknown;
198
+ try {
199
+ body = JSON.parse(await c.req.text());
200
+ } catch {
201
+ return c.json({ error: "expected a json body" }, 400);
202
+ }
203
+ const door = clientIssueDoor(body, {
204
+ now: now(),
205
+ userAgent: c.req.header("user-agent") ?? "",
206
+ userKey: options.resolveUser?.(c) ?? null,
207
+ });
208
+ if ("error" in door) return c.json({ error: door.error }, 400);
209
+ const db = typeof options.db === "function" ? options.db(c) : options.db;
210
+ const outcome = await recordClientIssueD1(db, door.row, bounds);
211
+ if (outcome === "capped") return c.json({ error: "too many reports this hour" }, 429);
212
+ return c.body(null, 204);
213
+ };
214
+ }
215
+
216
+ /** The Hono app to mount at {@link CLIENT_ISSUES_PATH}: `POST /` takes one report, answers 204. */
217
+ export function createD1ClientIssuesRecorder(options: ClientIssuesOptions): Hono {
218
+ const app = new Hono();
219
+ app.post("/", clientIssuesHandler(options));
220
+ return app;
221
+ }
@@ -24,6 +24,11 @@
24
24
  * local driver, so `sameShape.spec.ts` was green on a bug BOTH sides shared — the one
25
25
  * failure mode a two-implementation test cannot see. A real port of
26
26
  * `apps/patterns/src/server/tokens.ts` found it on its first atomic write.
27
+ * 7. **`changes` includes the rows a TRIGGER wrote — on `.all()` of a writing statement too.**
28
+ * Measured 2026-11-10 on family-stage's D1: a 3-row INSERT whose AFTER INSERT trigger writes
29
+ * two log rows each reports `changes: 9`; an `INSERT … RETURNING` of 2, read with `.all()`,
30
+ * reports 6. bun's `.run().changes` is a `total_changes()` difference and agrees (SQLite's
31
+ * own `changes()` would say 3); this file's `.all()` said 0 until it went through `runSync`.
27
32
  *
28
33
  * SQL semantics are real: it runs against an actual in-memory SQLite. Only the edges are
29
34
  * emulated, which are exactly the edges under test.
@@ -118,11 +123,9 @@ class FakeD1Statement implements D1BindingStatement {
118
123
  return wire[column];
119
124
  }
120
125
 
126
+ /** `runSync`'s counters too: D1's `.all()` of an `INSERT … RETURNING` reports what it wrote (see 7. above). */
121
127
  async all(): Promise<D1BindingResult> {
122
- assertRunnableOnD1(this.sql);
123
- const started = performance.now();
124
- const rows = this.db.query(this.sql).all(...(this.params as never[])) as Record<string, unknown>[];
125
- return { results: rows.map(toWireRow), success: true, meta: this.meta(started) };
128
+ return this.runSync();
126
129
  }
127
130
 
128
131
  async run(): Promise<D1BindingResult> {
@@ -159,8 +162,8 @@ class FakeD1Statement implements D1BindingStatement {
159
162
  const stmt = this.db.query(this.sql);
160
163
  const bound = this.params as never[];
161
164
 
162
- // No result columns → cannot return rows, and `.run()` is the only call that reports
163
- // `changes`. This is the ordinary batch member: an INSERT, UPDATE or DELETE.
165
+ // No result columns → cannot return rows: the ordinary batch member, an INSERT, UPDATE or
166
+ // DELETE. bun's `.run().changes` is a `total_changes()` difference, trigger rows in (see 7.).
164
167
  if (stmt.columnNames.length === 0) {
165
168
  const res = stmt.run(...bound);
166
169
  return { results: [], success: true, meta: this.meta(started, res.changes, Number(res.lastInsertRowid)) };
@@ -43,6 +43,17 @@ export { createPendingWrites, type InvocationD1, type PendingWrites, perInvocati
43
43
  export { createHttpD1, D1HttpError, type HttpD1Options } from './http.js';
44
44
  export { assertBatchSize, assertWithinLimits, chunkForBind, inArray, LIMITS } from './limits.js';
45
45
  export { createLocalD1, refuseInteractiveTransaction } from './local.js';
46
+ export {
47
+ LOW_CARDINALITY_COLUMNS,
48
+ type PlanCheckOptions,
49
+ type PlanRow,
50
+ perRowReads,
51
+ perRowSteps,
52
+ planOf,
53
+ planOffenders,
54
+ preparedBy,
55
+ wholeTablePages,
56
+ } from './plans.js';
46
57
  export {
47
58
  createRemoteD1,
48
59
  type D1BindingLike,
@@ -0,0 +1,129 @@
1
+ /**
2
+ * The plan checks (`./plans`): the cases photos found in production (forge tasks 4467, 4596), held as
3
+ * plan rows, and the same checks over a real `EXPLAIN QUERY PLAN` through the local driver.
4
+ */
5
+ import { Database } from 'bun:sqlite';
6
+ import { describe, expect, test } from 'bun:test';
7
+ import { createLocalD1 } from './local.js';
8
+ import { LOW_CARDINALITY_COLUMNS, type PlanRow, perRowReads, planOf, planOffenders, preparedBy, wholeTablePages } from './plans.js';
9
+
10
+ describe('perRowReads', () => {
11
+ const plan = (detail: string): PlanRow[] => [
12
+ { id: 2, parent: 0, detail: 'SCAN ai' },
13
+ { id: 30, parent: 0, detail: 'CORRELATED SCALAR SUBQUERY 2' },
14
+ { id: 35, parent: 30, detail },
15
+ ];
16
+
17
+ test('catches a per-row scan and a per-row low-cardinality search, and passes a keyed one', () => {
18
+ expect(perRowReads(plan('SEARCH j USING INDEX jobs_queue (state=?)'))).toEqual(['SEARCH j USING INDEX jobs_queue (state=?)']);
19
+ expect(perRowReads(plan('SCAN j'))).toEqual(['SCAN j']);
20
+ expect(perRowReads(plan('SEARCH j USING INDEX jobs_asset (asset_id=? AND kind=?)'))).toEqual([]);
21
+ expect(perRowReads(plan('SCAN json_each VIRTUAL TABLE INDEX 0:'))).toEqual([]);
22
+ expect(perRowReads(plan('SEARCH s USING INDEX assets_owner (owner_id=?)'))).toEqual(['SEARCH s USING INDEX assets_owner (owner_id=?)']);
23
+ });
24
+
25
+ test('an EXISTS semi-join is per row; an uncorrelated scalar inside a correlated one runs once', () => {
26
+ expect(
27
+ perRowReads([
28
+ { id: 3, parent: 0, detail: 'SEARCH n USING INDEX assets_timeline (deleted_at=?)' },
29
+ { id: 9, parent: 0, detail: 'SEARCH s EXISTS USING INDEX assets_owner (owner_id=?)' },
30
+ ]),
31
+ ).toEqual(['SEARCH s EXISTS USING INDEX assets_owner (owner_id=?)']);
32
+ expect(
33
+ perRowReads([
34
+ ...plan('SEARCH j USING INDEX jobs_asset (asset_id=?)'),
35
+ { id: 40, parent: 35, detail: 'SCALAR SUBQUERY 3' },
36
+ { id: 41, parent: 40, detail: 'SCAN members' },
37
+ ]),
38
+ ).toEqual([]);
39
+ });
40
+
41
+ test('perEvent counts the outer read too; a compound key is not low-cardinality', () => {
42
+ const outer: PlanRow[] = [{ id: 6, parent: 0, detail: 'SEARCH a USING INDEX assets_timeline (deleted_at=?)' }];
43
+ expect(perRowReads(outer)).toEqual([]);
44
+ expect(perRowReads(outer, { perEvent: true })).toEqual(['SEARCH a USING INDEX assets_timeline (deleted_at=?)']);
45
+ expect(perRowReads([{ id: 6, parent: 0, detail: 'SEARCH al USING INDEX albums_owner (owner_id=? AND deleted_at=?)' }], { perEvent: true })).toEqual([]);
46
+ });
47
+
48
+ test("an app widens the low-cardinality rule with its own columns, or empties it", () => {
49
+ const byKind = plan('SEARCH j USING INDEX jobs_kind (kind=?)');
50
+ expect(perRowReads(byKind)).toEqual([]);
51
+ expect(perRowReads(byKind, { lowCardinality: [...LOW_CARDINALITY_COLUMNS, 'kind'] })).toEqual(['SEARCH j USING INDEX jobs_kind (kind=?)']);
52
+ expect(perRowReads(plan('SEARCH j USING INDEX jobs_queue (state=?)'), { lowCardinality: [] })).toEqual([]);
53
+ // Still a bare scan: the rule only widens what a SEARCH counts as whole.
54
+ expect(perRowReads(plan('SCAN j'), { lowCardinality: [] })).toEqual(['SCAN j']);
55
+ });
56
+ });
57
+
58
+ describe('wholeTablePages', () => {
59
+ const sorted = (outer: string): PlanRow[] => [
60
+ { id: 7, parent: 0, detail: outer },
61
+ { id: 22, parent: 0, detail: 'CORRELATED SCALAR SUBQUERY 2' },
62
+ { id: 26, parent: 22, detail: 'SEARCH fr USING COVERING INDEX sqlite_autoindex_asset_frames_1 (asset_id=?)' },
63
+ { id: 111, parent: 0, detail: 'USE TEMP B-TREE FOR ORDER BY' },
64
+ ];
65
+
66
+ test('catches a page sorted out of the whole table, and passes one keyed by its cursor or walking its index', () => {
67
+ expect(wholeTablePages(sorted('SEARCH a USING INDEX assets_timeline (deleted_at=?)'))).toEqual(['SEARCH a USING INDEX assets_timeline (deleted_at=?)']);
68
+ expect(wholeTablePages(sorted('SCAN assets'))).toEqual(['SCAN assets']);
69
+ expect(wholeTablePages(sorted('SEARCH j USING INDEX jobs_one_waiting (kind=?)'))).toEqual([]);
70
+ expect(wholeTablePages([{ id: 7, parent: 0, detail: 'SEARCH a USING INDEX sqlite_autoindex_assets_1 (id>?)' }])).toEqual([]);
71
+ expect(
72
+ wholeTablePages([
73
+ { id: 7, parent: 0, detail: 'SEARCH a USING INDEX assets_timeline (deleted_at=?)' },
74
+ { id: 9, parent: 0, detail: 'USE TEMP B-TREE FOR LAST TERM OF ORDER BY' },
75
+ ]),
76
+ ).toEqual([]);
77
+ });
78
+ });
79
+
80
+ describe('over a real plan', () => {
81
+ const open = () => {
82
+ const db = createLocalD1(new Database(':memory:'));
83
+ return db
84
+ .batch([
85
+ db.prepare('CREATE TABLE assets (id TEXT PRIMARY KEY, owner_id TEXT, taken_at INTEGER)'),
86
+ db.prepare('CREATE TABLE jobs (id TEXT PRIMARY KEY, asset_id TEXT, state TEXT)'),
87
+ db.prepare('CREATE INDEX jobs_state ON jobs (state)'),
88
+ db.prepare('CREATE INDEX jobs_asset ON jobs (asset_id, state)'),
89
+ db.prepare('CREATE INDEX assets_owner ON assets (owner_id)'),
90
+ ])
91
+ .then(() => db);
92
+ };
93
+ const PER_ROW_BY_STATE = "SELECT a.id, (SELECT COUNT(*) FROM jobs j WHERE j.state = 'queued' AND j.asset_id || '' = a.id) AS n FROM assets a";
94
+ const KEYED = "SELECT a.id, (SELECT COUNT(*) FROM jobs j WHERE j.asset_id = a.id AND j.state = 'queued') AS n FROM assets a";
95
+
96
+ test('preparedBy records each distinct statement once and gives prepare back', async () => {
97
+ const db = await open();
98
+ const prepare = db.prepare;
99
+ const seen = await preparedBy(db, async () => {
100
+ await db.prepare(KEYED).all();
101
+ await db.prepare(KEYED).all();
102
+ await db.prepare('SELECT 1').first();
103
+ });
104
+ expect(seen).toEqual([KEYED, 'SELECT 1']);
105
+ expect(db.prepare).toBe(prepare);
106
+ // …even when the run throws.
107
+ await expect(preparedBy(db, () => Promise.reject(new Error('boom')))).rejects.toThrow('boom');
108
+ expect(db.prepare).toBe(prepare);
109
+ });
110
+
111
+ test("planOffenders names a correlated search by state, and passes the one keyed by the row it asks about", async () => {
112
+ const db = await open();
113
+ expect((await planOf(db, KEYED)).some((r) => r.detail.startsWith('CORRELATED'))).toBe(true);
114
+ const offenders = await planOffenders(db, [PER_ROW_BY_STATE, KEYED]);
115
+ expect(offenders).toHaveLength(1);
116
+ expect(offenders[0]).toMatch(/^SEARCH j USING INDEX jobs_state \(state=\?\) {2}← {2}SELECT a\.id, \(SELECT COUNT/);
117
+ });
118
+
119
+ test('a page read sorted out of the whole table is named; a write is held only when asked', async () => {
120
+ const db = await open();
121
+ expect(await planOffenders(db, ['SELECT id FROM assets ORDER BY taken_at DESC LIMIT 50'])).toEqual([
122
+ 'page: SCAN assets ← SELECT id FROM assets ORDER BY taken_at DESC LIMIT 50',
123
+ ]);
124
+ const update = "UPDATE jobs SET state = 'done' WHERE asset_id || '' = ?";
125
+ expect(await planOffenders(db, [update])).toEqual([]);
126
+ expect(await planOffenders(db, [update], { writes: true })).toEqual([`SCAN jobs ← ${update}`]);
127
+ expect(await planOffenders(db, ["UPDATE jobs SET state = 'done' WHERE asset_id = ?"], { writes: true })).toEqual([]);
128
+ });
129
+ });