@ultimat3/testing 31.9.0 → 31.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +22 -22
- package/src/audit-sink-conformance.ts +14 -0
- package/src/auth-adapter-conformance-sessions.ts +19 -0
- package/src/entity-conformance-checks.ts +12 -0
- package/src/entity-conformance-contains.ts +145 -0
- package/src/entity-conformance-counted-in.ts +229 -0
- package/src/entity-conformance-latest-by.ts +242 -0
- package/src/entity-conformance-lock-keys.ts +206 -0
- package/src/entity-conformance-measures.ts +166 -0
- package/src/entity-conformance-version-lock.ts +204 -0
- package/src/entity-driver-conformance.ts +10 -0
- package/src/plan-sweep-fix.ts +18 -0
- package/src/plan-sweep-report.ts +5 -2
- package/src/plan-trigram.ts +21 -0
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// Entity conformance · the declared optimistic lock, `entity({ version: 'lockVersion' })`: an
|
|
2
|
+
// `update` naming the version it read writes only over that version and moves it, a stale one is
|
|
3
|
+
// `X_ENTITY_STALE` and writes nothing; a write that cannot condition on it is refused or moves it
|
|
4
|
+
// unconditioned, per the rule table — so no write path leaves a stale reader believing it is current.
|
|
5
|
+
|
|
6
|
+
import { expect } from 'bun:test';
|
|
7
|
+
import type { Database, Driver } from '@ultimat3/entity';
|
|
8
|
+
import { entity, integer, text, timestamp, uuid } from '@ultimat3/entity';
|
|
9
|
+
import { remember } from './entity-conformance-entities';
|
|
10
|
+
import { checkOver, codeOf, idAt, inOrg } from './entity-conformance-support';
|
|
11
|
+
import type { EntityDriverCheck } from './entity-driver-conformance';
|
|
12
|
+
|
|
13
|
+
const docs = remember(
|
|
14
|
+
entity('ec_vl_docs', {
|
|
15
|
+
columns: {
|
|
16
|
+
id: uuid().primaryKey(),
|
|
17
|
+
orgId: uuid().tenant(),
|
|
18
|
+
title: text({ max: 20 }),
|
|
19
|
+
lockVersion: integer().default(0),
|
|
20
|
+
deletedAt: timestamp().nullable(),
|
|
21
|
+
},
|
|
22
|
+
version: 'lockVersion',
|
|
23
|
+
}),
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
const SET = { docs };
|
|
27
|
+
type Db = Database<typeof SET>;
|
|
28
|
+
const [ORG, OTHER_ORG] = [idAt('7a'), idAt('7b')];
|
|
29
|
+
const [D1, D2, D3] = [idAt('71'), idAt('72'), idAt('73')];
|
|
30
|
+
const STALE = 'X_ENTITY_STALE';
|
|
31
|
+
const INVALID = 'X_ENTITY_VERSION_INVALID';
|
|
32
|
+
const RACERS = 8;
|
|
33
|
+
|
|
34
|
+
const seed = (db: Db) =>
|
|
35
|
+
db.docs.insertAll([
|
|
36
|
+
{ id: D1, orgId: ORG, title: 'one' },
|
|
37
|
+
{ id: D2, orgId: ORG, title: 'two' },
|
|
38
|
+
{ id: D3, orgId: OTHER_ORG, title: 'theirs' },
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
/** Every row's `[title, version]` in id order, deleted rows included: each org read by the bare repo. */
|
|
42
|
+
const state = async (raw: { readonly driver: Driver }) => {
|
|
43
|
+
const read = (orgId: string) =>
|
|
44
|
+
raw.driver.repo(docs).findMany({
|
|
45
|
+
orgId,
|
|
46
|
+
includeDeleted: true,
|
|
47
|
+
orderBy: [{ column: 'id', direction: 'asc' }],
|
|
48
|
+
});
|
|
49
|
+
const rows = [...(await read(ORG)).rows, ...(await read(OTHER_ORG)).rows];
|
|
50
|
+
return rows.sort((a, b) => a.id.localeCompare(b.id)).map((row) => [row.title, row.lockVersion]);
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const byId: readonly EntityDriverCheck[] = [
|
|
54
|
+
checkOver(
|
|
55
|
+
SET,
|
|
56
|
+
'insert takes the declared default; update naming the version read moves it by one',
|
|
57
|
+
async (db, raw) => {
|
|
58
|
+
await seed(db);
|
|
59
|
+
await inOrg(ORG, () => db.docs.update(D1, { title: 'first', lockVersion: 0 }));
|
|
60
|
+
await inOrg(ORG, () => db.docs.update(D1, { title: 'second', lockVersion: 1 }));
|
|
61
|
+
expect(await state(raw)).toEqual([
|
|
62
|
+
['second', 2],
|
|
63
|
+
['two', 0],
|
|
64
|
+
['theirs', 0],
|
|
65
|
+
]);
|
|
66
|
+
},
|
|
67
|
+
),
|
|
68
|
+
checkOver(
|
|
69
|
+
SET,
|
|
70
|
+
'a stale version is X_ENTITY_STALE and writes nothing; an absent or foreign id is X_NOT_FOUND',
|
|
71
|
+
async (db, raw) => {
|
|
72
|
+
await seed(db);
|
|
73
|
+
await inOrg(ORG, () => db.docs.update(D1, { title: 'won', lockVersion: 0 }));
|
|
74
|
+
const answers = await inOrg(ORG, async () => [
|
|
75
|
+
await codeOf(() => db.docs.update(D1, { title: 'lost', lockVersion: 0 })),
|
|
76
|
+
await codeOf(() => db.docs.update(D1, { title: 'ahead', lockVersion: 5 })),
|
|
77
|
+
await codeOf(() => db.docs.update(idAt('7ff'), { title: 'ghost', lockVersion: 0 })),
|
|
78
|
+
await codeOf(() => db.docs.update(D3, { title: 'foreign', lockVersion: 0 })),
|
|
79
|
+
]);
|
|
80
|
+
expect(answers).toEqual([STALE, STALE, 'X_NOT_FOUND', 'X_NOT_FOUND']);
|
|
81
|
+
expect(await state(raw)).toEqual([
|
|
82
|
+
['won', 1],
|
|
83
|
+
['two', 0],
|
|
84
|
+
['theirs', 0],
|
|
85
|
+
]);
|
|
86
|
+
},
|
|
87
|
+
),
|
|
88
|
+
checkOver(
|
|
89
|
+
SET,
|
|
90
|
+
'an update by id that omits the version is refused: the lock is the point',
|
|
91
|
+
async (db, raw) => {
|
|
92
|
+
await seed(db);
|
|
93
|
+
expect(await inOrg(ORG, () => codeOf(() => db.docs.update(D1, { title: 'blind' })))).toBe(
|
|
94
|
+
INVALID,
|
|
95
|
+
);
|
|
96
|
+
expect((await state(raw))[0]).toEqual(['one', 0]);
|
|
97
|
+
},
|
|
98
|
+
),
|
|
99
|
+
checkOver(
|
|
100
|
+
SET,
|
|
101
|
+
`${RACERS} writers holding one version: exactly one wins, the rest are stale`,
|
|
102
|
+
async (db, raw) => {
|
|
103
|
+
await seed(db);
|
|
104
|
+
const answers = await inOrg(ORG, () =>
|
|
105
|
+
Promise.all(
|
|
106
|
+
Array.from({ length: RACERS }, (_, index) =>
|
|
107
|
+
codeOf(() => db.docs.update(D1, { title: `w${index}`, lockVersion: 0 })),
|
|
108
|
+
),
|
|
109
|
+
),
|
|
110
|
+
);
|
|
111
|
+
expect([...answers].sort()).toEqual([
|
|
112
|
+
...Array.from({ length: RACERS - 1 }, () => STALE),
|
|
113
|
+
'resolved',
|
|
114
|
+
]);
|
|
115
|
+
const [title, version] = (await state(raw))[0] ?? [];
|
|
116
|
+
expect([answers[Number(String(title).slice(1))], version]).toEqual(['resolved', 1]);
|
|
117
|
+
},
|
|
118
|
+
),
|
|
119
|
+
];
|
|
120
|
+
|
|
121
|
+
const filtered: readonly EntityDriverCheck[] = [
|
|
122
|
+
checkOver(
|
|
123
|
+
SET,
|
|
124
|
+
'updateWhere and chain updateAll move the version unconditioned; naming it is refused',
|
|
125
|
+
async (db, raw) => {
|
|
126
|
+
await seed(db);
|
|
127
|
+
await inOrg(ORG, async () => {
|
|
128
|
+
await db.docs.updateWhere({ id: D1 }, { title: 'a' });
|
|
129
|
+
await db.docs.where({ title: 'a' }).updateAll({ title: 'b' });
|
|
130
|
+
});
|
|
131
|
+
const named = await inOrg(ORG, async () => [
|
|
132
|
+
await codeOf(() => db.docs.updateWhere({ id: D1 }, { title: 'x', lockVersion: 9 })),
|
|
133
|
+
await codeOf(() => db.docs.where({ id: D1 }).updateAll({ title: 'x', lockVersion: 9 })),
|
|
134
|
+
]);
|
|
135
|
+
expect(named).toEqual([INVALID, INVALID]);
|
|
136
|
+
expect(await state(raw)).toEqual([
|
|
137
|
+
['b', 2],
|
|
138
|
+
['two', 0],
|
|
139
|
+
['theirs', 0],
|
|
140
|
+
]);
|
|
141
|
+
},
|
|
142
|
+
),
|
|
143
|
+
checkOver(
|
|
144
|
+
SET,
|
|
145
|
+
'compare-and-set through the filter: a chain naming the version read writes once',
|
|
146
|
+
async (db, raw) => {
|
|
147
|
+
await seed(db);
|
|
148
|
+
const cas = () =>
|
|
149
|
+
inOrg(ORG, () => db.docs.where({ id: D1, lockVersion: 0 }).updateAll({ title: 'cas' }));
|
|
150
|
+
expect([await cas(), await cas()]).toEqual([1, 0]);
|
|
151
|
+
expect((await state(raw))[0]).toEqual(['cas', 1]);
|
|
152
|
+
},
|
|
153
|
+
),
|
|
154
|
+
checkOver(SET, 'a soft delete moves the version too', async (db, raw) => {
|
|
155
|
+
await seed(db);
|
|
156
|
+
await inOrg(ORG, () => db.docs.delete(D2));
|
|
157
|
+
expect((await state(raw))[1]).toEqual(['two', 1]);
|
|
158
|
+
}),
|
|
159
|
+
checkOver(
|
|
160
|
+
SET,
|
|
161
|
+
'updateMany conditions every row on its version: one stale row refuses the batch whole',
|
|
162
|
+
async (db, raw) => {
|
|
163
|
+
await seed(db);
|
|
164
|
+
await inOrg(ORG, () => db.docs.update(D2, { title: 'moved', lockVersion: 0 }));
|
|
165
|
+
const batch = (v2: number) => [
|
|
166
|
+
{ id: D1, patch: { title: 'b1', lockVersion: 0 } },
|
|
167
|
+
{ id: D2, patch: { title: 'b2', lockVersion: v2 } },
|
|
168
|
+
];
|
|
169
|
+
const refusals = await inOrg(ORG, async () => [
|
|
170
|
+
await codeOf(() => db.docs.updateMany(batch(0))),
|
|
171
|
+
await codeOf(() => db.docs.updateMany([{ id: D1, patch: { title: 'blind' } }])),
|
|
172
|
+
]);
|
|
173
|
+
expect(refusals).toEqual([STALE, INVALID]);
|
|
174
|
+
expect(await state(raw)).toEqual([
|
|
175
|
+
['one', 0],
|
|
176
|
+
['moved', 1],
|
|
177
|
+
['theirs', 0],
|
|
178
|
+
]);
|
|
179
|
+
expect(await inOrg(ORG, () => db.docs.updateMany(batch(1)))).toBe(2);
|
|
180
|
+
expect(await state(raw)).toEqual([
|
|
181
|
+
['b1', 1],
|
|
182
|
+
['b2', 2],
|
|
183
|
+
['theirs', 0],
|
|
184
|
+
]);
|
|
185
|
+
},
|
|
186
|
+
),
|
|
187
|
+
checkOver(
|
|
188
|
+
SET,
|
|
189
|
+
'upsertAll that would overwrite a match is refused; one that keeps it is not',
|
|
190
|
+
async (db, raw) => {
|
|
191
|
+
await seed(db);
|
|
192
|
+
const row = { id: D1, orgId: ORG, title: 'over', lockVersion: 0 };
|
|
193
|
+
const answers = await inOrg(ORG, async () => [
|
|
194
|
+
await codeOf(() => db.docs.upsertAll([row], { onConflict: ['id'] })),
|
|
195
|
+
await codeOf(() => db.docs.upsertAll([row], { onConflict: ['id'], onMatch: 'nothing' })),
|
|
196
|
+
]);
|
|
197
|
+
expect(answers).toEqual([INVALID, 'resolved']);
|
|
198
|
+
expect((await state(raw))[0]).toEqual(['one', 0]);
|
|
199
|
+
},
|
|
200
|
+
['upsert'],
|
|
201
|
+
),
|
|
202
|
+
];
|
|
203
|
+
|
|
204
|
+
export const VERSION_LOCK_CHECKS: readonly EntityDriverCheck[] = [...byId, ...filtered];
|
|
@@ -30,6 +30,13 @@ export interface EntityDriverSubject {
|
|
|
30
30
|
* nothing: absent here, the history check is not run against it (there is no refusal to assert).
|
|
31
31
|
*/
|
|
32
32
|
readonly history?: boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Whether the store keeps a `references(…, { countedIn })` counter — Postgres by trigger, memory
|
|
35
|
+
* in its repository. A `defineDriver` store has no lifecycle hook, so it refuses a counted child's
|
|
36
|
+
* repository (`X_DRIVER_UNSUPPORTED`, capability `countedIn`): absent here, that refusal is
|
|
37
|
+
* asserted and the counter checks themselves are not run (there is no handle to run them on).
|
|
38
|
+
*/
|
|
39
|
+
readonly counters?: boolean;
|
|
33
40
|
/**
|
|
34
41
|
* How many lock requests are blocked behind a holder right now — `memoryLockWaiters` from
|
|
35
42
|
* `@ultimat3/entity/adapter`, or `pg_stat_activity`'s `wait_event_type = 'Lock'` on a pool. What
|
|
@@ -45,6 +52,8 @@ export interface EntityDriverRun {
|
|
|
45
52
|
readonly foreignKeys: boolean;
|
|
46
53
|
/** The subject's `history`, `false` when it declared none. */
|
|
47
54
|
readonly history: boolean;
|
|
55
|
+
/** The subject's `counters`, `false` when it declared none. */
|
|
56
|
+
readonly counters: boolean;
|
|
48
57
|
/** The subject's `lockWaiters`, when it can see one. */
|
|
49
58
|
readonly lockWaiters: (() => number | Promise<number>) | undefined;
|
|
50
59
|
}
|
|
@@ -103,6 +112,7 @@ export const runEntityDriverCheck = async (
|
|
|
103
112
|
driver,
|
|
104
113
|
foreignKeys: subject.foreignKeys,
|
|
105
114
|
history: subject.history === true,
|
|
115
|
+
counters: subject.counters === true,
|
|
106
116
|
lockWaiters: subject.lockWaiters,
|
|
107
117
|
});
|
|
108
118
|
};
|
package/src/plan-sweep-fix.ts
CHANGED
|
@@ -3,9 +3,11 @@
|
|
|
3
3
|
// lookup that pins a unique key reads one row whatever the planner walked to find it, and a whole
|
|
4
4
|
// read a keyed join side could probe by a declared index is one the planner declined on cost.
|
|
5
5
|
|
|
6
|
+
import { trigramDeclaration } from '@ultimat3/entity';
|
|
6
7
|
import type { PlanVerdict, PlanVerdictCode } from './plan-oracle';
|
|
7
8
|
import type { PlanUnservable } from './plan-sort-key';
|
|
8
9
|
import { sortKeyPart } from './plan-sort-key';
|
|
10
|
+
import { trigramColumns, trigramServed } from './plan-trigram';
|
|
9
11
|
import type { SeedEntity } from './seed-graph-shape';
|
|
10
12
|
|
|
11
13
|
export interface PlanFinding {
|
|
@@ -24,6 +26,11 @@ export interface PlanFinding {
|
|
|
24
26
|
* empty with it.
|
|
25
27
|
*/
|
|
26
28
|
readonly unserved?: PlanUnservable | 'declared';
|
|
29
|
+
/**
|
|
30
|
+
* The whole `indexes:` entry when a bare `on:` would not serve the statement: an `ilike` (a text
|
|
31
|
+
* `contains`) is served by a `gin_trgm_ops` index only (`plan-trigram.ts`).
|
|
32
|
+
*/
|
|
33
|
+
readonly declaration?: string;
|
|
27
34
|
}
|
|
28
35
|
|
|
29
36
|
/** Every column set the table holds unique: the primary key, unique columns, total unique rules. */
|
|
@@ -225,6 +232,17 @@ export function planFindings(
|
|
|
225
232
|
}
|
|
226
233
|
const description = entity.$describe();
|
|
227
234
|
const byColumn = new Map(description.columns.map((c) => [c.column, c.property]));
|
|
235
|
+
// BEFORE the btree rules: no btree serves an `ilike`, so a declared one argues nothing away.
|
|
236
|
+
const searched =
|
|
237
|
+
verdict.code === 'X_QUERY_UNINDEXED' ? trigramColumns(statement, verdict.range) : [];
|
|
238
|
+
if (searched.length > 0) {
|
|
239
|
+
return searched
|
|
240
|
+
.filter((column) => !trigramServed(entity, column))
|
|
241
|
+
.map((column) => {
|
|
242
|
+
const property = byColumn.get(column) ?? column;
|
|
243
|
+
return { ...finding, index: [property], declaration: trigramDeclaration(property) };
|
|
244
|
+
});
|
|
245
|
+
}
|
|
228
246
|
const walked = verdict.code === 'X_QUERY_UNINDEXED' && verdict.node !== 'Seq Scan';
|
|
229
247
|
// A walk filtered by a range already has its order: what it lacks is the bound. A btree serves
|
|
230
248
|
// no order after a range column, so the index is the equality columns, then the range.
|
package/src/plan-sweep-report.ts
CHANGED
|
@@ -21,9 +21,12 @@ const STATEMENT_CHARS = 160;
|
|
|
21
21
|
const excerpt = (statement: string): string =>
|
|
22
22
|
statement.length <= STATEMENT_CHARS ? statement : `${statement.slice(0, STATEMENT_CHARS)}…`;
|
|
23
23
|
|
|
24
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* `indexes: [{ on: ['orgId', 'authorId'] }]` — the line to paste into the entity; the finding's
|
|
26
|
+
* own `declaration` when a bare `on:` would not serve it (an `ilike` needs `gin_trgm_ops`).
|
|
27
|
+
*/
|
|
25
28
|
const indexLine = (finding: PlanFinding): string =>
|
|
26
|
-
`indexes: [{ on: [${finding.index.map((p) => `'${p}'`).join(', ')}] }]`;
|
|
29
|
+
finding.declaration ?? `indexes: [{ on: [${finding.index.map((p) => `'${p}'`).join(', ')}] }]`;
|
|
27
30
|
|
|
28
31
|
/**
|
|
29
32
|
* A read that compares no column of the table — a whole-table count, an unfiltered export — is
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// A text `contains` in a red statement: `ilike` as sent, `~~*` as a plan prints it. Only a
|
|
2
|
+
// `gin_trgm_ops` index serves it — a btree on the same column does not — so the finding names that
|
|
3
|
+
// declaration (`@ultimat3/entity`'s spelling) and only a declared trigram index argues it away.
|
|
4
|
+
|
|
5
|
+
import type { SeedEntity } from './seed-graph-shape';
|
|
6
|
+
|
|
7
|
+
const escaped = (name: string): string => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
8
|
+
|
|
9
|
+
/** `"title" ilike $1`, `title ~~* $1`, `p.title ILIKE …`: the column, then the operator. */
|
|
10
|
+
const searches = (statement: string, column: string): boolean =>
|
|
11
|
+
new RegExp(`(?:^|[\\s(.,])"?${escaped(column)}"?\\s+(?:ilike|~~\\*)\\s`, 'i').test(statement);
|
|
12
|
+
|
|
13
|
+
/** The physical columns among `range` the statement compares with `ilike`. */
|
|
14
|
+
export const trigramColumns = (statement: string, range: readonly string[]): readonly string[] =>
|
|
15
|
+
range.filter((column) => searches(statement, column));
|
|
16
|
+
|
|
17
|
+
/** A declared `gin_trgm_ops` index leading with this physical column, total or partial. */
|
|
18
|
+
export const trigramServed = (entity: SeedEntity, column: string): boolean =>
|
|
19
|
+
entity
|
|
20
|
+
.$describe()
|
|
21
|
+
.indexes.some((index) => index.operatorClass === 'gin_trgm_ops' && index.columns[0] === column);
|