cursedbelt-server 4.66.0 → 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.
- package/dist/server/d1/fakeD1.d.ts +5 -0
- package/dist/server/d1/fakeD1.js +9 -6
- package/dist/server/d1/index.d.ts +1 -0
- package/dist/server/d1/index.js +1 -0
- package/dist/server/d1/plans.d.ts +70 -0
- package/dist/server/d1/plans.js +127 -0
- package/dist/server/meaning/meaning.d.ts +7 -0
- package/dist/server/meaning/meaning.js +7 -0
- package/package.json +1 -1
- package/src/server/d1/fakeD1.ts +9 -6
- package/src/server/d1/index.ts +11 -0
- package/src/server/d1/plans.spec.ts +129 -0
- package/src/server/d1/plans.ts +148 -0
- package/src/server/d1/sameShape.spec.ts +40 -0
- package/src/server/meaning/meaning.spec.ts +8 -0
- package/src/server/meaning/meaning.ts +7 -0
|
@@ -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.
|
package/dist/server/d1/fakeD1.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
155
|
-
// `
|
|
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';
|
package/dist/server/d1/index.js
CHANGED
|
@@ -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.
|
|
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.",
|
package/src/server/d1/fakeD1.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
163
|
-
// `
|
|
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)) };
|
package/src/server/d1/index.ts
CHANGED
|
@@ -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
|
/**
|