@ultimat3/testing 31.8.0 → 31.9.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.8.0",
3
+ "version": "31.9.0",
4
4
  "description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -47,26 +47,26 @@
47
47
  "test": "bun test"
48
48
  },
49
49
  "dependencies": {
50
- "@ultimat3/action": "31.8.0",
51
- "@ultimat3/ai": "31.8.0",
52
- "@ultimat3/auth": "31.8.0",
53
- "@ultimat3/cache": "31.8.0",
54
- "@ultimat3/core": "31.8.0",
55
- "@ultimat3/db": "31.8.0",
56
- "@ultimat3/entity": "31.8.0",
57
- "@ultimat3/http": "31.8.0",
58
- "@ultimat3/i18n": "31.8.0",
59
- "@ultimat3/jobs": "31.8.0",
60
- "@ultimat3/mail": "31.8.0",
61
- "@ultimat3/notify": "31.8.0",
62
- "@ultimat3/policy": "31.8.0",
63
- "@ultimat3/pwa": "31.8.0",
64
- "@ultimat3/query": "31.8.0",
65
- "@ultimat3/realtime": "31.8.0",
66
- "@ultimat3/render": "31.8.0",
67
- "@ultimat3/schema": "31.8.0",
68
- "@ultimat3/scraping": "31.8.0",
69
- "@ultimat3/seo": "31.8.0",
70
- "@ultimat3/time": "31.8.0"
50
+ "@ultimat3/action": "31.9.0",
51
+ "@ultimat3/ai": "31.9.0",
52
+ "@ultimat3/auth": "31.9.0",
53
+ "@ultimat3/cache": "31.9.0",
54
+ "@ultimat3/core": "31.9.0",
55
+ "@ultimat3/db": "31.9.0",
56
+ "@ultimat3/entity": "31.9.0",
57
+ "@ultimat3/http": "31.9.0",
58
+ "@ultimat3/i18n": "31.9.0",
59
+ "@ultimat3/jobs": "31.9.0",
60
+ "@ultimat3/mail": "31.9.0",
61
+ "@ultimat3/notify": "31.9.0",
62
+ "@ultimat3/policy": "31.9.0",
63
+ "@ultimat3/pwa": "31.9.0",
64
+ "@ultimat3/query": "31.9.0",
65
+ "@ultimat3/realtime": "31.9.0",
66
+ "@ultimat3/render": "31.9.0",
67
+ "@ultimat3/schema": "31.9.0",
68
+ "@ultimat3/scraping": "31.9.0",
69
+ "@ultimat3/seo": "31.9.0",
70
+ "@ultimat3/time": "31.9.0"
71
71
  }
72
72
  }
@@ -0,0 +1,350 @@
1
+ // Entity conformance · the WRITE TERMINALS of the read chain: `db.x.where(…).updateAll(patch)` and
2
+ // `.deleteAll()` write exactly the rows the same chain reads — tenant-scoped as the read, soft delete
3
+ // and append-only honoured, a JS-only rule judged before anything stays, sealed values sealed, the
4
+ // change reported, history recorded — and an empty predicate is refused, never every row.
5
+
6
+ import { expect } from 'bun:test';
7
+ import type { Database } from '@ultimat3/entity';
8
+ import { history } from '@ultimat3/entity';
9
+ import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
10
+ import {
11
+ ledger,
12
+ logged,
13
+ loggedHistory,
14
+ notes,
15
+ posts,
16
+ swept,
17
+ vault,
18
+ } from './entity-conformance-write-entities';
19
+ import { accountedFor, heard } from './entity-conformance-write-support';
20
+ import type { EntityDriverCheck } from './entity-driver-conformance';
21
+
22
+ const [ONE, TWO, THREE] = [idAt('c1'), idAt('c2'), idAt('c3')];
23
+ const ORG = idAt('ca');
24
+ const OTHER_ORG = idAt('cb');
25
+ const WHEN = new Date('2020-01-02T03:04:05.000Z');
26
+ const UNFILTERED = 'X_WRITE_UNFILTERED';
27
+
28
+ const seedNotes = async (db: Database<{ notes: typeof notes }>): Promise<void> => {
29
+ await db.notes.insertAll([
30
+ { id: ONE, kind: 'a', title: 'one', body: 'b1', updatedAt: WHEN },
31
+ { id: TWO, kind: 'a', title: 'two', body: 'b2', updatedAt: WHEN },
32
+ { id: THREE, kind: 'b', title: 'three', body: 'b3', updatedAt: WHEN },
33
+ ]);
34
+ };
35
+
36
+ const titles = async (db: Database<{ notes: typeof notes }>) =>
37
+ (await db.notes.orderBy('id').all()).map((row) => [row.id, row.title, row.body]);
38
+
39
+ const terminals: readonly EntityDriverCheck[] = [
40
+ checkOver(
41
+ { notes },
42
+ 'chain updateAll writes the rows the chain reads, answers their count, keeps the rest',
43
+ async (db) => {
44
+ await seedNotes(db);
45
+ expect(await db.notes.where({ kind: 'a' }).updateAll({ title: 'swept' })).toBe(2);
46
+ expect(await titles(db)).toEqual([
47
+ [ONE, 'swept', 'b1'],
48
+ [TWO, 'swept', 'b2'],
49
+ [THREE, 'three', 'b3'],
50
+ ]);
51
+ },
52
+ ),
53
+ checkOver(
54
+ { notes },
55
+ 'chain updateAll and deleteAll over an in-list reach those ids',
56
+ async (db) => {
57
+ await seedNotes(db);
58
+ expect(await db.notes.andWhere('id', 'in', [ONE, THREE]).updateAll({ body: null })).toBe(2);
59
+ expect(await titles(db)).toEqual([
60
+ [ONE, 'one', null],
61
+ [TWO, 'two', 'b2'],
62
+ [THREE, 'three', null],
63
+ ]);
64
+ expect(await db.notes.andWhere('id', 'in', [ONE, THREE, idAt('cf')]).deleteAll()).toBe(2);
65
+ expect(await titles(db)).toEqual([[TWO, 'two', 'b2']]);
66
+ },
67
+ ),
68
+ checkOver(
69
+ { notes },
70
+ 'chain updateAll keeps a column the patch names as undefined, and stamps onUpdateNow',
71
+ async (db) => {
72
+ await seedNotes(db);
73
+ expect(await db.notes.where({ id: ONE }).updateAll({ title: 'moved', body: undefined })).toBe(
74
+ 1,
75
+ );
76
+ const row = await db.notes.where({ id: ONE }).one();
77
+ expect([row?.title, row?.body, row?.updatedAt.getTime() === WHEN.getTime()]).toEqual([
78
+ 'moved',
79
+ 'b1',
80
+ false,
81
+ ]);
82
+ },
83
+ ),
84
+ checkOver(
85
+ { notes },
86
+ 'an empty chain is refused, never every row; an empty patch is refused',
87
+ async (db) => {
88
+ await seedNotes(db);
89
+ const refusals = await Promise.all([
90
+ codeOf(() => db.notes.where({}).updateAll({ title: 'all' })),
91
+ codeOf(() => db.notes.where({}).deleteAll()),
92
+ codeOf(() => db.notes.where({ id: undefined }).deleteAll()),
93
+ codeOf(() => db.notes.where({ kind: 'a' }).updateAll({})),
94
+ ]);
95
+ expect(refusals).toEqual([UNFILTERED, UNFILTERED, UNFILTERED, 'X_PATCH_EMPTY']);
96
+ expect(await db.notes.count()).toBe(3);
97
+ expect((await titles(db)).map(([, title]) => title)).toEqual(['one', 'two', 'three']);
98
+ },
99
+ ),
100
+ checkOver(
101
+ { notes },
102
+ 'a write chain with a page — limit() or after() — is refused; an order is not a page',
103
+ async (db) => {
104
+ await seedNotes(db);
105
+ const paged = await Promise.all([
106
+ codeOf(() => db.notes.where({ kind: 'a' }).limit(1).updateAll({ title: 'x' })),
107
+ codeOf(() => db.notes.where({ kind: 'a' }).limit(1).deleteAll()),
108
+ codeOf(() => db.notes.where({ kind: 'a' }).after('cursor').deleteAll()),
109
+ ]);
110
+ expect(paged).toEqual([
111
+ 'X_INVARIANT_VIOLATED',
112
+ 'X_INVARIANT_VIOLATED',
113
+ 'X_INVARIANT_VIOLATED',
114
+ ]);
115
+ expect(await db.notes.count()).toBe(3);
116
+ expect(await db.notes.where({ kind: 'a' }).orderBy('title', 'desc').deleteAll()).toBe(2);
117
+ expect(await db.notes.count()).toBe(1);
118
+ },
119
+ ),
120
+ checkOver({ notes }, 'a chain matching no row writes nothing and answers 0', async (db) => {
121
+ await seedNotes(db);
122
+ expect(await db.notes.where({ kind: 'none' }).updateAll({ title: 'x' })).toBe(0);
123
+ expect(await db.notes.where({ kind: 'none' }).deleteAll()).toBe(0);
124
+ expect(await db.notes.count()).toBe(3);
125
+ }),
126
+ ];
127
+
128
+ const held = async (db: Database<{ posts: typeof posts }>) =>
129
+ [
130
+ ...(await db.posts.where({ orgId: ORG }).all()),
131
+ ...(await db.posts.where({ orgId: OTHER_ORG }).all()),
132
+ ]
133
+ .map((row) => `${row.orgId === ORG ? 'ours' : 'theirs'}:${row.title}`)
134
+ .sort();
135
+
136
+ const tenancy: readonly EntityDriverCheck[] = [
137
+ checkOver(
138
+ { posts },
139
+ 'chain updateAll and deleteAll reach only the actor’s tenant, as the chain’s read does',
140
+ async (db) => {
141
+ await db.posts.insertAll([
142
+ { id: ONE, orgId: ORG, title: 'same' },
143
+ { id: TWO, orgId: OTHER_ORG, title: 'same' },
144
+ ]);
145
+ expect(
146
+ await inOrg(ORG, () => db.posts.where({ title: 'same' }).updateAll({ title: 'x' })),
147
+ ).toBe(1);
148
+ expect(await held(db)).toEqual(['ours:x', 'theirs:same']);
149
+ expect(
150
+ await inOrg(ORG, () => db.posts.andWhere('title', 'in', ['x', 'same']).deleteAll()),
151
+ ).toBe(1);
152
+ expect(await held(db)).toEqual(['theirs:same']);
153
+ },
154
+ ),
155
+ checkOver(
156
+ { posts },
157
+ 'a chain the read refuses — no request, another tenant named — refuses the write alike',
158
+ async (db) => {
159
+ await db.posts.insertAll([
160
+ { id: ONE, orgId: ORG, title: 'same' },
161
+ { id: TWO, orgId: OTHER_ORG, title: 'same' },
162
+ ]);
163
+ const unscoped = db.posts.where({ title: 'same' });
164
+ const foreign = db.posts.where({ orgId: OTHER_ORG });
165
+ const answers = [
166
+ await codeOf(() => unscoped.all()),
167
+ await codeOf(() => unscoped.updateAll({ title: 'x' })),
168
+ await codeOf(() => unscoped.deleteAll()),
169
+ await inOrg(ORG, () => codeOf(() => foreign.all())),
170
+ await inOrg(ORG, () => codeOf(() => foreign.updateAll({ title: 'x' }))),
171
+ await inOrg(ORG, () => codeOf(() => foreign.deleteAll())),
172
+ ];
173
+ expect(answers).toEqual([
174
+ 'X_TENANCY_UNSCOPED',
175
+ 'X_TENANCY_UNSCOPED',
176
+ 'X_TENANCY_UNSCOPED',
177
+ 'X_TENANCY_ACTOR_MISMATCH',
178
+ 'X_TENANCY_ACTOR_MISMATCH',
179
+ 'X_TENANCY_ACTOR_MISMATCH',
180
+ ]);
181
+ expect(await held(db)).toEqual(['ours:same', 'theirs:same']);
182
+ },
183
+ ),
184
+ checkOver(
185
+ { posts },
186
+ 'a chain updateAll handing rows to another tenant is refused, matched or not',
187
+ async (db) => {
188
+ await db.posts.insert({ id: ONE, orgId: ORG, title: 'same' });
189
+ for (const title of ['same', 'none']) {
190
+ const move = () => db.posts.where({ title }).updateAll({ orgId: OTHER_ORG });
191
+ expect([title, await inOrg(ORG, () => codeOf(move))]).toEqual([
192
+ title,
193
+ 'X_TENANCY_ACTOR_MISMATCH',
194
+ ]);
195
+ }
196
+ expect(await held(db)).toEqual(['ours:same']);
197
+ },
198
+ ),
199
+ ];
200
+
201
+ const semantics: readonly EntityDriverCheck[] = [
202
+ checkOver(
203
+ { swept },
204
+ 'chain deleteAll soft-deletes; chain updateAll cannot reach a soft-deleted row',
205
+ async (db, { driver }) => {
206
+ await db.swept.insertAll([
207
+ { id: ONE, kind: 'k', reason: 'r', deletedAt: null },
208
+ { id: TWO, kind: 'k', reason: 'r', deletedAt: null },
209
+ ]);
210
+ expect(await db.swept.where({ id: ONE }).deleteAll()).toBe(1);
211
+ expect(await db.swept.where({ kind: 'k' }).updateAll({ reason: 'later' })).toBe(1);
212
+ const { rows } = await driver.repo(swept).findMany({
213
+ includeDeleted: true,
214
+ orderBy: [{ column: 'id', direction: 'asc' }],
215
+ });
216
+ expect(rows.map((row) => [row.id, row.reason, row.deletedAt === null])).toEqual([
217
+ [ONE, 'r', false],
218
+ [TWO, 'later', true],
219
+ ]);
220
+ },
221
+ ),
222
+ checkOver(
223
+ { swept },
224
+ 'a chain write breaking a JS-only rule on one row is refused as one; no row moves',
225
+ async (db) => {
226
+ await db.swept.insertAll([
227
+ { id: ONE, kind: 'k', reason: 'fine', deletedAt: null },
228
+ { id: TWO, kind: 'k', reason: null, deletedAt: null },
229
+ ]);
230
+ const stamp = () => db.swept.where({ kind: 'k' }).updateAll({ deletedAt: WHEN });
231
+ expect(await codeOf(stamp)).toBe('X_INVARIANT_VIOLATED');
232
+ expect(await codeOf(() => db.swept.where({ kind: 'k' }).deleteAll())).toBe(
233
+ 'X_INVARIANT_VIOLATED',
234
+ );
235
+ expect((await db.swept.orderBy('id').all()).map((row) => row.reason)).toEqual(['fine', null]);
236
+ },
237
+ ),
238
+ checkOver(
239
+ { ledger },
240
+ 'an append-only table refuses chain updateAll and deleteAll',
241
+ async (db) => {
242
+ await db.ledger.insert({ id: ONE, account: 'cash', note: 'n' });
243
+ expect(
244
+ await codeOf(() => db.ledger.where({ account: 'cash' }).updateAll({ note: 'x' })),
245
+ ).toBe('X_ENTITY_APPEND_ONLY');
246
+ expect(await codeOf(() => db.ledger.where({ account: 'cash' }).deleteAll())).toBe(
247
+ 'X_ENTITY_APPEND_ONLY',
248
+ );
249
+ expect((await db.ledger.all()).map((row) => row.note)).toEqual(['n']);
250
+ },
251
+ ),
252
+ checkOver(
253
+ { vault },
254
+ 'a chain updateAll seals what it writes, filters on a lookup column, refuses a sealed one',
255
+ async (db) => {
256
+ await db.vault.insertAll([
257
+ { id: ONE, label: 'a', secret: null, email: 'a@example.com' },
258
+ { id: TWO, label: 'b', secret: null, email: 'b@example.com' },
259
+ ]);
260
+ expect(
261
+ await db.vault.where({ email: 'a@example.com' }).updateAll({ secret: 'hunter2' }),
262
+ ).toBe(1);
263
+ const [one, two] = await db.vault.orderBy('id').all();
264
+ expect([one?.secret, two?.secret]).toEqual(['hunter2', null]);
265
+ // `secret` is sealed and not a lookup: no predicate may name it, on a write as on a read.
266
+ const named = db.vault.where({ secret: 'hunter2' } as never);
267
+ expect(await codeOf(() => named.updateAll({ label: 'x' }))).toBe('X_ENTITY_SEALED_PREDICATE');
268
+ expect(await codeOf(() => named.deleteAll())).toBe('X_ENTITY_SEALED_PREDICATE');
269
+ expect(await db.vault.count()).toBe(2);
270
+ },
271
+ ),
272
+ ];
273
+
274
+ const reported: readonly EntityDriverCheck[] = [
275
+ checkOver(
276
+ { notes },
277
+ 'a chain write is reported to the row observer as the count it wrote, never silence',
278
+ async (db) => {
279
+ await seedNotes(db);
280
+ const update = await heard('ec_wr_notes', () =>
281
+ db.notes.where({ kind: 'a' }).updateAll({ title: 'x' }),
282
+ );
283
+ const nothing = await heard('ec_wr_notes', () =>
284
+ db.notes.where({ kind: 'none' }).updateAll({ title: 'x' }),
285
+ );
286
+ const remove = await heard('ec_wr_notes', () => db.notes.where({ kind: 'a' }).deleteAll());
287
+ expect([update.answer, accountedFor(update.heard)]).toEqual([2, 2]);
288
+ expect(update.heard.bulk).toEqual([{ entity: 'ec_wr_notes', op: 'update', rows: 2 }]);
289
+ expect([nothing.answer, accountedFor(nothing.heard)]).toEqual([0, 0]);
290
+ expect([remove.answer, accountedFor(remove.heard)]).toEqual([2, 2]);
291
+ expect(remove.heard.bulk).toEqual([{ entity: 'ec_wr_notes', op: 'delete', rows: 2 }]);
292
+ },
293
+ ),
294
+ checkOver(
295
+ { logged, loggedHistory },
296
+ 'a chain updateAll and deleteAll each write one history version per row',
297
+ async (db, raw) => {
298
+ // A `defineDriver` store records no history (`EntityDriverSubject.history`): no claim to hold.
299
+ if (!raw.history) return;
300
+ const versions = await inOrg(ORG, async () => {
301
+ await db.logged.insertAll([
302
+ { id: ONE, orgId: ORG, title: 'a' },
303
+ { id: TWO, orgId: ORG, title: 'a' },
304
+ ]);
305
+ await db.logged.where({ title: 'a' }).updateAll({ title: 'b' });
306
+ await db.logged.where({ id: ONE }).deleteAll();
307
+ return [await history(db.loggedHistory, ONE), await history(db.loggedHistory, TWO)];
308
+ });
309
+ const title = (image: unknown): string | null =>
310
+ (image as { title?: string } | null)?.title ?? null;
311
+ expect(
312
+ versions.map((all) => all.map((v) => [v.op, title(v.before), title(v.after)])),
313
+ ).toEqual([
314
+ [
315
+ ['insert', null, 'a'],
316
+ ['update', 'a', 'b'],
317
+ ['delete', 'b', null],
318
+ ],
319
+ [
320
+ ['insert', null, 'a'],
321
+ ['update', 'a', 'b'],
322
+ ],
323
+ ]);
324
+ },
325
+ ),
326
+ checkOver(
327
+ { notes },
328
+ 'a chain write inside a transaction that fails is undone with it',
329
+ async (db, { driver }) => {
330
+ await seedNotes(db);
331
+ const failed = await codeOf(() =>
332
+ driver.transactor().run(async () => {
333
+ await db.notes.where({ kind: 'a' }).updateAll({ title: 'gone' });
334
+ await db.notes.where({ kind: 'b' }).deleteAll();
335
+ await db.notes.insert({ id: ONE, kind: 'dup', title: 'dup' });
336
+ }),
337
+ );
338
+ expect(failed).toBe('X_DB_UNIQUE_VIOLATION');
339
+ expect((await titles(db)).map(([, title]) => title)).toEqual(['one', 'two', 'three']);
340
+ },
341
+ ['transactions'],
342
+ ),
343
+ ];
344
+
345
+ export const CHAIN_WRITE_CHECKS: readonly EntityDriverCheck[] = [
346
+ ...terminals,
347
+ ...tenancy,
348
+ ...semantics,
349
+ ...reported,
350
+ ];
@@ -4,11 +4,16 @@
4
4
  import { AGGREGATE_CHECKS } from './entity-conformance-aggregates';
5
5
  import { BATCH_CHECKS } from './entity-conformance-batches';
6
6
  import { BULK_CHECKS } from './entity-conformance-bulk';
7
+ import { CHAIN_WRITE_CHECKS } from './entity-conformance-chain-writes';
7
8
  import { HISTORY_CHECKS } from './entity-conformance-history';
8
9
  import { LOCK_CHECKS } from './entity-conformance-locks';
9
10
  import { MATRIX_CHECKS } from './entity-conformance-matrix';
11
+ import { MATRIX_WRITE_CHECKS } from './entity-conformance-matrix-writes';
12
+ import { PAGE_BYTE_CHECKS } from './entity-conformance-page-bytes';
10
13
  import { READ_CHECKS } from './entity-conformance-reads';
11
14
  import { TENANCY_CHECKS } from './entity-conformance-tenancy';
15
+ import { UNRETURNED_CHECKS } from './entity-conformance-unreturned';
16
+ import { UPDATE_MANY_CHECKS } from './entity-conformance-update-many';
12
17
  import { VALUE_CHECKS } from './entity-conformance-values';
13
18
  import { VERSION_CHECKS } from './entity-conformance-versions';
14
19
  import { WRITE_CHECKS } from './entity-conformance-writes';
@@ -18,12 +23,17 @@ export const ENTITY_DRIVER_CHECKS: readonly EntityDriverCheck[] = [
18
23
  ...WRITE_CHECKS,
19
24
  ...VALUE_CHECKS,
20
25
  ...READ_CHECKS,
26
+ ...PAGE_BYTE_CHECKS,
21
27
  ...BULK_CHECKS,
28
+ ...CHAIN_WRITE_CHECKS,
29
+ ...UPDATE_MANY_CHECKS,
30
+ ...UNRETURNED_CHECKS,
22
31
  ...AGGREGATE_CHECKS,
23
32
  ...TENANCY_CHECKS,
24
33
  ...BATCH_CHECKS,
25
34
  ...LOCK_CHECKS,
26
35
  ...MATRIX_CHECKS,
36
+ ...MATRIX_WRITE_CHECKS,
27
37
  ...VERSION_CHECKS,
28
38
  ...HISTORY_CHECKS,
29
39
  ];
@@ -0,0 +1,75 @@
1
+ // Entity conformance · the column matrix through the WRITE PATHS that bind rows their own way:
2
+ // `copyAll` (COPY's text format on Postgres — a tab, a newline, a backslash and the word NULL are
3
+ // its own syntax), `insertAll({ returning: false })` and `updateMany`. Every row of the matrix,
4
+ // written each way, reads back exactly what the reference `memoryDriver()` reads after `insert`.
5
+
6
+ import { expect } from 'bun:test';
7
+ import type { Driver } from '@ultimat3/entity';
8
+ import { memoryDriver } from '@ultimat3/entity';
9
+ import {
10
+ idFor,
11
+ MATRIX_ROWS,
12
+ type MatrixWrite,
13
+ matrix,
14
+ matrixDb,
15
+ } from './entity-conformance-matrix';
16
+ import { checkOver } from './entity-conformance-support';
17
+ import type { EntityDriverCheck } from './entity-driver-conformance';
18
+
19
+ /** The row a keyed read answers after `insert`, on memory: what every path must read back. */
20
+ const reference = async (write: MatrixWrite) => {
21
+ const db = matrixDb(memoryDriver());
22
+ await db.rows.insert(write);
23
+ return db.rows.where({ id: write.id as string }).one();
24
+ };
25
+
26
+ /** A row naming every scalar and no array: what `updateMany` starts from. */
27
+ const base = (id: string, write: MatrixWrite): MatrixWrite => ({
28
+ id,
29
+ label: 'base',
30
+ mood: 'sad',
31
+ count: 0,
32
+ flag: false,
33
+ at: new Date('2000-01-01T00:00:00.000Z'),
34
+ rate: '0',
35
+ day: write.day,
36
+ big: '0',
37
+ data: { plan: 'base', seats: 0 },
38
+ });
39
+
40
+ type Path = (driver: Driver, write: MatrixWrite) => Promise<number>;
41
+
42
+ const PATHS: Readonly<Record<string, Path>> = {
43
+ copyAll: (driver, write) => matrixDb(driver).rows.copyAll([write]),
44
+ 'insertAll({ returning: false })': (driver, write) =>
45
+ matrixDb(driver).rows.insertAll([write], { returning: false }),
46
+ updateMany: async (driver, write) => {
47
+ const db = matrixDb(driver);
48
+ const { id, ...patch } = write;
49
+ if (id === undefined) return expect.unreachable('every matrix row is written with its id');
50
+ await db.rows.insert(base(id, write));
51
+ return db.rows.updateMany([{ id, patch }]);
52
+ },
53
+ };
54
+
55
+ const checks: readonly EntityDriverCheck[] = Object.entries(PATHS).flatMap(([path, run]) =>
56
+ Object.entries(MATRIX_ROWS).map(([name, row], index) =>
57
+ checkOver(
58
+ { matrix },
59
+ `column matrix · ${path} · ${name}: reads back what memory reads back`,
60
+ async (_db, { driver }) => {
61
+ const write = { ...row, id: idFor(index) };
62
+ const expected = await reference(write);
63
+ expect(await run(driver, write)).toBe(1);
64
+ const read = await matrixDb(driver)
65
+ .rows.where({ id: idFor(index) })
66
+ .one();
67
+ expect(read).toEqual(expected);
68
+ // Not two wrong answers agreeing: the reference holds the row as written.
69
+ expect(expected?.label).toBe(write.label);
70
+ },
71
+ ),
72
+ ),
73
+ );
74
+
75
+ export const MATRIX_WRITE_CHECKS: readonly EntityDriverCheck[] = checks;
@@ -38,7 +38,7 @@ const MOODS = ['sad', 'ok', 'happy'] as const;
38
38
  * NULL inside a row value, the one shape a driver's binary array reader has to carry a null bitmap
39
39
  * for. Every array column is nullable so one row can hold `null` for the whole column.
40
40
  */
41
- const matrix = remember(
41
+ export const matrix = remember(
42
42
  entity('ec_m_rows', {
43
43
  columns: {
44
44
  id: uuid().primaryKey(),
@@ -76,9 +76,9 @@ const matrix = remember(
76
76
  }),
77
77
  );
78
78
 
79
- type MatrixWrite = Parameters<ReturnType<typeof matrixDb>['rows']['insert']>[0];
79
+ export type MatrixWrite = Parameters<ReturnType<typeof matrixDb>['rows']['insert']>[0];
80
80
 
81
- const matrixDb = (driver: Driver) => database({ rows: matrix }, { driver });
81
+ export const matrixDb = (driver: Driver) => database({ rows: matrix }, { driver });
82
82
 
83
83
  const A = '01a12719-28e5-735e-b5bb-000000000001';
84
84
  const B = '01a12719-28e5-735e-b5bb-000000000002';
@@ -113,7 +113,7 @@ const NASTY_TEXT = [
113
113
  ] as const;
114
114
 
115
115
  /** Named, so a failure says which row of the matrix it was. */
116
- const MATRIX_ROWS: Readonly<Record<string, MatrixWrite>> = Object.freeze({
116
+ export const MATRIX_ROWS: Readonly<Record<string, MatrixWrite>> = Object.freeze({
117
117
  'every array holds two members': {
118
118
  ...SCALARS,
119
119
  label: 'full',
@@ -279,7 +279,7 @@ const matches = async (driver: Driver, id: string, column: string, member: unkno
279
279
  };
280
280
 
281
281
  /** Fixed per row so a SQL subject and the memory reference write the same key. */
282
- const idFor = (index: number): string =>
282
+ export const idFor = (index: number): string =>
283
283
  `01a12719-28e5-735e-b5bb-0000000001${String(index).padStart(2, '0')}`;
284
284
 
285
285
  /** The ratchet: a kind added to `COLUMN_KINDS` with no column here is red, for every driver. */
@@ -0,0 +1,57 @@
1
+ // Entity conformance · the page BYTE bound: a page whose raw cells weigh past `MAX_PAGE_BYTES` is
2
+ // refused with `X_ENTITY_PAGE_TOO_LARGE` before it is decoded, naming the two ways out — and both
3
+ // ways out, a narrower `select()` and a smaller `limit()`, answer. Every driver, one bound.
4
+
5
+ import { expect } from 'bun:test';
6
+ import { isUltimateError } from '@ultimat3/core';
7
+ import { entity, MAX_PAGE_BYTES, text, uuid } from '@ultimat3/entity';
8
+ import { remember } from './entity-conformance-entities';
9
+ import { checkOver, idAt } from './entity-conformance-support';
10
+ import type { EntityDriverCheck } from './entity-driver-conformance';
11
+
12
+ const heavy = remember(
13
+ entity('ec_pb_heavy', {
14
+ columns: { id: uuid().primaryKey(), label: text({ max: 20 }), body: text() },
15
+ }),
16
+ );
17
+
18
+ /** Five bodies, each just over a fifth of the bound: the whole table is past it, four are not. */
19
+ const ROWS = 5;
20
+ const BODY = 'x'.repeat(Math.floor(MAX_PAGE_BYTES / ROWS) + 1024);
21
+
22
+ /** The refusal's code and fix, or what the read answered when nothing was refused. */
23
+ const refusal = async (work: () => Promise<unknown>) => {
24
+ try {
25
+ return { answered: await work() };
26
+ } catch (error) {
27
+ return isUltimateError(error)
28
+ ? { code: error.code, fix: error.fix }
29
+ : { uncoded: String(error) };
30
+ }
31
+ };
32
+
33
+ export const PAGE_BYTE_CHECKS: readonly EntityDriverCheck[] = [
34
+ checkOver(
35
+ { heavy },
36
+ 'a page past the byte bound is refused, naming select() and a limit() — and both answer',
37
+ async (db) => {
38
+ // One row per statement: the bound is on what a READ answers, not on what a write binds.
39
+ for (let index = 1; index <= ROWS; index += 1) {
40
+ await db.heavy.insert({ id: idAt(index), label: `r${index}`, body: BODY });
41
+ }
42
+ const refused = await refusal(() => db.heavy.all());
43
+ expect(refused).toMatchObject({ code: 'X_ENTITY_PAGE_TOO_LARGE' });
44
+ const fix = 'fix' in refused ? String(refused.fix) : '';
45
+ expect([fix.includes('.select('), fix.includes('.limit(')]).toEqual([true, true]);
46
+ const narrow = await db.heavy.orderBy('id').select({ id: true, label: true }).all();
47
+ expect(narrow.map((row) => row.label)).toEqual(['r1', 'r2', 'r3', 'r4', 'r5']);
48
+ const fewer = await db.heavy
49
+ .orderBy('id')
50
+ .limit(ROWS - 1)
51
+ .all();
52
+ expect(fewer.map((row) => [row.label, row.body.length])).toEqual(
53
+ [1, 2, 3, 4].map((index) => [`r${index}`, BODY.length]),
54
+ );
55
+ },
56
+ ),
57
+ ];
@@ -206,6 +206,7 @@ const writeTenancy: readonly EntityDriverCheck[] = [
206
206
 
207
207
  const VIOLATION = 'X_DB_FOREIGN_KEY_VIOLATION';
208
208
  const [THREAD_A, THREAD_B, MISSING] = [idAt('1a'), idAt('1b'), idAt('ff')];
209
+ const THREAD_C = idAt('1c');
209
210
  const SET = { orgs, threads, comments };
210
211
  const comment = (suffix: string, over: Record<string, unknown> = {}) =>
211
212
  ({ id: idAt(suffix), orgId: ORG, threadId: THREAD_A, ...over }) as never;
@@ -293,4 +294,48 @@ const sameTenant: readonly EntityDriverCheck[] = [
293
294
  ),
294
295
  ];
295
296
 
296
- export const TENANCY_CHECKS: readonly EntityDriverCheck[] = [...writeTenancy, ...sameTenant];
297
+ /** The many-row writes (`copyAll`, the count-only insert, `updateMany`, a chain write) refuse alike. */
298
+ const sameTenantBulk: readonly EntityDriverCheck[] = [
299
+ checkOver(
300
+ SET,
301
+ 'copyAll and insertAll({ returning: false }) refuse a reference into another tenant whole',
302
+ async (db) => {
303
+ await seedThreads(db);
304
+ const batch = [comment('81'), comment('82', { threadId: THREAD_B })];
305
+ expect(await codeOf(() => db.comments.copyAll(batch))).toBe(VIOLATION);
306
+ expect(await codeOf(() => db.comments.insertAll(batch, { returning: false }))).toBe(
307
+ VIOLATION,
308
+ );
309
+ expect(await db.comments.where({ orgId: ORG }).count()).toBe(0);
310
+ expect(await db.comments.copyAll([comment('83')])).toBe(1);
311
+ },
312
+ ),
313
+ checkOver(
314
+ SET,
315
+ 'updateMany and a chain updateAll refuse moving a row onto another tenant’s parent',
316
+ async (db) => {
317
+ await seedThreads(db);
318
+ await db.threads.insert({ id: THREAD_C, orgId: ORG, title: 'c' });
319
+ await db.comments.insertAll([comment('91'), comment('92')]);
320
+ // The first patch is legal: a batch that wrote row by row would move it before refusing.
321
+ const many = () =>
322
+ db.comments.updateMany([
323
+ { id: idAt('91'), patch: { threadId: THREAD_C } },
324
+ { id: idAt('92'), patch: { threadId: THREAD_B } },
325
+ ]);
326
+ // In the actor's own org: unscoped, these are `X_TENANCY_UNSCOPED` before any reference.
327
+ expect(await inOrg(ORG, () => codeOf(many))).toBe(VIOLATION);
328
+ const chain = () =>
329
+ db.comments.where({ orgId: ORG }).updateAll({ threadId: THREAD_B } as never);
330
+ expect(await inOrg(ORG, () => codeOf(chain))).toBe(VIOLATION);
331
+ const kept = await db.comments.where({ orgId: ORG }).orderBy('id').all();
332
+ expect(kept.map((row) => row.threadId)).toEqual([THREAD_A, THREAD_A]);
333
+ },
334
+ ),
335
+ ];
336
+
337
+ export const TENANCY_CHECKS: readonly EntityDriverCheck[] = [
338
+ ...writeTenancy,
339
+ ...sameTenant,
340
+ ...sameTenantBulk,
341
+ ];