@ultimat3/testing 30.9.0 → 31.1.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 (151) hide show
  1. package/CLAUDE.md +46 -55
  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 +20 -2
  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-line.ts +98 -0
  55. package/src/exercise-report.ts +138 -115
  56. package/src/exercise-room-mail.ts +40 -0
  57. package/src/exercise.ts +33 -29
  58. package/src/factories.ts +192 -179
  59. package/src/factory-api.ts +131 -0
  60. package/src/factory-associations.ts +67 -0
  61. package/src/factory-errors.ts +38 -0
  62. package/src/factory-lint.ts +92 -0
  63. package/src/factory-persist.ts +74 -16
  64. package/src/factory-pipeline.ts +191 -0
  65. package/src/factory-registry.ts +2 -1
  66. package/src/factory-types.ts +131 -0
  67. package/src/failure-store-conformance.ts +137 -0
  68. package/src/fixture-jobs.ts +27 -11
  69. package/src/fixture-mail.ts +7 -7
  70. package/src/fixture-seed.ts +111 -0
  71. package/src/fixture-statements.ts +68 -52
  72. package/src/framework-fixtures.ts +1 -1
  73. package/src/idempotency-store-conformance.ts +186 -0
  74. package/src/idempotency-store-replay-conformance.ts +140 -0
  75. package/src/idempotency-store-tx-conformance.ts +132 -0
  76. package/src/idempotency-store-world-conformance.ts +82 -0
  77. package/src/identity-provider-conformance.ts +144 -0
  78. package/src/image-transform-conformance.ts +89 -0
  79. package/src/index.ts +68 -157
  80. package/src/isr-store-conformance.ts +113 -0
  81. package/src/job-sim-effects.ts +19 -31
  82. package/src/job-sim-world.ts +6 -15
  83. package/src/lease-store-conformance.ts +195 -0
  84. package/src/mail-driver-conformance.ts +108 -0
  85. package/src/matcher-doubles.ts +104 -0
  86. package/src/matcher-stub.ts +78 -0
  87. package/src/matcher-surface.ts +21 -0
  88. package/src/matchers.ts +19 -1
  89. package/src/mcp-confirmation-store-conformance.ts +262 -0
  90. package/src/meter-store-conformance.ts +135 -0
  91. package/src/notify-digest-conformance.ts +133 -0
  92. package/src/notify-inbox-conformance.ts +130 -0
  93. package/src/notify-ledger-conformance.ts +134 -0
  94. package/src/notify-preference-conformance.ts +49 -0
  95. package/src/notify-stores-conformance.ts +73 -0
  96. package/src/outbox-store-conformance-claims.ts +112 -0
  97. package/src/outbox-store-conformance-subject.ts +65 -0
  98. package/src/outbox-store-conformance.ts +71 -0
  99. package/src/per-test-reset.ts +55 -20
  100. package/src/preload.ts +4 -2
  101. package/src/purge-conformance.ts +79 -0
  102. package/src/push-device-conformance.ts +124 -0
  103. package/src/push-subscription-conformance.ts +123 -0
  104. package/src/quiet-logs.ts +4 -4
  105. package/src/rate-limit-store-conformance.ts +178 -0
  106. package/src/registry-leak-error.ts +8 -1
  107. package/src/scale-sweep-run.ts +6 -9
  108. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  109. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  110. package/src/scrape-driver-conformance-site.ts +84 -0
  111. package/src/scrape-driver-conformance.ts +34 -0
  112. package/src/sealed-network.ts +20 -2
  113. package/src/search-index-conformance-list.ts +76 -0
  114. package/src/search-index-conformance-support.ts +69 -0
  115. package/src/search-index-conformance-versions.ts +66 -0
  116. package/src/search-index-conformance.ts +126 -0
  117. package/src/secret-source-conformance.ts +91 -0
  118. package/src/seed-factories.ts +57 -0
  119. package/src/seed-writer.ts +8 -19
  120. package/src/semantic-cache-factory-conformance.ts +86 -0
  121. package/src/sms-transport-conformance.ts +102 -0
  122. package/src/step-store-conformance.ts +171 -0
  123. package/src/storage-conformance-read-checks.ts +132 -0
  124. package/src/storage-conformance-shape.ts +121 -0
  125. package/src/storage-conformance-stream-checks.ts +226 -0
  126. package/src/storage-conformance.ts +34 -0
  127. package/src/stub-action.ts +24 -0
  128. package/src/stub-errors.ts +86 -0
  129. package/src/stub-job.ts +30 -0
  130. package/src/stub-query.ts +25 -0
  131. package/src/stub-script.ts +76 -0
  132. package/src/stub-stack.ts +29 -0
  133. package/src/stub.ts +73 -0
  134. package/src/swap-adapter.ts +135 -0
  135. package/src/test-scope.ts +96 -0
  136. package/src/test-types.ts +1 -1
  137. package/src/totp-replay-guard-conformance.ts +76 -0
  138. package/src/transport-conformance.ts +179 -0
  139. package/src/upload-scanner-conformance.ts +112 -0
  140. package/src/vector-store-conformance-checks.ts +174 -0
  141. package/src/vector-store-conformance.ts +21 -0
  142. package/src/cdp-connection.ts +0 -291
  143. package/src/cdp-errors.ts +0 -179
  144. package/src/cdp-launch-attempt.ts +0 -224
  145. package/src/cdp-launch-candidates.ts +0 -62
  146. package/src/cdp-launch-profile.ts +0 -106
  147. package/src/cdp-launch-reap.ts +0 -68
  148. package/src/cdp-launch-wire.ts +0 -171
  149. package/src/cdp-launch.ts +0 -175
  150. package/src/cdp-pipe.ts +0 -77
  151. package/src/cdp-wire-watch.ts +0 -113
@@ -0,0 +1,241 @@
1
+ // Entity conformance · what a READ answers: a predicate compares by value (decimal text, a uuid in
2
+ // any case, an instant written as text), text orders by code point, an unknown operator is one
3
+ // refusal, `select` projects, and LIKE / has-key / array operators read the rows Postgres reads.
4
+ // Lifted from `entity/src/{compare,select,instant-text,write}-parity.test.ts`.
5
+
6
+ import { expect } from 'bun:test';
7
+ import { bigint, decimal, entity, integer, text, timestamp, uuid } from '@ultimat3/entity';
8
+ import { remember } from './entity-conformance-entities';
9
+ import { checkOver, codeOf, idAt } from './entity-conformance-support';
10
+ import { conformanceDocs as docs } from './entity-conformance-writes';
11
+ import type { EntityDriverCheck } from './entity-driver-conformance';
12
+
13
+ const ledger = remember(
14
+ entity('ec_r_ledger', {
15
+ columns: {
16
+ id: uuid().primaryKey(),
17
+ label: text({ max: 20 }),
18
+ total: bigint(),
19
+ rate: decimal({ precision: 12, scale: 2 }),
20
+ loose: decimal(),
21
+ seats: integer(),
22
+ },
23
+ }),
24
+ );
25
+
26
+ const notes = remember(
27
+ entity('ec_r_notes', {
28
+ columns: { id: uuid().primaryKey(), title: text(), body: text(), rank: integer() },
29
+ }),
30
+ );
31
+
32
+ const events = remember(
33
+ entity('ec_r_events', {
34
+ columns: { id: uuid().primaryKey(), label: text({ max: 20 }), createdAt: timestamp() },
35
+ }),
36
+ );
37
+
38
+ /** Hex LETTERS, so an id has a case to change; text order and numeric order differ on every pair. */
39
+ const hexId = (hex: string): string => `00000000-0000-7000-8000-0000000000${hex}`;
40
+ const SEEDED = [
41
+ { id: hexId('0a'), label: 'ten', total: '10', rate: '2.50', loose: '0.1', seats: 10 },
42
+ { id: hexId('0b'), label: 'nine', total: '9', rate: '10.00', loose: '0', seats: 9 },
43
+ {
44
+ id: hexId('1a'),
45
+ label: 'big',
46
+ total: '9007199254740993',
47
+ rate: '-1.50',
48
+ loose: '-2.25',
49
+ seats: 2,
50
+ },
51
+ ] as const;
52
+
53
+ const UNKNOWN = 'X_ENTITY_OPERATOR_UNKNOWN';
54
+
55
+ type Column = 'id' | 'total' | 'rate' | 'loose' | 'seats';
56
+ type Op = 'eq' | 'neq' | 'in' | 'gt' | 'gte' | 'lt' | 'lte';
57
+
58
+ const PREDICATES: readonly (readonly [Column, Op, unknown, readonly string[]])[] = [
59
+ ['total', 'eq', 10, ['ten']],
60
+ ['total', 'eq', '10', ['ten']],
61
+ ['total', 'neq', 10, ['big', 'nine']],
62
+ ['total', 'in', [9, '10'], ['nine', 'ten']],
63
+ ['total', 'gt', 9, ['big', 'ten']],
64
+ ['total', 'lte', '10', ['nine', 'ten']],
65
+ ['rate', 'eq', '2.5', ['ten']],
66
+ ['rate', 'eq', 2.5, ['ten']],
67
+ ['rate', 'eq', '2.500', ['ten']],
68
+ ['rate', 'neq', '2.5', ['big', 'nine']],
69
+ ['rate', 'in', ['10', '-1.5'], ['big', 'nine']],
70
+ ['rate', 'lt', '10', ['big', 'ten']],
71
+ ['loose', 'eq', '0.10', ['ten']],
72
+ ['loose', 'eq', '-0.00', ['nine']],
73
+ ['loose', 'eq', 0, ['nine']],
74
+ ['id', 'eq', hexId('0A'), ['ten']],
75
+ ['id', 'gt', hexId('0A'), ['big', 'nine']],
76
+ ['id', 'gte', hexId('0B'), ['big', 'nine']],
77
+ ['id', 'lt', hexId('0B'), ['ten']],
78
+ ['id', 'lte', hexId('1A'), ['big', 'nine', 'ten']],
79
+ ];
80
+
81
+ const comparisons: readonly EntityDriverCheck[] = [
82
+ checkOver({ ledger }, 'decimal text and a uuid in any case compare by value', async (db) => {
83
+ for (const row of SEEDED) await db.ledger.insert({ ...row });
84
+ for (const [column, op, value, expected] of PREDICATES) {
85
+ const labels = (await db.ledger.andWhere(column, op, value).all()).map((row) => row.label);
86
+ expect([column, op, value, labels.sort()]).toEqual([column, op, value, [...expected]]);
87
+ }
88
+ }),
89
+ checkOver({ ledger }, 'order by a decimal-text column orders by value', async (db) => {
90
+ for (const row of SEEDED) await db.ledger.insert({ ...row });
91
+ const order = async (column: Column, direction: 'asc' | 'desc') =>
92
+ (await db.ledger.orderBy(column, direction).all()).map((row) => row.label);
93
+ expect(await order('total', 'asc')).toEqual(['nine', 'ten', 'big']);
94
+ expect(await order('rate', 'desc')).toEqual(['nine', 'ten', 'big']);
95
+ expect(await order('loose', 'asc')).toEqual(['big', 'nine', 'ten']);
96
+ }),
97
+ checkOver(
98
+ { ledger },
99
+ 'an operator outside the vocabulary is X_ENTITY_OPERATOR_UNKNOWN',
100
+ async (db, { driver }) => {
101
+ // On an empty table first: the refusal is the call's, never the rows'.
102
+ const empty = [{ column: 'seats', op: '>' as Op, value: 5 }];
103
+ expect(await codeOf(() => driver.repo(ledger).findMany({ where: empty }))).toBe(UNKNOWN);
104
+ for (const row of SEEDED) await db.ledger.insert({ ...row });
105
+ for (const op of ['>', '<>', 'GTE']) {
106
+ // Both doors: the typed chain, and the repository a hand-written caller reaches.
107
+ const where = [{ column: 'seats', op: op as Op, value: 5 }];
108
+ const chain = await codeOf(() => db.ledger.andWhere('seats', op as Op, 5).all());
109
+ const repo = await codeOf(() => driver.repo(ledger).findMany({ where }));
110
+ expect([op, chain, repo]).toEqual([op, UNKNOWN, UNKNOWN]);
111
+ }
112
+ },
113
+ ),
114
+ ];
115
+
116
+ const projection: readonly EntityDriverCheck[] = [
117
+ checkOver(
118
+ { notes },
119
+ 'select answers the asked columns and the primary key, nothing else',
120
+ async (_db, { driver }) => {
121
+ const repo = driver.repo(notes);
122
+ for (const n of [1, 2, 3])
123
+ await repo.insert({ id: idAt(n), title: `t${n}`, body: `b${n}`, rank: 4 - n });
124
+ const { rows } = await repo.findMany({ select: ['title'] });
125
+ expect(rows.map((row) => Object.keys(row).sort())).toEqual([
126
+ ['id', 'title'],
127
+ ['id', 'title'],
128
+ ['id', 'title'],
129
+ ]);
130
+ },
131
+ ),
132
+ checkOver(
133
+ { notes },
134
+ 'a selected page carries its sort key, so the cursor can be minted',
135
+ async (_db, { driver }) => {
136
+ const repo = driver.repo(notes);
137
+ for (const n of [1, 2, 3])
138
+ await repo.insert({ id: idAt(n), title: `t${n}`, body: `b${n}`, rank: 4 - n });
139
+ const orderBy = [{ column: 'rank', direction: 'asc' as const }];
140
+ const first = await repo.findMany({ select: ['title'], orderBy, limit: 2 });
141
+ const cursor = first.nextCursor === null ? {} : { cursor: first.nextCursor };
142
+ const next = await repo.findMany({ select: ['title'], orderBy, limit: 2, ...cursor });
143
+ const rows = [...first.rows, ...next.rows];
144
+ expect(rows.map((row) => row.title)).toEqual(['t3', 't2', 't1']);
145
+ expect(Object.keys(rows[0] ?? {}).sort()).toEqual(['id', 'rank', 'title']);
146
+ },
147
+ ),
148
+ ];
149
+
150
+ const at = (second: number): Date => new Date(Date.UTC(2026, 0, 1, 0, 0, second));
151
+ const newestFirst = [{ column: 'createdAt', direction: 'desc' as const }];
152
+
153
+ const instants: readonly EntityDriverCheck[] = [
154
+ checkOver(
155
+ { events },
156
+ 'an ISO instant as text compares as the instant it names',
157
+ async (_db, { driver }) => {
158
+ const repo = driver.repo(events);
159
+ for (const n of [1, 2, 3, 4, 5])
160
+ await repo.insert({ id: idAt(n), label: `e${n}`, createdAt: at(n) });
161
+ const where = async (op: Op, value: string) =>
162
+ (
163
+ await repo.findMany({ where: [{ column: 'createdAt', op, value }], orderBy: newestFirst })
164
+ ).rows.map((row) => row.label);
165
+ expect(await where('eq', '2026-01-01T00:00:03.000Z')).toEqual(['e3']);
166
+ expect(await where('eq', '2026-01-01T01:00:03+01:00')).toEqual(['e3']);
167
+ expect(await where('neq', '2026-01-01T00:00:03Z')).toEqual(['e5', 'e4', 'e2', 'e1']);
168
+ expect(await where('gte', '2026-01-01T00:00:04Z')).toEqual(['e5', 'e4']);
169
+ expect(await where('gt', '2026-01-01T00:00:04Z')).toEqual(['e5']);
170
+ expect(await where('lte', '2026-01-01T00:00:02Z')).toEqual(['e2', 'e1']);
171
+ },
172
+ ),
173
+ checkOver(
174
+ { events },
175
+ 'page two of a hand-kept keyset over an instant is the older rows',
176
+ async (_db, { driver }) => {
177
+ const repo = driver.repo(events);
178
+ for (const n of [1, 2, 3, 4, 5])
179
+ await repo.insert({ id: idAt(n), label: `e${n}`, createdAt: at(n) });
180
+ const first = await repo.findMany({ orderBy: newestFirst, limit: 2 });
181
+ expect(first.rows.map((row) => row.label)).toEqual(['e5', 'e4']);
182
+ const after = first.rows.at(-1)?.createdAt.toISOString();
183
+ const second = await repo.findMany({
184
+ where: [{ column: 'createdAt', op: 'lt', value: after }],
185
+ orderBy: newestFirst,
186
+ limit: 2,
187
+ });
188
+ expect(second.rows.map((row) => row.label)).toEqual(['e3', 'e2']);
189
+ },
190
+ ),
191
+ ];
192
+
193
+ type DocOp = 'like' | 'has-key' | 'contains' | 'contained-by' | 'overlaps';
194
+
195
+ const operators: readonly EntityDriverCheck[] = [
196
+ checkOver({ docs }, 'LIKE counts characters: _ is one, astral or not', async (db) => {
197
+ for (const [index, slug] of ['a', 'b', 'c', '😀', 'ab'].entries()) {
198
+ await db.docs.insert({ id: idAt(index + 1), slug });
199
+ }
200
+ const slugs = async (value: string) =>
201
+ (await db.docs.andWhere('slug', 'like', value).all()).map((row) => row.slug).sort();
202
+ expect([await slugs('_'), await slugs('%_%_%')]).toEqual([['a', 'b', 'c', '😀'], ['ab']]);
203
+ }),
204
+ checkOver(
205
+ { docs },
206
+ 'has-key takes a STRING key; any other operand matches no row',
207
+ async (db) => {
208
+ await db.docs.insert({ id: idAt(1), slug: 'digit', data: { '1': 'x' } });
209
+ await db.docs.insert({ id: idAt(2), slug: 'word', data: { a: 'x', null: 'y' } });
210
+ const answers: (readonly string[])[] = [];
211
+ for (const key of ['1', 1, ['a'], null, undefined, true]) {
212
+ answers.push((await db.docs.andWhere('data', 'has-key', key).all()).map((row) => row.slug));
213
+ }
214
+ expect(answers).toEqual([['digit'], [], [], [], [], []]);
215
+ },
216
+ ),
217
+ checkOver(
218
+ { docs },
219
+ 'a NULL array element matches nothing, on either side of @>, <@ and &&',
220
+ async (db) => {
221
+ await db.docs.insert({ id: idAt(1), slug: 'holed', marks: ['red', null] });
222
+ await db.docs.insert({ id: idAt(2), slug: 'whole', marks: ['red'] });
223
+ const slugs = async (op: DocOp, value: unknown) =>
224
+ (await db.docs.andWhere('marks', op, value).all()).map((row) => row.slug).sort();
225
+ expect([
226
+ await slugs('contains', [null]),
227
+ await slugs('contains', ['red', null]),
228
+ await slugs('overlaps', [null]),
229
+ await slugs('overlaps', [null, 'red']),
230
+ await slugs('contained-by', ['red', null]),
231
+ ]).toEqual([[], [], [], ['holed', 'whole'], ['whole']]);
232
+ },
233
+ ),
234
+ ];
235
+
236
+ export const READ_CHECKS: readonly EntityDriverCheck[] = [
237
+ ...comparisons,
238
+ ...projection,
239
+ ...instants,
240
+ ...operators,
241
+ ];
@@ -0,0 +1,56 @@
1
+ // The small vocabulary every entity conformance check is written in: an outcome that is a value or
2
+ // a code (never a raw throw), an id from a suffix, an actor in an org, a typed handle per driver.
3
+
4
+ import { ctxOf, isUltimateError, runWithContext, userActor } from '@ultimat3/core';
5
+ import type { Database, Driver, EntitySet } from '@ultimat3/entity';
6
+ import { database } from '@ultimat3/entity';
7
+ import type { DriverCapability } from '@ultimat3/entity/adapter';
8
+ import type { EntityDriverCheck, EntityDriverRun } from './entity-driver-conformance';
9
+
10
+ export type Outcome = { readonly ok: unknown } | { readonly code: string };
11
+
12
+ /** The body's answer, or the code it refused with. */
13
+ export const outcome = async (work: () => Promise<unknown>): Promise<Outcome> => {
14
+ try {
15
+ return { ok: await work() };
16
+ } catch (error) {
17
+ return { code: isUltimateError(error) ? error.code : `not coded: ${String(error)}` };
18
+ }
19
+ };
20
+
21
+ /** `'resolved'`, or the code — `'uncoded'` for a throw that carries none. */
22
+ export const codeOf = async (work: () => unknown): Promise<string> => {
23
+ try {
24
+ await work();
25
+ return 'resolved';
26
+ } catch (error) {
27
+ return isUltimateError(error) ? error.code : 'uncoded';
28
+ }
29
+ };
30
+
31
+ export const idAt = (suffix: string | number): string =>
32
+ `00000000-0000-7000-8000-${String(suffix).padStart(12, '0')}`;
33
+
34
+ /** Inside a request whose actor belongs to `orgId`. */
35
+ export const inOrg = <T>(orgId: string, work: () => Promise<T>): Promise<T> =>
36
+ runWithContext(ctxOf({ actor: userActor({ id: idAt('990'), orgId }) }), work);
37
+
38
+ /** A typed handle over the opened driver. */
39
+ export const handleOf = <E extends EntitySet>(entities: E, driver: Driver): Database<E> =>
40
+ database(entities, { driver });
41
+
42
+ /**
43
+ * One check over a set of tables, typed against them: `run` gets the handle `database()` builds
44
+ * over exactly those tables, plus the raw run for a check that needs a bare repository.
45
+ */
46
+ export const checkOver = <E extends EntitySet>(
47
+ entities: E,
48
+ name: string,
49
+ run: (db: Database<E>, raw: EntityDriverRun) => Promise<void>,
50
+ needs: readonly DriverCapability[] = [],
51
+ ): EntityDriverCheck => ({
52
+ name,
53
+ entities: Object.values(entities),
54
+ needs,
55
+ run: (raw) => run(handleOf(entities, raw.driver), raw),
56
+ });
@@ -0,0 +1,296 @@
1
+ // Entity conformance · TENANCY on writes: a row may name the actor's tenant or none, a batch is
2
+ // refused whole, an upsert collision cannot land in another tenant, and a reference into another
3
+ // tenant is refused like a missing parent. Each refusal is asserted through the store's contents:
4
+ // nothing written. Lifted from `entity/src/{write-tenancy,same-tenant}-parity.test.ts`.
5
+
6
+ import { expect } from 'bun:test';
7
+ import { ctxOf, isUltimateError, runWithContext, serviceActor } from '@ultimat3/core';
8
+ import type { Database, Repo } from '@ultimat3/entity';
9
+ import { CROSS_TENANT_SCOPE, crossTenant, entity, text, uuid } from '@ultimat3/entity';
10
+ import { remember } from './entity-conformance-entities';
11
+ import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
12
+ import type { EntityDriverCheck } from './entity-driver-conformance';
13
+
14
+ const posts = remember(
15
+ entity('ec_t_posts', {
16
+ columns: {
17
+ id: uuid().primaryKey(),
18
+ orgId: uuid().tenant(),
19
+ slug: text({ max: 40 }),
20
+ title: text({ max: 40 }),
21
+ },
22
+ indexes: [
23
+ { on: ['orgId', 'slug'], unique: true },
24
+ { on: ['slug'], unique: true },
25
+ ],
26
+ }),
27
+ );
28
+ type Post = typeof posts.$row;
29
+
30
+ const orgs = remember(entity('ec_t_orgs', { columns: { id: uuid().primaryKey() } }));
31
+
32
+ const threads = remember(
33
+ entity('ec_t_threads', {
34
+ columns: {
35
+ id: uuid().primaryKey(),
36
+ orgId: uuid()
37
+ .references(() => orgs.id)
38
+ .tenant(),
39
+ title: text({ max: 40 }),
40
+ },
41
+ }),
42
+ );
43
+
44
+ const commentPk = uuid().primaryKey();
45
+ const comments = remember(
46
+ entity('ec_t_comments', {
47
+ columns: {
48
+ id: commentPk,
49
+ orgId: uuid().tenant(),
50
+ threadId: uuid().references(() => threads.id),
51
+ parentId: uuid()
52
+ .nullable()
53
+ .references(() => commentPk),
54
+ sharedThreadId: uuid()
55
+ .nullable()
56
+ .references(() => threads.id, { crossTenant: 'a thread another org shared with this one' }),
57
+ },
58
+ indexes: [{ on: ['orgId', 'id'], unique: true }],
59
+ }),
60
+ );
61
+
62
+ const ORG = idAt('a1');
63
+ const OTHER_ORG = idAt('a2');
64
+ const MINE = idAt('11');
65
+ const THEIRS = idAt('22');
66
+ const MISMATCH = 'X_TENANCY_ACTOR_MISMATCH';
67
+
68
+ const post = (over: Partial<Post> = {}): Post => ({
69
+ id: MINE,
70
+ orgId: ORG,
71
+ slug: 'ours',
72
+ title: 'ours',
73
+ ...over,
74
+ });
75
+
76
+ /** Seeded outside any request, as a script would, and counted there: the table's own answer. */
77
+ const seeded = async (repo: Repo<Post>): Promise<Repo<Post>> => {
78
+ await repo.insertAll([post(), post({ id: THEIRS, orgId: OTHER_ORG, slug: 'theirs' })]);
79
+ return repo;
80
+ };
81
+ const held = async (repo: Repo<Post>): Promise<readonly string[]> =>
82
+ [
83
+ ...(await repo.findMany({ orgId: ORG })).rows,
84
+ ...(await repo.findMany({ orgId: OTHER_ORG })).rows,
85
+ ]
86
+ .map((row) => `${row.slug}:${row.title}`)
87
+ .sort();
88
+ const UNTOUCHED = ['ours:ours', 'theirs:ours'];
89
+
90
+ const asReconciler = <T>(work: () => Promise<T>): Promise<T> =>
91
+ runWithContext(
92
+ ctxOf({ actor: serviceActor({ id: idAt('91'), orgId: ORG, scopes: [CROSS_TENANT_SCOPE] }) }),
93
+ () => crossTenant('nightly reconciliation writes into every org', work),
94
+ );
95
+
96
+ /** One refused write: the code, and a store holding exactly what it held before. */
97
+ const refusedWrite = (
98
+ name: string,
99
+ code: string,
100
+ write: (repo: Repo<Post>) => Promise<unknown>,
101
+ needs: readonly ['upsert'] | [] = [],
102
+ ) =>
103
+ checkOver(
104
+ { posts },
105
+ name,
106
+ async (_db, { driver }) => {
107
+ const repo = await seeded(driver.repo(posts));
108
+ expect(await inOrg(ORG, () => codeOf(() => write(repo)))).toBe(code);
109
+ expect(await held(repo)).toEqual(UNTOUCHED);
110
+ },
111
+ needs,
112
+ );
113
+
114
+ const writeTenancy: readonly EntityDriverCheck[] = [
115
+ refusedWrite(
116
+ 'an insert into another tenant is refused, and nothing is written',
117
+ MISMATCH,
118
+ (repo) => repo.insert(post({ id: idAt('33'), orgId: OTHER_ORG, slug: 'stolen' })),
119
+ ),
120
+ refusedWrite('one bad row refuses the whole batch before any of it lands', MISMATCH, (repo) =>
121
+ repo.insertAll([
122
+ post({ id: idAt('34'), slug: 'a' }),
123
+ post({ id: idAt('35'), orgId: OTHER_ORG, slug: 'b' }),
124
+ ]),
125
+ ),
126
+ refusedWrite(
127
+ 'an upsert naming another tenant is refused even where it would be skipped',
128
+ MISMATCH,
129
+ (repo) =>
130
+ repo.upsertAll([post({ id: idAt('36'), orgId: OTHER_ORG, slug: 'theirs' })], {
131
+ onConflict: ['slug'],
132
+ onMatch: 'nothing',
133
+ }),
134
+ ['upsert'],
135
+ ),
136
+ refusedWrite('a patch handing a row to another tenant is refused by id', MISMATCH, (repo) =>
137
+ repo.update(MINE, { orgId: OTHER_ORG }),
138
+ ),
139
+ refusedWrite('a patch handing rows to another tenant is refused by filter', MISMATCH, (repo) =>
140
+ repo.updateWhere({ slug: 'ours' }, { orgId: OTHER_ORG }),
141
+ ),
142
+ refusedWrite('the patch is refused even when the filter matches no row', MISMATCH, (repo) =>
143
+ repo.updateWhere({ slug: 'no-such-slug' }, { orgId: OTHER_ORG }),
144
+ ),
145
+ refusedWrite(
146
+ 'an upsert target without the tenant column is refused under onMatch: update',
147
+ 'X_TENANCY_UNSCOPED',
148
+ (repo) => repo.upsertAll([post({ id: idAt('41'), slug: 'ours' })], { onConflict: ['slug'] }),
149
+ ['upsert'],
150
+ ),
151
+ refusedWrite(
152
+ 'with the tenant in the target, another tenant’s row is still unreachable',
153
+ MISMATCH,
154
+ (repo) =>
155
+ repo.upsertAll([post({ id: THEIRS, orgId: OTHER_ORG, slug: 'theirs', title: 'taken' })], {
156
+ onConflict: ['orgId', 'slug'],
157
+ }),
158
+ ['upsert'],
159
+ ),
160
+ checkOver(
161
+ { posts },
162
+ 'naming the actor’s own tenant, or none, writes',
163
+ async (_db, { driver }) => {
164
+ const repo = await seeded(driver.repo(posts));
165
+ await inOrg(ORG, () => repo.insert(post({ id: idAt('37'), slug: 'fresh' })));
166
+ await inOrg(ORG, () => repo.update(MINE, { title: 'renamed' } as Partial<Post>));
167
+ expect(await held(repo)).toEqual(['fresh:ours', 'ours:renamed', 'theirs:ours']);
168
+ },
169
+ ),
170
+ checkOver(
171
+ { posts },
172
+ 'an upsert keyed on tenant and slug overwrites the actor’s own row',
173
+ async (_db, { driver }) => {
174
+ const repo = await seeded(driver.repo(posts));
175
+ const renamed = post({ title: 'renamed' });
176
+ await inOrg(ORG, () => repo.upsertAll([renamed], { onConflict: ['orgId', 'slug'] }));
177
+ expect(await held(repo)).toEqual(['ours:renamed', 'theirs:ours']);
178
+ },
179
+ ['upsert'],
180
+ ),
181
+ checkOver(
182
+ { posts },
183
+ 'an actor with no tenant writes nothing tenant-scoped',
184
+ async (_db, { driver }) => {
185
+ const repo = await seeded(driver.repo(posts));
186
+ const anon = () => repo.insert(post({ id: idAt('38'), slug: 'anon' }));
187
+ expect(await runWithContext(ctxOf(), () => codeOf(anon))).toBe(
188
+ 'X_TENANCY_ACTOR_ORG_REQUIRED',
189
+ );
190
+ expect(await held(repo)).toEqual(UNTOUCHED);
191
+ },
192
+ ),
193
+ checkOver(
194
+ { posts },
195
+ 'outside a request a seed writes the tenant it names; crossTenant too',
196
+ async (_db, { driver }) => {
197
+ const repo = await seeded(driver.repo(posts));
198
+ await repo.insert(post({ id: idAt('39'), orgId: OTHER_ORG, slug: 'seeded' }));
199
+ await asReconciler(() =>
200
+ repo.insert(post({ id: idAt('40'), orgId: OTHER_ORG, slug: 'swept' })),
201
+ );
202
+ expect(await held(repo)).toEqual(['ours:ours', 'seeded:ours', 'swept:ours', 'theirs:ours']);
203
+ },
204
+ ),
205
+ ];
206
+
207
+ const VIOLATION = 'X_DB_FOREIGN_KEY_VIOLATION';
208
+ const [THREAD_A, THREAD_B, MISSING] = [idAt('1a'), idAt('1b'), idAt('ff')];
209
+ const SET = { orgs, threads, comments };
210
+ const comment = (suffix: string, over: Record<string, unknown> = {}) =>
211
+ ({ id: idAt(suffix), orgId: ORG, threadId: THREAD_A, ...over }) as never;
212
+
213
+ const seedThreads = async (db: Database<typeof SET>): Promise<void> => {
214
+ await db.orgs.insertAll([{ id: ORG }, { id: OTHER_ORG }]);
215
+ await db.threads.insert({ id: THREAD_A, orgId: ORG, title: 'a' });
216
+ await db.threads.insert({ id: THREAD_B, orgId: OTHER_ORG, title: 'b' });
217
+ };
218
+
219
+ const sameTenant: readonly EntityDriverCheck[] = [
220
+ checkOver(SET, 'a reference into another tenant is refused by every write', async (db) => {
221
+ await seedThreads(db);
222
+ expect(await codeOf(() => db.comments.insert(comment('21', { threadId: THREAD_B })))).toBe(
223
+ VIOLATION,
224
+ );
225
+ expect(
226
+ await codeOf(() =>
227
+ db.comments.insertAll([comment('22'), comment('23', { threadId: THREAD_B })]),
228
+ ),
229
+ ).toBe(VIOLATION);
230
+ const nullable = comment('25', { parentId: idAt('31'), threadId: THREAD_B });
231
+ expect(await codeOf(() => db.comments.insert(nullable))).toBe(VIOLATION);
232
+ await db.comments.insert(comment('41'));
233
+ const move = () => db.comments.update(idAt('41'), { threadId: THREAD_B }, { orgId: ORG });
234
+ expect(await codeOf(move)).toBe(VIOLATION);
235
+ await db.comments.insert(comment('51', { orgId: OTHER_ORG, threadId: THREAD_B }));
236
+ expect(await codeOf(() => db.comments.insert(comment('52', { parentId: idAt('51') })))).toBe(
237
+ VIOLATION,
238
+ );
239
+ const kept = await db.comments.where({ orgId: ORG }).all();
240
+ expect(kept.map((row) => [row.id, row.threadId])).toEqual([[idAt('41'), THREAD_A]]);
241
+ }),
242
+ checkOver(
243
+ SET,
244
+ 'an upsert referencing another tenant is refused',
245
+ async (db) => {
246
+ await seedThreads(db);
247
+ const upsert = () =>
248
+ db.comments.upsertAll([comment('24', { threadId: THREAD_B })], {
249
+ onConflict: ['orgId', 'id'],
250
+ });
251
+ expect(await codeOf(upsert)).toBe(VIOLATION);
252
+ },
253
+ ['upsert'],
254
+ ),
255
+ checkOver(
256
+ SET,
257
+ 'the same tenant, a null key, a declared cross-tenant edge and a forward self-reference write',
258
+ async (db) => {
259
+ await seedThreads(db);
260
+ await db.comments.insert(comment('61'));
261
+ await db.comments.insert(comment('62', { parentId: null }));
262
+ await db.comments.insert(comment('63', { sharedThreadId: THREAD_B }));
263
+ await db.comments.insertAll([comment('64', { parentId: idAt('65') }), comment('65')]);
264
+ expect(await db.comments.where({ orgId: ORG }).count()).toBe(5);
265
+ },
266
+ ),
267
+ checkOver(
268
+ SET,
269
+ 'a missing parent is refused exactly as a foreign one, or accepted by a store with no keys',
270
+ async (db, { foreignKeys }) => {
271
+ await seedThreads(db);
272
+ const absent: unknown = await db.comments
273
+ .insert(comment('72', { threadId: MISSING }))
274
+ .catch((error: unknown) => error);
275
+ const foreign: unknown = await db.comments
276
+ .insert(comment('73', { threadId: THREAD_B }))
277
+ .catch((error: unknown) => error);
278
+ if (!isUltimateError(foreign))
279
+ return expect.unreachable('a foreign reference is always refused');
280
+ if (!foreignKeys) {
281
+ expect(isUltimateError(absent)).toBe(false);
282
+ return;
283
+ }
284
+ if (!isUltimateError(absent))
285
+ return expect.unreachable('a store with foreign keys refuses a missing parent');
286
+ // No existence oracle: absent and foreign read the same.
287
+ expect([absent.code, absent.fix, absent.meta?.['constraint']]).toEqual([
288
+ foreign.code,
289
+ foreign.fix,
290
+ foreign.meta?.['constraint'],
291
+ ]);
292
+ },
293
+ ),
294
+ ];
295
+
296
+ export const TENANCY_CHECKS: readonly EntityDriverCheck[] = [...writeTenancy, ...sameTenant];