@ultimat3/testing 30.8.0 → 31.0.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.
Files changed (159) hide show
  1. package/CLAUDE.md +49 -62
  2. package/README.md +179 -39
  3. package/package.json +23 -17
  4. package/src/ai-conformance-answer.ts +67 -0
  5. package/src/ai-gateway-conformance.ts +105 -0
  6. package/src/ai-provider-conformance.ts +69 -0
  7. package/src/ai-provider-transport-conformance.ts +170 -0
  8. package/src/audit-sink-conformance.ts +204 -0
  9. package/src/auth-adapter-conformance-credentials.ts +124 -0
  10. package/src/auth-adapter-conformance-mfa.ts +70 -0
  11. package/src/auth-adapter-conformance-passkeys.ts +133 -0
  12. package/src/auth-adapter-conformance-sessions.ts +115 -0
  13. package/src/auth-adapter-conformance-support.ts +71 -0
  14. package/src/auth-adapter-conformance-users.ts +128 -0
  15. package/src/auth-adapter-conformance.ts +34 -0
  16. package/src/auth-limiter-factory-conformance.ts +224 -0
  17. package/src/auth-server-store-conformance-records.ts +69 -0
  18. package/src/auth-server-store-conformance.ts +208 -0
  19. package/src/cache-tier-conformance-checks.ts +142 -0
  20. package/src/cache-tier-conformance.ts +24 -0
  21. package/src/cassette-format.ts +8 -13
  22. package/src/cassette-record.ts +1 -1
  23. package/src/cdp-browser.ts +10 -11
  24. package/src/cdp-e2e-page.ts +2 -2
  25. package/src/cdp-e2e-session.ts +2 -2
  26. package/src/cdp-network-probe.ts +1 -1
  27. package/src/cdp-offline-script.ts +2 -2
  28. package/src/clock-conformance.ts +126 -0
  29. package/src/conformance.ts +239 -0
  30. package/src/e2e-browser-handle.ts +1 -2
  31. package/src/e2e-error-codes.ts +17 -16
  32. package/src/e2e-run.ts +4 -3
  33. package/src/embedder-conformance.ts +101 -0
  34. package/src/entity-conformance-aggregates.ts +210 -0
  35. package/src/entity-conformance-batches.ts +216 -0
  36. package/src/entity-conformance-bulk.ts +379 -0
  37. package/src/entity-conformance-checks.ts +27 -0
  38. package/src/entity-conformance-entities.ts +52 -0
  39. package/src/entity-conformance-locks.ts +286 -0
  40. package/src/entity-conformance-matrix.ts +397 -0
  41. package/src/entity-conformance-reads.ts +241 -0
  42. package/src/entity-conformance-support.ts +56 -0
  43. package/src/entity-conformance-tenancy.ts +296 -0
  44. package/src/entity-conformance-values.ts +305 -0
  45. package/src/entity-conformance-versions.ts +60 -0
  46. package/src/entity-conformance-writes.ts +348 -0
  47. package/src/entity-driver-conformance.ts +103 -0
  48. package/src/error-groups-store-conformance.ts +198 -0
  49. package/src/error-reporter-conformance.ts +119 -0
  50. package/src/errors.ts +41 -11
  51. package/src/event-bus-conformance.ts +161 -0
  52. package/src/exercise-drift-hint.ts +4 -1
  53. package/src/exercise-judge.ts +5 -3
  54. package/src/exercise-override-input.ts +22 -9
  55. package/src/exercise-override-line.ts +98 -0
  56. package/src/exercise-report.ts +30 -51
  57. package/src/exercise-sweeps.ts +3 -1
  58. package/src/exercise.ts +38 -19
  59. package/src/factories.ts +192 -179
  60. package/src/factory-api.ts +131 -0
  61. package/src/factory-associations.ts +67 -0
  62. package/src/factory-errors.ts +38 -0
  63. package/src/factory-lint.ts +92 -0
  64. package/src/factory-persist.ts +74 -16
  65. package/src/factory-pipeline.ts +191 -0
  66. package/src/factory-registry.ts +2 -1
  67. package/src/factory-types.ts +131 -0
  68. package/src/failure-store-conformance.ts +137 -0
  69. package/src/fixture-jobs.ts +50 -15
  70. package/src/fixture-mail.ts +7 -7
  71. package/src/fixture-seed.ts +111 -0
  72. package/src/fixture-statements.ts +68 -52
  73. package/src/framework-fixtures.ts +1 -1
  74. package/src/idempotency-store-conformance.ts +186 -0
  75. package/src/idempotency-store-replay-conformance.ts +140 -0
  76. package/src/idempotency-store-tx-conformance.ts +132 -0
  77. package/src/idempotency-store-world-conformance.ts +82 -0
  78. package/src/identity-provider-conformance.ts +144 -0
  79. package/src/image-transform-conformance.ts +89 -0
  80. package/src/index.ts +68 -157
  81. package/src/isr-store-conformance.ts +113 -0
  82. package/src/job-sim-effects.ts +19 -31
  83. package/src/job-sim-world.ts +6 -15
  84. package/src/lease-store-conformance.ts +195 -0
  85. package/src/mail-driver-conformance.ts +108 -0
  86. package/src/matcher-doubles.ts +104 -0
  87. package/src/matcher-stub.ts +78 -0
  88. package/src/matcher-surface.ts +21 -0
  89. package/src/matchers.ts +19 -1
  90. package/src/mcp-confirmation-store-conformance.ts +262 -0
  91. package/src/meter-store-conformance.ts +135 -0
  92. package/src/notify-digest-conformance.ts +133 -0
  93. package/src/notify-inbox-conformance.ts +130 -0
  94. package/src/notify-ledger-conformance.ts +134 -0
  95. package/src/notify-preference-conformance.ts +49 -0
  96. package/src/notify-stores-conformance.ts +73 -0
  97. package/src/outbox-store-conformance-claims.ts +112 -0
  98. package/src/outbox-store-conformance-subject.ts +65 -0
  99. package/src/outbox-store-conformance.ts +71 -0
  100. package/src/per-test-reset.ts +55 -20
  101. package/src/plan-oracle.ts +10 -3
  102. package/src/plan-sweep.ts +37 -12
  103. package/src/preload.ts +4 -2
  104. package/src/purge-conformance.ts +79 -0
  105. package/src/push-device-conformance.ts +124 -0
  106. package/src/push-subscription-conformance.ts +123 -0
  107. package/src/quiet-logs.ts +4 -4
  108. package/src/rate-limit-store-conformance.ts +178 -0
  109. package/src/registry-leak-error.ts +8 -1
  110. package/src/scale-sweep-run.ts +3 -1
  111. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  112. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  113. package/src/scrape-driver-conformance-site.ts +84 -0
  114. package/src/scrape-driver-conformance.ts +34 -0
  115. package/src/sealed-dns-resolver.ts +56 -0
  116. package/src/sealed-dns.ts +63 -64
  117. package/src/sealed-network.ts +13 -12
  118. package/src/sealed-node-sockets.ts +63 -0
  119. package/src/sealed-sockets.ts +13 -8
  120. package/src/sealed-udp.ts +118 -0
  121. package/src/search-index-conformance-list.ts +76 -0
  122. package/src/search-index-conformance-support.ts +69 -0
  123. package/src/search-index-conformance-versions.ts +66 -0
  124. package/src/search-index-conformance.ts +126 -0
  125. package/src/secret-source-conformance.ts +91 -0
  126. package/src/seed-factories.ts +57 -0
  127. package/src/seed-writer.ts +8 -19
  128. package/src/semantic-cache-factory-conformance.ts +86 -0
  129. package/src/sms-transport-conformance.ts +102 -0
  130. package/src/step-store-conformance.ts +171 -0
  131. package/src/storage-conformance-read-checks.ts +132 -0
  132. package/src/storage-conformance-shape.ts +121 -0
  133. package/src/storage-conformance-stream-checks.ts +226 -0
  134. package/src/storage-conformance.ts +34 -0
  135. package/src/stub-action.ts +24 -0
  136. package/src/stub-errors.ts +86 -0
  137. package/src/stub-job.ts +30 -0
  138. package/src/stub-query.ts +25 -0
  139. package/src/stub-script.ts +76 -0
  140. package/src/stub-stack.ts +29 -0
  141. package/src/stub.ts +73 -0
  142. package/src/swap-adapter.ts +135 -0
  143. package/src/test-scope.ts +96 -0
  144. package/src/test-types.ts +1 -1
  145. package/src/totp-replay-guard-conformance.ts +76 -0
  146. package/src/transport-conformance.ts +179 -0
  147. package/src/upload-scanner-conformance.ts +112 -0
  148. package/src/vector-store-conformance-checks.ts +174 -0
  149. package/src/vector-store-conformance.ts +21 -0
  150. package/src/cdp-connection.ts +0 -291
  151. package/src/cdp-errors.ts +0 -179
  152. package/src/cdp-launch-attempt.ts +0 -224
  153. package/src/cdp-launch-candidates.ts +0 -62
  154. package/src/cdp-launch-profile.ts +0 -106
  155. package/src/cdp-launch-reap.ts +0 -68
  156. package/src/cdp-launch-wire.ts +0 -171
  157. package/src/cdp-launch.ts +0 -175
  158. package/src/cdp-pipe.ts +0 -77
  159. package/src/cdp-wire-watch.ts +0 -113
@@ -0,0 +1,286 @@
1
+ // Entity conformance · `lock` and `lockKey`: 20 racing read-modify-writes lose nothing, the read is
2
+ // the read path's (another org's id, a soft-deleted row: `X_NOT_FOUND`), a throw undoes what the
3
+ // callback wrote, a nested lock joins and holds to the outer end, a plain write waits for the
4
+ // holder. Lifted from `entity/src/lock-parity.test.ts`.
5
+
6
+ import { expect } from 'bun:test';
7
+ import { ctxOf, runWithContext, userActor } from '@ultimat3/core';
8
+ import type { Database, Tx } from '@ultimat3/entity';
9
+ import {
10
+ CROSS_TENANT_SCOPE,
11
+ crossTenant,
12
+ entity,
13
+ integer,
14
+ text,
15
+ timestamp,
16
+ uuid,
17
+ } from '@ultimat3/entity';
18
+ import { remember } from './entity-conformance-entities';
19
+ import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
20
+ import type { EntityDriverCheck } from './entity-driver-conformance';
21
+
22
+ const counters = remember(
23
+ entity('ec_l_counters', {
24
+ columns: {
25
+ id: uuid().primaryKey(),
26
+ orgId: uuid().tenant(),
27
+ hits: integer(),
28
+ deletedAt: timestamp().nullable(),
29
+ },
30
+ }),
31
+ );
32
+ const globals = remember(
33
+ entity('ec_l_globals', { columns: { id: uuid().primaryKey(), label: text({ max: 10 }) } }),
34
+ );
35
+
36
+ const SET = { counters, globals };
37
+ type Db = Database<typeof SET>;
38
+ const [ORG_A, ORG_B] = [idAt('a'), idAt('b')];
39
+ const LOCK = ['lock'] as const;
40
+ const LOCK_TX = ['lock', 'transactions'] as const;
41
+
42
+ // A foreign failure handed to the subject: test input, never its verdict.
43
+ const CALLBACK_FAILED = new Error('the callback failed');
44
+
45
+ /** A turn of the event loop, so a read-modify-write has a window if the lock does not close it. */
46
+ const yieldNow = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 1));
47
+
48
+ const counter = (db: Db, id: string, hits = 0, deletedAt: Date | null = null) =>
49
+ db.counters.insert({ id, orgId: ORG_A, hits, deletedAt });
50
+ const hitsOf = async (db: Db, id: string) =>
51
+ (await db.counters.where({ id, orgId: ORG_A }).one())?.hits;
52
+
53
+ const lockChecks: readonly EntityDriverCheck[] = [
54
+ checkOver(
55
+ SET,
56
+ 'lock: 20 racers end at 20',
57
+ async (db) => {
58
+ await counter(db, idAt('1'));
59
+ await inOrg(ORG_A, () =>
60
+ Promise.all(
61
+ Array.from({ length: 20 }, () =>
62
+ db.counters.lock(idAt('1'), async (row, tx) => {
63
+ await yieldNow();
64
+ await db.counters.update(idAt('1'), { hits: row.hits + 1 }, { tx });
65
+ }),
66
+ ),
67
+ ),
68
+ );
69
+ expect(await hitsOf(db, idAt('1'))).toBe(20);
70
+ },
71
+ LOCK_TX,
72
+ ),
73
+ checkOver(
74
+ SET,
75
+ 'lock reads as a read: another org, an unknown id, a soft-deleted row',
76
+ async (db) => {
77
+ await counter(db, idAt('2'));
78
+ await counter(db, idAt('3'), 0, new Date(0));
79
+ let ran = false;
80
+ const touch = async () => {
81
+ ran = true;
82
+ };
83
+ expect(await codeOf(() => inOrg(ORG_B, () => db.counters.lock(idAt('2'), touch)))).toBe(
84
+ 'X_NOT_FOUND',
85
+ );
86
+ expect(ran).toBe(false);
87
+ expect(await codeOf(() => inOrg(ORG_A, () => db.counters.lock(idAt('ff'), () => 1)))).toBe(
88
+ 'X_NOT_FOUND',
89
+ );
90
+ expect(await codeOf(() => inOrg(ORG_A, () => db.counters.lock(idAt('3'), () => 1)))).toBe(
91
+ 'X_NOT_FOUND',
92
+ );
93
+ expect(await codeOf(() => db.counters.lock(idAt('2'), () => 1))).toBe('X_TENANCY_UNSCOPED');
94
+ await db.globals.insert({ id: idAt('6'), label: 'x' });
95
+ expect(await db.globals.lock(idAt('6'), (row) => row.label)).toBe('x');
96
+ },
97
+ LOCK,
98
+ ),
99
+ checkOver(
100
+ SET,
101
+ 'lock: a throw rolls back what the callback wrote',
102
+ async (db) => {
103
+ await counter(db, idAt('4'), 7);
104
+ const failing = () =>
105
+ db.counters.lock(idAt('4'), async (_row, tx) => {
106
+ await db.counters.update(idAt('4'), { hits: 99 }, { tx });
107
+ throw CALLBACK_FAILED;
108
+ });
109
+ expect(await codeOf(() => inOrg(ORG_A, failing))).toBe('uncoded');
110
+ expect(await hitsOf(db, idAt('4'))).toBe(7);
111
+ },
112
+ LOCK_TX,
113
+ ),
114
+ checkOver(
115
+ SET,
116
+ 'lock answers what the callback answered, and may be taken again inside',
117
+ async (db) => {
118
+ await counter(db, idAt('5'), 1);
119
+ const answer = await inOrg(ORG_A, () =>
120
+ db.counters.lock(idAt('5'), (outer) =>
121
+ db.counters.lock(idAt('5'), (inner) => `${outer.hits}-${inner.hits}`),
122
+ ),
123
+ );
124
+ expect(answer).toBe('1-1');
125
+ },
126
+ LOCK,
127
+ ),
128
+ checkOver(
129
+ SET,
130
+ 'a nested lock joins: the outer throw undoes its write',
131
+ async (db) => {
132
+ await counter(db, idAt('c1'));
133
+ await counter(db, idAt('c2'), 5);
134
+ const nested = inOrg(ORG_A, () =>
135
+ db.counters.lock(idAt('c1'), async () => {
136
+ await db.counters.lock(idAt('c2'), (_row, tx) =>
137
+ db.counters.update(idAt('c2'), { hits: 6 }, { tx }),
138
+ );
139
+ throw CALLBACK_FAILED;
140
+ }),
141
+ );
142
+ await nested.catch(() => undefined);
143
+ expect(await hitsOf(db, idAt('c2'))).toBe(5);
144
+ },
145
+ LOCK_TX,
146
+ ),
147
+ checkOver(
148
+ SET,
149
+ 'a nested lock is held to the outer end, not released with its own',
150
+ async (db) => {
151
+ await counter(db, idAt('c3'));
152
+ await counter(db, idAt('c4'));
153
+ const order: string[] = [];
154
+ await inOrg(ORG_A, () =>
155
+ Promise.all([
156
+ db.counters.lock(idAt('c3'), async () => {
157
+ await db.counters.lock(idAt('c4'), () => undefined);
158
+ await yieldNow();
159
+ await yieldNow();
160
+ order.push('outer ending');
161
+ }),
162
+ (async () => {
163
+ await yieldNow();
164
+ await db.counters.lock(idAt('c4'), () => {
165
+ order.push('second ran');
166
+ });
167
+ })(),
168
+ ]),
169
+ );
170
+ expect(order).toEqual(['outer ending', 'second ran']);
171
+ },
172
+ LOCK,
173
+ ),
174
+ checkOver(
175
+ SET,
176
+ 'a plain update waits for the holder: the locked write cannot overwrite it',
177
+ async (db) => {
178
+ await counter(db, idAt('c5'));
179
+ await inOrg(ORG_A, async () => {
180
+ const entered = Promise.withResolvers<void>();
181
+ const locked = db.counters.lock(idAt('c5'), async (row, tx) => {
182
+ entered.resolve();
183
+ await yieldNow();
184
+ await yieldNow();
185
+ await db.counters.update(idAt('c5'), { hits: row.hits + 1 }, { tx });
186
+ });
187
+ await entered.promise;
188
+ await Promise.all([locked, db.counters.update(idAt('c5'), { hits: 100 })]);
189
+ });
190
+ expect(await hitsOf(db, idAt('c5'))).toBe(100);
191
+ },
192
+ LOCK_TX,
193
+ ),
194
+ checkOver(
195
+ SET,
196
+ 'a plain delete waits for the holder, and finds the row it kept',
197
+ async (db) => {
198
+ await counter(db, idAt('c6'));
199
+ const order: string[] = [];
200
+ await inOrg(ORG_A, async () => {
201
+ const entered = Promise.withResolvers<void>();
202
+ const locked = db.counters.lock(idAt('c6'), async () => {
203
+ entered.resolve();
204
+ await yieldNow();
205
+ order.push('holder done');
206
+ });
207
+ await entered.promise;
208
+ await Promise.all([
209
+ locked,
210
+ db.counters.delete(idAt('c6')).then(() => order.push('deleted')),
211
+ ]);
212
+ });
213
+ expect(order).toEqual(['holder done', 'deleted']);
214
+ },
215
+ LOCK_TX,
216
+ ),
217
+ ];
218
+
219
+ const lockKeyChecks: readonly EntityDriverCheck[] = [
220
+ checkOver(
221
+ SET,
222
+ 'lockKey: 20 racers on one key end at 20',
223
+ async (db) => {
224
+ await counter(db, idAt('7'));
225
+ await inOrg(ORG_A, () =>
226
+ Promise.all(
227
+ Array.from({ length: 20 }, () =>
228
+ db.counters.lockKey('recount', async (tx: Tx) => {
229
+ const row = await db.counters.where({ id: idAt('7') }).one();
230
+ await yieldNow();
231
+ await db.counters.update(idAt('7'), { hits: (row?.hits ?? 0) + 1 }, { tx });
232
+ }),
233
+ ),
234
+ ),
235
+ );
236
+ expect(await hitsOf(db, idAt('7'))).toBe(20);
237
+ },
238
+ LOCK_TX,
239
+ ),
240
+ checkOver(
241
+ SET,
242
+ 'lockKey: a throw rolls back',
243
+ async (db) => {
244
+ await counter(db, idAt('8'), 3);
245
+ await codeOf(() =>
246
+ inOrg(ORG_A, () =>
247
+ db.counters.lockKey('k', async (tx: Tx) => {
248
+ await db.counters.update(idAt('8'), { hits: 4 }, { tx });
249
+ throw CALLBACK_FAILED;
250
+ }),
251
+ ),
252
+ );
253
+ expect(await hitsOf(db, idAt('8'))).toBe(3);
254
+ },
255
+ LOCK_TX,
256
+ ),
257
+ checkOver(
258
+ SET,
259
+ 'lockKey is scoped as a read, and a blank key is refused',
260
+ async (db) => {
261
+ expect(await codeOf(() => db.counters.lockKey('k', () => 1))).toBe('X_TENANCY_UNSCOPED');
262
+ expect(await codeOf(() => db.counters.lockKey('k', () => 1, { orgId: ORG_A }))).toBe(
263
+ 'resolved',
264
+ );
265
+ expect(await codeOf(() => db.globals.lockKey('k', () => 1))).toBe('resolved');
266
+ expect(await codeOf(() => db.globals.lockKey(' ', () => 1))).toBe('X_INVARIANT');
267
+ },
268
+ LOCK,
269
+ ),
270
+ checkOver(
271
+ SET,
272
+ 'crossTenant takes the key an org would, when it names the org',
273
+ async (db) => {
274
+ const sweeper = userActor({ id: 's', orgId: ORG_A, scopes: [CROSS_TENANT_SCOPE] });
275
+ const answer = await runWithContext(ctxOf({ actor: sweeper }), () =>
276
+ crossTenant('nightly sweep', () =>
277
+ db.counters.lockKey('sweep', () => 'held', { orgId: ORG_B }),
278
+ ),
279
+ );
280
+ expect(answer).toBe('held');
281
+ },
282
+ LOCK,
283
+ ),
284
+ ];
285
+
286
+ export const LOCK_CHECKS: readonly EntityDriverCheck[] = [...lockChecks, ...lockKeyChecks];
@@ -0,0 +1,397 @@
1
+ // Entity conformance · every column kind and every `arrayOf()` element kind round-trips: through
2
+ // the insert's answer, a keyed read, a listed read and an update's answer, each equal to what the
3
+ // reference `memoryDriver()` reads back; a bound array compares against every array type; and a
4
+ // unique decimal is one value under two spellings. Lifted from `entity/src/column-matrix-parity`.
5
+
6
+ import { expect } from 'bun:test';
7
+ import type { Driver } from '@ultimat3/entity';
8
+ import {
9
+ arrayOf,
10
+ bigint,
11
+ boolean,
12
+ bytes,
13
+ COLUMN_KINDS,
14
+ database,
15
+ date,
16
+ decimal,
17
+ entity,
18
+ enumerated,
19
+ integer,
20
+ json,
21
+ memoryDriver,
22
+ money,
23
+ t,
24
+ text,
25
+ timestamp,
26
+ url,
27
+ uuid,
28
+ } from '@ultimat3/entity';
29
+ import type { PlainDate } from '@ultimat3/time';
30
+ import { remember } from './entity-conformance-entities';
31
+ import { checkOver, codeOf } from './entity-conformance-support';
32
+ import type { EntityDriverCheck } from './entity-driver-conformance';
33
+
34
+ const MOODS = ['sad', 'ok', 'happy'] as const;
35
+
36
+ /**
37
+ * `<kind>s` is `arrayOf(<kind>)` and `<kind>Gaps` is the same array with nullable ELEMENTS — a SQL
38
+ * NULL inside a row value, the one shape a driver's binary array reader has to carry a null bitmap
39
+ * for. Every array column is nullable so one row can hold `null` for the whole column.
40
+ */
41
+ const matrix = remember(
42
+ entity('ec_m_rows', {
43
+ columns: {
44
+ id: uuid().primaryKey(),
45
+ label: text({ max: 40 }),
46
+ mood: enumerated(MOODS),
47
+ link: url().nullable(),
48
+ count: integer(),
49
+ flag: boolean(),
50
+ at: timestamp(),
51
+ rate: decimal({ precision: 18, scale: 8 }),
52
+ day: date(),
53
+ big: bigint(),
54
+ data: json(t.object({ plan: t.string, seats: t.number })),
55
+ blob: bytes().nullable(),
56
+ price: money().nullable(),
57
+ uuids: arrayOf(uuid()).nullable(),
58
+ uuidGaps: arrayOf(uuid().nullable()).nullable(),
59
+ texts: arrayOf(text()).nullable(),
60
+ textGaps: arrayOf(text().nullable()).nullable(),
61
+ moods: arrayOf(enumerated(MOODS)).nullable(),
62
+ links: arrayOf(url()).nullable(),
63
+ counts: arrayOf(integer()).nullable(),
64
+ countGaps: arrayOf(integer().nullable()).nullable(),
65
+ flags: arrayOf(boolean()).nullable(),
66
+ flagGaps: arrayOf(boolean().nullable()).nullable(),
67
+ ats: arrayOf(timestamp()).nullable(),
68
+ atGaps: arrayOf(timestamp().nullable()).nullable(),
69
+ rates: arrayOf(decimal({ precision: 18, scale: 8 })).nullable(),
70
+ rateGaps: arrayOf(decimal().nullable()).nullable(),
71
+ days: arrayOf(date()).nullable(),
72
+ dayGaps: arrayOf(date().nullable()).nullable(),
73
+ bigs: arrayOf(bigint()).nullable(),
74
+ bigGaps: arrayOf(bigint().nullable()).nullable(),
75
+ },
76
+ }),
77
+ );
78
+
79
+ type MatrixWrite = Parameters<ReturnType<typeof matrixDb>['rows']['insert']>[0];
80
+
81
+ const matrixDb = (driver: Driver) => database({ rows: matrix }, { driver });
82
+
83
+ const A = '01a12719-28e5-735e-b5bb-000000000001';
84
+ const B = '01a12719-28e5-735e-b5bb-000000000002';
85
+ const day = (value: string): PlainDate => value as PlainDate;
86
+
87
+ const SCALARS = {
88
+ mood: 'ok',
89
+ count: 7,
90
+ flag: true,
91
+ at: new Date('2026-01-02T03:04:05.123Z'),
92
+ rate: '1.23456789',
93
+ day: day('2026-03-14'),
94
+ big: '9007199254740993',
95
+ data: { plan: 'team', seats: 12 },
96
+ } as const;
97
+
98
+ /** The element text a Postgres array literal has to quote or escape, each one a single element. */
99
+ const NASTY_TEXT = [
100
+ 'plain',
101
+ 'with,comma',
102
+ 'quote"inside',
103
+ 'back\\slash',
104
+ '{braces}',
105
+ '',
106
+ ' padded ',
107
+ 'NULL',
108
+ 'null',
109
+ 'line\nbreak',
110
+ 'tab\there',
111
+ 'ünï©ode ✓',
112
+ "single'quote",
113
+ ] as const;
114
+
115
+ /** Named, so a failure says which row of the matrix it was. */
116
+ const MATRIX_ROWS: Readonly<Record<string, MatrixWrite>> = Object.freeze({
117
+ 'every array holds two members': {
118
+ ...SCALARS,
119
+ label: 'full',
120
+ link: 'https://example.com/a?b=c,d',
121
+ blob: new Uint8Array([0, 255, 16]),
122
+ price: { minor: 1999, currency: 'EUR' },
123
+ uuids: [A, B],
124
+ uuidGaps: [A, B],
125
+ texts: ['alpha', 'beta'],
126
+ textGaps: ['alpha', 'beta'],
127
+ moods: ['sad', 'happy'],
128
+ links: ['https://example.com/a,b', 'http://example.com/{c}'],
129
+ counts: [1, -2147483648],
130
+ countGaps: [2147483647, 0],
131
+ flags: [true, false],
132
+ flagGaps: [false, true],
133
+ ats: [new Date('2026-01-02T03:04:05.123Z'), new Date('1999-12-31T23:59:59.999Z')],
134
+ atGaps: [new Date('2026-06-01T00:00:00.000Z'), new Date(0)],
135
+ rates: ['1.23456789', '-0.5'],
136
+ rateGaps: ['12345678901234567890.123456789', '0'],
137
+ days: [day('2026-03-14'), day('1970-01-01')],
138
+ dayGaps: [day('2024-02-29'), day('2026-12-31')],
139
+ bigs: ['9007199254740993', '-9223372036854775808'],
140
+ bigGaps: ['9223372036854775807', '0'],
141
+ },
142
+ 'every array holds one member': {
143
+ ...SCALARS,
144
+ label: 'single',
145
+ uuids: [A],
146
+ uuidGaps: [A],
147
+ texts: ['only'],
148
+ textGaps: ['only'],
149
+ moods: ['ok'],
150
+ links: ['https://example.com/'],
151
+ counts: [42],
152
+ countGaps: [42],
153
+ flags: [true],
154
+ flagGaps: [false],
155
+ ats: [new Date('2026-01-02T03:04:05.123Z')],
156
+ atGaps: [new Date('2026-01-02T03:04:05.123Z')],
157
+ rates: ['1.5'],
158
+ rateGaps: ['1.5'],
159
+ days: [day('2026-03-14')],
160
+ dayGaps: [day('2026-03-14')],
161
+ bigs: ['1'],
162
+ bigGaps: ['1'],
163
+ },
164
+ 'every array is empty': {
165
+ ...SCALARS,
166
+ label: 'empty',
167
+ uuids: [],
168
+ uuidGaps: [],
169
+ texts: [],
170
+ textGaps: [],
171
+ moods: [],
172
+ links: [],
173
+ counts: [],
174
+ countGaps: [],
175
+ flags: [],
176
+ flagGaps: [],
177
+ ats: [],
178
+ atGaps: [],
179
+ rates: [],
180
+ rateGaps: [],
181
+ days: [],
182
+ dayGaps: [],
183
+ bigs: [],
184
+ bigGaps: [],
185
+ },
186
+ 'every array column is null': {
187
+ ...SCALARS,
188
+ label: 'null columns',
189
+ link: null,
190
+ blob: null,
191
+ price: null,
192
+ uuids: null,
193
+ uuidGaps: null,
194
+ texts: null,
195
+ textGaps: null,
196
+ moods: null,
197
+ links: null,
198
+ counts: null,
199
+ countGaps: null,
200
+ flags: null,
201
+ flagGaps: null,
202
+ ats: null,
203
+ atGaps: null,
204
+ rates: null,
205
+ rateGaps: null,
206
+ days: null,
207
+ dayGaps: null,
208
+ bigs: null,
209
+ bigGaps: null,
210
+ },
211
+ 'a null sits between two members': {
212
+ ...SCALARS,
213
+ label: 'gaps',
214
+ uuidGaps: [A, null, B],
215
+ textGaps: ['a', null, 'NULL', ''],
216
+ countGaps: [1, null, 3],
217
+ flagGaps: [true, null, false],
218
+ atGaps: [new Date('2026-01-02T03:04:05.123Z'), null],
219
+ rateGaps: ['1.5', null, '2'],
220
+ dayGaps: [day('2026-03-14'), null],
221
+ bigGaps: ['9007199254740993', null],
222
+ },
223
+ 'every member is null': {
224
+ ...SCALARS,
225
+ label: 'all gaps',
226
+ uuidGaps: [null],
227
+ textGaps: [null, null],
228
+ countGaps: [null],
229
+ flagGaps: [null],
230
+ atGaps: [null],
231
+ rateGaps: [null],
232
+ dayGaps: [null],
233
+ bigGaps: [null],
234
+ },
235
+ 'text the array literal has to quote': {
236
+ ...SCALARS,
237
+ label: 'nasty',
238
+ texts: [...NASTY_TEXT],
239
+ textGaps: [...NASTY_TEXT, null],
240
+ },
241
+ });
242
+
243
+ const roundTrip = async (driver: Driver, write: MatrixWrite) => {
244
+ const db = matrixDb(driver);
245
+ const inserted = await db.rows.insert(write);
246
+ const keyed = await db.rows.where({ id: inserted.id }).one();
247
+ const listed = (await db.rows.where({}).all()).find((row) => row.id === inserted.id) ?? null;
248
+ const updated = await db.rows.update(inserted.id, { label: `${write.label} again` });
249
+ const detach = <R extends { readonly label?: string } | null>(row: R) =>
250
+ row === null ? null : { ...row, label: write.label };
251
+ return { inserted, keyed, listed, updated: detach(updated) };
252
+ };
253
+
254
+ /** The array columns, read off the declaration so a column added above is a column tested below. */
255
+ const ARRAY_COLUMNS = Object.entries(matrix.$columns)
256
+ .filter(([, column]) => column.$meta.kind === 'array')
257
+ .map(([property]) => property);
258
+
259
+ /**
260
+ * The WRITE direction: a JS array bound as the operand of `@>` and `&&` against every array type.
261
+ * A literal that reads back correctly can still be one the server refuses to COMPARE — an untyped
262
+ * parameter takes the column's type, and `{"2026-01-02T03:04:05.123Z"}` has to parse as a
263
+ * `timestamptz[]` there. Asked of both drivers, because memory answering alone proves nothing.
264
+ */
265
+ const matches = async (driver: Driver, id: string, column: string, member: unknown) => {
266
+ const repo = driver.repo(matrix);
267
+ const found = async (op: 'contains' | 'overlaps') =>
268
+ (
269
+ await repo.findMany({
270
+ where: [
271
+ { column: 'id', op: 'eq', value: id },
272
+ { column, op, value: [member] },
273
+ ],
274
+ orderBy: [{ column: 'id', direction: 'asc' }],
275
+ limit: 5,
276
+ })
277
+ ).rows.length;
278
+ return { contains: await found('contains'), overlaps: await found('overlaps') };
279
+ };
280
+
281
+ /** Fixed per row so a SQL subject and the memory reference write the same key. */
282
+ const idFor = (index: number): string =>
283
+ `01a12719-28e5-735e-b5bb-0000000001${String(index).padStart(2, '0')}`;
284
+
285
+ /** The ratchet: a kind added to `COLUMN_KINDS` with no column here is red, for every driver. */
286
+ const declaresEveryKind: EntityDriverCheck = checkOver(
287
+ { matrix },
288
+ 'column matrix · declares every column kind',
289
+ async () => {
290
+ const declared = new Set<string>(
291
+ Object.values(matrix.$columns).map((column) => column.$meta.kind),
292
+ );
293
+ // `char` has no constructor of its own: it is the currency half of `money()`.
294
+ expect(COLUMN_KINDS.filter((kind) => kind !== 'char' && !declared.has(kind))).toEqual([]);
295
+ },
296
+ );
297
+
298
+ const roundTrips: readonly EntityDriverCheck[] = Object.entries(MATRIX_ROWS).map(
299
+ ([name, write], index) =>
300
+ checkOver(
301
+ { matrix },
302
+ `column matrix · ${name}: reads back what memory reads back`,
303
+ async (_db, { driver }) => {
304
+ const id = idFor(index);
305
+ const reference = await roundTrip(memoryDriver(), { ...write, id });
306
+ const real = await roundTrip(driver, { ...write, id });
307
+ expect(real).toEqual(reference);
308
+ // Memory is not merely agreeing with itself: every array read back IS a JS array of the
309
+ // members written — the one claim `toEqual` between two wrong answers cannot make.
310
+ const source = new Map(Object.entries(write as Readonly<Record<string, unknown>>));
311
+ const keyed = new Map(
312
+ Object.entries((real.keyed ?? {}) as Readonly<Record<string, unknown>>),
313
+ );
314
+ for (const column of ARRAY_COLUMNS) {
315
+ const wrote = source.get(column) ?? null;
316
+ const read = keyed.get(column);
317
+ const shape =
318
+ wrote === null
319
+ ? read === null
320
+ : Array.isArray(read) && read.length === (wrote as unknown[]).length;
321
+ expect({ column, shape }).toEqual({ column, shape: true });
322
+ }
323
+ },
324
+ ),
325
+ );
326
+
327
+ const operand: EntityDriverCheck = checkOver(
328
+ { matrix },
329
+ 'column matrix · a bound array is an operand every array type compares against',
330
+ async (_db, { driver }) => {
331
+ const write = MATRIX_ROWS['every array holds two members'];
332
+ if (write === undefined) return expect.unreachable('the two-member row left the corpus');
333
+ const id = idFor(99);
334
+ await matrixDb(driver).rows.insert({ ...write, id });
335
+ const source = new Map(Object.entries(write as Readonly<Record<string, unknown>>));
336
+ for (const column of ARRAY_COLUMNS) {
337
+ const [member] = source.get(column) as readonly unknown[];
338
+ expect({ column, ...(await matches(driver, id, column, member)) }).toEqual({
339
+ column,
340
+ contains: 1,
341
+ overlaps: 1,
342
+ });
343
+ }
344
+ },
345
+ );
346
+
347
+ const amounts = remember(
348
+ entity('ec_m_amounts', {
349
+ columns: { id: uuid().primaryKey(), d: decimal().unique(), label: text({ max: 8 }).nullable() },
350
+ }),
351
+ );
352
+ const bounded = remember(
353
+ entity('ec_m_bounded', {
354
+ columns: { id: uuid().primaryKey(), d: decimal({ precision: 10, scale: 2 }).unique() },
355
+ }),
356
+ );
357
+ const UNIQUE = 'X_DB_UNIQUE_VIOLATION';
358
+ const SET = { amounts, bounded };
359
+ const UPDATE = { onConflict: ['d'], onMatch: 'update' } as const;
360
+
361
+ const uniqueDecimals: readonly EntityDriverCheck[] = [
362
+ checkOver(
363
+ SET,
364
+ 'a unique decimal is one value: 2.5 and 2.50 collide, 2.51 does not',
365
+ async (db) => {
366
+ await db.amounts.insert({ d: '2.5' });
367
+ expect(await codeOf(() => db.amounts.insert({ d: '2.50' }))).toBe(UNIQUE);
368
+ expect(await db.amounts.where({ d: '2.500' }).all()).toHaveLength(1);
369
+ expect(await codeOf(() => db.amounts.insert({ d: '2.51' }))).toBe('resolved');
370
+ await db.bounded.insert({ d: '2.5' });
371
+ expect(await codeOf(() => db.bounded.insert({ d: '2.50' }))).toBe(UNIQUE);
372
+ },
373
+ ),
374
+ checkOver(
375
+ SET,
376
+ 'an upsert on a unique decimal lands on the one row; a batch spelling it twice is refused whole',
377
+ async (db) => {
378
+ const pair = [
379
+ { d: '2.5', label: 'a' },
380
+ { d: '2.50', label: 'b' },
381
+ ];
382
+ expect(await codeOf(() => db.amounts.upsertAll(pair, UPDATE))).not.toBe('resolved');
383
+ expect(await db.amounts.all()).toHaveLength(0);
384
+ await db.amounts.upsertAll([{ d: '2.5', label: 'a' }], UPDATE);
385
+ await db.amounts.upsertAll([{ d: '2.50', label: 'b' }], UPDATE);
386
+ expect((await db.amounts.all()).map((row) => row.label)).toEqual(['b']);
387
+ },
388
+ ['upsert'],
389
+ ),
390
+ ];
391
+
392
+ export const MATRIX_CHECKS: readonly EntityDriverCheck[] = [
393
+ declaresEveryKind,
394
+ ...roundTrips,
395
+ operand,
396
+ ...uniqueDecimals,
397
+ ];