cursedbelt-server 4.79.2 → 4.80.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.
@@ -41,7 +41,48 @@ function keyedByNull(detail, sql) {
41
41
  if (!m || !sql)
42
42
  return false;
43
43
  const [, alias, column] = m;
44
- return new RegExp(`(?<![\\w.+])(?:${escapeRegExp(alias)}\\.)?${escapeRegExp(column)}\\s+IS\\s+NULL\\b`, 'i').test(sql);
44
+ return testsNull(sql, alias, column);
45
+ }
46
+ /** Whether `sql` tests `alias.column IS NULL` (or a bare `column IS NULL`); a unary `+` keeps the term off every index. */
47
+ const testsNull = (sql, alias, column) => new RegExp(`(?<![\\w.+])(?:${escapeRegExp(alias)}\\.)?${escapeRegExp(column)}\\s+IS\\s+NULL\\b`, 'i').test(sql);
48
+ /**
49
+ * Whether a search is keyed by two or more columns, EVERY one of them low-cardinality (or tested `IS NULL` by `sql`) and
50
+ * none set equal to an outer row's column by `sql` (`a.owner_id = m.user_id` is keyed by the member asked about):
51
+ * `SEARCH al USING INDEX albums_owner (owner_id=? AND deleted_at=?)`. No term names the outer row, so inside a correlated
52
+ * subquery it reads the same set — every live album of the owner — again for each outer row. Photos' `albums/assets`
53
+ * did that for 68 albums × 1,000 photographs a page: 100,405 rows a page, twenty pages in six seconds, and D1
54
+ * overloaded (forge task 5909). Held per row of a READ only: a `perEvent` statement already reaches its outer rows by
55
+ * key, so its correlated set is read once per event — bounded, like a rename's "no other live album has this title".
56
+ */
57
+ function keyedByLowAlone(detail, columns, sql) {
58
+ const key = /^SEARCH (\S+) (?:EXISTS )?USING (?:COVERING )?INDEX \S+ \((.+)\)$/.exec(detail);
59
+ if (!key)
60
+ return false;
61
+ const [, alias, terms] = key;
62
+ const parts = terms.split(' AND ');
63
+ if (parts.length < 2)
64
+ return false;
65
+ return parts.every((term) => {
66
+ const column = /^(\w+)=\?$/.exec(term)?.[1];
67
+ if (!column)
68
+ return false;
69
+ if (sql !== undefined && namesOuterRow(sql, alias, column))
70
+ return false;
71
+ if (columns.includes(column))
72
+ return true;
73
+ return sql !== undefined && testsNull(sql, alias, column);
74
+ });
75
+ }
76
+ /** Whether `sql` sets `alias.column` equal to another alias's column (`a.owner_id = m.user_id`): the key is the outer row. */
77
+ function namesOuterRow(sql, alias, column) {
78
+ const self = `(?<![\\w.])${escapeRegExp(alias)}\\.${escapeRegExp(column)}\\b`;
79
+ const other = '(?<![\\w.])(\\w+)\\.\\w+\\b';
80
+ for (const re of [new RegExp(`${self}\\s*=\\s*${other}`, 'gi'), new RegExp(`${other}\\s*=\\s*${self}`, 'gi')]) {
81
+ for (const m of sql.matchAll(re))
82
+ if (m[1] && m[1].toLowerCase() !== alias.toLowerCase())
83
+ return true;
84
+ }
85
+ return false;
45
86
  }
46
87
  /** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column (or NULL) alone. */
47
88
  function readsWhole(detail, derived, low, sql) {
@@ -75,8 +116,13 @@ export function perRowSteps(plan) {
75
116
  */
76
117
  export function perRowReads(plan, opts = {}) {
77
118
  const derived = derivedOf(plan);
78
- const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
79
- return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
119
+ const columns = opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS;
120
+ const low = lowCardinalityRule(columns);
121
+ if (opts.perEvent)
122
+ return plan.filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
123
+ return perRowSteps(plan)
124
+ .filter((r) => readsWhole(r.detail, derived, low, opts.sql) || keyedByLowAlone(r.detail, columns, opts.sql))
125
+ .map((r) => r.detail);
80
126
  }
81
127
  /**
82
128
  * The outer steps of a paged read that reads its table whole and then sorts every row it kept (`USE
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.79.2",
3
+ "version": "4.80.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.",
@@ -459,7 +459,7 @@
459
459
  "@node-rs/argon2": "^2.0.2",
460
460
  "@types/bun": "^1.3.14",
461
461
  "@types/node": "^24",
462
- "cursedbelt": "^6.31.1",
462
+ "cursedbelt": "^6.32.0",
463
463
  "hono": "4.12.28",
464
464
  "kysely": "^0.28.17",
465
465
  "kysely-bun-sqlite": "^0.4.0",
@@ -38,13 +38,39 @@ describe('perRowReads', () => {
38
38
  ).toEqual([]);
39
39
  });
40
40
 
41
- test('perEvent counts the outer read too; a compound key is not low-cardinality', () => {
41
+ test('perEvent counts the outer read too; a compound key on an outer read is not low-cardinality', () => {
42
42
  const outer: PlanRow[] = [{ id: 6, parent: 0, detail: 'SEARCH a USING INDEX assets_timeline (deleted_at=?)' }];
43
43
  expect(perRowReads(outer)).toEqual([]);
44
44
  expect(perRowReads(outer, { perEvent: true })).toEqual(['SEARCH a USING INDEX assets_timeline (deleted_at=?)']);
45
45
  expect(perRowReads([{ id: 6, parent: 0, detail: 'SEARCH al USING INDEX albums_owner (owner_id=? AND deleted_at=?)' }], { perEvent: true })).toEqual([]);
46
46
  });
47
47
 
48
+ test('per row, a search keyed by low-cardinality columns alone reads the same set again each row (forge task 5909)', () => {
49
+ const byOwner = 'SEARCH al USING INDEX albums_owner (owner_id=? AND deleted_at=?)';
50
+ expect(perRowReads(plan(byOwner))).toEqual([byOwner]);
51
+ expect(perRowReads([{ id: 9, parent: 0, detail: 'SEARCH al EXISTS USING INDEX albums_owner (owner_id=? AND deleted_at=?)' }])).toEqual([
52
+ 'SEARCH al EXISTS USING INDEX albums_owner (owner_id=? AND deleted_at=?)',
53
+ ]);
54
+ // A term on the outer row keys it; so does a range or a column the app has not called low.
55
+ expect(perRowReads(plan('SEARCH aa USING COVERING INDEX album_assets_pk (album_id=? AND asset_id=?)'))).toEqual([]);
56
+ expect(perRowReads(plan('SEARCH j USING INDEX jobs_asset (asset_id=? AND state=?)'))).toEqual([]);
57
+ expect(perRowReads(plan('SEARCH al USING INDEX albums_owner (owner_id=? AND deleted_at>?)'))).toEqual([]);
58
+ expect(perRowReads(plan(byOwner), { lowCardinality: ['owner_id'] })).toEqual([]);
59
+ // …unless the statement tests that column IS NULL: the key is every row with no value yet.
60
+ expect(perRowReads(plan('SEARCH al USING INDEX albums_hidden (owner_id=? AND hidden_at=?)'), { sql: 'WHERE al.hidden_at IS NULL' })).toEqual([
61
+ 'SEARCH al USING INDEX albums_hidden (owner_id=? AND hidden_at=?)',
62
+ ]);
63
+ expect(perRowReads(plan(byOwner), { lowCardinality: ['owner_id'], sql: 'WHERE al.deleted_at IS NULL' })).toEqual([byOwner]);
64
+ // A low-cardinality column set equal to the outer row's is keyed by that row: each member's own photographs.
65
+ const theirs = 'SEARCH a EXISTS USING INDEX assets_owner (owner_id=? AND deleted_at=?)';
66
+ const byMember = [{ id: 9, parent: 0, detail: theirs }];
67
+ expect(perRowReads(byMember, { sql: 'FROM members m WHERE EXISTS (SELECT 1 FROM assets a WHERE a.owner_id = m.user_id AND a.deleted_at IS NULL)' })).toEqual([]);
68
+ expect(perRowReads(byMember, { sql: 'FROM members m WHERE EXISTS (SELECT 1 FROM assets a WHERE m.user_id = a.owner_id AND a.deleted_at IS NULL)' })).toEqual([]);
69
+ expect(perRowReads(byMember, { sql: 'FROM members m WHERE EXISTS (SELECT 1 FROM assets a WHERE a.owner_id = ? AND a.deleted_at IS NULL)' })).toEqual([theirs]);
70
+ // A statement held per event reaches its outer rows by key: the set is read once per event, which is bounded.
71
+ expect(perRowReads(plan(byOwner), { perEvent: true })).toEqual(['SCAN ai']);
72
+ });
73
+
48
74
  test("an app widens the low-cardinality rule with its own columns, or empties it", () => {
49
75
  const byKind = plan('SEARCH j USING INDEX jobs_kind (kind=?)');
50
76
  expect(perRowReads(byKind)).toEqual([]);
@@ -65,7 +65,45 @@ function keyedByNull(detail: string, sql: string | undefined): boolean {
65
65
  const m = sql ? ONE_KEY.exec(detail) : null;
66
66
  if (!m || !sql) return false;
67
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);
68
+ return testsNull(sql, alias, column);
69
+ }
70
+
71
+ /** Whether `sql` tests `alias.column IS NULL` (or a bare `column IS NULL`); a unary `+` keeps the term off every index. */
72
+ const testsNull = (sql: string, alias: string, column: string): boolean =>
73
+ new RegExp(`(?<![\\w.+])(?:${escapeRegExp(alias)}\\.)?${escapeRegExp(column)}\\s+IS\\s+NULL\\b`, 'i').test(sql);
74
+
75
+ /**
76
+ * Whether a search is keyed by two or more columns, EVERY one of them low-cardinality (or tested `IS NULL` by `sql`) and
77
+ * none set equal to an outer row's column by `sql` (`a.owner_id = m.user_id` is keyed by the member asked about):
78
+ * `SEARCH al USING INDEX albums_owner (owner_id=? AND deleted_at=?)`. No term names the outer row, so inside a correlated
79
+ * subquery it reads the same set — every live album of the owner — again for each outer row. Photos' `albums/assets`
80
+ * did that for 68 albums × 1,000 photographs a page: 100,405 rows a page, twenty pages in six seconds, and D1
81
+ * overloaded (forge task 5909). Held per row of a READ only: a `perEvent` statement already reaches its outer rows by
82
+ * key, so its correlated set is read once per event — bounded, like a rename's "no other live album has this title".
83
+ */
84
+ function keyedByLowAlone(detail: string, columns: readonly string[], sql: string | undefined): boolean {
85
+ const key = /^SEARCH (\S+) (?:EXISTS )?USING (?:COVERING )?INDEX \S+ \((.+)\)$/.exec(detail);
86
+ if (!key) return false;
87
+ const [, alias, terms] = key as unknown as [string, string, string];
88
+ const parts = terms.split(' AND ');
89
+ if (parts.length < 2) return false;
90
+ return parts.every((term) => {
91
+ const column = /^(\w+)=\?$/.exec(term)?.[1];
92
+ if (!column) return false;
93
+ if (sql !== undefined && namesOuterRow(sql, alias, column)) return false;
94
+ if (columns.includes(column)) return true;
95
+ return sql !== undefined && testsNull(sql, alias, column);
96
+ });
97
+ }
98
+
99
+ /** Whether `sql` sets `alias.column` equal to another alias's column (`a.owner_id = m.user_id`): the key is the outer row. */
100
+ function namesOuterRow(sql: string, alias: string, column: string): boolean {
101
+ const self = `(?<![\\w.])${escapeRegExp(alias)}\\.${escapeRegExp(column)}\\b`;
102
+ const other = '(?<![\\w.])(\\w+)\\.\\w+\\b';
103
+ for (const re of [new RegExp(`${self}\\s*=\\s*${other}`, 'gi'), new RegExp(`${other}\\s*=\\s*${self}`, 'gi')]) {
104
+ for (const m of sql.matchAll(re)) if (m[1] && m[1].toLowerCase() !== alias.toLowerCase()) return true;
105
+ }
106
+ return false;
69
107
  }
70
108
 
71
109
  /** A step that reads its table whole: a scan with no index, or a search by a low-cardinality column (or NULL) alone. */
@@ -103,8 +141,12 @@ export function perRowSteps(plan: readonly PlanRow[]): PlanRow[] {
103
141
  */
104
142
  export function perRowReads(plan: readonly PlanRow[], opts: PlanCheckOptions & { perEvent?: boolean } = {}): string[] {
105
143
  const derived = derivedOf(plan);
106
- const low = lowCardinalityRule(opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS);
107
- return (opts.perEvent ? plan : perRowSteps(plan)).filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
144
+ const columns = opts.lowCardinality ?? LOW_CARDINALITY_COLUMNS;
145
+ const low = lowCardinalityRule(columns);
146
+ if (opts.perEvent) return plan.filter((r) => readsWhole(r.detail, derived, low, opts.sql)).map((r) => r.detail);
147
+ return perRowSteps(plan)
148
+ .filter((r) => readsWhole(r.detail, derived, low, opts.sql) || keyedByLowAlone(r.detail, columns, opts.sql))
149
+ .map((r) => r.detail);
108
150
  }
109
151
 
110
152
  /**