cursedbelt-server 4.75.0 → 4.76.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/plans.d.ts +12 -0
- package/dist/server/d1/plans.js +26 -7
- package/package.json +2 -2
- package/src/server/d1/plans.spec.ts +39 -0
- package/src/server/d1/plans.ts +33 -7
|
@@ -10,6 +10,12 @@
|
|
|
10
10
|
* 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
|
|
11
11
|
* LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
|
|
12
12
|
*
|
|
13
|
+
* A search keyed by `col IS NULL` alone is held the same way, whatever the column: the plan prints it as
|
|
14
|
+
* `(col=?)`, a keyed search, but the key is every row that has no value yet — usually most of the table.
|
|
15
|
+
* Photos' art-face hides reached `faces` through `faces_entity (entity_id=?)` for `f.entity_id IS NULL`,
|
|
16
|
+
* 16,314 of 23,978 faces per statement, twice per described photograph: 1.78 M rows read by one sync
|
|
17
|
+
* (forge task 5517). The plan cannot tell `= ?` from `IS NULL`, so the check reads the statement too.
|
|
18
|
+
*
|
|
13
19
|
* ```ts
|
|
14
20
|
* const statements = await preparedBy(db, () => app.request('/api/heavy'));
|
|
15
21
|
* expect(await planOffenders(db, statements)).toEqual([]);
|
|
@@ -32,6 +38,12 @@ export declare const LOW_CARDINALITY_COLUMNS: readonly string[];
|
|
|
32
38
|
export interface PlanCheckOptions {
|
|
33
39
|
/** Replaces {@link LOW_CARDINALITY_COLUMNS}. */
|
|
34
40
|
lowCardinality?: readonly string[];
|
|
41
|
+
/**
|
|
42
|
+
* The statement the plan is of. Given, a search keyed by one column alone that the statement tests
|
|
43
|
+
* `IS NULL` (`f.entity_id IS NULL` → `SEARCH f USING INDEX faces_entity (entity_id=?)`) reads every
|
|
44
|
+
* row with no value, and counts as reading its table whole. {@link planOffenders} always passes it.
|
|
45
|
+
*/
|
|
46
|
+
sql?: string;
|
|
35
47
|
}
|
|
36
48
|
/** The steps of `plan` that run once per outer row: inside a correlated subquery, or an `EXISTS` semi-join. */
|
|
37
49
|
export declare function perRowSteps(plan: readonly PlanRow[]): PlanRow[];
|
package/dist/server/d1/plans.js
CHANGED
|
@@ -10,6 +10,12 @@
|
|
|
10
10
|
* 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
|
|
11
11
|
* LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
|
|
12
12
|
*
|
|
13
|
+
* A search keyed by `col IS NULL` alone is held the same way, whatever the column: the plan prints it as
|
|
14
|
+
* `(col=?)`, a keyed search, but the key is every row that has no value yet — usually most of the table.
|
|
15
|
+
* Photos' art-face hides reached `faces` through `faces_entity (entity_id=?)` for `f.entity_id IS NULL`,
|
|
16
|
+
* 16,314 of 23,978 faces per statement, twice per described photograph: 1.78 M rows read by one sync
|
|
17
|
+
* (forge task 5517). The plan cannot tell `= ?` from `IS NULL`, so the check reads the statement too.
|
|
18
|
+
*
|
|
13
19
|
* ```ts
|
|
14
20
|
* const statements = await preparedBy(db, () => app.request('/api/heavy'));
|
|
15
21
|
* expect(await planOffenders(db, statements)).toEqual([]);
|
|
@@ -24,13 +30,26 @@
|
|
|
24
30
|
export const LOW_CARDINALITY_COLUMNS = ['state', 'status', 'deleted_at', 'owner_id'];
|
|
25
31
|
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
26
32
|
const lowCardinalityRule = (columns) => columns.length === 0 ? null : new RegExp(` USING (?:COVERING )?INDEX \\S+ \\((?:${columns.map(escapeRegExp).join('|')})=\\?\\)`);
|
|
27
|
-
/**
|
|
28
|
-
|
|
33
|
+
/** `SEARCH <alias> [EXISTS ]USING [COVERING ]INDEX <index> (<column>=?)` — a search keyed by one column alone. */
|
|
34
|
+
const ONE_KEY = /^SEARCH (\S+) (?:EXISTS )?USING (?:COVERING )?INDEX \S+ \((\w+)=\?\)$/;
|
|
35
|
+
/**
|
|
36
|
+
* Whether `sql` tests `alias.column IS NULL` (or a bare `column IS NULL`): the search {@link ONE_KEY} names is then
|
|
37
|
+
* keyed by NULL. A unary `+` (`+f.entity_id IS NULL`) is SQLite's way to keep a term off every index, so it is not one.
|
|
38
|
+
*/
|
|
39
|
+
function keyedByNull(detail, sql) {
|
|
40
|
+
const m = sql ? ONE_KEY.exec(detail) : null;
|
|
41
|
+
if (!m || !sql)
|
|
42
|
+
return false;
|
|
43
|
+
const [, alias, column] = m;
|
|
44
|
+
return new RegExp(`(?<![\\w.+])(?:${escapeRegExp(alias)}\\.)?${escapeRegExp(column)}\\s+IS\\s+NULL\\b`, 'i').test(sql);
|
|
45
|
+
}
|
|
46
|
+
/** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column (or NULL) alone. */
|
|
47
|
+
function readsWhole(detail, derived, low, sql) {
|
|
29
48
|
const bareScan = /^SCAN (?!CONSTANT ROW)/.test(detail) &&
|
|
30
49
|
!detail.includes(' VIRTUAL TABLE ') &&
|
|
31
50
|
!derived.has(detail.split(' ')[1] ?? '') &&
|
|
32
51
|
!/ USING (?:COVERING )?INDEX /.test(detail);
|
|
33
|
-
return bareScan || (low?.test(detail) ?? false);
|
|
52
|
+
return bareScan || (low?.test(detail) ?? false) || keyedByNull(detail, sql);
|
|
34
53
|
}
|
|
35
54
|
/** What a subquery made (`MATERIALIZE hit`, `CO-ROUTINE (subquery-1)`): its rows were counted where they were made. */
|
|
36
55
|
const derivedOf = (plan) => new Set(plan.flatMap((r) => /^(?:MATERIALIZE|CO-ROUTINE) (\S+)/.exec(r.detail)?.[1] ?? []));
|
|
@@ -57,7 +76,7 @@ export function perRowSteps(plan) {
|
|
|
57
76
|
export function perRowReads(plan, opts = {}) {
|
|
58
77
|
const derived = derivedOf(plan);
|
|
59
78
|
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);
|
|
79
|
+
return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
|
|
61
80
|
}
|
|
62
81
|
/**
|
|
63
82
|
* The outer steps of a paged read that reads its table whole and then sorts every row it kept (`USE
|
|
@@ -70,7 +89,7 @@ export function wholeTablePages(plan, opts = {}) {
|
|
|
70
89
|
return [];
|
|
71
90
|
const derived = derivedOf(plan);
|
|
72
91
|
const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
|
|
73
|
-
return outer.filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
|
|
92
|
+
return outer.filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
|
|
74
93
|
}
|
|
75
94
|
/**
|
|
76
95
|
* Every distinct statement `run` prepares on `db`, in first-prepared order. `db.prepare` is restored
|
|
@@ -117,10 +136,10 @@ export async function planOffenders(db, statements, opts = {}) {
|
|
|
117
136
|
continue;
|
|
118
137
|
const plan = await planOf(db, sql);
|
|
119
138
|
const where = sql.replace(/\s+/g, ' ').trim().slice(0, 160);
|
|
120
|
-
for (const step of perRowReads(plan, { ...opts, perEvent: write }))
|
|
139
|
+
for (const step of perRowReads(plan, { ...opts, perEvent: write, sql }))
|
|
121
140
|
offenders.push(`${step} ← ${where}`);
|
|
122
141
|
if (!write && /\bLIMIT\b/i.test(sql))
|
|
123
|
-
for (const step of wholeTablePages(plan, opts))
|
|
142
|
+
for (const step of wholeTablePages(plan, { ...opts, sql }))
|
|
124
143
|
offenders.push(`page: ${step} ← ${where}`);
|
|
125
144
|
}
|
|
126
145
|
return offenders;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cursedbelt-server",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.76.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.",
|
|
@@ -447,7 +447,7 @@
|
|
|
447
447
|
"@node-rs/argon2": "^2.0.2",
|
|
448
448
|
"@types/bun": "^1.3.14",
|
|
449
449
|
"@types/node": "^24",
|
|
450
|
-
"cursedbelt": "^6.
|
|
450
|
+
"cursedbelt": "^6.13.1",
|
|
451
451
|
"hono": "4.12.28",
|
|
452
452
|
"kysely": "^0.28.17",
|
|
453
453
|
"kysely-bun-sqlite": "^0.4.0",
|
|
@@ -55,6 +55,45 @@ describe('perRowReads', () => {
|
|
|
55
55
|
});
|
|
56
56
|
});
|
|
57
57
|
|
|
58
|
+
describe('a search keyed by NULL (forge task 5517)', () => {
|
|
59
|
+
const byEntity = 'SEARCH f USING INDEX faces_entity (entity_id=?)';
|
|
60
|
+
const outer: PlanRow[] = [{ id: 4, parent: 0, detail: byEntity }];
|
|
61
|
+
|
|
62
|
+
test("the statement's `IS NULL` makes a one-column key read the table whole; `= ?` on the same plan does not", () => {
|
|
63
|
+
const hide = "UPDATE faces SET dismissed_at = ? WHERE id IN (SELECT f.id FROM faces f WHERE f.asset_id IN (SELECT value FROM json_each(?)) AND f.entity_id IS NULL)";
|
|
64
|
+
expect(perRowReads(outer, { perEvent: true, sql: hide })).toEqual([byEntity]);
|
|
65
|
+
expect(perRowReads(outer, { perEvent: true, sql: 'UPDATE faces SET dismissed_at = ? WHERE id IN (SELECT f.id FROM faces f WHERE f.entity_id = ?)' })).toEqual([]);
|
|
66
|
+
// Without the statement the plan alone cannot tell, so it stays a keyed search.
|
|
67
|
+
expect(perRowReads(outer, { perEvent: true })).toEqual([]);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test('another alias, a compound key, IS NOT NULL and a unary + are not a NULL key', () => {
|
|
71
|
+
expect(perRowReads(outer, { perEvent: true, sql: 'SELECT 1 FROM faces f JOIN faces g ON g.entity_id IS NULL WHERE f.entity_id = ?' })).toEqual([]);
|
|
72
|
+
expect(perRowReads(outer, { perEvent: true, sql: 'SELECT 1 FROM faces f WHERE f.entity_id IS NOT NULL' })).toEqual([]);
|
|
73
|
+
expect(perRowReads(outer, { perEvent: true, sql: 'SELECT 1 FROM faces f WHERE +f.entity_id IS NULL' })).toEqual([]);
|
|
74
|
+
expect(perRowReads([{ id: 4, parent: 0, detail: 'SEARCH f USING INDEX faces_entity (entity_id=? AND kind=?)' }], { perEvent: true, sql: 'SELECT 1 FROM faces f WHERE f.entity_id IS NULL AND f.kind = ?' })).toEqual([]);
|
|
75
|
+
// A bare column, the table read under its own name.
|
|
76
|
+
expect(perRowReads([{ id: 4, parent: 0, detail: 'SEARCH faces USING INDEX faces_entity (entity_id=?)' }], { perEvent: true, sql: 'UPDATE faces SET x = 1 WHERE entity_id IS NULL' })).toEqual([
|
|
77
|
+
'SEARCH faces USING INDEX faces_entity (entity_id=?)',
|
|
78
|
+
]);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test('planOffenders reads the statement itself: a write reaching its rows by NULL is named, by the asked-for key passes', async () => {
|
|
82
|
+
const db = createLocalD1(new Database(':memory:'));
|
|
83
|
+
await db.batch([
|
|
84
|
+
db.prepare('CREATE TABLE faces (id TEXT PRIMARY KEY, asset_id TEXT, entity_id TEXT)'),
|
|
85
|
+
db.prepare('CREATE INDEX faces_asset ON faces (asset_id)'),
|
|
86
|
+
db.prepare('CREATE INDEX faces_entity ON faces (entity_id)'),
|
|
87
|
+
]);
|
|
88
|
+
const where = 'f.asset_id IN (SELECT value FROM json_each(?)) AND f.entity_id IS NULL';
|
|
89
|
+
const byNull = `UPDATE faces SET entity_id = 'x' WHERE id IN (SELECT f.id FROM faces f WHERE ${where})`;
|
|
90
|
+
expect((await planOf(db, byNull)).some((r) => r.detail === 'SEARCH f USING INDEX faces_entity (entity_id=?)')).toBe(true);
|
|
91
|
+
expect(await planOffenders(db, [byNull], { writes: true })).toEqual([`SEARCH f USING INDEX faces_entity (entity_id=?) ← ${byNull}`]);
|
|
92
|
+
const byAsset = `UPDATE faces SET entity_id = 'x' WHERE id IN (SELECT f.id FROM faces f INDEXED BY faces_asset WHERE ${where})`;
|
|
93
|
+
expect(await planOffenders(db, [byAsset], { writes: true })).toEqual([]);
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
58
97
|
describe('wholeTablePages', () => {
|
|
59
98
|
const sorted = (outer: string): PlanRow[] => [
|
|
60
99
|
{ id: 7, parent: 0, detail: outer },
|
package/src/server/d1/plans.ts
CHANGED
|
@@ -10,6 +10,12 @@
|
|
|
10
10
|
* 963 photographs. A page is held too: one that reads its table whole and sorts it to hand back its
|
|
11
11
|
* LIMIT pays for the archive on every page (photos' `albums/assets`, 331,190 rows for one page).
|
|
12
12
|
*
|
|
13
|
+
* A search keyed by `col IS NULL` alone is held the same way, whatever the column: the plan prints it as
|
|
14
|
+
* `(col=?)`, a keyed search, but the key is every row that has no value yet — usually most of the table.
|
|
15
|
+
* Photos' art-face hides reached `faces` through `faces_entity (entity_id=?)` for `f.entity_id IS NULL`,
|
|
16
|
+
* 16,314 of 23,978 faces per statement, twice per described photograph: 1.78 M rows read by one sync
|
|
17
|
+
* (forge task 5517). The plan cannot tell `= ?` from `IS NULL`, so the check reads the statement too.
|
|
18
|
+
*
|
|
13
19
|
* ```ts
|
|
14
20
|
* const statements = await preparedBy(db, () => app.request('/api/heavy'));
|
|
15
21
|
* expect(await planOffenders(db, statements)).toEqual([]);
|
|
@@ -36,20 +42,40 @@ export const LOW_CARDINALITY_COLUMNS: readonly string[] = ['state', 'status', 'd
|
|
|
36
42
|
export interface PlanCheckOptions {
|
|
37
43
|
/** Replaces {@link LOW_CARDINALITY_COLUMNS}. */
|
|
38
44
|
lowCardinality?: readonly string[];
|
|
45
|
+
/**
|
|
46
|
+
* The statement the plan is of. Given, a search keyed by one column alone that the statement tests
|
|
47
|
+
* `IS NULL` (`f.entity_id IS NULL` → `SEARCH f USING INDEX faces_entity (entity_id=?)`) reads every
|
|
48
|
+
* row with no value, and counts as reading its table whole. {@link planOffenders} always passes it.
|
|
49
|
+
*/
|
|
50
|
+
sql?: string;
|
|
39
51
|
}
|
|
40
52
|
|
|
41
53
|
const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
42
54
|
const lowCardinalityRule = (columns: readonly string[]): RegExp | null =>
|
|
43
55
|
columns.length === 0 ? null : new RegExp(` USING (?:COVERING )?INDEX \\S+ \\((?:${columns.map(escapeRegExp).join('|')})=\\?\\)`);
|
|
44
56
|
|
|
45
|
-
/**
|
|
46
|
-
|
|
57
|
+
/** `SEARCH <alias> [EXISTS ]USING [COVERING ]INDEX <index> (<column>=?)` — a search keyed by one column alone. */
|
|
58
|
+
const ONE_KEY = /^SEARCH (\S+) (?:EXISTS )?USING (?:COVERING )?INDEX \S+ \((\w+)=\?\)$/;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Whether `sql` tests `alias.column IS NULL` (or a bare `column IS NULL`): the search {@link ONE_KEY} names is then
|
|
62
|
+
* keyed by NULL. A unary `+` (`+f.entity_id IS NULL`) is SQLite's way to keep a term off every index, so it is not one.
|
|
63
|
+
*/
|
|
64
|
+
function keyedByNull(detail: string, sql: string | undefined): boolean {
|
|
65
|
+
const m = sql ? ONE_KEY.exec(detail) : null;
|
|
66
|
+
if (!m || !sql) return false;
|
|
67
|
+
const [, alias, column] = m as unknown as [string, string, string];
|
|
68
|
+
return new RegExp(`(?<![\\w.+])(?:${escapeRegExp(alias)}\\.)?${escapeRegExp(column)}\\s+IS\\s+NULL\\b`, 'i').test(sql);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column (or NULL) alone. */
|
|
72
|
+
function readsWhole(detail: string, derived: ReadonlySet<string>, low: RegExp | null, sql?: string): boolean {
|
|
47
73
|
const bareScan =
|
|
48
74
|
/^SCAN (?!CONSTANT ROW)/.test(detail) &&
|
|
49
75
|
!detail.includes(' VIRTUAL TABLE ') &&
|
|
50
76
|
!derived.has(detail.split(' ')[1] ?? '') &&
|
|
51
77
|
!/ USING (?:COVERING )?INDEX /.test(detail);
|
|
52
|
-
return bareScan || (low?.test(detail) ?? false);
|
|
78
|
+
return bareScan || (low?.test(detail) ?? false) || keyedByNull(detail, sql);
|
|
53
79
|
}
|
|
54
80
|
|
|
55
81
|
/** What a subquery made (`MATERIALIZE hit`, `CO-ROUTINE (subquery-1)`): its rows were counted where they were made. */
|
|
@@ -78,7 +104,7 @@ export function perRowSteps(plan: readonly PlanRow[]): PlanRow[] {
|
|
|
78
104
|
export function perRowReads(plan: readonly PlanRow[], opts: PlanCheckOptions & { perEvent?: boolean } = {}): string[] {
|
|
79
105
|
const derived = derivedOf(plan);
|
|
80
106
|
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);
|
|
107
|
+
return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
|
|
82
108
|
}
|
|
83
109
|
|
|
84
110
|
/**
|
|
@@ -91,7 +117,7 @@ export function wholeTablePages(plan: readonly PlanRow[], opts: PlanCheckOptions
|
|
|
91
117
|
if (!outer.some((r) => r.detail === 'USE TEMP B-TREE FOR ORDER BY')) return [];
|
|
92
118
|
const derived = derivedOf(plan);
|
|
93
119
|
const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
|
|
94
|
-
return outer.filter((r) => readsWhole(r.detail, derived, low)).map((r) => r.detail);
|
|
120
|
+
return outer.filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
|
|
95
121
|
}
|
|
96
122
|
|
|
97
123
|
/**
|
|
@@ -141,8 +167,8 @@ export async function planOffenders(
|
|
|
141
167
|
if (write ? !opts.writes : !/^\s*(?:SELECT|WITH)\b/i.test(sql)) continue;
|
|
142
168
|
const plan = await planOf(db, sql);
|
|
143
169
|
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}`);
|
|
170
|
+
for (const step of perRowReads(plan, { ...opts, perEvent: write, sql })) offenders.push(`${step} ← ${where}`);
|
|
171
|
+
if (!write && /\bLIMIT\b/i.test(sql)) for (const step of wholeTablePages(plan, { ...opts, sql })) offenders.push(`page: ${step} ← ${where}`);
|
|
146
172
|
}
|
|
147
173
|
return offenders;
|
|
148
174
|
}
|