cursedbelt-server 4.65.1 → 4.67.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,48 @@
1
+ /**
2
+ * The ctgr chunk store as ROWS in an app's own D1 — the rendezvous every isolate shares, for an
3
+ * app that keeps no Durable Objects (forge task 4806).
4
+ *
5
+ * ── Why this exists ──────────────────────────────────────────────────────────
6
+ * A GET-only device splits a body over one chunk (1,800 bytes after gzip) into several
7
+ * `/ctgr<xx>` GETs, and {@link mountCtgrTunnel} reassembles them. A module-scope `ChunkStore` is
8
+ * one ISOLATE's memory, so chunks that reach two isolates never meet and the last one answers
9
+ * 502 `CTGR_INCOMPLETE` every time. `createDurableChunkStore` (`./ctgrChunkDurable.ts`) is one
10
+ * answer; this is the other, for an app whose `wrangler.jsonc` decided "NO durable_objects, NO
11
+ * migrations" (music): state between requests is rows in the one database it already has.
12
+ *
13
+ * ── The rows are a rendezvous, not a decoder ─────────────────────────────────
14
+ * Each chunk's raw query params are kept by `(cid, idx)`. The request whose chunk completes the
15
+ * set CLAIMS it — `DELETE … RETURNING`, so two requests completing at once cannot both deliver
16
+ * the write — and runs the ordered set through a fresh `ChunkStore`: the SAME crc/sha/size/decode
17
+ * path a Mac process uses, so nothing about verification is re-implemented here. A single-chunk
18
+ * twin (the norm) never touches the table.
19
+ *
20
+ * ── One round trip per chunk ─────────────────────────────────────────────────
21
+ * A `batch()` (atomic on D1) sweeps rows past the idle TTL, inserts this chunk, and counts its
22
+ * payload's rows. The claim is a second trip, made only by the completing chunk.
23
+ *
24
+ * ── Bounded, because it sits before the gate ─────────────────────────────────
25
+ * The tunnel is mounted ahead of the sign-in gate: the gate judges the DECODED request, so an
26
+ * anonymous caller can write chunks. `ChunkStore` caps that with `maxInFlight` payloads in memory;
27
+ * here the insert itself refuses once the whole table holds `maxRows`, and the refusal THROWS
28
+ * (→ 503 "send it again"), because a full table is the store unable to answer, not a bad payload.
29
+ * A payload over `maxPayloadBytes` is refused as a bad one (→ 400), and its rows dropped.
30
+ */
31
+ import { type ChunkStoreOpts } from 'cursedbelt-core/ctgr/chunk-store';
32
+ import type { D1LikeDatabase } from './d1/types.js';
33
+ import type { CtgrChunkSink } from './ctgrTunnel.js';
34
+ export declare const CTGR_CHUNKS_TABLE = "ctgr_chunks";
35
+ /**
36
+ * The table and its sweep index, each statement on ONE line (D1's `exec` splits on newlines).
37
+ * Idempotent, so an app's `db/schema.sql` built from it applies to a database that has it.
38
+ */
39
+ export declare const CTGR_CHUNKS_DDL: readonly string[];
40
+ export interface D1ChunkStoreOpts extends Pick<ChunkStoreOpts, 'maxPayloadBytes' | 'ttlMs' | 'now'> {
41
+ /** Rows the whole table may hold before a new chunk is refused (→ 503). Default 4,000 (~10 MB). */
42
+ maxRows?: number;
43
+ }
44
+ /**
45
+ * A {@link CtgrChunkSink} for {@link mountCtgrTunnel} whose multi-chunk partials are rows in `db`.
46
+ * Cheap to build — build it per request over the request's D1 handle.
47
+ */
48
+ export declare function createD1ChunkStore(db: D1LikeDatabase, options?: D1ChunkStoreOpts): CtgrChunkSink;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * The ctgr chunk store as ROWS in an app's own D1 — the rendezvous every isolate shares, for an
3
+ * app that keeps no Durable Objects (forge task 4806).
4
+ *
5
+ * ── Why this exists ──────────────────────────────────────────────────────────
6
+ * A GET-only device splits a body over one chunk (1,800 bytes after gzip) into several
7
+ * `/ctgr<xx>` GETs, and {@link mountCtgrTunnel} reassembles them. A module-scope `ChunkStore` is
8
+ * one ISOLATE's memory, so chunks that reach two isolates never meet and the last one answers
9
+ * 502 `CTGR_INCOMPLETE` every time. `createDurableChunkStore` (`./ctgrChunkDurable.ts`) is one
10
+ * answer; this is the other, for an app whose `wrangler.jsonc` decided "NO durable_objects, NO
11
+ * migrations" (music): state between requests is rows in the one database it already has.
12
+ *
13
+ * ── The rows are a rendezvous, not a decoder ─────────────────────────────────
14
+ * Each chunk's raw query params are kept by `(cid, idx)`. The request whose chunk completes the
15
+ * set CLAIMS it — `DELETE … RETURNING`, so two requests completing at once cannot both deliver
16
+ * the write — and runs the ordered set through a fresh `ChunkStore`: the SAME crc/sha/size/decode
17
+ * path a Mac process uses, so nothing about verification is re-implemented here. A single-chunk
18
+ * twin (the norm) never touches the table.
19
+ *
20
+ * ── One round trip per chunk ─────────────────────────────────────────────────
21
+ * A `batch()` (atomic on D1) sweeps rows past the idle TTL, inserts this chunk, and counts its
22
+ * payload's rows. The claim is a second trip, made only by the completing chunk.
23
+ *
24
+ * ── Bounded, because it sits before the gate ─────────────────────────────────
25
+ * The tunnel is mounted ahead of the sign-in gate: the gate judges the DECODED request, so an
26
+ * anonymous caller can write chunks. `ChunkStore` caps that with `maxInFlight` payloads in memory;
27
+ * here the insert itself refuses once the whole table holds `maxRows`, and the refusal THROWS
28
+ * (→ 503 "send it again"), because a full table is the store unable to answer, not a bad payload.
29
+ * A payload over `maxPayloadBytes` is refused as a bad one (→ 400), and its rows dropped.
30
+ */
31
+ import { ChunkStore } from 'cursedbelt-core/ctgr/chunk-store';
32
+ import { parseChunk } from 'cursedbelt-core/ctgr';
33
+ export const CTGR_CHUNKS_TABLE = 'ctgr_chunks';
34
+ /**
35
+ * The table and its sweep index, each statement on ONE line (D1's `exec` splits on newlines).
36
+ * Idempotent, so an app's `db/schema.sql` built from it applies to a database that has it.
37
+ */
38
+ export const CTGR_CHUNKS_DDL = [
39
+ `CREATE TABLE IF NOT EXISTS ${CTGR_CHUNKS_TABLE} ( cid TEXT NOT NULL, idx INTEGER NOT NULL, total INTEGER NOT NULL, bytes INTEGER NOT NULL, params TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (cid, idx) )`,
40
+ `CREATE INDEX IF NOT EXISTS ${CTGR_CHUNKS_TABLE}_at ON ${CTGR_CHUNKS_TABLE} (at)`,
41
+ ];
42
+ /** 2 MB: about 1,100 chunks — a bulk edit of thousands of ids is a few dozen. */
43
+ const DEFAULT_MAX_PAYLOAD_BYTES = 2 * 1024 * 1024;
44
+ const DEFAULT_TTL_MS = 30_000;
45
+ const DEFAULT_MAX_ROWS = 4_000;
46
+ /**
47
+ * A {@link CtgrChunkSink} for {@link mountCtgrTunnel} whose multi-chunk partials are rows in `db`.
48
+ * Cheap to build — build it per request over the request's D1 handle.
49
+ */
50
+ export function createD1ChunkStore(db, options = {}) {
51
+ const maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
52
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
53
+ const maxRows = options.maxRows ?? DEFAULT_MAX_ROWS;
54
+ const now = options.now ?? Date.now;
55
+ // The final decode's own caps: the size cap is this store's; its TTL never matters (one call).
56
+ const decodeOpts = { maxPayloadBytes };
57
+ return {
58
+ async add(input) {
59
+ const params = input instanceof URLSearchParams ? Object.fromEntries(input) : { ...input };
60
+ let chunk;
61
+ try {
62
+ chunk = parseChunk(params);
63
+ }
64
+ catch (error) {
65
+ return error instanceof Error ? error : new Error(String(error));
66
+ }
67
+ // One chunk needs no rendezvous — decode it here, in this isolate.
68
+ if (chunk.total === 1)
69
+ return new ChunkStore(decodeOpts).add(params);
70
+ if (chunk.payloadLength > maxPayloadBytes)
71
+ return new Error('ctgr: payload exceeds size cap');
72
+ const at = now();
73
+ const [, , counted] = await db.batch([
74
+ db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE at < ?`).bind(at - ttlMs),
75
+ db
76
+ .prepare(`INSERT OR IGNORE INTO ${CTGR_CHUNKS_TABLE} (cid, idx, total, bytes, params, at) SELECT ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE}) < ?`)
77
+ .bind(chunk.cid, chunk.index, chunk.total, chunk.bytes.length, JSON.stringify(params), at, maxRows),
78
+ db
79
+ .prepare(`SELECT COUNT(*) AS n, COALESCE(SUM(bytes), 0) AS b, MAX(idx = ?) AS mine FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`)
80
+ .bind(chunk.index, chunk.cid),
81
+ ]);
82
+ const row = counted?.results[0];
83
+ // Neither inserted now nor held from before: the table is at `maxRows`.
84
+ if (!row?.mine)
85
+ throw new Error(`ctgr: the chunk table is full (${maxRows} rows)`);
86
+ if (row.b > maxPayloadBytes) {
87
+ await db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`).bind(chunk.cid).run();
88
+ return new Error('ctgr: payload exceeds size cap');
89
+ }
90
+ if (row.n < chunk.total)
91
+ return false;
92
+ // Complete: claim the set. Only one request's DELETE can return its rows.
93
+ const claimed = await db
94
+ .prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ? RETURNING idx, params`)
95
+ .bind(chunk.cid)
96
+ .all();
97
+ if (claimed.results.length < chunk.total)
98
+ return false;
99
+ const assemble = new ChunkStore(decodeOpts);
100
+ let result = new Error('ctgr: empty chunk set');
101
+ for (const part of [...claimed.results].sort((a, b) => a.idx - b.idx)) {
102
+ result = await assemble.add(JSON.parse(part.params));
103
+ }
104
+ return result;
105
+ },
106
+ };
107
+ }
@@ -1,9 +1,10 @@
1
1
  import { type CtgrDecoded } from 'cursedbelt-core/ctgr/types';
2
2
  import type { Env, Hono } from 'hono';
3
3
  /**
4
- * What the tunnel needs of an accumulator: a {@link ChunkStore}, or the Worker's
5
- * `createDurableChunkStore` (`cursedbelt-server/ctgr-tunnel/durable`), whose partials every
6
- * isolate shares. `false` is an intermediate chunk (→ 202), an `Error` a bad payload (→ 400);
4
+ * What the tunnel needs of an accumulator: a {@link ChunkStore}, or one whose partials every
5
+ * isolate of a Worker shares — `createDurableChunkStore` (`cursedbelt-server/ctgr-tunnel/durable`,
6
+ * a Durable Object) or `createD1ChunkStore` (`cursedbelt-server/ctgr-tunnel/d1`, rows in the app's
7
+ * own D1, for an app that keeps no Durable Objects). `false` is an intermediate chunk (→ 202), an `Error` a bad payload (→ 400);
7
8
  * a THROW means the store itself could not answer (→ 503).
8
9
  */
9
10
  export interface CtgrChunkSink {
@@ -14,7 +15,8 @@ export interface CtgrTunnelOptions {
14
15
  * The accumulator for multi-chunk payloads. Share ONE across an app (the default is
15
16
  * a fresh singleton); pass your own to tune the DoS caps ({@link ChunkStore}).
16
17
  * 🔴 On a Cloudflare Worker a module-scope `ChunkStore` is one ISOLATE's memory — pass
17
- * `createDurableChunkStore(env.<BINDING>)` there, or a multi-chunk payload whose chunks
18
+ * `createDurableChunkStore(env.<BINDING>)` or `createD1ChunkStore(db)` there, built per
19
+ * request, or a multi-chunk payload whose chunks
18
20
  * land on different isolates is silently never delivered.
19
21
  */
20
22
  store?: CtgrChunkSink;
@@ -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.
@@ -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.
@@ -114,11 +119,9 @@ class FakeD1Statement {
114
119
  throw new Error(`D1_ERROR: no such column: ${column}`);
115
120
  return wire[column];
116
121
  }
122
+ /** `runSync`'s counters too: D1's `.all()` of an `INSERT … RETURNING` reports what it wrote (see 7. above). */
117
123
  async all() {
118
- assertRunnableOnD1(this.sql);
119
- const started = performance.now();
120
- const rows = this.db.query(this.sql).all(...this.params);
121
- return { results: rows.map(toWireRow), success: true, meta: this.meta(started) };
124
+ return this.runSync();
122
125
  }
123
126
  async run() {
124
127
  assertRunnableOnD1(this.sql);
@@ -151,8 +154,8 @@ class FakeD1Statement {
151
154
  const started = performance.now();
152
155
  const stmt = this.db.query(this.sql);
153
156
  const bound = this.params;
154
- // No result columns → cannot return rows, and `.run()` is the only call that reports
155
- // `changes`. This is the ordinary batch member: an INSERT, UPDATE or DELETE.
157
+ // No result columns → cannot return rows: the ordinary batch member, an INSERT, UPDATE or
158
+ // DELETE. bun's `.run().changes` is a `total_changes()` difference, trigger rows in (see 7.).
156
159
  if (stmt.columnNames.length === 0) {
157
160
  const res = stmt.run(...bound);
158
161
  return { results: [], success: true, meta: this.meta(started, res.changes, Number(res.lastInsertRowid)) };
@@ -18,6 +18,7 @@ export { createPendingWrites, type InvocationD1, type PendingWrites, perInvocati
18
18
  export { createHttpD1, D1HttpError, type HttpD1Options } from './http.js';
19
19
  export { assertBatchSize, assertWithinLimits, chunkForBind, inArray, LIMITS } from './limits.js';
20
20
  export { createLocalD1, refuseInteractiveTransaction } from './local.js';
21
+ export { LOW_CARDINALITY_COLUMNS, type PlanCheckOptions, type PlanRow, perRowReads, perRowSteps, planOf, planOffenders, preparedBy, wholeTablePages, } from './plans.js';
21
22
  export { createRemoteD1, type D1BindingLike, type D1BindingMeta, type D1BindingResult, type D1BindingStatement, } from './remote.js';
22
23
  export { classifySchedule, cronFieldCount, jobsForCron, type PortableJob, type PortableJobContext, type ScheduleVerdict, toCronTriggers, toFiveField, type TriggerShape, type WorkersPrimitive, } from './scheduling.js';
23
24
  export { D1BindError, type D1LikeBindable, type D1LikeDatabase, type D1LikeMeta, type D1LikeResult, type D1LikeRow, type D1LikeStatement, type D1LikeValue, D1LimitError, D1UnsupportedError, } from './types.js';
@@ -37,6 +37,7 @@ export { createPendingWrites, perInvocation } from './invocation.js';
37
37
  export { createHttpD1, D1HttpError } from './http.js';
38
38
  export { assertBatchSize, assertWithinLimits, chunkForBind, inArray, LIMITS } from './limits.js';
39
39
  export { createLocalD1, refuseInteractiveTransaction } from './local.js';
40
+ export { LOW_CARDINALITY_COLUMNS, perRowReads, perRowSteps, planOf, planOffenders, preparedBy, wholeTablePages, } from './plans.js';
40
41
  export { createRemoteD1, } from './remote.js';
41
42
  export { classifySchedule, cronFieldCount, jobsForCron, toCronTriggers, toFiveField, } from './scheduling.js';
42
43
  export { D1BindError, D1LimitError, D1UnsupportedError, } from './types.js';
@@ -0,0 +1,70 @@
1
+ /**
2
+ * `cursedbelt-server/d1` plan checks — an app's route tests hold its reads to the archive's size, not
3
+ * the fixture's.
4
+ *
5
+ * Every statement a route prepares is put through `EXPLAIN QUERY PLAN`. A subquery that runs once
6
+ * per outer row (`CORRELATED`, or an `EXISTS` semi-join) must find its rows by the row it is asked
7
+ * about: a `SCAN` there, or a search keyed by a low-cardinality column alone (a job's state, "not
8
+ * deleted", the owner), reads the whole table again for every row. That is what reset photos' D1 on
9
+ * 2026-11-05 (forge task 4467): a correlated search of `jobs_queue` by state, ~26,000 rows, for each of
10
+ * 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
11
+ * LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
12
+ *
13
+ * ```ts
14
+ * const statements = await preparedBy(db, () => app.request('/api/heavy'));
15
+ * expect(await planOffenders(db, statements)).toEqual([]);
16
+ * ```
17
+ *
18
+ * Lifted from photos (`src/server/knowledge/plans.test.ts`, forge task 4595), which holds the cases.
19
+ */
20
+ import type { D1LikeDatabase } from './types.js';
21
+ /** One row of `EXPLAIN QUERY PLAN`. */
22
+ export interface PlanRow {
23
+ id: number;
24
+ parent: number;
25
+ detail: string;
26
+ }
27
+ /**
28
+ * The columns a search keyed by alone still reads the table whole: one value matches most rows.
29
+ * An app widens it with its own (`[...LOW_CARDINALITY_COLUMNS, 'kind']`).
30
+ */
31
+ export declare const LOW_CARDINALITY_COLUMNS: readonly string[];
32
+ export interface PlanCheckOptions {
33
+ /** Replaces {@link LOW_CARDINALITY_COLUMNS}. */
34
+ lowCardinality?: readonly string[];
35
+ }
36
+ /** The steps of `plan` that run once per outer row: inside a correlated subquery, or an `EXISTS` semi-join. */
37
+ export declare function perRowSteps(plan: readonly PlanRow[]): PlanRow[];
38
+ /**
39
+ * The steps of `plan` that re-read a table for every outer row — or, with `perEvent`, every step
40
+ * that reads a table whole (a statement that itself runs once per event, so ANY step of it is per row).
41
+ */
42
+ export declare function perRowReads(plan: readonly PlanRow[], opts?: PlanCheckOptions & {
43
+ perEvent?: boolean;
44
+ }): string[];
45
+ /**
46
+ * The outer steps of a paged read that reads its table whole and then sorts every row it kept (`USE
47
+ * TEMP B-TREE FOR ORDER BY`) to hand back its LIMIT. A read keyed by its cursor (`(id>?)`), or walking
48
+ * an index in its own order (only `LAST TERM OF ORDER BY` sorted), stops at its page.
49
+ */
50
+ export declare function wholeTablePages(plan: readonly PlanRow[], opts?: PlanCheckOptions): string[];
51
+ /**
52
+ * Every distinct statement `run` prepares on `db`, in first-prepared order. `db.prepare` is restored
53
+ * after. Any handle with a `prepare(sql)` will do — an app's own async wrapper as well as this seam.
54
+ */
55
+ export declare function preparedBy(db: {
56
+ prepare(sql: string): unknown;
57
+ }, run: () => Promise<unknown>): Promise<string[]>;
58
+ /** `EXPLAIN QUERY PLAN` of `sql` on `db` — the app's own schema, so its indexes decide. */
59
+ export declare function planOf(db: D1LikeDatabase, sql: string): Promise<PlanRow[]>;
60
+ /**
61
+ * Every statement in `statements` that re-reads a table per row, or pages out of a sorted whole table
62
+ * — one line each, naming the step and the statement. `[]` is the pass.
63
+ *
64
+ * Reads are held to {@link perRowReads} and {@link wholeTablePages}. With `writes`, every INSERT,
65
+ * UPDATE, DELETE and REPLACE is held as `perEvent`: a write runs once per request or event, so ANY step
66
+ * of it that reads its table whole is the archive per call (desk's `UPDATE` that read 1.5 M rows).
67
+ */
68
+ export declare function planOffenders(db: D1LikeDatabase, statements: readonly string[], opts?: PlanCheckOptions & {
69
+ writes?: boolean;
70
+ }): Promise<string[]>;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * `cursedbelt-server/d1` plan checks — an app's route tests hold its reads to the archive's size, not
3
+ * the fixture's.
4
+ *
5
+ * Every statement a route prepares is put through `EXPLAIN QUERY PLAN`. A subquery that runs once
6
+ * per outer row (`CORRELATED`, or an `EXISTS` semi-join) must find its rows by the row it is asked
7
+ * about: a `SCAN` there, or a search keyed by a low-cardinality column alone (a job's state, "not
8
+ * deleted", the owner), reads the whole table again for every row. That is what reset photos' D1 on
9
+ * 2026-11-05 (forge task 4467): a correlated search of `jobs_queue` by state, ~26,000 rows, for each of
10
+ * 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
11
+ * LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
12
+ *
13
+ * ```ts
14
+ * const statements = await preparedBy(db, () => app.request('/api/heavy'));
15
+ * expect(await planOffenders(db, statements)).toEqual([]);
16
+ * ```
17
+ *
18
+ * Lifted from photos (`src/server/knowledge/plans.test.ts`, forge task 4595), which holds the cases.
19
+ */
20
+ /**
21
+ * The columns a search keyed by alone still reads the table whole: one value matches most rows.
22
+ * An app widens it with its own (`[...LOW_CARDINALITY_COLUMNS, 'kind']`).
23
+ */
24
+ export const LOW_CARDINALITY_COLUMNS = ['state', 'status', 'deleted_at', 'owner_id'];
25
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
26
+ const lowCardinalityRule = (columns) => columns.length === 0 ? null : new RegExp(` USING (?:COVERING )?INDEX \\S+ \\((?:${columns.map(escapeRegExp).join('|')})=\\?\\)`);
27
+ /** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column alone. */
28
+ function readsWhole(detail, derived, low) {
29
+ const bareScan = /^SCAN (?!CONSTANT ROW)/.test(detail) &&
30
+ !detail.includes(' VIRTUAL TABLE ') &&
31
+ !derived.has(detail.split(' ')[1] ?? '') &&
32
+ !/ USING (?:COVERING )?INDEX /.test(detail);
33
+ return bareScan || (low?.test(detail) ?? false);
34
+ }
35
+ /** What a subquery made (`MATERIALIZE hit`, `CO-ROUTINE (subquery-1)`): its rows were counted where they were made. */
36
+ const derivedOf = (plan) => new Set(plan.flatMap((r) => /^(?:MATERIALIZE|CO-ROUTINE) (\S+)/.exec(r.detail)?.[1] ?? []));
37
+ /** The steps of `plan` that run once per outer row: inside a correlated subquery, or an `EXISTS` semi-join. */
38
+ export function perRowSteps(plan) {
39
+ const byId = new Map(plan.map((r) => [r.id, r]));
40
+ // The nearest subquery around a step decides: an uncorrelated one inside a correlated one is computed once.
41
+ const correlated = (row) => {
42
+ // Newer SQLite runs `EXISTS (…)` as a semi-join, a loop inside the outer one: `SEARCH s EXISTS USING …`.
43
+ if (/^SEARCH \S+ EXISTS /.test(row.detail))
44
+ return true;
45
+ for (let p = byId.get(row.parent); p; p = byId.get(p.parent)) {
46
+ if (/SUBQUERY|^CORRELATED/.test(p.detail))
47
+ return p.detail.startsWith('CORRELATED');
48
+ }
49
+ return false;
50
+ };
51
+ return plan.filter(correlated);
52
+ }
53
+ /**
54
+ * The steps of `plan` that re-read a table for every outer row — or, with `perEvent`, every step
55
+ * that reads a table whole (a statement that itself runs once per event, so ANY step of it is per row).
56
+ */
57
+ export function perRowReads(plan, opts = {}) {
58
+ const derived = derivedOf(plan);
59
+ const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
60
+ return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
61
+ }
62
+ /**
63
+ * The outer steps of a paged read that reads its table whole and then sorts every row it kept (`USE
64
+ * TEMP B-TREE FOR ORDER BY`) to hand back its LIMIT. A read keyed by its cursor (`(id>?)`), or walking
65
+ * an index in its own order (only `LAST TERM OF ORDER BY` sorted), stops at its page.
66
+ */
67
+ export function wholeTablePages(plan, opts = {}) {
68
+ const outer = plan.filter((r) => r.parent === 0);
69
+ if (!outer.some((r) => r.detail === 'USE TEMP B-TREE FOR ORDER BY'))
70
+ return [];
71
+ const derived = derivedOf(plan);
72
+ const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
73
+ return outer.filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
74
+ }
75
+ /**
76
+ * Every distinct statement `run` prepares on `db`, in first-prepared order. `db.prepare` is restored
77
+ * after. Any handle with a `prepare(sql)` will do — an app's own async wrapper as well as this seam.
78
+ */
79
+ export async function preparedBy(db, run) {
80
+ const seen = new Set();
81
+ // Put back exactly what was there: an own property as it was, a prototype method by removing the shadow.
82
+ const own = Object.hasOwn(db, 'prepare');
83
+ const original = db.prepare;
84
+ const real = original.bind(db);
85
+ db.prepare = (sql) => {
86
+ seen.add(sql);
87
+ return real(sql);
88
+ };
89
+ try {
90
+ await run();
91
+ }
92
+ finally {
93
+ if (own)
94
+ db.prepare = original;
95
+ else
96
+ delete db.prepare;
97
+ }
98
+ return [...seen];
99
+ }
100
+ /** `EXPLAIN QUERY PLAN` of `sql` on `db` — the app's own schema, so its indexes decide. */
101
+ export async function planOf(db, sql) {
102
+ return (await db.prepare(`EXPLAIN QUERY PLAN ${sql}`).all()).results;
103
+ }
104
+ /**
105
+ * Every statement in `statements` that re-reads a table per row, or pages out of a sorted whole table
106
+ * — one line each, naming the step and the statement. `[]` is the pass.
107
+ *
108
+ * Reads are held to {@link perRowReads} and {@link wholeTablePages}. With `writes`, every INSERT,
109
+ * UPDATE, DELETE and REPLACE is held as `perEvent`: a write runs once per request or event, so ANY step
110
+ * of it that reads its table whole is the archive per call (desk's `UPDATE` that read 1.5 M rows).
111
+ */
112
+ export async function planOffenders(db, statements, opts = {}) {
113
+ const offenders = [];
114
+ for (const sql of statements) {
115
+ const write = /^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i.test(sql);
116
+ if (write ? !opts.writes : !/^\s*(?:SELECT|WITH)\b/i.test(sql))
117
+ continue;
118
+ const plan = await planOf(db, sql);
119
+ const where = sql.replace(/\s+/g, ' ').trim().slice(0, 160);
120
+ for (const step of perRowReads(plan, { ...opts, perEvent: write }))
121
+ offenders.push(`${step} ← ${where}`);
122
+ if (!write && /\bLIMIT\b/i.test(sql))
123
+ for (const step of wholeTablePages(plan, opts))
124
+ offenders.push(`page: ${step} ← ${where}`);
125
+ }
126
+ return offenders;
127
+ }
@@ -1,6 +1,13 @@
1
1
  /** The text embedder for both sides: a document and a query. Measured by photos, 2026-11-05. */
2
2
  export declare const EMBED_MODEL = "@cf/baai/bge-m3";
3
3
  export declare const EMBED_DIMS = 1024;
4
+ /**
5
+ * The image engines' widths — photos' Mac writes them, family's door refuses any other length, so
6
+ * they live once, here (forge task 4828). ArcFace: 512 float32, little-endian.
7
+ */
8
+ export declare const FACE_DIMS = 512;
9
+ /** The image region embedder: 1536 floats, sent as float16. */
10
+ export declare const REGION_DIMS = 1536;
4
11
  /** The cross-encoder that reads the query beside each candidate's document. */
5
12
  export declare const RERANK_MODEL = "@cf/baai/bge-reranker-base";
6
13
  /**
@@ -22,6 +22,13 @@
22
22
  /** The text embedder for both sides: a document and a query. Measured by photos, 2026-11-05. */
23
23
  export const EMBED_MODEL = '@cf/baai/bge-m3';
24
24
  export const EMBED_DIMS = 1024;
25
+ /**
26
+ * The image engines' widths — photos' Mac writes them, family's door refuses any other length, so
27
+ * they live once, here (forge task 4828). ArcFace: 512 float32, little-endian.
28
+ */
29
+ export const FACE_DIMS = 512;
30
+ /** The image region embedder: 1536 floats, sent as float16. */
31
+ export const REGION_DIMS = 1536;
25
32
  /** The cross-encoder that reads the query beside each candidate's document. */
26
33
  export const RERANK_MODEL = '@cf/baai/bge-reranker-base';
27
34
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.65.1",
3
+ "version": "4.67.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
@@ -72,6 +72,12 @@
72
72
  "source": "./src/server/ctgrChunkDurable.ts",
73
73
  "import": "./dist/server/ctgrChunkDurable.js"
74
74
  },
75
+ "./ctgr-tunnel/d1": {
76
+ "types": "./dist/server/ctgrChunkD1.d.ts",
77
+ "bun": "./src/server/ctgrChunkD1.ts",
78
+ "source": "./src/server/ctgrChunkD1.ts",
79
+ "import": "./dist/server/ctgrChunkD1.js"
80
+ },
75
81
  "./analytics": {
76
82
  "types": "./dist/server/analytics/index.d.ts",
77
83
  "bun": "./src/server/analytics/index.ts",
@@ -429,7 +435,7 @@
429
435
  "@node-rs/argon2": "^2.0.2",
430
436
  "@types/bun": "^1.3.14",
431
437
  "@types/node": "^24",
432
- "cursedbelt": "^5.122.2",
438
+ "cursedbelt": "^5.135.1",
433
439
  "hono": "4.12.28",
434
440
  "kysely": "^0.28.17",
435
441
  "kysely-bun-sqlite": "^0.4.0",
@@ -0,0 +1,177 @@
1
+ import { Database } from 'bun:sqlite';
2
+ import { describe, expect, test } from 'bun:test';
3
+ import { encodeRequest } from 'cursedbelt-core/ctgr';
4
+ import { ChunkStore } from 'cursedbelt-core/ctgr/chunk-store';
5
+ import { Hono } from 'hono';
6
+ import { CTGR_CHUNKS_DDL, CTGR_CHUNKS_TABLE, createD1ChunkStore } from './ctgrChunkD1.js';
7
+ import { mountCtgrTunnel } from './ctgrTunnel.js';
8
+ import { createLocalD1 } from './d1/local.js';
9
+ import type { D1LikeDatabase } from './d1/types.js';
10
+
11
+ /** One database, as D1 is: every isolate's handle reaches the same rows. */
12
+ function database() {
13
+ const sqlite = new Database(':memory:');
14
+ for (const ddl of CTGR_CHUNKS_DDL) sqlite.run(ddl);
15
+ const rows = (): number => (sqlite.query(`SELECT COUNT(*) AS n FROM ${CTGR_CHUNKS_TABLE}`).get() as { n: number }).n;
16
+ return { handle: () => createLocalD1(sqlite), rows };
17
+ }
18
+
19
+ const bigBody = { note: 'x'.repeat(9000), n: 7 };
20
+
21
+ async function multiChunk() {
22
+ // Incompressible enough to stay multi-chunk after gzip.
23
+ const random = Array.from({ length: 6000 }, (_, i) => ((i * 2654435761) >>> 0).toString(36)).join('');
24
+ const { chunks } = await encodeRequest('POST', '/api/v1/notes', { ...bigBody, random });
25
+ expect(chunks.length).toBeGreaterThan(2);
26
+ return { chunks, body: { ...bigBody, random } };
27
+ }
28
+
29
+ const bodyOf = (result: unknown): unknown =>
30
+ result && typeof result === 'object' && 'body' in result ? (result as { body: unknown }).body : null;
31
+
32
+ describe('createD1ChunkStore — two isolates, one database', () => {
33
+ test('chunks alternating between two isolates reassemble, in any order, and leave no rows', async () => {
34
+ const db = database();
35
+ const isolates = [createD1ChunkStore(db.handle()), createD1ChunkStore(db.handle())];
36
+ const { chunks, body } = await multiChunk();
37
+ const order = chunks.map((_, i) => i).reverse();
38
+ const results = [];
39
+ for (const [n, i] of order.entries()) results.push(await isolates[n % 2].add(chunks[i].params));
40
+ for (const intermediate of results.slice(0, -1)) expect(intermediate).toBe(false);
41
+ expect(results.at(-1)).not.toBeInstanceOf(Error);
42
+ expect(bodyOf(results.at(-1))).toEqual(body);
43
+ expect(db.rows()).toBe(0);
44
+ });
45
+
46
+ test('🔴 the failure it replaces: two per-isolate ChunkStores never finish the payload', async () => {
47
+ const isolates = [new ChunkStore(), new ChunkStore()];
48
+ const { chunks } = await multiChunk();
49
+ const results = [];
50
+ for (const [n, chunk] of chunks.entries()) results.push(await isolates[n % 2].add(chunk.params));
51
+ expect(results.every((r) => r === false)).toBe(true);
52
+ });
53
+
54
+ test('a single-chunk twin is decoded inline and never writes a row', async () => {
55
+ const db = database();
56
+ const { chunks } = await encodeRequest('PUT', '/api/v1/tags/a', { name: 'fast' });
57
+ expect(chunks.length).toBe(1);
58
+ expect(bodyOf(await createD1ChunkStore(db.handle()).add(chunks[0].params))).toEqual({ name: 'fast' });
59
+ expect(db.rows()).toBe(0);
60
+ });
61
+
62
+ test('a chunk sent twice counts once', async () => {
63
+ const db = database();
64
+ const store = createD1ChunkStore(db.handle());
65
+ const { chunks, body } = await multiChunk();
66
+ expect(await store.add(chunks[0].params)).toBe(false);
67
+ expect(await store.add(chunks[0].params)).toBe(false);
68
+ for (const chunk of chunks.slice(1, -1)) expect(await store.add(chunk.params)).toBe(false);
69
+ expect(bodyOf(await store.add(chunks.at(-1)!.params))).toEqual(body);
70
+ });
71
+
72
+ test('🔴 two requests completing the set at once deliver it ONCE — the claim is one DELETE', async () => {
73
+ const db = database();
74
+ const { chunks, body } = await multiChunk();
75
+ const seed = createD1ChunkStore(db.handle());
76
+ for (const chunk of chunks.slice(0, -1)) await seed.add(chunk.params);
77
+ // Both requests have counted a COMPLETE set before either claims it: each one's batch is
78
+ // held until the other's has run too — the interleaving two isolates can really make.
79
+ let arrived = 0;
80
+ let release = (): void => undefined;
81
+ const bothCounted = new Promise<void>((resolve) => {
82
+ release = resolve;
83
+ });
84
+ const held = (): D1LikeDatabase => {
85
+ const real = db.handle();
86
+ return {
87
+ ...real,
88
+ prepare: (sql) => real.prepare(sql),
89
+ batch: async (statements) => {
90
+ const results = await real.batch(statements);
91
+ if (++arrived === 2) release();
92
+ await bothCounted;
93
+ return results as never;
94
+ },
95
+ };
96
+ };
97
+ const isolates = [createD1ChunkStore(held()), createD1ChunkStore(held())];
98
+ const last = chunks.at(-1)!.params;
99
+ const both = await Promise.all([isolates[0].add(last), isolates[1].add(last)]);
100
+ expect(both.filter((r) => r === false)).toHaveLength(1);
101
+ expect(both.map(bodyOf).filter(Boolean)).toEqual([body]);
102
+ });
103
+
104
+ test('a partial left past the idle TTL is swept by the next multi-chunk twin', async () => {
105
+ const db = database();
106
+ let clock = 1_000_000;
107
+ const store = createD1ChunkStore(db.handle(), { now: () => clock, ttlMs: 30_000 });
108
+ const first = await multiChunk();
109
+ await store.add(first.chunks[0].params);
110
+ expect(db.rows()).toBe(1);
111
+ clock += 31_000;
112
+ const second = await encodeRequest('POST', '/api/v1/other', {
113
+ pad: Array.from({ length: 6000 }, (_, i) => ((i * 40503) >>> 0).toString(36)).join(''),
114
+ });
115
+ await store.add(second.chunks[0].params);
116
+ expect(db.rows()).toBe(1);
117
+ // The swept payload cannot complete any more: its first chunk is gone.
118
+ for (const chunk of first.chunks.slice(1)) expect(await store.add(chunk.params)).toBe(false);
119
+ });
120
+
121
+ test('a full table refuses by THROWING — the tunnel answers 503 "send it again", nothing half-kept', async () => {
122
+ const db = database();
123
+ const { chunks } = await multiChunk();
124
+ const store = createD1ChunkStore(db.handle(), { maxRows: 1 });
125
+ expect(await store.add(chunks[0].params)).toBe(false);
126
+ await expect(store.add(chunks[1].params)).rejects.toThrow(/chunk table is full/);
127
+ // A chunk already held is not refused by the cap it counts toward.
128
+ expect(await store.add(chunks[0].params)).toBe(false);
129
+ });
130
+
131
+ test('a payload over its size cap is refused as a bad one, and its rows dropped', async () => {
132
+ const db = database();
133
+ const { chunks } = await multiChunk();
134
+ const store = createD1ChunkStore(db.handle(), { maxPayloadBytes: 1024 });
135
+ expect(await store.add(chunks[0].params)).toBeInstanceOf(Error);
136
+ expect(db.rows()).toBe(0);
137
+ });
138
+ });
139
+
140
+ describe('createD1ChunkStore behind mountCtgrTunnel', () => {
141
+ /** The app a Worker builds per request: a fresh store over that request's handle, each time. */
142
+ function isolate(db: ReturnType<typeof database>, seen: unknown[]) {
143
+ const app = new Hono();
144
+ mountCtgrTunnel(app, { store: createD1ChunkStore(db.handle()) });
145
+ app.post('/api/v1/notes', async (c) => {
146
+ seen.push(await c.req.json());
147
+ return c.json({ saved: true }, 201);
148
+ });
149
+ return app;
150
+ }
151
+
152
+ test('a 3+-chunk twin through two isolates reaches the real route once, at its real method', async () => {
153
+ const db = database();
154
+ const seen: unknown[] = [];
155
+ const apps = [isolate(db, seen), isolate(db, seen)];
156
+ const { chunks, body } = await multiChunk();
157
+ const statuses: number[] = [];
158
+ for (const [n, chunk] of chunks.entries()) {
159
+ const response = await apps[n % 2].fetch(new Request(`https://music.test${chunk.url}`));
160
+ statuses.push(response.status);
161
+ }
162
+ expect(statuses.slice(0, -1).every((s) => s === 202)).toBe(true);
163
+ expect(statuses.at(-1)).toBe(201);
164
+ expect(seen).toEqual([body]);
165
+ });
166
+
167
+ test('a full table answers 503 CTGR_STORE_UNAVAILABLE, not 202', async () => {
168
+ const db = database();
169
+ const app = new Hono();
170
+ mountCtgrTunnel(app, { store: createD1ChunkStore(db.handle(), { maxRows: 1 }) });
171
+ const { chunks } = await multiChunk();
172
+ expect((await app.fetch(new Request(`https://music.test${chunks[0].url}`))).status).toBe(202);
173
+ const refused = await app.fetch(new Request(`https://music.test${chunks[1].url}`));
174
+ expect(refused.status).toBe(503);
175
+ expect(((await refused.json()) as { code: string }).code).toBe('CTGR_STORE_UNAVAILABLE');
176
+ });
177
+ });
@@ -0,0 +1,127 @@
1
+ /**
2
+ * The ctgr chunk store as ROWS in an app's own D1 — the rendezvous every isolate shares, for an
3
+ * app that keeps no Durable Objects (forge task 4806).
4
+ *
5
+ * ── Why this exists ──────────────────────────────────────────────────────────
6
+ * A GET-only device splits a body over one chunk (1,800 bytes after gzip) into several
7
+ * `/ctgr<xx>` GETs, and {@link mountCtgrTunnel} reassembles them. A module-scope `ChunkStore` is
8
+ * one ISOLATE's memory, so chunks that reach two isolates never meet and the last one answers
9
+ * 502 `CTGR_INCOMPLETE` every time. `createDurableChunkStore` (`./ctgrChunkDurable.ts`) is one
10
+ * answer; this is the other, for an app whose `wrangler.jsonc` decided "NO durable_objects, NO
11
+ * migrations" (music): state between requests is rows in the one database it already has.
12
+ *
13
+ * ── The rows are a rendezvous, not a decoder ─────────────────────────────────
14
+ * Each chunk's raw query params are kept by `(cid, idx)`. The request whose chunk completes the
15
+ * set CLAIMS it — `DELETE … RETURNING`, so two requests completing at once cannot both deliver
16
+ * the write — and runs the ordered set through a fresh `ChunkStore`: the SAME crc/sha/size/decode
17
+ * path a Mac process uses, so nothing about verification is re-implemented here. A single-chunk
18
+ * twin (the norm) never touches the table.
19
+ *
20
+ * ── One round trip per chunk ─────────────────────────────────────────────────
21
+ * A `batch()` (atomic on D1) sweeps rows past the idle TTL, inserts this chunk, and counts its
22
+ * payload's rows. The claim is a second trip, made only by the completing chunk.
23
+ *
24
+ * ── Bounded, because it sits before the gate ─────────────────────────────────
25
+ * The tunnel is mounted ahead of the sign-in gate: the gate judges the DECODED request, so an
26
+ * anonymous caller can write chunks. `ChunkStore` caps that with `maxInFlight` payloads in memory;
27
+ * here the insert itself refuses once the whole table holds `maxRows`, and the refusal THROWS
28
+ * (→ 503 "send it again"), because a full table is the store unable to answer, not a bad payload.
29
+ * A payload over `maxPayloadBytes` is refused as a bad one (→ 400), and its rows dropped.
30
+ */
31
+ import { ChunkStore, type ChunkStoreOpts } from 'cursedbelt-core/ctgr/chunk-store';
32
+ import { parseChunk, type ParsedChunk } from 'cursedbelt-core/ctgr';
33
+ import type { CtgrDecoded } from 'cursedbelt-core/ctgr/types';
34
+ import type { D1LikeDatabase } from './d1/types.js';
35
+ import type { CtgrChunkSink } from './ctgrTunnel.js';
36
+
37
+ export const CTGR_CHUNKS_TABLE = 'ctgr_chunks';
38
+
39
+ /**
40
+ * The table and its sweep index, each statement on ONE line (D1's `exec` splits on newlines).
41
+ * Idempotent, so an app's `db/schema.sql` built from it applies to a database that has it.
42
+ */
43
+ export const CTGR_CHUNKS_DDL: readonly string[] = [
44
+ `CREATE TABLE IF NOT EXISTS ${CTGR_CHUNKS_TABLE} ( cid TEXT NOT NULL, idx INTEGER NOT NULL, total INTEGER NOT NULL, bytes INTEGER NOT NULL, params TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (cid, idx) )`,
45
+ `CREATE INDEX IF NOT EXISTS ${CTGR_CHUNKS_TABLE}_at ON ${CTGR_CHUNKS_TABLE} (at)`,
46
+ ];
47
+
48
+ export interface D1ChunkStoreOpts extends Pick<ChunkStoreOpts, 'maxPayloadBytes' | 'ttlMs' | 'now'> {
49
+ /** Rows the whole table may hold before a new chunk is refused (→ 503). Default 4,000 (~10 MB). */
50
+ maxRows?: number;
51
+ }
52
+
53
+ /** 2 MB: about 1,100 chunks — a bulk edit of thousands of ids is a few dozen. */
54
+ const DEFAULT_MAX_PAYLOAD_BYTES = 2 * 1024 * 1024;
55
+ const DEFAULT_TTL_MS = 30_000;
56
+ const DEFAULT_MAX_ROWS = 4_000;
57
+
58
+ interface CountRow {
59
+ n: number;
60
+ b: number;
61
+ mine: number | null;
62
+ }
63
+
64
+ /**
65
+ * A {@link CtgrChunkSink} for {@link mountCtgrTunnel} whose multi-chunk partials are rows in `db`.
66
+ * Cheap to build — build it per request over the request's D1 handle.
67
+ */
68
+ export function createD1ChunkStore(db: D1LikeDatabase, options: D1ChunkStoreOpts = {}): CtgrChunkSink {
69
+ const maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
70
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
71
+ const maxRows = options.maxRows ?? DEFAULT_MAX_ROWS;
72
+ const now = options.now ?? Date.now;
73
+ // The final decode's own caps: the size cap is this store's; its TTL never matters (one call).
74
+ const decodeOpts: ChunkStoreOpts = { maxPayloadBytes };
75
+
76
+ return {
77
+ async add(input) {
78
+ const params = input instanceof URLSearchParams ? Object.fromEntries(input) : { ...input };
79
+ let chunk: ParsedChunk;
80
+ try {
81
+ chunk = parseChunk(params);
82
+ } catch (error) {
83
+ return error instanceof Error ? error : new Error(String(error));
84
+ }
85
+ // One chunk needs no rendezvous — decode it here, in this isolate.
86
+ if (chunk.total === 1) return new ChunkStore(decodeOpts).add(params);
87
+ if (chunk.payloadLength > maxPayloadBytes) return new Error('ctgr: payload exceeds size cap');
88
+
89
+ const at = now();
90
+ const [, , counted] = await db.batch<CountRow>([
91
+ db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE at < ?`).bind(at - ttlMs),
92
+ db
93
+ .prepare(
94
+ `INSERT OR IGNORE INTO ${CTGR_CHUNKS_TABLE} (cid, idx, total, bytes, params, at) SELECT ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE}) < ?`,
95
+ )
96
+ .bind(chunk.cid, chunk.index, chunk.total, chunk.bytes.length, JSON.stringify(params), at, maxRows),
97
+ db
98
+ .prepare(
99
+ `SELECT COUNT(*) AS n, COALESCE(SUM(bytes), 0) AS b, MAX(idx = ?) AS mine FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`,
100
+ )
101
+ .bind(chunk.index, chunk.cid),
102
+ ]);
103
+ const row = counted?.results[0];
104
+ // Neither inserted now nor held from before: the table is at `maxRows`.
105
+ if (!row?.mine) throw new Error(`ctgr: the chunk table is full (${maxRows} rows)`);
106
+ if (row.b > maxPayloadBytes) {
107
+ await db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`).bind(chunk.cid).run();
108
+ return new Error('ctgr: payload exceeds size cap');
109
+ }
110
+ if (row.n < chunk.total) return false;
111
+
112
+ // Complete: claim the set. Only one request's DELETE can return its rows.
113
+ const claimed = await db
114
+ .prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ? RETURNING idx, params`)
115
+ .bind(chunk.cid)
116
+ .all<{ idx: number; params: string }>();
117
+ if (claimed.results.length < chunk.total) return false;
118
+
119
+ const assemble = new ChunkStore(decodeOpts);
120
+ let result: CtgrDecoded | false | Error = new Error('ctgr: empty chunk set');
121
+ for (const part of [...claimed.results].sort((a, b) => a.idx - b.idx)) {
122
+ result = await assemble.add(JSON.parse(part.params) as Record<string, string>);
123
+ }
124
+ return result;
125
+ },
126
+ };
127
+ }
@@ -29,9 +29,10 @@ const isCtgrParam = (key: string): boolean =>
29
29
  key === '_d' || key === '_sha' || key.startsWith('_c');
30
30
 
31
31
  /**
32
- * What the tunnel needs of an accumulator: a {@link ChunkStore}, or the Worker's
33
- * `createDurableChunkStore` (`cursedbelt-server/ctgr-tunnel/durable`), whose partials every
34
- * isolate shares. `false` is an intermediate chunk (→ 202), an `Error` a bad payload (→ 400);
32
+ * What the tunnel needs of an accumulator: a {@link ChunkStore}, or one whose partials every
33
+ * isolate of a Worker shares — `createDurableChunkStore` (`cursedbelt-server/ctgr-tunnel/durable`,
34
+ * a Durable Object) or `createD1ChunkStore` (`cursedbelt-server/ctgr-tunnel/d1`, rows in the app's
35
+ * own D1, for an app that keeps no Durable Objects). `false` is an intermediate chunk (→ 202), an `Error` a bad payload (→ 400);
35
36
  * a THROW means the store itself could not answer (→ 503).
36
37
  */
37
38
  export interface CtgrChunkSink {
@@ -43,7 +44,8 @@ export interface CtgrTunnelOptions {
43
44
  * The accumulator for multi-chunk payloads. Share ONE across an app (the default is
44
45
  * a fresh singleton); pass your own to tune the DoS caps ({@link ChunkStore}).
45
46
  * 🔴 On a Cloudflare Worker a module-scope `ChunkStore` is one ISOLATE's memory — pass
46
- * `createDurableChunkStore(env.<BINDING>)` there, or a multi-chunk payload whose chunks
47
+ * `createDurableChunkStore(env.<BINDING>)` or `createD1ChunkStore(db)` there, built per
48
+ * request, or a multi-chunk payload whose chunks
47
49
  * land on different isolates is silently never delivered.
48
50
  */
49
51
  store?: CtgrChunkSink;
@@ -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
+ });
@@ -0,0 +1,148 @@
1
+ /**
2
+ * `cursedbelt-server/d1` plan checks — an app's route tests hold its reads to the archive's size, not
3
+ * the fixture's.
4
+ *
5
+ * Every statement a route prepares is put through `EXPLAIN QUERY PLAN`. A subquery that runs once
6
+ * per outer row (`CORRELATED`, or an `EXISTS` semi-join) must find its rows by the row it is asked
7
+ * about: a `SCAN` there, or a search keyed by a low-cardinality column alone (a job's state, "not
8
+ * deleted", the owner), reads the whole table again for every row. That is what reset photos' D1 on
9
+ * 2026-11-05 (forge task 4467): a correlated search of `jobs_queue` by state, ~26,000 rows, for each of
10
+ * 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
11
+ * LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
12
+ *
13
+ * ```ts
14
+ * const statements = await preparedBy(db, () => app.request('/api/heavy'));
15
+ * expect(await planOffenders(db, statements)).toEqual([]);
16
+ * ```
17
+ *
18
+ * Lifted from photos (`src/server/knowledge/plans.test.ts`, forge task 4595), which holds the cases.
19
+ */
20
+
21
+ import type { D1LikeDatabase } from './types.js';
22
+
23
+ /** One row of `EXPLAIN QUERY PLAN`. */
24
+ export interface PlanRow {
25
+ id: number;
26
+ parent: number;
27
+ detail: string;
28
+ }
29
+
30
+ /**
31
+ * The columns a search keyed by alone still reads the table whole: one value matches most rows.
32
+ * An app widens it with its own (`[...LOW_CARDINALITY_COLUMNS, 'kind']`).
33
+ */
34
+ export const LOW_CARDINALITY_COLUMNS: readonly string[] = ['state', 'status', 'deleted_at', 'owner_id'];
35
+
36
+ export interface PlanCheckOptions {
37
+ /** Replaces {@link LOW_CARDINALITY_COLUMNS}. */
38
+ lowCardinality?: readonly string[];
39
+ }
40
+
41
+ const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
42
+ const lowCardinalityRule = (columns: readonly string[]): RegExp | null =>
43
+ columns.length === 0 ? null : new RegExp(` USING (?:COVERING )?INDEX \\S+ \\((?:${columns.map(escapeRegExp).join('|')})=\\?\\)`);
44
+
45
+ /** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column alone. */
46
+ function readsWhole(detail: string, derived: ReadonlySet<string>, low: RegExp | null): boolean {
47
+ const bareScan =
48
+ /^SCAN (?!CONSTANT ROW)/.test(detail) &&
49
+ !detail.includes(' VIRTUAL TABLE ') &&
50
+ !derived.has(detail.split(' ')[1] ?? '') &&
51
+ !/ USING (?:COVERING )?INDEX /.test(detail);
52
+ return bareScan || (low?.test(detail) ?? false);
53
+ }
54
+
55
+ /** What a subquery made (`MATERIALIZE hit`, `CO-ROUTINE (subquery-1)`): its rows were counted where they were made. */
56
+ const derivedOf = (plan: readonly PlanRow[]): Set<string> =>
57
+ new Set(plan.flatMap((r) => /^(?:MATERIALIZE|CO-ROUTINE) (\S+)/.exec(r.detail)?.[1] ?? []));
58
+
59
+ /** The steps of `plan` that run once per outer row: inside a correlated subquery, or an `EXISTS` semi-join. */
60
+ export function perRowSteps(plan: readonly PlanRow[]): PlanRow[] {
61
+ const byId = new Map(plan.map((r) => [r.id, r]));
62
+ // The nearest subquery around a step decides: an uncorrelated one inside a correlated one is computed once.
63
+ const correlated = (row: PlanRow): boolean => {
64
+ // Newer SQLite runs `EXISTS (…)` as a semi-join, a loop inside the outer one: `SEARCH s EXISTS USING …`.
65
+ if (/^SEARCH \S+ EXISTS /.test(row.detail)) return true;
66
+ for (let p = byId.get(row.parent); p; p = byId.get(p.parent)) {
67
+ if (/SUBQUERY|^CORRELATED/.test(p.detail)) return p.detail.startsWith('CORRELATED');
68
+ }
69
+ return false;
70
+ };
71
+ return plan.filter(correlated);
72
+ }
73
+
74
+ /**
75
+ * The steps of `plan` that re-read a table for every outer row — or, with `perEvent`, every step
76
+ * that reads a table whole (a statement that itself runs once per event, so ANY step of it is per row).
77
+ */
78
+ export function perRowReads(plan: readonly PlanRow[], opts: PlanCheckOptions & { perEvent?: boolean } = {}): string[] {
79
+ const derived = derivedOf(plan);
80
+ const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
81
+ return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
82
+ }
83
+
84
+ /**
85
+ * The outer steps of a paged read that reads its table whole and then sorts every row it kept (`USE
86
+ * TEMP B-TREE FOR ORDER BY`) to hand back its LIMIT. A read keyed by its cursor (`(id>?)`), or walking
87
+ * an index in its own order (only `LAST TERM OF ORDER BY` sorted), stops at its page.
88
+ */
89
+ export function wholeTablePages(plan: readonly PlanRow[], opts: PlanCheckOptions = {}): string[] {
90
+ const outer = plan.filter((r) => r.parent === 0);
91
+ if (!outer.some((r) => r.detail === 'USE TEMP B-TREE FOR ORDER BY')) return [];
92
+ const derived = derivedOf(plan);
93
+ const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
94
+ return outer.filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
95
+ }
96
+
97
+ /**
98
+ * Every distinct statement `run` prepares on `db`, in first-prepared order. `db.prepare` is restored
99
+ * after. Any handle with a `prepare(sql)` will do — an app's own async wrapper as well as this seam.
100
+ */
101
+ export async function preparedBy(db: { prepare(sql: string): unknown }, run: () => Promise<unknown>): Promise<string[]> {
102
+ const seen = new Set<string>();
103
+ // Put back exactly what was there: an own property as it was, a prototype method by removing the shadow.
104
+ const own = Object.hasOwn(db, 'prepare');
105
+ const original = db.prepare;
106
+ const real = original.bind(db);
107
+ db.prepare = (sql: string) => {
108
+ seen.add(sql);
109
+ return real(sql);
110
+ };
111
+ try {
112
+ await run();
113
+ } finally {
114
+ if (own) db.prepare = original;
115
+ else delete (db as { prepare?: unknown }).prepare;
116
+ }
117
+ return [...seen];
118
+ }
119
+
120
+ /** `EXPLAIN QUERY PLAN` of `sql` on `db` — the app's own schema, so its indexes decide. */
121
+ export async function planOf(db: D1LikeDatabase, sql: string): Promise<PlanRow[]> {
122
+ return (await db.prepare(`EXPLAIN QUERY PLAN ${sql}`).all<PlanRow>()).results;
123
+ }
124
+
125
+ /**
126
+ * Every statement in `statements` that re-reads a table per row, or pages out of a sorted whole table
127
+ * — one line each, naming the step and the statement. `[]` is the pass.
128
+ *
129
+ * Reads are held to {@link perRowReads} and {@link wholeTablePages}. With `writes`, every INSERT,
130
+ * UPDATE, DELETE and REPLACE is held as `perEvent`: a write runs once per request or event, so ANY step
131
+ * of it that reads its table whole is the archive per call (desk's `UPDATE` that read 1.5 M rows).
132
+ */
133
+ export async function planOffenders(
134
+ db: D1LikeDatabase,
135
+ statements: readonly string[],
136
+ opts: PlanCheckOptions & { writes?: boolean } = {},
137
+ ): Promise<string[]> {
138
+ const offenders: string[] = [];
139
+ for (const sql of statements) {
140
+ const write = /^\s*(?:INSERT|UPDATE|DELETE|REPLACE)\b/i.test(sql);
141
+ if (write ? !opts.writes : !/^\s*(?:SELECT|WITH)\b/i.test(sql)) continue;
142
+ const plan = await planOf(db, sql);
143
+ const where = sql.replace(/\s+/g, ' ').trim().slice(0, 160);
144
+ for (const step of perRowReads(plan, { ...opts, perEvent: write })) offenders.push(`${step} ← ${where}`);
145
+ if (!write && /\bLIMIT\b/i.test(sql)) for (const step of wholeTablePages(plan, opts)) offenders.push(`page: ${step} ← ${where}`);
146
+ }
147
+ return offenders;
148
+ }
@@ -300,6 +300,46 @@ describe('local and D1 drivers return identical shapes', () => {
300
300
  expect(local).toEqual([3, 1]);
301
301
  });
302
302
 
303
+ // 🔴 D1 counts the rows a TRIGGER writes in `meta.changes`; SQLite's own `changes()` does not.
304
+ // Measured 2026-11-10 on family-stage's D1: this exact trigger (two log rows per insert) made a
305
+ // 3-row INSERT report 9 and an `INSERT … RETURNING` of 2 report 6. These are absolute numbers,
306
+ // not a comparison of the two drivers — both drivers once agreed on 3 and 2.
307
+ const TRIGGERED = `CREATE TABLE tlog (id INTEGER PRIMARY KEY, v TEXT);
308
+ CREATE TRIGGER t_log AFTER INSERT ON t BEGIN
309
+ INSERT INTO tlog (v) VALUES (new.text_col);
310
+ INSERT INTO tlog (v) VALUES (new.text_col);
311
+ END;`;
312
+
313
+ test('run() counts the rows a trigger wrote, as D1 does — 9 for a 3-row insert, on both', async () => {
314
+ p.seed(TRIGGERED);
315
+ const { local, remote } = await both(p, async (db) => {
316
+ const res = await db.prepare("INSERT INTO t (text_col) VALUES ('a'), ('b'), ('c')").run();
317
+ return { changes: res.meta.changes, last_row_id: res.meta.last_row_id };
318
+ });
319
+ expect(local).toEqual({ changes: 9, last_row_id: 3 });
320
+ expect(remote).toEqual({ changes: 9, last_row_id: 3 });
321
+ });
322
+
323
+ test('all() of an INSERT … RETURNING counts its trigger rows too — 6 for 2, on both', async () => {
324
+ p.seed(TRIGGERED);
325
+ const { local, remote } = await both(p, async (db) => {
326
+ const res = await db.prepare("INSERT INTO t (text_col) VALUES ('d'), ('e') RETURNING id").all<{ id: number }>();
327
+ return { ids: res.results.map((r) => r.id), changes: res.meta.changes };
328
+ });
329
+ expect(local).toEqual({ ids: [1, 2], changes: 6 });
330
+ expect(remote).toEqual({ ids: [1, 2], changes: 6 });
331
+ });
332
+
333
+ test('a batch member counts its trigger rows, on both', async () => {
334
+ p.seed(TRIGGERED);
335
+ const { local, remote } = await both(p, async (db) => {
336
+ const res = await db.batch([db.prepare("INSERT INTO t (text_col) VALUES ('a')"), db.prepare("UPDATE t SET text_col = 'z'")]);
337
+ return res.map((r) => r.meta.changes);
338
+ });
339
+ expect(local).toEqual([3, 1]);
340
+ expect(remote).toEqual([3, 1]);
341
+ });
342
+
303
343
  test('batch() reports last_row_id for an insert, on both', async () => {
304
344
  const { local, remote } = await both(p, async (db) => {
305
345
  const res = await db.batch([
@@ -9,6 +9,7 @@ import {
9
9
  d1MeaningStore,
10
10
  EMBED_DIMS,
11
11
  EMBED_MODEL,
12
+ FACE_DIMS,
12
13
  fuse,
13
14
  MEANING_CACHE_DAYS,
14
15
  MEANING_D1_DDL,
@@ -17,6 +18,7 @@ import {
17
18
  meaningCacheKey,
18
19
  RERANK_MODEL,
19
20
  rerankOrder,
21
+ REGION_DIMS,
20
22
  rerankScores,
21
23
  whyFound,
22
24
  } from './meaning.js';
@@ -97,6 +99,12 @@ function d1() {
97
99
  }
98
100
 
99
101
  describe('the shared pieces', () => {
102
+ // photos' Mac writes these widths and family's door refuses any other length (forge task 4828):
103
+ // a change here is a model change, and both apps' stored vectors go with it.
104
+ it("the image engines' widths are ArcFace's 512 and the region embedder's 1536", () => {
105
+ expect([FACE_DIMS, REGION_DIMS]).toEqual([512, 1536]);
106
+ });
107
+
100
108
  it('fuse: an id both lists found leads, a tie keeps first-seen order', () => {
101
109
  expect(fuse([['a', 'b', 'c'], ['c', 'd']])).toEqual(['c', 'a', 'b', 'd']);
102
110
  expect(fuse([['x'], ['y']])).toEqual(['x', 'y']);
@@ -23,6 +23,13 @@
23
23
  /** The text embedder for both sides: a document and a query. Measured by photos, 2026-11-05. */
24
24
  export const EMBED_MODEL = '@cf/baai/bge-m3';
25
25
  export const EMBED_DIMS = 1024;
26
+ /**
27
+ * The image engines' widths — photos' Mac writes them, family's door refuses any other length, so
28
+ * they live once, here (forge task 4828). ArcFace: 512 float32, little-endian.
29
+ */
30
+ export const FACE_DIMS = 512;
31
+ /** The image region embedder: 1536 floats, sent as float16. */
32
+ export const REGION_DIMS = 1536;
26
33
  /** The cross-encoder that reads the query beside each candidate's document. */
27
34
  export const RERANK_MODEL = '@cf/baai/bge-reranker-base';
28
35
  /**