@ultimat3/testing 31.1.0 → 31.3.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/README.md CHANGED
@@ -30,7 +30,7 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
30
30
  | `sealed-sockets.ts` | the `WebSocket` and `Bun.connect` patches, behind `sealed-network.ts`'s one gate |
31
31
  | `factories.ts` | `defineFactory` — seeded rows, traits, associations, `build` vs `create` |
32
32
  | `factory-registry.ts` | `factoriesFor(registry)` — one factory per entity, each value read off its column's declaration (default, enum, kind, money, nullability) through `$parse`, never off its name |
33
- | `seed-graph.ts` | `seedGraph(entities, { tenants, perTable, seed, factories, beside })` — rows for every table with no factory written: parents first, same-tenant keys, every declared rule kept. Pure, same seed same bytes |
33
+ | `seed-graph.ts` | `seedGraph(entities, { tenants, perTable, seed, factories, beside, now })` — rows for every table with no factory written: parents first, same-tenant keys, every declared rule kept. A `partitionBy` column lands in the UTC bucket holding `now` (default `systemClock.now()`; under a frozen test clock pass the database's `now()`) — the partition the migration always makes (`seed-graph-partition.ts`). Pure, same seed and `now`, same bytes |
34
34
  | `repro.ts` | `reproduce(bundle, { driver })` and `reproJob(runJobs, failure)` — what a test `x repro --write` generated calls: captured reads seeded, clock frozen at the failure, the same actor and input (masked fields stood in from the schema); a dead job's completed steps replayed from storage |
35
35
  | `seed-graph-plan.ts` | the plan's types and `insertSeedGraph(graph, writer)` — every insert, then every deferred key, sequentially |
36
36
  | `seed-graph-values.ts` | one column's candidate values, off its declaration, kept only where `$parse` accepts them — `factoriesFor`'s source too |
@@ -383,6 +383,7 @@ postFactory.attributesFor(); // an action input: no i
383
383
  | | |
384
384
  |---|---|
385
385
  | **strategies** | `build` (memory, never a database), `create` (writes, answers the row AS STORED: declared defaults, generated columns, timestamps), `attributesFor` (an input: no primary key, no `belongsTo` key, no transient), `buildList` / `createList` |
386
+ | **literals** | `defaults` is checked against the entity's columns as written: `status: 'open'` for an `enumerated(['open', 'closed'])` column compiles with no `as const`, `status: 'nope'` does not. Once checked, a default's literal widens (``title: `t${n}` `` → `string`), so `build({ title: 'x' })` compiles (`factories-literals.test.ts`) |
386
387
  | **sequence** | `index` (`n` above), per factory, shared by every `with()` view and `extend()` child — ids never repeat |
387
388
  | **trait** | a named partial (or `(n, ids, transient) => partial`). `with('a', 'b')` composes left to right; a call's override wins. An undeclared one fails at `with()` (`X_TEST_FACTORY_TRAIT_UNKNOWN`) |
388
389
  | **transient** | declared defaults a call may override; read by `defaults`, traits and callbacks; never written |
@@ -517,7 +518,7 @@ is meant to FAIL it. The subject is called once per test.
517
518
  | `AuthServerStore` (auth) | `behavesLike(authServerStoreConformance, () => store)` |
518
519
  | `BudgetStore` (ai) | `behavesLike(budgetStoreConformance, () => store)` |
519
520
  | `CacheTier` (cache) | `behavesLike(cacheTierConformance, () => tier)` — each check runs inside a request |
520
- | entity `Driver` (entity) | `behavesLike(entityDriverConformance, () => ({ open: (entities) => driver, capabilities, foreignKeys }))` — `open` hands a driver over EMPTY tables for `entities`; an undeclared capability is asserted REFUSED |
521
+ | entity `Driver` (entity) | `behavesLike(entityDriverConformance, () => ({ open: (entities) => driver, capabilities, foreignKeys }))` — `open` hands a driver over EMPTY tables for `entities`; an undeclared capability is asserted REFUSED. `history: true` when the store records `entity({ history: true })` (memory, Postgres): the history check runs `history(table, id)` against it; absent, as for a `defineDriver` store with no lifecycle hook, that check is skipped |
521
522
  | `ErrorGroupsStore` (admin) | `behavesLike(errorGroupsStoreConformance, () => store)` |
522
523
  | `ErrorReporter` (core) | `behavesLike(errorReporterConformance, () => ({ reporter, delivered }))` — `delivered()` is the text each report left as; only a `localErrorSink`-marked reporter may carry a secret |
523
524
  | `EventBus` (jobs) | `behavesLike(eventBusConformance, () => ({ bus, elapse }))` |
@@ -806,6 +807,57 @@ Each tamper is refused by `@ultimat3/auth`'s real `verifyIdToken` with the code
806
807
  broken token gets (`packages/testing/src/fake-identity-provider.test.ts`). An unknown `sub` and an
807
808
  empty `users` are `X_INVARIANT`.
808
809
 
810
+ ### SAML
811
+
812
+ `As of 31.3`. `fakeSamlIdentityProvider({ audience, users, clock? })` is the SAML twin: metadata
813
+ for `samlIdentityProvider`, and a signed answer to the AuthnRequest an SP's redirect carries — no
814
+ socket, no browser. `audience` is the SP's `spEntityId`; a user is `{ nameId, email?, name? }`.
815
+
816
+ ```ts
817
+ import { memoryTotpReplayGuard, parseSamlMetadata, samlIdentityProvider } from '@ultimat3/auth';
818
+ import { frozenClock } from '@ultimat3/core';
819
+ import { expect, fakeSamlIdentityProvider, unitTest } from '@ultimat3/testing';
820
+
821
+ unitTest('a SAML sign-in completes as the IdP user', async () => {
822
+ const clock = frozenClock('2026-11-10T09:00:00.000Z');
823
+ const spEntityId = 'https://app.example.test/saml/metadata';
824
+ const callbackUrl = 'https://app.example.test/auth/sso/corp/callback';
825
+ const idp = await fakeSamlIdentityProvider({
826
+ audience: spEntityId,
827
+ clock,
828
+ users: [{ nameId: 'u-ada', email: 'ada@corp.example' }],
829
+ });
830
+ const provider = samlIdentityProvider({
831
+ id: 'corp',
832
+ idp: parseSamlMetadata(idp.metadataXml),
833
+ spEntityId,
834
+ trustEmail: true,
835
+ emailDomains: ['corp.example'],
836
+ });
837
+ const redirect = await provider.begin({ callbackUrl, clock });
838
+ const identity = await provider.complete({
839
+ state: redirect.state,
840
+ params: await idp.answer(redirect.location), // { SAMLResponse, RelayState }
841
+ callbackUrl,
842
+ clock,
843
+ replay: memoryTotpReplayGuard(),
844
+ });
845
+ expect(identity.profile.providerAccountId).toBe('u-ada');
846
+ });
847
+ ```
848
+
849
+ | Member | Does |
850
+ |---|---|
851
+ | `entityId` · `metadataXml` | the IdP's identity; `parseSamlMetadata(metadataXml)` is the provider's `idp` |
852
+ | `signInAs(nameId)` | who the next answer signs in as; the first user until called |
853
+ | `tamper({ wrongAudience?, expired?, unsigned?, wrongKey? })` | every answer after it is broken that way; `tamper({})` restores honesty |
854
+ | `readAuthnRequest(location)` | the inflated AuthnRequest: `id`, `relayState`, `acsUrl`, `xml` |
855
+ | `answer(location)` | the ACS form body for that request: `{ SAMLResponse, RelayState }` |
856
+
857
+ The signer is `@ultimat3/auth/saml-test-idp`'s, the one auth's own SAML suites sign with —
858
+ loaded on first call, so this barrel stays auth-free. Each tamper is refused by the real verifier
859
+ with an `X_SAML_*` code (`fake-saml-identity-provider.test.ts`).
860
+
809
861
  ## Testing a passkey ceremony
810
862
 
811
863
  `As of 2026-11`. `softAuthenticator({ origin, algorithm?, counter? })` is a passkey on no device:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "31.1.0",
3
+ "version": "31.3.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.1.0",
51
- "@ultimat3/ai": "31.1.0",
52
- "@ultimat3/auth": "31.1.0",
53
- "@ultimat3/cache": "31.1.0",
54
- "@ultimat3/core": "31.1.0",
55
- "@ultimat3/db": "31.1.0",
56
- "@ultimat3/entity": "31.1.0",
57
- "@ultimat3/http": "31.1.0",
58
- "@ultimat3/i18n": "31.1.0",
59
- "@ultimat3/jobs": "31.1.0",
60
- "@ultimat3/mail": "31.1.0",
61
- "@ultimat3/notify": "31.1.0",
62
- "@ultimat3/policy": "31.1.0",
63
- "@ultimat3/pwa": "31.1.0",
64
- "@ultimat3/query": "31.1.0",
65
- "@ultimat3/realtime": "31.1.0",
66
- "@ultimat3/render": "31.1.0",
67
- "@ultimat3/schema": "31.1.0",
68
- "@ultimat3/scraping": "31.1.0",
69
- "@ultimat3/seo": "31.1.0",
70
- "@ultimat3/time": "31.1.0"
50
+ "@ultimat3/action": "31.3.0",
51
+ "@ultimat3/ai": "31.3.0",
52
+ "@ultimat3/auth": "31.3.0",
53
+ "@ultimat3/cache": "31.3.0",
54
+ "@ultimat3/core": "31.3.0",
55
+ "@ultimat3/db": "31.3.0",
56
+ "@ultimat3/entity": "31.3.0",
57
+ "@ultimat3/http": "31.3.0",
58
+ "@ultimat3/i18n": "31.3.0",
59
+ "@ultimat3/jobs": "31.3.0",
60
+ "@ultimat3/mail": "31.3.0",
61
+ "@ultimat3/notify": "31.3.0",
62
+ "@ultimat3/policy": "31.3.0",
63
+ "@ultimat3/pwa": "31.3.0",
64
+ "@ultimat3/query": "31.3.0",
65
+ "@ultimat3/realtime": "31.3.0",
66
+ "@ultimat3/render": "31.3.0",
67
+ "@ultimat3/schema": "31.3.0",
68
+ "@ultimat3/scraping": "31.3.0",
69
+ "@ultimat3/seo": "31.3.0",
70
+ "@ultimat3/time": "31.3.0"
71
71
  }
72
72
  }
@@ -3,6 +3,8 @@
3
3
  // (`e2e-run.ts`) with Bun's own hooks and a real browser. With no root named it is INERT.
4
4
 
5
5
  import { afterAll, beforeEach } from 'bun:test';
6
+ import { DETECTED_ZONE_COOKIE } from '@ultimat3/render';
7
+ import type { E2eBrowser } from './cdp-browser';
6
8
  import { openE2eBrowser } from './cdp-browser';
7
9
  import { startE2eApp } from './e2e-app';
8
10
  import { E2E_ROOT_ENV } from './e2e-browser-handle';
@@ -10,15 +12,31 @@ import { installE2eDriver } from './e2e-driver';
10
12
  import { e2eDefaultLocale } from './e2e-locale';
11
13
  import { startE2eRun } from './e2e-run';
12
14
 
15
+ /** Seed the same device zone a rendered document would report before the browser can navigate. */
16
+ export async function seedDetectedZone(
17
+ browser: E2eBrowser,
18
+ origin: string,
19
+ timeZone: string,
20
+ ): Promise<E2eBrowser> {
21
+ await browser.session.setCookie(origin, DETECTED_ZONE_COOKIE, timeZone);
22
+ return browser;
23
+ }
24
+
13
25
  const root = Bun.env[E2E_ROOT_ENV];
14
26
  if (root !== undefined && root !== '') {
15
27
  // Read once, before the app boots: every browser this run opens — the first and every relaunch —
16
28
  // asks for the app's default locale, so a page's language never depends on the runner's Chrome.
17
29
  const acceptLanguage = await e2eDefaultLocale(root);
30
+ const app = await startE2eApp({ root });
31
+ const timeZone = Bun.env['TZ'] ?? 'UTC';
32
+ const openBrowser = async (): Promise<E2eBrowser> => {
33
+ const browser = await openE2eBrowser(acceptLanguage === undefined ? {} : { acceptLanguage });
34
+ return seedDetectedZone(browser, app.base, timeZone);
35
+ };
18
36
  await startE2eRun({
19
- app: await startE2eApp({ root }),
37
+ app,
20
38
  // `openE2eBrowser`, never the `IfAvailable` door: the step only names a root after finding one.
21
- openBrowser: () => openE2eBrowser(acceptLanguage === undefined ? {} : { acceptLanguage }),
39
+ openBrowser,
22
40
  install: installE2eDriver,
23
41
  beforeEach,
24
42
  afterAll,
@@ -4,6 +4,7 @@
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 { HISTORY_CHECKS } from './entity-conformance-history';
7
8
  import { LOCK_CHECKS } from './entity-conformance-locks';
8
9
  import { MATRIX_CHECKS } from './entity-conformance-matrix';
9
10
  import { READ_CHECKS } from './entity-conformance-reads';
@@ -24,4 +25,5 @@ export const ENTITY_DRIVER_CHECKS: readonly EntityDriverCheck[] = [
24
25
  ...LOCK_CHECKS,
25
26
  ...MATRIX_CHECKS,
26
27
  ...VERSION_CHECKS,
28
+ ...HISTORY_CHECKS,
27
29
  ];
@@ -0,0 +1,70 @@
1
+ // Entity conformance · HISTORY: `entity({ history: true })` read back through `history(table, id)`.
2
+ // One transaction's versions tie on `now()` and still read back in write order, numbered from 1; a
3
+ // transaction that fails writes no version; another tenant reads none. Run only where the subject
4
+ // declares `history` — a `defineDriver` store has no lifecycle hook (`EntityDriverSubject.history`).
5
+
6
+ import { expect } from 'bun:test';
7
+ import { entity, history, text, uuid } from '@ultimat3/entity';
8
+ import { remember } from './entity-conformance-entities';
9
+ import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
10
+ import type { EntityDriverCheck } from './entity-driver-conformance';
11
+
12
+ const notes = remember(
13
+ entity('ec_h_notes', {
14
+ columns: { id: uuid().primaryKey(), orgId: uuid().tenant(), title: text({ max: 40 }) },
15
+ history: true,
16
+ }),
17
+ );
18
+ const notesHistory = remember(
19
+ notes.$history ?? expect.unreachable('history: true declares a history entity'),
20
+ );
21
+
22
+ const ORG = idAt('b1');
23
+ const OTHER_ORG = idAt('b2');
24
+ const NOTE = idAt('b11');
25
+ const FAILED = idAt('b12');
26
+ const TITLES = ['b', 'c', 'd'];
27
+
28
+ export const HISTORY_CHECKS: readonly EntityDriverCheck[] = [
29
+ checkOver(
30
+ { notes, notesHistory },
31
+ 'history: one transaction reads back in order, a failed one writes none, no other tenant reads it',
32
+ async (db, raw) => {
33
+ // A `defineDriver` store has no lifecycle hook: it records no history and refuses nothing, so
34
+ // there is no answer to hold it to. Skipped, not asserted refused, as a capability would be.
35
+ if (!raw.history) return;
36
+ const tx = () => raw.driver.transactor();
37
+ const own = await inOrg(ORG, async () => {
38
+ await tx().run(async () => {
39
+ await db.notes.insert({ id: NOTE, orgId: ORG, title: 'a' });
40
+ for (const title of TITLES) await db.notes.update(NOTE, { title });
41
+ await db.notes.delete(NOTE);
42
+ });
43
+ const failed = await codeOf(() =>
44
+ tx().run(async () => {
45
+ await db.notes.insert({ id: FAILED, orgId: ORG, title: 'a' });
46
+ await db.notes.insert({ id: FAILED, orgId: ORG, title: 'again' });
47
+ }),
48
+ );
49
+ return {
50
+ versions: await history(db.notesHistory, NOTE),
51
+ failed,
52
+ failedVersions: await history(db.notesHistory, FAILED),
53
+ };
54
+ });
55
+ const title = (image: unknown): string | null =>
56
+ (image as { title?: string } | null)?.title ?? null;
57
+ expect(own.versions.map((v) => [v.version, v.op, title(v.before), title(v.after)])).toEqual([
58
+ [1, 'insert', null, 'a'],
59
+ [2, 'update', 'a', 'b'],
60
+ [3, 'update', 'b', 'c'],
61
+ [4, 'update', 'c', 'd'],
62
+ [5, 'delete', 'd', null],
63
+ ]);
64
+ expect(own.failed).toBe('X_DB_UNIQUE_VIOLATION');
65
+ expect(own.failedVersions).toEqual([]);
66
+ expect(await inOrg(OTHER_ORG, () => history(db.notesHistory, NOTE))).toEqual([]);
67
+ },
68
+ ['transactions'],
69
+ ),
70
+ ];
@@ -147,22 +147,34 @@ const lockChecks: readonly EntityDriverCheck[] = [
147
147
  checkOver(
148
148
  SET,
149
149
  'a nested lock is held to the outer end, not released with its own',
150
- async (db) => {
150
+ async (db, raw) => {
151
+ // Sequenced on what the driver REPORTS, never on a clock: the outer ends once the contender is
152
+ // queued behind c4 (a held lock) or has run (a released one) — whichever the driver does. A
153
+ // wall-clock window let a broken driver pass whenever its contender was slow.
154
+ const waiters = raw.lockWaiters;
155
+ if (waiters === undefined) return;
151
156
  await counter(db, idAt('c3'));
152
157
  await counter(db, idAt('c4'));
153
158
  const order: string[] = [];
159
+ const nestedHeld = Promise.withResolvers<void>();
160
+ let secondRan = false;
161
+ const queuedOrRan = async (): Promise<void> => {
162
+ while (!secondRan && (await waiters()) < 1) {
163
+ await new Promise<void>((resolve) => setImmediate(resolve));
164
+ }
165
+ };
154
166
  await inOrg(ORG_A, () =>
155
167
  Promise.all([
156
168
  db.counters.lock(idAt('c3'), async () => {
157
- await db.counters.lock(idAt('c4'), () => undefined);
158
- await yieldNow();
159
- await yieldNow();
169
+ await db.counters.lock(idAt('c4'), () => nestedHeld.resolve());
170
+ await queuedOrRan();
160
171
  order.push('outer ending');
161
172
  }),
162
173
  (async () => {
163
- await yieldNow();
174
+ await nestedHeld.promise;
164
175
  await db.counters.lock(idAt('c4'), () => {
165
176
  order.push('second ran');
177
+ secondRan = true;
166
178
  });
167
179
  })(),
168
180
  ]),
@@ -3,6 +3,8 @@
3
3
  // and a column stores only what Postgres stores. Lifted from `entity/src/write-parity.test.ts`.
4
4
 
5
5
  import { expect } from 'bun:test';
6
+ import { isUltimateError } from '@ultimat3/core';
7
+ import { SQLSTATE, sqlState } from '@ultimat3/db';
6
8
  import {
7
9
  arrayOf,
8
10
  bigint,
@@ -106,7 +108,19 @@ const docs = remember(
106
108
  );
107
109
 
108
110
  const ID = idAt(1);
109
- const UNIQUE = 'X_DB_UNIQUE_VIOLATION';
111
+ /** A duplicate key: the framework's code AND Postgres' SQLSTATE, on every driver — a caller that
112
+ * branches on `sqlState(error)` (an upsert retry, a "taken" message) must not see Postgres only. */
113
+ const DUPLICATE = { code: 'X_DB_UNIQUE_VIOLATION', sqlState: SQLSTATE.uniqueViolation };
114
+
115
+ /** The refusal's code and SQLSTATE, or the value when nothing was refused. */
116
+ const duplicate = async (work: () => Promise<unknown>): Promise<unknown> => {
117
+ try {
118
+ return { ok: await work() };
119
+ } catch (error) {
120
+ return { code: isUltimateError(error) ? error.code : 'uncoded', sqlState: sqlState(error) };
121
+ }
122
+ };
123
+
110
124
  const REFUSED = { code: 'X_INVARIANT_VIOLATED' };
111
125
 
112
126
  const undefinedIsAbsent: readonly EntityDriverCheck[] = [
@@ -142,23 +156,19 @@ const undefinedIsAbsent: readonly EntityDriverCheck[] = [
142
156
  const keysAreKept: readonly EntityDriverCheck[] = [
143
157
  checkOver({ tags }, 'a duplicate primary key is refused, not a silent replace', async (db) => {
144
158
  await db.tags.insert({ code: 'a', slug: 'one' });
145
- expect(await outcome(() => db.tags.insert({ code: 'a', slug: 'two' }))).toEqual({
146
- code: UNIQUE,
147
- });
159
+ expect(await duplicate(() => db.tags.insert({ code: 'a', slug: 'two' }))).toEqual(DUPLICATE);
148
160
  expect((await db.tags.all()).map((row) => row.slug)).toEqual(['one']);
149
161
  }),
150
162
  checkOver({ tags }, 'a duplicate unique column is refused', async (db) => {
151
163
  await db.tags.insert({ code: 'a', slug: 'one' });
152
- expect(await outcome(() => db.tags.insert({ code: 'b', slug: 'one' }))).toEqual({
153
- code: UNIQUE,
154
- });
164
+ expect(await duplicate(() => db.tags.insert({ code: 'b', slug: 'one' }))).toEqual(DUPLICATE);
155
165
  }),
156
166
  checkOver({ tags }, 'insertAll with a duplicate inside the batch stores nothing', async (db) => {
157
167
  const batch = [
158
168
  { code: 'a', slug: 'one' },
159
169
  { code: 'a', slug: 'two' },
160
170
  ];
161
- expect(await outcome(() => db.tags.insertAll(batch))).toEqual({ code: UNIQUE });
171
+ expect(await duplicate(() => db.tags.insertAll(batch))).toEqual(DUPLICATE);
162
172
  expect(await db.tags.all()).toHaveLength(0);
163
173
  }),
164
174
  checkOver({ tags }, 'a patch moving the primary key leaves one row, not two', async (db) => {
@@ -194,9 +204,9 @@ const keysAreKept: readonly EntityDriverCheck[] = [
194
204
  async (db) => {
195
205
  await db.notes.insert({ id: idAt(1), title: 'one', body: 'same' });
196
206
  await db.notes.insert({ id: idAt(2), title: 'two', body: 'same' });
197
- expect(await outcome(() => db.notes.updateWhere({ body: 'same' }, { id: idAt(3) }))).toEqual({
198
- code: UNIQUE,
199
- });
207
+ expect(
208
+ await duplicate(() => db.notes.updateWhere({ body: 'same' }, { id: idAt(3) })),
209
+ ).toEqual(DUPLICATE);
200
210
  const kept = (await db.notes.all()).map((row) => [row.id, row.title, row.body]).sort();
201
211
  expect(kept).toEqual([
202
212
  [idAt(1), 'one', 'same'],
@@ -211,10 +221,8 @@ const keysAreKept: readonly EntityDriverCheck[] = [
211
221
  await db.countries.insert({ id: idAt(1), iso: 'AA', name: 'Same' });
212
222
  await db.countries.insert({ id: idAt(2), iso: 'BB', name: 'Same' });
213
223
  expect(
214
- await outcome(() => db.countries.updateWhere({ name: 'Same' }, { iso: 'ZZ' })),
215
- ).toEqual({
216
- code: UNIQUE,
217
- });
224
+ await duplicate(() => db.countries.updateWhere({ name: 'Same' }, { iso: 'ZZ' })),
225
+ ).toEqual(DUPLICATE);
218
226
  const kept = (await db.countries.all()).map((row) => [row.id, row.iso]).sort();
219
227
  expect(kept).toEqual([
220
228
  [idAt(1), 'AA'],
@@ -224,9 +232,7 @@ const keysAreKept: readonly EntityDriverCheck[] = [
224
232
  ),
225
233
  checkOver({ docs }, 'a unique declared as an invariant refuses a second row', async (db) => {
226
234
  await db.docs.insert({ id: idAt(1), slug: 'one' });
227
- expect(await outcome(() => db.docs.insert({ id: idAt(2), slug: 'one' }))).toEqual({
228
- code: UNIQUE,
229
- });
235
+ expect(await duplicate(() => db.docs.insert({ id: idAt(2), slug: 'one' }))).toEqual(DUPLICATE);
230
236
  }),
231
237
  checkOver(
232
238
  { docs },
@@ -234,14 +240,12 @@ const keysAreKept: readonly EntityDriverCheck[] = [
234
240
  async (db) => {
235
241
  await db.docs.insert({ id: idAt(1), slug: 'one' });
236
242
  await db.docs.insert({ id: idAt(2), slug: 'two' });
237
- expect(await outcome(() => db.docs.update(idAt(2), { slug: 'one' }))).toEqual({
238
- code: UNIQUE,
239
- });
243
+ expect(await duplicate(() => db.docs.update(idAt(2), { slug: 'one' }))).toEqual(DUPLICATE);
240
244
  const pair = [
241
245
  { id: idAt(3), slug: 'three' },
242
246
  { id: idAt(4), slug: 'three' },
243
247
  ];
244
- expect(await outcome(() => db.docs.insertAll(pair))).toEqual({ code: UNIQUE });
248
+ expect(await duplicate(() => db.docs.insertAll(pair))).toEqual(DUPLICATE);
245
249
  expect((await db.docs.all()).map((row) => row.slug).sort()).toEqual(['one', 'two']);
246
250
  },
247
251
  ),
@@ -24,12 +24,29 @@ export interface EntityDriverSubject {
24
24
  readonly capabilities: readonly DriverCapability[];
25
25
  /** Whether a reference to a row that does not exist is refused (`X_DB_FOREIGN_KEY_VIOLATION`). */
26
26
  readonly foreignKeys: boolean;
27
+ /**
28
+ * Whether the store records `entity({ history: true })` — Postgres by trigger, memory in its
29
+ * repository. A `defineDriver` store has no lifecycle hook, so it records nothing and refuses
30
+ * nothing: absent here, the history check is not run against it (there is no refusal to assert).
31
+ */
32
+ readonly history?: boolean;
33
+ /**
34
+ * How many lock requests are blocked behind a holder right now — `memoryLockWaiters` from
35
+ * `@ultimat3/entity/adapter`, or `pg_stat_activity`'s `wait_event_type = 'Lock'` on a pool. What
36
+ * the hold check waits on to know a contender REACHED the lock, never a clock. Absent (PGlite:
37
+ * one connection, so a contender waits on the client where no query sees it): that check skips.
38
+ */
39
+ readonly lockWaiters?: (() => number | Promise<number>) | undefined;
27
40
  }
28
41
 
29
42
  /** What one check sees: the opened driver, and the subject's declared traits. */
30
43
  export interface EntityDriverRun {
31
44
  readonly driver: Driver;
32
45
  readonly foreignKeys: boolean;
46
+ /** The subject's `history`, `false` when it declared none. */
47
+ readonly history: boolean;
48
+ /** The subject's `lockWaiters`, when it can see one. */
49
+ readonly lockWaiters: (() => number | Promise<number>) | undefined;
33
50
  }
34
51
 
35
52
  export interface EntityDriverCheck {
@@ -82,7 +99,12 @@ export const runEntityDriverCheck = async (
82
99
  for (const capability of missing) await assertRefused(driver, capability);
83
100
  return;
84
101
  }
85
- await check.run({ driver, foreignKeys: subject.foreignKeys });
102
+ await check.run({
103
+ driver,
104
+ foreignKeys: subject.foreignKeys,
105
+ history: subject.history === true,
106
+ lockWaiters: subject.lockWaiters,
107
+ });
86
108
  };
87
109
 
88
110
  /** Generous: a SQL subject re-creates its tables per check, and one check writes 40,000 rows. */
package/src/factories.ts CHANGED
@@ -10,10 +10,12 @@ import { persistRow } from './factory-persist';
10
10
  import { attributesOf, type FactorySpec, rowSteps, type Step } from './factory-pipeline';
11
11
  import type {
12
12
  BelongsToMap,
13
+ DefaultsBound,
13
14
  EntityLike,
14
15
  FactoryIds,
15
16
  HasManyMap,
16
17
  None,
18
+ SettledAttrs,
17
19
  StoredOf,
18
20
  TraitMap,
19
21
  } from './factory-types';
@@ -162,22 +164,30 @@ function extended(
162
164
  }
163
165
 
164
166
  export function defineFactory<
165
- TAttrs extends object,
167
+ TAttrs extends DefaultsBound<TAttrs, E>,
166
168
  E extends EntityLike = EntityLike,
167
169
  TTransient extends object = None,
168
- TTraits extends TraitMap<TAttrs & StoredOf<E, TAttrs>, TTransient> = TraitMap<
169
- TAttrs & StoredOf<E, TAttrs>,
170
+ TTraits extends TraitMap<
171
+ SettledAttrs<TAttrs> & StoredOf<E, SettledAttrs<TAttrs>>,
170
172
  TTransient
171
- >,
173
+ > = TraitMap<SettledAttrs<TAttrs> & StoredOf<E, SettledAttrs<TAttrs>>, TTransient>,
172
174
  TBelongs extends BelongsToMap = None,
173
175
  TMany extends HasManyMap = None,
174
176
  >(
175
177
  entity: E,
176
- options: FactoryOptions<TAttrs, TTraits, TTransient, TBelongs, TMany, StoredOf<E, TAttrs>, E>,
178
+ options: FactoryOptions<
179
+ TAttrs,
180
+ TTraits,
181
+ TTransient,
182
+ TBelongs,
183
+ TMany,
184
+ StoredOf<E, SettledAttrs<TAttrs>>,
185
+ E
186
+ >,
177
187
  ): Factory<
178
- TAttrs,
188
+ SettledAttrs<TAttrs>,
179
189
  Extract<keyof TTraits, string>,
180
- StoredOf<E, TAttrs>,
190
+ StoredOf<E, SettledAttrs<TAttrs>>,
181
191
  TTransient,
182
192
  TBelongs,
183
193
  TMany
@@ -211,9 +221,9 @@ export function defineFactory<
211
221
  afterCreate: erased.afterCreate === undefined ? [] : [erased.afterCreate.bind(options)],
212
222
  };
213
223
  return view(spec, sequence, seed, []) as unknown as Factory<
214
- TAttrs,
224
+ SettledAttrs<TAttrs>,
215
225
  Extract<keyof TTraits, string>,
216
- StoredOf<E, TAttrs>,
226
+ StoredOf<E, SettledAttrs<TAttrs>>,
217
227
  TTransient,
218
228
  TBelongs,
219
229
  TMany
@@ -12,6 +12,7 @@ import type {
12
12
  ForeignKeysOf,
13
13
  HasManyMap,
14
14
  None,
15
+ SettledAttrs,
15
16
  TraitMap,
16
17
  WriteBound,
17
18
  } from './factory-types';
@@ -31,19 +32,26 @@ export interface FactoryOptions<
31
32
  * Every column the factory owns; called once per row. `index` is the sequence. It must name each
32
33
  * `belongsTo` key, so a key that is not a column is a compile error HERE: a check written as a
33
34
  * constraint on `belongsTo` fixed the row type before this was read, and every row became `object`.
35
+ * `Readonly<TAttrs>` is the slot that keeps an enum literal literal (`DefaultsBound`).
34
36
  */
35
37
  defaults(
36
38
  index: number,
37
39
  ids: FactoryIds,
38
40
  transient: TTransient,
39
- ): TAttrs & WriteBound<E> & Readonly<Record<ForeignKeysOf<TBelongs>, unknown>>;
41
+ ): TAttrs & Readonly<TAttrs> & WriteBound<E> & Readonly<Record<ForeignKeysOf<TBelongs>, unknown>>;
40
42
  readonly traits?: TTraits;
41
43
  /** Attributes a call may pass that are never written: read by `defaults`, traits and callbacks. */
42
44
  readonly transient?: TTransient;
43
45
  readonly belongsTo?: TBelongs;
44
46
  readonly hasMany?: TMany;
45
- /** After the row is assembled, before any write — both strategies. */
46
- afterBuild?(row: NoInfer<TAttrs>, context: FactoryContext<TTransient>): void;
47
+ /**
48
+ * After the row is assembled, before any write — both strategies. The row is `build()`'s own
49
+ * type: a column holds its declared union, never the widened `SettledAttrs` one.
50
+ */
51
+ afterBuild?(
52
+ row: NoInfer<SettledAttrs<TAttrs> & Partial<TRow>>,
53
+ context: FactoryContext<TTransient>,
54
+ ): void;
47
55
  /** After the row and its `hasMany` children are stored — `create()` only. */
48
56
  afterCreate?(
49
57
  row: NoInfer<Created<TRow, TMany>>,
@@ -68,7 +76,7 @@ export interface FactoryExtension<
68
76
  readonly traits?: TTraits;
69
77
  readonly transient?: Partial<TTransient>;
70
78
  readonly hasMany?: TMoreMany;
71
- afterBuild?(row: TAttrs, context: FactoryContext<TTransient>): void;
79
+ afterBuild?(row: TAttrs & Partial<TRow>, context: FactoryContext<TTransient>): void;
72
80
  afterCreate?(
73
81
  row: Created<TRow, TMany & TMoreMany>,
74
82
  context: FactoryContext<TTransient>,
@@ -129,3 +129,34 @@ export type StoredOf<E, TAttrs> = E extends { readonly $row: infer R extends obj
129
129
  export type WriteBound<E> = E extends { readonly $columns: infer C extends ColumnMap }
130
130
  ? Partial<Insertable<C>>
131
131
  : object;
132
+
133
+ /**
134
+ * Any value at all (`{} | null | undefined` is `unknown`, so `Record<string, unknown>` fits), but
135
+ * spelled as a union so the checker sees it include `string` — `unknown` alone would not keep a literal.
136
+ */
137
+ // biome-ignore lint/complexity/noBannedTypes: `{}` is what makes the union admit `unknown`.
138
+ export type AttrValue = string | number | boolean | bigint | symbol | {} | null | undefined;
139
+
140
+ /**
141
+ * The bound on what `defaults` returns. Its per-key `AttrValue` is what keeps `status: 'open'` a
142
+ * literal: TypeScript widens a literal unless the slot it lands in is a type variable whose
143
+ * constraint holds `string`, and `WriteBound<E>` is a conditional over an unfixed `E` that never
144
+ * is. Self-referential (`keyof A`) rather than a `Record`, so an `interface` still satisfies it.
145
+ */
146
+ export type DefaultsBound<A, E> = { readonly [K in keyof A]: AttrValue } & WriteBound<E>;
147
+
148
+ type Widened<V> = V extends string
149
+ ? string
150
+ : V extends number
151
+ ? number
152
+ : V extends boolean
153
+ ? boolean
154
+ : V extends bigint
155
+ ? bigint
156
+ : V;
157
+
158
+ /**
159
+ * The literals `DefaultsBound` kept, widened back once checked: `title: \`t${n}\`` must not make
160
+ * `build({ title: 'x' })` a type error. A column's own union returns through `Partial<TRow>`.
161
+ */
162
+ export type SettledAttrs<A> = { [K in keyof A]: Widened<A[K]> };
@@ -0,0 +1,110 @@
1
+ // A fake SAML IdP for an app's sign-in tests, the SAML twin of `fakeIdentityProvider`: metadata to
2
+ // hand `samlIdentityProvider`, and a signed answer to the AuthnRequest an SP's redirect carries, as a
3
+ // chosen user. `tamper()` mints the refusals that matter. The signer is `@ultimat3/auth/saml-test-idp`'s
4
+ // — the one auth's own suites sign with — loaded on first use, so this barrel stays auth-free.
5
+
6
+ import type { Clock } from '@ultimat3/core';
7
+ import { assert, systemClock } from '@ultimat3/core';
8
+
9
+ export interface FakeSamlUser {
10
+ /** The `NameID`: what `profile.providerAccountId` reads. */
11
+ readonly nameId: string;
12
+ /** The `email` attribute; `null` omits it. Defaults to none. */
13
+ readonly email?: string | null | undefined;
14
+ /** The `displayName` attribute; absent omits it. */
15
+ readonly name?: string | undefined;
16
+ }
17
+
18
+ export interface FakeSamlTamper {
19
+ /** The audience names another SP. */
20
+ readonly wrongAudience?: boolean | undefined;
21
+ /** The assertion's window closed an hour ago. */
22
+ readonly expired?: boolean | undefined;
23
+ /** No signature at either level. */
24
+ readonly unsigned?: boolean | undefined;
25
+ /** Signed by a key the metadata does not publish. */
26
+ readonly wrongKey?: boolean | undefined;
27
+ }
28
+
29
+ export interface FakeSamlIdentityProviderInput {
30
+ /** The SP's entity id — `samlIdentityProvider({ spEntityId })` — that each response is for. */
31
+ readonly audience: string;
32
+ readonly users: readonly FakeSamlUser[];
33
+ readonly clock?: Clock | undefined;
34
+ }
35
+
36
+ export interface FakeSamlAuthnRequest {
37
+ readonly id: string;
38
+ readonly relayState: string;
39
+ /** Where the SP asked the answer posted: its `AssertionConsumerServiceURL`. */
40
+ readonly acsUrl: string;
41
+ readonly xml: string;
42
+ }
43
+
44
+ export interface FakeSamlIdentityProvider {
45
+ readonly entityId: string;
46
+ /** `parseSamlMetadata(metadataXml)` is `samlIdentityProvider`'s `idp`. */
47
+ readonly metadataXml: string;
48
+ /** Who the next answer signs in as. Defaults to the first user. */
49
+ signInAs(nameId: string): void;
50
+ /** Applies to every answer after it; `tamper({})` restores honesty. */
51
+ tamper(flags: FakeSamlTamper): void;
52
+ /** The AuthnRequest on an SP's redirect `location`, inflated. */
53
+ readAuthnRequest(location: string): FakeSamlAuthnRequest;
54
+ /** The browser's POST back for the request on `location`: the ACS's form body. */
55
+ answer(location: string): Promise<{ readonly SAMLResponse: string; readonly RelayState: string }>;
56
+ }
57
+
58
+ const HOUR_MS = 3_600_000;
59
+
60
+ export async function fakeSamlIdentityProvider(
61
+ input: FakeSamlIdentityProviderInput,
62
+ ): Promise<FakeSamlIdentityProvider> {
63
+ assert(
64
+ input.users.length > 0,
65
+ 'fakeSamlIdentityProvider was given no users',
66
+ 'pass users: [{ nameId, email }]',
67
+ );
68
+ const saml = await import('@ultimat3/auth/saml-test-idp');
69
+ const [idp, rogue] = await Promise.all([saml.samlTestIdp(), saml.testRsaSigner()]);
70
+ const users = new Map(input.users.map((user) => [user.nameId, user]));
71
+ const clock = input.clock ?? systemClock;
72
+ let current = input.users[0]?.nameId ?? '';
73
+ let flags: FakeSamlTamper = {};
74
+
75
+ const readAuthnRequest = (location: string): FakeSamlAuthnRequest => {
76
+ const request = saml.readAuthnRequest(location);
77
+ const acsUrl = /\bAssertionConsumerServiceURL="([^"]+)"/.exec(request.xml)?.[1] ?? '';
78
+ return { ...request, acsUrl };
79
+ };
80
+
81
+ return {
82
+ entityId: saml.TEST_IDP_ENTITY_ID,
83
+ metadataXml: idp.metadataXml,
84
+ signInAs(nameId) {
85
+ assert(users.has(nameId), `fake SAML IdP has no user ${nameId}`, 'add it to users: [...]');
86
+ current = nameId;
87
+ },
88
+ tamper(next) {
89
+ flags = next;
90
+ },
91
+ readAuthnRequest,
92
+ async answer(location) {
93
+ const request = readAuthnRequest(location);
94
+ const user = users.get(current);
95
+ const now = clock.now();
96
+ const xml = await idp.responseXml({
97
+ requestId: request.id,
98
+ acsUrl: request.acsUrl,
99
+ audience: flags.wrongAudience === true ? `${input.audience}#other` : input.audience,
100
+ now: flags.expired === true ? new Date(now.getTime() - HOUR_MS) : now,
101
+ nameId: current,
102
+ email: user?.email ?? null,
103
+ name: user?.name ?? null,
104
+ signAssertion: flags.unsigned !== true,
105
+ ...(flags.wrongKey === true ? { signer: rogue } : {}),
106
+ });
107
+ return { SAMLResponse: saml.encodeResponse(xml), RelayState: request.relayState };
108
+ },
109
+ };
110
+ }
package/src/index.ts CHANGED
@@ -171,10 +171,12 @@ export type { EntityRegistry, FactoryRegistry } from './factory-registry';
171
171
  export { factoriesFor } from './factory-registry';
172
172
  export type {
173
173
  AttributesFor,
174
+ AttrValue,
174
175
  BelongsTo,
175
176
  BelongsToMap,
176
177
  Built,
177
178
  Created,
179
+ DefaultsBound,
178
180
  EntityLike,
179
181
  FactoryContext,
180
182
  FactoryIds,
@@ -184,6 +186,7 @@ export type {
184
186
  HasMany,
185
187
  HasManyMap,
186
188
  None,
189
+ SettledAttrs,
187
190
  StoredOf,
188
191
  Trait,
189
192
  TraitMap,
@@ -196,6 +199,14 @@ export type {
196
199
  FakeIdpUser,
197
200
  } from './fake-identity-provider';
198
201
  export { fakeIdentityProvider } from './fake-identity-provider';
202
+ export type {
203
+ FakeSamlAuthnRequest,
204
+ FakeSamlIdentityProvider,
205
+ FakeSamlIdentityProviderInput,
206
+ FakeSamlTamper,
207
+ FakeSamlUser,
208
+ } from './fake-saml-identity-provider';
209
+ export { fakeSamlIdentityProvider } from './fake-saml-identity-provider';
199
210
  export type { FaultMode, FaultProxy, FaultProxyCounts } from './fault-proxy';
200
211
  export { faultProxy } from './fault-proxy';
201
212
  export type { TestClock, TestDuration } from './fixture-clock';
@@ -0,0 +1,69 @@
1
+ // Single responsibility: where a seeded `partitionBy` column's values may land: the UTC bucket
2
+ // holding the anchor (`date_trunc(unit, … at time zone 'UTC')`, as `ultimate_partitions` cuts it),
3
+ // read off the entity's own `$describe().partition` — never a date of ours.
4
+ //
5
+ // Storable while the database's partitions cover the anchor: the migration makes them around its
6
+ // APPLY time and only the app's `partitions()` job keeps them ahead; past that, the seed pass
7
+ // refuses naming that job.
8
+
9
+ import type { PartitionDescription } from '@ultimat3/entity';
10
+
11
+ /** One UTC bucket: `[startMs, startMs + spanMs)`. */
12
+ export interface PartitionWindow {
13
+ readonly startMs: number;
14
+ readonly spanMs: number;
15
+ }
16
+
17
+ const DAY = 86_400_000;
18
+
19
+ /** `date_trunc(unit, anchor at time zone 'UTC')` and the bucket's length, as Postgres reads both. */
20
+ export function partitionWindow(
21
+ partition: PartitionDescription | null | undefined,
22
+ anchor: Date,
23
+ ): PartitionWindow | null {
24
+ if (partition === null || partition === undefined) return null;
25
+ const y = anchor.getUTCFullYear();
26
+ const m = anchor.getUTCMonth();
27
+ const today = Date.UTC(y, m, anchor.getUTCDate());
28
+ switch (partition.interval) {
29
+ case 'day':
30
+ return { startMs: today, spanMs: DAY };
31
+ case 'week':
32
+ // ISO: a week starts on a Monday, as `date_trunc('week', …)` does. getUTCDay(): Sunday is 0.
33
+ return { startMs: today - ((anchor.getUTCDay() + 6) % 7) * DAY, spanMs: 7 * DAY };
34
+ case 'month':
35
+ return { startMs: Date.UTC(y, m, 1), spanMs: Date.UTC(y, m + 1, 1) - Date.UTC(y, m, 1) };
36
+ case 'year':
37
+ return { startMs: Date.UTC(y, 0, 1), spanMs: Date.UTC(y + 1, 0, 1) - Date.UTC(y, 0, 1) };
38
+ }
39
+ }
40
+
41
+ /** How many distinct values one row is offered: enough for the row solver to step past a unique. */
42
+ const OFFERED = 8;
43
+
44
+ /**
45
+ * Candidates for one row's partition column, every one inside `window`: instants for a
46
+ * `timestamptz`, `YYYY-MM-DD` for a `date`, rotated by the row's ordinal so rows spread over the
47
+ * bucket. Any other kind is no partition bound this reads — none of its own, the kind's own apply.
48
+ */
49
+ export function valuesInWindow(
50
+ kind: string,
51
+ window: PartitionWindow,
52
+ ordinal: number,
53
+ position: number,
54
+ ): readonly unknown[] {
55
+ if (kind === 'date') {
56
+ const days = Math.max(1, Math.floor(window.spanMs / DAY));
57
+ return Array.from({ length: Math.min(OFFERED, days) }, (_, i) =>
58
+ new Date(window.startMs + ((ordinal + i) % days) * DAY).toISOString().slice(0, 10),
59
+ );
60
+ }
61
+ if (kind === 'timestamptz') {
62
+ const minutes = Math.floor(window.spanMs / 60_000);
63
+ return Array.from(
64
+ { length: OFFERED },
65
+ (_, i) => new Date(window.startMs + ((ordinal * 7 + position + i) % minutes) * 60_000),
66
+ );
67
+ }
68
+ return [];
69
+ }
@@ -31,9 +31,22 @@ const ROW_REFUSALS: ReadonlySet<string> = new Set([
31
31
  'X_DB_STATEMENT_FAILED',
32
32
  ]);
33
33
 
34
+ /** Postgres' 23514 for a row whose partition key no partition covers, in its own words. */
35
+ const NO_PARTITION = 'no partition of relation';
36
+
34
37
  const refused = (write: SeedRow | SeedUpdate, error: unknown): unknown => {
35
38
  if (isUltimateError(error) && !ROW_REFUSALS.has(error.code)) return error;
36
39
  const why = isUltimateError(error) ? `${error.code}: ${error.cause}` : renderThrowable(error);
40
+ if (why.includes(NO_PARTITION)) {
41
+ // No factory repairs this: the database's partitions stop short of the seed's anchor — made
42
+ // around a migrate long past (or a clock other than the seed's) and never kept ahead since.
43
+ return seedGraphUnsatisfied({
44
+ entity: write.entity,
45
+ what: `the database holds no partition for a generated row — ${why}. The seed anchors a partitionBy column on its clock's now; the partitions were made around the migration's apply time and are kept ahead only by the app's partitions() job`,
46
+ columns: [],
47
+ fix: "await maintainPartitions.enqueue({}); // the app's partitions() job: every partition up to now and its ahead — or pass seedGraph(entities, { now }) the database's select now()",
48
+ });
49
+ }
37
50
  return seedGraphUnsatisfied({
38
51
  entity: write.entity,
39
52
  what: `the database refused a generated row — ${why}`,
@@ -29,6 +29,12 @@ export interface SeedGraphOptions {
29
29
  * from a position (`code: \`c${index}\``) never repeats one of its rows on a unique column.
30
30
  */
31
31
  readonly beside?: SeedGraph;
32
+ /**
33
+ * The instant the database's partitions were made around — the migration's apply time. A
34
+ * `partitionBy` column's values land in the bucket holding it, which the migration always makes.
35
+ * Default `systemClock.now()`: in a test under a frozen clock, pass the database's `now()`.
36
+ */
37
+ readonly now?: Date | undefined;
32
38
  }
33
39
 
34
40
  export interface SeedRow {
package/src/seed-graph.ts CHANGED
@@ -2,11 +2,12 @@
2
2
  // key accepts, each child pointing at a parent of its OWN tenant, every value storable and every
3
3
  // declared rule kept. Pure: it returns the plan, `insertSeedGraph` writes it. Same seed, same bytes.
4
4
 
5
- import { finiteCount, finiteOption, fnv1a } from '@ultimat3/core';
5
+ import { finiteCount, finiteOption, fnv1a, systemClock } from '@ultimat3/core';
6
6
  import type { ReferenceDescription } from '@ultimat3/entity';
7
7
  import { DEFAULT_SEED, seededUuid } from './determinism';
8
8
  import { seedGraphUnsatisfied } from './seed-graph-error';
9
9
  import { edgeKey, insertOrder } from './seed-graph-order';
10
+ import { partitionWindow, valuesInWindow } from './seed-graph-partition';
10
11
  import { declaredPatterns } from './seed-graph-patterns';
11
12
  import type {
12
13
  SeedCanary,
@@ -97,6 +98,7 @@ export function seedGraph(
97
98
  const seed = finiteOption('seedGraph', 'seed', options.seed ?? DEFAULT_SEED);
98
99
  const tenantCount = finiteCount('seedGraph', 'tenants', options.tenants ?? 2, 1);
99
100
  const perTable = finiteCount('seedGraph', 'perTable', options.perTable ?? 3, 1);
101
+ const anchor = options.now ?? systemClock.now();
100
102
  // A view entity is a relation Postgres derives: no row is ever written to it, so it is no part of
101
103
  // the graph (`X_ENTITY_VIEW_READ_ONLY` otherwise) — the tables it reads from carry the rows. A
102
104
  // history table is the same from this side: its trigger writes every row, from the parent's.
@@ -197,6 +199,12 @@ export function seedGraph(
197
199
  const rootProperty = roots.get(name);
198
200
  // Read once per table: each `matches(/…/)` an invariant holds a column to, sampled from.
199
201
  const patterns = declaredPatterns(entity);
202
+ // A `partitionBy` column takes values from the bucket the migration made first (`anchor`'s).
203
+ const description = entity.$describe();
204
+ const window = partitionWindow(description.partition, anchor);
205
+ const partitioned = description.columns.find(
206
+ (column) => column.column === description.partition?.column,
207
+ );
200
208
  const buckets: readonly (string | null)[] = scoped(name) ? tenants : [null];
201
209
  // Positions continue past the graph written before this one: a reset factory rebuilt that
202
210
  // graph's first values, and a unique column refused the second copy.
@@ -231,13 +239,18 @@ export function seedGraph(
231
239
  : parentValues(reference, tenant, index)
232
240
  : Object.hasOwn(built, property)
233
241
  ? storable(column, [built[property]])
234
- : candidatesFor(property, column, {
235
- ordinal,
236
- canary,
237
- position,
238
- patterns: patterns.get(property),
239
- uuid: stream,
240
- });
242
+ : window !== null && property === partitioned?.property
243
+ ? storable(
244
+ column,
245
+ valuesInWindow(partitioned.kind, window, ordinal, position),
246
+ )
247
+ : candidatesFor(property, column, {
248
+ ordinal,
249
+ canary,
250
+ position,
251
+ patterns: patterns.get(property),
252
+ uuid: stream,
253
+ });
241
254
  return [
242
255
  property,
243
256
  candidates.length === 0 ? refuseEmpty(shape, property, tenant) : candidates,
@@ -23,14 +23,29 @@ type SeedRepo = Repo<Record<string, unknown>>;
23
23
  */
24
24
  export const digestRow = (row: unknown): string => fingerprint(row);
25
25
 
26
- /** The physical columns of an entity's primary key, in key order. */
27
- const keyColumns = (entity: EntityCore): readonly string[] => {
26
+ /** The physical columns of an entity's primary key, in key order, with each one's kind. */
27
+ const keyColumns = (entity: EntityCore): readonly { name: string; kind: string }[] => {
28
28
  const columns = entity.$describe().columns;
29
- return entity.$primaryKey.map(
30
- (property) => columns.find((column) => column.property === property)?.column ?? property,
31
- );
29
+ return entity.$primaryKey.map((property) => {
30
+ const found = columns.find((column) => column.property === property);
31
+ return { name: found?.column ?? property, kind: found?.kind ?? 'text' };
32
+ });
32
33
  };
33
34
 
35
+ /**
36
+ * One key part as text, the same on both sides of the match: a `Date` as its ISO instant — never
37
+ * `String(date)`, the process zone's `… GMT-0500 (…)` that no server parses — which is also what
38
+ * `instantText` below spells a stored `timestamptz` as, whatever the session's zone.
39
+ */
40
+ const keyText = (value: unknown): string =>
41
+ value instanceof Date ? value.toISOString() : String(value);
42
+
43
+ /** A key column as text: a `timestamptz` in UTC ISO to the millisecond, as `toISOString` is. */
44
+ const columnText = (column: { name: string; kind: string }): SqlFragment =>
45
+ column.kind === 'timestamptz'
46
+ ? sql`to_char(${identifier(column.name)} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`
47
+ : sql`${identifier(column.name)}::text`;
48
+
34
49
  /** Joins a composite key's parts, in Postgres and here alike: no seeded key holds a unit separator. */
35
50
  const KEY_SEPARATOR = '\u001f';
36
51
 
@@ -53,17 +68,18 @@ async function snapshotOnClient(
53
68
  else indexes.push(i);
54
69
  });
55
70
  const keyOf = (entity: EntityCore, i: number): string =>
56
- entity.$primaryKey.map((property) => String(rows[i]?.row[property])).join(KEY_SEPARATOR);
71
+ entity.$primaryKey.map((property) => keyText(rows[i]?.row[property])).join(KEY_SEPARATOR);
57
72
  const branches = [...byEntity].map(([entity, indexes], at): SqlFragment => {
58
- const columns = keyColumns(entity).map((column) => identifier(column));
73
+ const keys = keyColumns(entity);
74
+ const columns = keys.map((column) => identifier(column.name));
59
75
  // Each key column against its values, the parameter UNTYPED so Postgres types it as the
60
76
  // column: `id::text = any(…)` read every row of a table that grows with the primitives. A
61
77
  // composite key matches a superset here; the full key is matched below.
62
78
  const matched = entity.$primaryKey.map(
63
79
  (property, part) =>
64
- sql`${columns[part] as SqlFragment} = any(${[...new Set(indexes.map((i) => String(rows[i]?.row[property])))]})`,
80
+ sql`${columns[part] as SqlFragment} = any(${[...new Set(indexes.map((i) => keyText(rows[i]?.row[property])))]})`,
65
81
  );
66
- const texts = columns.map((column) => sql`${column}::text`);
82
+ const texts = keys.map(columnText);
67
83
  return sql`select ${at}::int as e, concat_ws(${KEY_SEPARATOR}, ${join(texts)}) as k, md5(t::text) as h from ${identifier(entity.$table)} t where ${join(matched, ' and ')}`;
68
84
  });
69
85
  if (branches.length === 0) return [];
@@ -19,6 +19,8 @@ export interface UploadScannerLike {
19
19
  scan(input: {
20
20
  readonly key: string;
21
21
  readonly pendingKey: string;
22
+ /** Which bytes under `pendingKey`: a held decision is keyed by `(pendingKey, revision)`. */
23
+ readonly revision?: string | undefined;
22
24
  readonly size: number;
23
25
  readonly contentType: string;
24
26
  readonly body: ReadableStream<Uint8Array>;
@@ -47,14 +49,25 @@ function streamOf(bytes: Uint8Array, size: number): ReadableStream<Uint8Array> {
47
49
  });
48
50
  }
49
51
 
50
- const scan = (scanner: UploadScannerLike, bytes: Uint8Array, chunk = 64 * 1024) =>
51
- scanner.scan({
52
- key: 'org/conformance/pending/scan/a1-u-1.txt',
52
+ /**
53
+ * The revision `promoteAttachment` would hand over for these bytes: one identity per content. A true
54
+ * retry of the same bytes keeps it; different bytes never share it — so a scanner caching by
55
+ * `(pendingKey, revision)`, as a held decision must, is judged on what it was actually sent.
56
+ */
57
+ const revisionOf = (bytes: Uint8Array): string =>
58
+ `sha256:${new Bun.CryptoHasher('sha256').update(bytes).digest('hex')}`;
59
+
60
+ const scan = (scanner: UploadScannerLike, bytes: Uint8Array, chunk = 64 * 1024) => {
61
+ const revision = revisionOf(bytes);
62
+ return scanner.scan({
63
+ key: `org/conformance/pending/scan/${revision.slice(7, 19)}-u-1.txt`,
53
64
  pendingKey: 'org/conformance/pending/u-1.txt',
65
+ revision,
54
66
  size: bytes.byteLength,
55
67
  contentType: 'text/plain',
56
68
  body: streamOf(bytes, chunk),
57
69
  });
70
+ };
58
71
 
59
72
  const PLAIN = encode('A plain note: nothing in here is a virus.\n');
60
73
 
@@ -98,6 +111,18 @@ export const UPLOAD_SCANNER_CHECKS: readonly UploadScannerCheck[] = [
98
111
  expect(await scan(scanner, PLAIN)).toEqual({ verdict: 'clean' });
99
112
  },
100
113
  },
114
+ {
115
+ // The upload URL stays valid after the sniff: the bytes under one pending key can be rewritten
116
+ // between two confirms. A scanner (or the review behind it) keyed by `pendingKey` alone clears
117
+ // the rewrite with the original's verdict — EICAR attached unscanned.
118
+ name: 'a new revision of one upload is judged on its own bytes: clean, then EICAR is never clean',
119
+ async run(scanner) {
120
+ const first = await scan(scanner, PLAIN);
121
+ expect(first.verdict === 'infected').toBe(false);
122
+ const second = await scan(scanner, encode(UPLOAD_SCANNER_EICAR));
123
+ expect(second.verdict).not.toBe('clean');
124
+ },
125
+ },
101
126
  ];
102
127
 
103
128
  export const uploadScannerConformance: SharedExamples<UploadScannerLike> = sharedExamples(