@ultimat3/entity 31.50.0 → 31.52.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/CLAUDE.md CHANGED
@@ -142,7 +142,7 @@ A rule marked `†` has its full text in [`docs/history/entity-rules.md`](../../
142
142
  - **`crossTenant(reason, fn)` is the ONE way to read across tenants** — an `asyncContext` scope from
143
143
  core (`scripts/async-context-guard.ts`), `CROSS_TENANT_SCOPE` (`tenancy:cross`) proven at the call
144
144
  and at every plan (`X_TENANCY_CROSS_DENIED`), refused outside a request, blank reason `X_INVARIANT`.
145
- - **`deleteWhere` / `updateWhere` are the only filtered writes** — a chain's `updateAll`/`deleteAll` (`query-write.ts`) IS one, its predicates in `FilteredWriteOptions.where`, one plan (`write-where.ts`). `updateMany`/`insertAllCount`/`upsertAllCount`/`copyAll` are `Repo`-optional with typed-handle fallbacks; every wrapper (sealed, append-only, view, mirror, observer, memory-observed) handles each (`query-write-wrappers.test.ts`). Empty filter `X_WRITE_UNFILTERED`,
145
+ - **`deleteWhere` / `updateWhere` (and `updateWhereReturning`, the same write answering its rows: `pg-driver.ts`'s `filteredPatch` is the shared half, a bounded Postgres transaction handles a drifting pre-write count; count-only stores and a `Repo` without the method refuse before mutation, `returningUnsupported`) are the only filtered writes** — a chain's `updateAll`/`deleteAll` (`query-write.ts`) IS one, its predicates in `FilteredWriteOptions.where`, one plan (`write-where.ts`). `updateMany`/`insertAllCount`/`upsertAllCount`/`copyAll` are `Repo`-optional with typed-handle fallbacks; every wrapper (sealed, append-only, view, mirror, observer, memory-observed) handles each (`query-write-wrappers.test.ts`). Empty filter `X_WRITE_UNFILTERED`,
146
146
  empty patch `X_PATCH_EMPTY` (undefined values dropped first); soft delete respected; both return a
147
147
  count; a JS-only invariant is judged
148
148
  in the statement's transaction (`judged-write.ts`), refused past `MAX_ASSERTED_ROWS`. Full rule: `docs/history/entity.md`.
@@ -163,6 +163,11 @@ A rule marked `†` has its full text in [`docs/history/entity-rules.md`](../../
163
163
  - **Custom stores: `defineDriver` from `@ultimat3/entity/adapter` only** — scoped plan in, rows
164
164
  re-checked, `X_DRIVER_UNSUPPORTED` per capability; the store owns its schema, `x db`/drift are
165
165
  Postgres-only. README "Custom drivers". **One row identity: `rowKey`** (`row-key.ts`).
166
+ **A judged unversioned update writes through the store's OPTIONAL `updateChecked`** (CAS on the
167
+ rows judged; lost → re-judge, bounded, then `X_DB_SERIALIZATION_FAILURE`); `updateMany`'s
168
+ rollback restores only a row still as written, else refuses torn; `updateWhereReturning` exists
169
+ only with it. Absent → unconditional `update`, warned once per driver. Never required (#1379).
170
+ Files: `driver-kit-*.ts`.
166
171
  - **`shared: '<why>'` is the one way an untenanted child of a tenant-owned table says so**
167
172
  (`assertShared`, `describe.ts`); the reach check is the CLI's `exercise-static.ts`
168
173
  (`X_ENTITY_TENANT_UNDECLARED`), over `EntityDescription.shared`.
package/README.md CHANGED
@@ -1001,6 +1001,8 @@ db.posts.update(id, { title }); // ditto; named colu
1001
1001
  db.likes.deleteWhere({ postId, userId }); // -> 1 · the only way to unlike
1002
1002
  db.likes.deleteWhere({ postId }); // -> n · every like on that post
1003
1003
  db.participants.updateWhere({ conversationId, userId }, { lastReadAt }); // -> 1 · mark read
1004
+ // The rows it wrote, decided by the one `update … returning *`: no explicit lock
1005
+ const claimed = await db.posts.updateWhereReturning({ id, status: 'open' }, { status: 'claimed' }); // -> Row[]; [] when it was no longer open
1004
1006
 
1005
1007
  db.likes.deleteWhere({}); // X_WRITE_UNFILTERED, never every row
1006
1008
  db.participants.updateWhere({ conversationId }, {}); // X_PATCH_EMPTY, never a silent no-op
@@ -1021,6 +1023,21 @@ it), the search mirror and the `entity.bulk` report cannot differ. No predicate
1021
1023
  `X_WRITE_UNFILTERED`; `limit()`, `after()` and `search()` are refused. `updateMany` is `Repo`-optional:
1022
1024
  a hand-written repository without it gets one `updateWhere` per row from the typed handle.
1023
1025
 
1026
+ `updateWhereReturning(filter, patch, options?)` is `updateWhere` answering `readonly Row[]`, the rows as
1027
+ stored. On Postgres one `update … where … returning *` is the decision: "update if it is still open" and
1028
+ "which rows did this call move" need no explicit lock. A filter that matches nothing (already moved,
1029
+ soft-deleted, another tenant's) answers `[]`, never `X_NOT_FOUND`. It takes the equality filter, not a
1030
+ chain, and shares `updateWhere`'s plan and judging: `X_WRITE_UNFILTERED`, `X_PATCH_EMPTY`, tenancy, soft
1031
+ delete, invariants, the `onUpdateNow()` stamp, the version column, sealing, append-only and view refusals,
1032
+ the search mirror and the `entity.bulk` report are the same.
1033
+
1034
+ | `updateWhereReturning` | |
1035
+ |---|---|
1036
+ | Bound | a pre-write count past `MAX_ASSERTED_ROWS` is `X_INVARIANT_VIOLATED`. Postgres also bounds returned rows inside a transaction, rolling back if the count drifts. Sweep with `.where(filter).inBatches(1000)`, or use `updateWhere`, which answers a count |
1037
+ | Statements on Postgres | one when the filter names the whole primary key and no rule only the app can judge is declared. Otherwise a `count(*)` goes first, without an explicit lock |
1038
+ | `defineDriver` store | with `updateChecked` on an unversioned entity: the won compare-and-set names exactly the rows written, read back by key (a raced row is re-judged, one that left the filter is not answered). Otherwise refuses before writing: the store reports only a count, not the rows it wrote — use `updateWhere`, or implement `updateChecked` ("Custom drivers") |
1039
+ | `Repo` without it | optional on the contract: the call is `X_INVARIANT_VIOLATED` with nothing written |
1040
+
1024
1041
  | Bulk insert | Resolves | Statement |
1025
1042
  |---|---|---|
1026
1043
  | `insertAll(rows)` · `upsertAll(rows, args)` | the rows as stored | `insert … returning *` |
@@ -1468,6 +1485,14 @@ export const kvDriver = defineDriver({
1468
1485
  for (const row of hit) rows.set(key(row), { ...row, ...patch });
1469
1486
  return hit.length;
1470
1487
  },
1488
+ // Optional, and what keeps a judged update honest under a concurrent writer: no await
1489
+ // between the comparison and the set, so nothing lands between them.
1490
+ updateChecked: async (filter, expected, patch) => {
1491
+ const hit = matched(filter);
1492
+ if (!Bun.deepEquals(hit, expected)) return false;
1493
+ for (const row of hit) rows.set(key(row), { ...row, ...patch });
1494
+ return true;
1495
+ },
1471
1496
  delete: async (filter) => {
1472
1497
  const hit = matched(filter);
1473
1498
  for (const row of hit) rows.delete(key(row));
@@ -1491,6 +1516,25 @@ Capabilities (`DRIVER_CAPABILITIES`): `transactions`, `lock`, `series`, `upsert`
1491
1516
  `aggregate:approximateCount`. A duplicate key is `entityUniqueViolation(entity, constraint)` —
1492
1517
  `X_DB_UNIQUE_VIOLATION`, the code Postgres' `23505` becomes, with no faked SQLSTATE.
1493
1518
 
1519
+ **A judged update is a compare-and-set only when the store implements `updateChecked`.** An
1520
+ update of an entity with an invariant or a same-tenant reference (and no `version`) reads the
1521
+ matching rows, judges every merged row, then writes. `updateChecked(filter, expected, patch,
1522
+ advance?)` is optional and detected by presence (no capability to declare): atomically, when the
1523
+ rows `filter` matches are exactly `expected` — the rows `select` answered, every value equal — it
1524
+ sets `patch` on each and answers `true`; otherwise it writes nothing and answers `false`. The kit
1525
+ then re-reads, re-judges (a row that left the filter is skipped, one the newer value breaks is
1526
+ `X_INVARIANT_VIOLATED`) and retries, `MAX_CHECKED_RETRIES` (16) times, then refuses
1527
+ `X_DB_SERIALIZATION_FAILURE` — retryable, the code Postgres' `40001` becomes. **Without it the
1528
+ write is today's unconditional `update`**: a writer landing between the judge and the write can
1529
+ leave a row the invariant refuses (#1379). The first judged table a driver opens without it logs
1530
+ `entity.driver.update_unchecked` once (`code: 'X_DRIVER_UNSUPPORTED'`, `capability:
1531
+ 'updateChecked'`). A versioned entity needs neither: its writes compare-and-set on the version.
1532
+ `updateMany`'s rollback (one store write per row, so a refusal part way writes the moved rows
1533
+ back) goes through it too: a row is restored only while it still holds what the batch wrote. A row
1534
+ another writer changed first is kept as that writer left it, and the call refuses
1535
+ `X_DB_SERIALIZATION_FAILURE` naming it, rather than the original error; a plain store restores
1536
+ unconditionally.
1537
+
1494
1538
  **A custom store owns its own schema, uniqueness and foreign keys.** Migrations, drift and every
1495
1539
  `x db` command describe Postgres only; `x verify`'s drift step skips (and says why) when no SQL
1496
1540
  store was constructed (`driverStores()`). The meanings a custom store borrows — `matchesPredicate`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/entity",
3
- "version": "31.50.0",
3
+ "version": "31.52.0",
4
4
  "description": "A table + its domain type + invariants the database also enforces",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -45,9 +45,9 @@
45
45
  "test": "bun test"
46
46
  },
47
47
  "dependencies": {
48
- "@ultimat3/core": "31.50.0",
49
- "@ultimat3/db": "31.50.0",
50
- "@ultimat3/schema": "31.50.0",
51
- "@ultimat3/time": "31.50.0"
48
+ "@ultimat3/core": "31.52.0",
49
+ "@ultimat3/db": "31.52.0",
50
+ "@ultimat3/schema": "31.52.0",
51
+ "@ultimat3/time": "31.52.0"
52
52
  }
53
53
  }
@@ -11,6 +11,7 @@ export type AppendOnlyRefusedCall =
11
11
  | 'update'
12
12
  | 'delete'
13
13
  | 'updateWhere'
14
+ | 'updateWhereReturning'
14
15
  | 'deleteWhere'
15
16
  | 'updateMany'
16
17
  | 'upsertAll';
@@ -78,7 +78,13 @@ export const appendOnlyRepo = <Row, R extends Repo<Row>>(entity: AppendOnlySourc
78
78
  const name = entity.$name;
79
79
  const refusing: Pick<
80
80
  Repo<Row>,
81
- 'update' | 'delete' | 'updateWhere' | 'deleteWhere' | 'upsertAll' | 'updateMany'
81
+ | 'update'
82
+ | 'delete'
83
+ | 'updateWhere'
84
+ | 'updateWhereReturning'
85
+ | 'deleteWhere'
86
+ | 'upsertAll'
87
+ | 'updateMany'
82
88
  > = {
83
89
  update: async () => {
84
90
  throw appendOnlyRefused(name, 'update');
@@ -89,6 +95,9 @@ export const appendOnlyRepo = <Row, R extends Repo<Row>>(entity: AppendOnlySourc
89
95
  updateWhere: async () => {
90
96
  throw appendOnlyRefused(name, 'updateWhere');
91
97
  },
98
+ updateWhereReturning: async () => {
99
+ throw appendOnlyRefused(name, 'updateWhereReturning');
100
+ },
92
101
  // The one door out of a history table: a subject's erase, inside `purgingHistory` naming it.
93
102
  deleteWhere: async (filter, options) => {
94
103
  const historyOf = entity.$historyOf;
@@ -9,6 +9,7 @@ import type { Driver } from './database';
9
9
  import { refuseCounters } from './driver-counters';
10
10
  import { driverCapabilityMissing, driverUnsupported } from './driver-errors';
11
11
  import type { DriverCapability, DriverDefinition, DriverRepo } from './driver-kit-types';
12
+ import { noteUncheckedUpdates } from './driver-kit-unchecked-warning';
12
13
  import { noteDriverStore } from './driver-registry';
13
14
  import { driverReads } from './driver-repo-reads';
14
15
  import { driverWrites } from './driver-repo-writes';
@@ -78,6 +79,7 @@ const driverRepo = <Row>(
78
79
  const scope = driverScope(definition, entity, rawFor);
79
80
  assertImplemented(definition, scope.raw as DriverRepo<unknown>);
80
81
  const { raw } = scope;
82
+ noteUncheckedUpdates(definition, entity, raw);
81
83
  // Absent unless declared, so the typed handle answers the shipped `X_LOCK_UNSUPPORTED`.
82
84
  const locks = (): Pick<Repo<Row>, 'lock' | 'lockKey' | 'lockKeys'> => {
83
85
  const { lock, lockKey } = raw;
@@ -0,0 +1,81 @@
1
+ // Single responsibility: write `updateMany`'s moved rows BACK after a refusal part way, on a custom
2
+ // store. With `updateChecked` a row is restored only while it still holds what this batch wrote: a
3
+ // newer write is never clobbered, and the batch is refused as torn. Without it, today's
4
+ // unconditional restore (#1379).
5
+
6
+ import { renderThrowable } from '@ultimat3/core';
7
+ import { driverError, SQLSTATE } from '@ultimat3/db';
8
+ import { valueAt } from './cursor';
9
+ import { MAX_CHECKED_RETRIES } from './driver-kit-checked-update';
10
+ import type { DriverScope } from './driver-scope';
11
+ import { idPlan, namedColumns } from './plan';
12
+ import type { RepoOptions, Tx } from './repo';
13
+
14
+ /** One row the batch wrote: as read before, as written, and the patch that moved it. */
15
+ export interface MovedRow<Row> {
16
+ readonly stored: Row;
17
+ readonly result: Row;
18
+ readonly patch: object;
19
+ }
20
+
21
+ export interface Rollback {
22
+ readonly op: string;
23
+ /** The key `updateMany` addresses rows by. */
24
+ readonly key: string;
25
+ /** Every property the batch's patches named: what an unconditional restore writes. */
26
+ readonly properties: readonly string[];
27
+ readonly options: RepoOptions | undefined;
28
+ readonly tx: Tx | undefined;
29
+ }
30
+
31
+ /** A batch whose rollback met a newer write: left as the newer writer made it, and refused. */
32
+ export const tornBatch = (table: string, kept: readonly string[], cause: unknown) =>
33
+ driverError(`update ${table}`, {
34
+ code: SQLSTATE.serializationFailure,
35
+ message: `updateMany refused part way (${renderThrowable(cause)}), and ${String(kept.length)} row(s) it had written were changed by another writer before they could be written back — kept as that writer left them (${kept.join(', ')}); re-read them and re-run the batch`,
36
+ });
37
+
38
+ /**
39
+ * Writes each moved row back, newest first. Answers the keys left as another writer made them —
40
+ * empty when every row was restored. A plain store answers empty: its restore is unconditional.
41
+ */
42
+ export const restoreMoved = async <Row>(
43
+ scope: DriverScope<Row>,
44
+ moved: readonly MovedRow<Row>[],
45
+ rollback: Rollback,
46
+ ): Promise<readonly string[]> => {
47
+ const { entity, raw } = scope;
48
+ const { op, key, options, tx } = rollback;
49
+ const kept: string[] = [];
50
+ for (const { stored, result, patch } of [...moved].reverse()) {
51
+ const id = String(valueAt(result, key));
52
+ const where = scope.storePlan(op, idPlan(entity, id, options, op), true);
53
+ const { updateChecked } = raw;
54
+ if (updateChecked === undefined) {
55
+ const values = Object.fromEntries(
56
+ [...rollback.properties, key].map((property) => [property, valueAt(stored, property)]),
57
+ );
58
+ await raw.update({ plan: where, tx }, values);
59
+ continue;
60
+ }
61
+ // Only what this row's patch named: a property it never touched is another writer's to keep.
62
+ const named = [...namedColumns(patch).map(([property]) => property), key];
63
+ const values = Object.fromEntries(
64
+ named.map((property) => [property, valueAt(stored, property)]),
65
+ );
66
+ let restored = false;
67
+ for (let attempt = 0; attempt <= MAX_CHECKED_RETRIES && !restored; attempt += 1) {
68
+ const read = await raw.select({ plan: where, after: undefined, limit: 1, tx });
69
+ const [now] = scope.checked(op, where, read);
70
+ const ours =
71
+ now !== undefined &&
72
+ named.every((property) =>
73
+ Bun.deepEquals(valueAt(now, property), valueAt(result, property)),
74
+ );
75
+ if (!ours) break;
76
+ restored = await updateChecked.call(raw, { plan: where, tx }, read, values);
77
+ }
78
+ if (!restored) kept.push(id);
79
+ }
80
+ return kept;
81
+ };
@@ -0,0 +1,81 @@
1
+ // Single responsibility: a `defineDriver` JUDGED update of an unversioned entity — read the rows,
2
+ // judge every merged row, then write — with the write conditioned on the rows still being the ones
3
+ // judged when the store offers `updateChecked`. A lost set is another writer's progress: re-read,
4
+ // re-judge, retry, bounded; a store without it keeps the unconditional `update` (#1379).
5
+
6
+ import { driverError, SQLSTATE } from '@ultimat3/db';
7
+ import type { DriverAdvance } from './driver-kit-types';
8
+ import type { DriverScope } from './driver-scope';
9
+ import { assertedRowsTooMany, MAX_ASSERTED_ROWS } from './invariants';
10
+ import { mergedRow } from './memory-update';
11
+ import { namedColumns } from './plan';
12
+ import type { Tx } from './repo';
13
+ import { assertRowTenant, type QueryPlan } from './tenancy';
14
+
15
+ /**
16
+ * How many times a judged update re-reads a set a concurrent writer keeps moving. Each lost set is
17
+ * another writer's progress; the bound only stops a store whose compare never matches.
18
+ */
19
+ export const MAX_CHECKED_RETRIES = 16;
20
+
21
+ export interface CheckedUpdate<Row> {
22
+ readonly op: string;
23
+ readonly plan: QueryPlan;
24
+ readonly patch: object;
25
+ readonly advance: DriverAdvance | undefined;
26
+ readonly narrowed: Readonly<Record<string, unknown>>;
27
+ readonly tx: Tx | undefined;
28
+ /** Same-tenant references of the merged rows, judged as a batch. */
29
+ readonly references: (rows: readonly Row[]) => Promise<void>;
30
+ /** Asked of every read's match count first: `updateWhereReturning`'s `returnedBound`. */
31
+ readonly bound?: (matched: number) => void;
32
+ }
33
+
34
+ /** What the write did: how many rows, and the rows as they were judged (for the search mirror). */
35
+ export interface CheckedResult<Row> {
36
+ readonly written: number;
37
+ readonly found: readonly Row[];
38
+ }
39
+
40
+ /** The lost race, as Postgres says it under serializable isolation: retryable, coded alike. */
41
+ const lostEveryRace = (table: string, attempts: number) =>
42
+ driverError(`update ${table}`, {
43
+ code: SQLSTATE.serializationFailure,
44
+ message: `the rows this update judged changed before every one of ${attempts} conditioned writes — nothing was written; re-run the call`,
45
+ });
46
+
47
+ export const checkedUpdate = async <Row>(
48
+ scope: DriverScope<Row>,
49
+ write: CheckedUpdate<Row>,
50
+ ): Promise<CheckedResult<Row>> => {
51
+ const { entity, raw } = scope;
52
+ const { op, plan, patch, advance, narrowed, tx } = write;
53
+ for (let attempt = 0; attempt <= MAX_CHECKED_RETRIES; attempt += 1) {
54
+ // Every invariant, a SQL-expressible one too: a custom store enforces no CHECK.
55
+ const read = await raw.select({ plan, after: undefined, limit: MAX_ASSERTED_ROWS + 1, tx });
56
+ const found = scope.checked(op, plan, read);
57
+ write.bound?.(found.length);
58
+ if (found.length > MAX_ASSERTED_ROWS) throw assertedRowsTooMany(entity.$name, op, found.length);
59
+ const [first] = found;
60
+ if (first === undefined) return { written: 0, found };
61
+ const results = found.map((row) => mergedRow(entity, row, patch));
62
+ for (const merged of results) {
63
+ assertRowTenant(entity.$name, entity.$tenantColumn, op, merged);
64
+ entity.$assert(merged);
65
+ }
66
+ await write.references(results);
67
+ // The narrowed values the merge produced — the same for every row — so the store holds what
68
+ // was judged rather than a money `bigint` the row type never carries. The version is the
69
+ // patch's instant: the store advances it per row.
70
+ const merged = mergedRow(entity, first, patch) as Record<string, unknown>;
71
+ const values = Object.fromEntries(namedColumns(patch).map(([key]) => [key, merged[key]]));
72
+ if (advance !== undefined) values[advance.property] = narrowed[advance.property];
73
+ if (raw.updateChecked === undefined) {
74
+ return { written: await raw.update({ plan, tx }, values, advance), found };
75
+ }
76
+ if (await raw.updateChecked({ plan, tx }, read, values, advance)) {
77
+ return { written: found.length, found };
78
+ }
79
+ }
80
+ throw lostEveryRace(entity.$table, MAX_CHECKED_RETRIES + 1);
81
+ };
@@ -83,6 +83,24 @@ export interface DriverRepo<Row> {
83
83
  patch: Readonly<Record<string, unknown>>,
84
84
  advance?: DriverAdvance,
85
85
  ): Promise<number>;
86
+ /**
87
+ * OPTIONAL, detected by presence (no capability to declare, so `capabilities: DRIVER_CAPABILITIES`
88
+ * stays valid). The compare-and-set a JUDGED update writes through — an entity with an invariant
89
+ * or a same-tenant reference, and no `version`. Atomically, with no other write between the
90
+ * comparison and the set: when the rows `filter` matches are exactly `expected` (as `select`
91
+ * answered them — same rows, every stored value equal; in code, `Bun.deepEquals`), set `patch`
92
+ * (and `advance`, as `update` does) on every one and answer `true`; otherwise write NOTHING and
93
+ * answer `false`. The kit re-reads, re-judges and retries a lost set, then refuses
94
+ * `X_DB_SERIALIZATION_FAILURE`. Absent, the kit writes through `update` and a concurrent writer
95
+ * between its judge and its write can leave a row no invariant would pass — warned once per
96
+ * driver (`driver-kit-unchecked-warning.ts`).
97
+ */
98
+ updateChecked?(
99
+ filter: DriverFilter,
100
+ expected: readonly Row[],
101
+ patch: Readonly<Record<string, unknown>>,
102
+ advance?: DriverAdvance,
103
+ ): Promise<boolean>;
86
104
  delete(filter: DriverFilter): Promise<number>;
87
105
  /** `'upsert'`. The plan is `bulk-write.ts`'s — target, overwritten columns — already judged. */
88
106
  upsert?(rows: readonly Row[], plan: UpsertPlan, write: DriverWrite): Promise<readonly Row[]>;
@@ -0,0 +1,41 @@
1
+ // Single responsibility: say, once per custom driver, that its judged updates are unguarded — the
2
+ // store has no `updateChecked`, so a concurrent writer between the kit's judge and its write can
3
+ // leave a row no invariant would pass (#1379). Refusing is a break for every shipped driver, so in
4
+ // 31.x this is a coded `log.record` warning, as `X_ENTITY_ALL_TRUNCATED` is.
5
+
6
+ import { logger, renderCauseValue } from '@ultimat3/core';
7
+ import type { DriverDefinition, DriverRepo } from './driver-kit-types';
8
+ import { sameTenantProperties } from './driver-write-scope';
9
+ import type { EntityCore } from './entity';
10
+ import { versionOf } from './version-lock';
11
+
12
+ /** The one log message this writes: a subscriber matches `log.record`'s `message` against it. */
13
+ export const UNCHECKED_UPDATES = 'entity.driver.update_unchecked';
14
+
15
+ /** Drivers already warned about: keyed by the definition, so one `defineDriver` warns once. */
16
+ const warned = new WeakSet<DriverDefinition>();
17
+
18
+ /**
19
+ * Called as each table opens. Silent for a store with `updateChecked`, for a table whose updates
20
+ * judge nothing (no invariant, no same-tenant reference) and for a versioned one — its writes are
21
+ * conditioned on the version already (`driver-versioned-write.ts`). Every environment: the race is
22
+ * production's, and one line per driver per process costs nothing.
23
+ */
24
+ export function noteUncheckedUpdates<Row>(
25
+ definition: DriverDefinition,
26
+ entity: EntityCore<Row>,
27
+ raw: DriverRepo<Row>,
28
+ ): void {
29
+ if (typeof raw.updateChecked === 'function' || warned.has(definition)) return;
30
+ const judged = entity.$invariants.length > 0 || sameTenantProperties(entity).size > 0;
31
+ if (!judged || versionOf(entity) !== null) return;
32
+ warned.add(definition);
33
+ logger.warn(UNCHECKED_UPDATES, {
34
+ code: 'X_DRIVER_UNSUPPORTED',
35
+ capability: 'updateChecked',
36
+ driver: definition.name,
37
+ entity: entity.$name,
38
+ cause: `driver ${renderCauseValue(definition.name)} has no updateChecked, so ${entity.$name}'s judged updates read, judge, then write unconditionally — a concurrent writer between the judge and the write can leave a row its invariants refuse`,
39
+ fix: `defineDriver({ name: ${JSON.stringify(definition.name)}, capabilities, repo: (entity) => ({ ...store, updateChecked: async (filter, expected, patch) => /* atomically: rows filter matches deep-equal expected ? set patch, true : false */ }) }) # README "Custom drivers"`,
40
+ });
41
+ }
@@ -10,6 +10,8 @@ import { narrowRow } from './columns';
10
10
  import { copyColumns } from './copy-plan';
11
11
  import { kindOf, valueAt } from './cursor';
12
12
  import { byKeys, checkedDelete } from './driver-delete';
13
+ import { type MovedRow, restoreMoved, tornBatch } from './driver-kit-checked-rollback';
14
+ import { checkedUpdate } from './driver-kit-checked-update';
13
15
  import type { DriverScope } from './driver-scope';
14
16
  import { versionedWrites } from './driver-versioned-write';
15
17
  import {
@@ -19,10 +21,10 @@ import {
19
21
  } from './driver-write-scope';
20
22
  import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
21
23
  import { notFound } from './errors';
22
- import { assertedRowsTooMany, MAX_ASSERTED_ROWS } from './invariants';
24
+ import { assertedRowsTooMany, MAX_ASSERTED_ROWS, returnedBound } from './invariants';
23
25
  import { mergedRow } from './memory-update';
24
26
  import { idPlan, namedColumns, singleKeyOf } from './plan';
25
- import type { Repo, RepoOptions, Tx } from './repo';
27
+ import type { FilteredWriteOptions, Repo, RepoOptions, Tx } from './repo';
26
28
  import { rowKey } from './row-key';
27
29
  import { advancingVersionColumn, deletionStamp, VERSION_STEP_MS } from './search-index-version';
28
30
  import { writtenRowsSink } from './search-written-rows';
@@ -41,6 +43,7 @@ export type DriverWrites<Row> = Pick<
41
43
  | 'delete'
42
44
  | 'deleteWhere'
43
45
  | 'updateWhere'
46
+ | 'updateWhereReturning'
44
47
  | 'insertAllCount'
45
48
  | 'upsertAllCount'
46
49
  | 'copyAll'
@@ -83,19 +86,36 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
83
86
  return read;
84
87
  };
85
88
 
89
+ /** What a patch writes: its narrowed values, and the searchable version the store advances. */
90
+ const shapeOf = (patch: object) => {
91
+ const version = advancingVersionColumn(entity as EntityCore<unknown>);
92
+ const advance =
93
+ version !== undefined && namedColumns(patch).some(([key]) => key === version)
94
+ ? { property: version, stepMs: VERSION_STEP_MS }
95
+ : undefined;
96
+ const narrowed = narrowRow<Record<string, unknown>>(
97
+ entity.$columns,
98
+ Object.fromEntries(namedColumns(patch)),
99
+ );
100
+ return { advance, narrowed };
101
+ };
102
+
86
103
  /**
87
104
  * A patch applied to the rows a plan matches. With an invariant declared, every merged row is
88
105
  * judged first, bounded as a judged write is on Postgres; then one store call. Answers how many
89
106
  * rows the store wrote. A searchable entity's version is the STORE's to advance, per row and
90
107
  * atomically (`DriverRepo.update`'s `advance`): a value the kit computed from a read would let a
91
- * second process's newer version be written over.
108
+ * second process's newer version be written over. `found` is the rows a won compare-and-set
109
+ * compared against — the row as it stood when written, which `updateMany`'s rollback restores;
110
+ * `cas` takes that path even with nothing to judge, so a CAS store always reports them.
92
111
  */
93
- const patched = async (
112
+ const patchedRows = async (
94
113
  op: string,
95
114
  plan: QueryPlan,
96
115
  patch: object,
97
116
  options: RepoOptions | undefined,
98
- ): Promise<number> => {
117
+ cas = false,
118
+ ): Promise<{ readonly written: number; readonly found: readonly Row[] | undefined }> => {
99
119
  const tx = scope.txOf(op, options);
100
120
  // Nothing to judge: no read-back and no cap — one store call, as Postgres sends one statement.
101
121
  // The patch's tenant was judged by the caller; a soft-delete stamp names none.
@@ -103,19 +123,12 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
103
123
  sameTenantProperties(entity).has(key),
104
124
  );
105
125
  const sink = writtenRowsSink();
106
- const version = advancingVersionColumn(entity as EntityCore<unknown>);
107
- const advance =
108
- version !== undefined && namedColumns(patch).some(([key]) => key === version)
109
- ? { property: version, stepMs: VERSION_STEP_MS }
110
- : undefined;
111
- const narrowed = narrowRow<Record<string, unknown>>(
112
- entity.$columns,
113
- Object.fromEntries(namedColumns(patch)),
114
- );
126
+ const { advance, narrowed } = shapeOf(patch);
115
127
  // A declared version lock is per row (`v = stored + 1`), which one store patch cannot say: the
116
128
  // judged path below, one write per row (`driver-versioned-write.ts`).
117
129
  const lock = versionOf(entity);
118
- if (entity.$invariants.length === 0 && !movesReference && lock === null) {
130
+ const nothingToJudge = entity.$invariants.length === 0 && !movesReference;
131
+ if (nothingToJudge && lock === null && !(cas && raw.updateChecked !== undefined)) {
119
132
  // The search mirror asked for the rows: read them first, as the judged path does. Past the
120
133
  // judged bound they are not handed over — the mirror logs the write it could not name.
121
134
  const before =
@@ -130,7 +143,23 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
130
143
  if (sink !== undefined && before.length <= MAX_ASSERTED_ROWS) {
131
144
  sink(await writtenBack(op, plan, before, tx));
132
145
  }
133
- return written;
146
+ return { written, found: undefined };
147
+ }
148
+ // Unversioned: the judge and the write are one compare-and-set when the store offers it.
149
+ if (lock === null) {
150
+ const checked = await checkedUpdate(scope, {
151
+ op,
152
+ plan,
153
+ patch,
154
+ advance,
155
+ narrowed,
156
+ tx,
157
+ references,
158
+ });
159
+ if (sink !== undefined && checked.found.length > 0) {
160
+ sink(await writtenBack(op, plan, checked.found, tx));
161
+ }
162
+ return { written: checked.written, found: checked.found };
134
163
  }
135
164
  // Every invariant, a SQL-expressible one too: a custom store enforces no CHECK.
136
165
  const found = scope.checked(
@@ -140,39 +169,37 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
140
169
  );
141
170
  if (found.length > MAX_ASSERTED_ROWS) throw assertedRowsTooMany(entity.$name, op, found.length);
142
171
  const [first] = found;
143
- if (first === undefined) return 0;
172
+ if (first === undefined) return { written: 0, found };
144
173
  const results = found.map((row) => mergedRow(entity, row, patch));
145
174
  for (const merged of results) {
146
175
  assertRowTenant(entity.$name, entity.$tenantColumn, op, merged);
147
176
  entity.$assert(merged);
148
177
  }
149
178
  await references(results);
150
- if (lock !== null) {
151
- const written = await versionedWrites(scope, {
152
- op,
153
- plan,
154
- patch,
155
- lock,
156
- found,
157
- results,
158
- advance,
159
- narrowed,
160
- tx,
161
- references,
162
- });
163
- if (sink !== undefined) sink(await writtenBack(op, plan, found, tx));
164
- return written;
165
- }
166
- // The narrowed values the merge produced — the same for every row — so the store holds what
167
- // was judged rather than a money `bigint` the row type never carries. The version is the
168
- // patch's instant: the store advances it per row.
169
- const merged = mergedRow(entity, first, patch) as Record<string, unknown>;
170
- const values = Object.fromEntries(namedColumns(patch).map(([key]) => [key, merged[key]]));
171
- if (advance !== undefined) values[advance.property] = narrowed[advance.property];
172
- const written = await raw.update({ plan, tx }, values, advance);
179
+ // The row each won write was conditioned on: what `updateMany`'s rollback restores.
180
+ const won: Row[] = [];
181
+ const written = await versionedWrites(scope, {
182
+ op,
183
+ plan,
184
+ patch,
185
+ lock,
186
+ found,
187
+ results,
188
+ advance,
189
+ narrowed,
190
+ tx,
191
+ references,
192
+ wrote: (row) => won.push(row),
193
+ });
173
194
  if (sink !== undefined) sink(await writtenBack(op, plan, found, tx));
174
- return written;
195
+ return { written, found: won };
175
196
  };
197
+ const patched = async (
198
+ op: string,
199
+ plan: QueryPlan,
200
+ patch: object,
201
+ options: RepoOptions | undefined,
202
+ ): Promise<number> => (await patchedRows(op, plan, patch, options)).written;
176
203
 
177
204
  /** Hard or soft, decided once so `delete(id)` and `deleteWhere` cannot drift apart. */
178
205
  const removed = (op: string, plan: QueryPlan, options: RepoOptions | undefined) =>
@@ -185,7 +212,51 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
185
212
  )
186
213
  : checkedDelete(scope, op, plan, options);
187
214
 
215
+ const updated = async (
216
+ op: 'updateWhere',
217
+ filter: RowPatch<Row>,
218
+ given: RowPatch<Row>,
219
+ options: FilteredWriteOptions | undefined,
220
+ ): Promise<number> => {
221
+ refuseAbandoned();
222
+ const patch = entity.$parsePatch(given) as RowPatch<Row>;
223
+ const plan = scope.storePlan(op, updateWherePlan(entity, filter, patch, options, op));
224
+ assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
225
+ return patched(op, plan, patch, options);
226
+ };
227
+
228
+ /**
229
+ * `updateWhereReturning`, offered only over a store with `updateChecked` and an unversioned
230
+ * entity: the won compare-and-set names exactly the rows written — the ones judged — so they can
231
+ * be answered, read back under the keys the patch left them. A count-only store cannot tell its
232
+ * rows from a concurrent writer's, so the typed handle refuses the call there (#1369).
233
+ */
234
+ const returning = async (
235
+ filter: RowPatch<Row>,
236
+ given: RowPatch<Row>,
237
+ options: FilteredWriteOptions | undefined,
238
+ ): Promise<readonly Row[]> => {
239
+ refuseAbandoned();
240
+ const op = 'updateWhereReturning';
241
+ const patch = entity.$parsePatch(given) as RowPatch<Row>;
242
+ const plan = scope.storePlan(op, updateWherePlan(entity, filter, patch, options, op));
243
+ assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
244
+ const tx = scope.txOf(op, options);
245
+ const bound = (matched: number) => returnedBound(entity.$name, matched);
246
+ const write = { op, plan, patch, ...shapeOf(patch), tx, references, bound };
247
+ const { written, found } = await checkedUpdate(scope, write);
248
+ if (written === 0) return [];
249
+ // What the won set wrote, as `returning *` answers it: a read-back would carry a later
250
+ // writer's values, or drop a counted row. Only an advanced version is the store's to tell.
251
+ const merged = found.map((row) => mergedRow(entity, row, patch));
252
+ const rows = write.advance === undefined ? merged : await writtenBack(op, plan, merged, tx);
253
+ writtenRowsSink()?.(rows);
254
+ return rows;
255
+ };
256
+ const answers = raw.updateChecked !== undefined && versionOf(entity) === null;
257
+
188
258
  const writes: DriverWrites<Row> = {
259
+ ...(answers ? { updateWhereReturning: returning } : {}),
189
260
  async insert(values, options) {
190
261
  refuseAbandoned();
191
262
  const [row] = judged('insert', [values]);
@@ -262,14 +333,7 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
262
333
  return removed(op, scope.storePlan(op, writeWherePlan(entity, filter, options, op)), options);
263
334
  },
264
335
 
265
- async updateWhere(filter, given, options) {
266
- refuseAbandoned();
267
- const op = 'updateWhere';
268
- const patch = entity.$parsePatch(given) as RowPatch<Row>;
269
- const plan = scope.storePlan(op, updateWherePlan(entity, filter, patch, options, op));
270
- assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
271
- return patched(op, plan, patch, options);
272
- },
336
+ updateWhere: async (filter, given, options) => updated('updateWhere', filter, given, options),
273
337
 
274
338
  // A store answers rows from every insert, so the count is their length: one judging path.
275
339
  insertAllCount: async (given, options) => (await writes.insertAll(given, options)).length,
@@ -305,7 +369,7 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
305
369
  const cell = (row: unknown) => keyOf(kind, valueAt(row, plan.key));
306
370
  const before = new Map(found.map((row) => [cell(row), row]));
307
371
  const after = new Map(merged.map((row, at) => [cell(found[at]), row]));
308
- const moved: (readonly [Row, Row])[] = [];
372
+ const moved: MovedRow<Row>[] = [];
309
373
  let written = 0;
310
374
  try {
311
375
  for (const { id, patch } of plan.patches) {
@@ -313,18 +377,16 @@ export const driverWrites = <Row>(scope: DriverScope<Row>): DriverWrites<Row> =>
313
377
  const result = after.get(keyOf(kind, id));
314
378
  if (stored === undefined || result === undefined) continue;
315
379
  const one = scope.storePlan(op, idPlan(entity, id, options, op));
316
- const count = await patched(op, one, patch, options);
317
- if (count > 0) moved.push([stored, result]);
380
+ // A CAS store reports the row its won set compared against: THAT is what was overwritten,
381
+ // so the rollback restores it — the batch's first read may predate a newer writer.
382
+ const { written: count, found: won } = await patchedRows(op, one, patch, options, true);
383
+ if (count > 0) moved.push({ stored: won?.[0] ?? stored, result, patch });
318
384
  written += count;
319
385
  }
320
386
  } catch (error) {
321
- for (const [stored, result] of moved.reverse()) {
322
- const where = idPlan(entity, String(valueAt(result, plan.key)), options, op);
323
- const values = Object.fromEntries(
324
- [...plan.properties, plan.key].map((property) => [property, valueAt(stored, property)]),
325
- );
326
- await raw.update({ plan: scope.storePlan(op, where, true), tx }, values);
327
- }
387
+ const rollback = { op, key: plan.key, properties: plan.properties, options, tx };
388
+ const kept = await restoreMoved(scope, moved, rollback);
389
+ if (kept.length > 0) throw tornBatch(entity.$table, kept, error);
328
390
  throw error;
329
391
  }
330
392
  return written;
@@ -32,6 +32,8 @@ export interface VersionedWrite<Row> {
32
32
  readonly tx: Tx | undefined;
33
33
  /** Same-tenant references of a re-merged row, judged as the batch was. */
34
34
  readonly references: (rows: readonly Row[]) => Promise<void>;
35
+ /** Told each row this write wrote: a row gone or out of the filter by then is skipped. */
36
+ readonly wrote?: ((row: Row) => void) | undefined;
35
37
  }
36
38
 
37
39
  /**
@@ -78,6 +80,7 @@ export const versionedWrites = async <Row>(
78
80
  const count = await raw.update({ plan: keyed(read, true), tx }, valuesOf(result), advance);
79
81
  if (count > 0) {
80
82
  written += count;
83
+ write.wrote?.(read);
81
84
  break;
82
85
  }
83
86
  if (checks || attempt >= MAX_VERSION_RETRIES) throw stale(read);
package/src/invariants.ts CHANGED
@@ -114,6 +114,27 @@ export const assertedRowsTooMany = (
114
114
  fix: `${describeCommand(entityName)} # shows the invariant with sql: null that forces the read-back; then sweep the filter with inBatches()`,
115
115
  });
116
116
 
117
+ /** The call the three refusals below name: the one write whose ANSWER is its rows. */
118
+ const CALL = 'updateWhereReturning';
119
+
120
+ /** Asked before the write: every matched row would be held at once, decoded, to be answered. */
121
+ export const returnedBound = (entityName: string, matched: number): void => {
122
+ if (matched <= MAX_ASSERTED_ROWS) return;
123
+ throw new EntityError({
124
+ code: 'X_INVARIANT_VIOLATED',
125
+ cause: `${entityName}.${CALL}() matches ${matched} rows and answers every one it writes — past ${MAX_ASSERTED_ROWS} that is the whole table in memory. Read the same filter with .where(filter).inBatches(1000) and write each page, or use updateWhere(filter, patch), which answers a count and has no bound`,
126
+ fix: `${describeCommand(entityName)} # then sweep the filter with inBatches(), or count it with updateWhere()`,
127
+ });
128
+ };
129
+
130
+ /** Raised before the write: a count cannot be turned back into the rows it counted. */
131
+ export const returningUnsupported = (entityName: string): EntityError =>
132
+ new EntityError({
133
+ code: 'X_INVARIANT_VIOLATED',
134
+ cause: `${entityName}.${CALL}() reached a repository that does not implement it: the contract lets a hand-written Repo omit it, and its updateWhere answers a count, never the rows. Nothing was written`,
135
+ fix: `${describeCommand(entityName)} # then implement ${CALL} on that Repo, or serve ${entityName} with postgresDriver() or memoryDriver()`,
136
+ });
137
+
117
138
  /** Runs on every write. Reports every violation at once so one round trip fixes all. */
118
139
  export const assertInvariants = <T>(
119
140
  entityName: string,
@@ -40,6 +40,7 @@ const OPERATIONS = {
40
40
  updateMany: { verb: 'update', rows: counted },
41
41
  update: { verb: 'update', rows: one },
42
42
  updateWhere: { verb: 'update', rows: counted },
43
+ updateWhereReturning: { verb: 'update', rows: listed },
43
44
  delete: { verb: 'delete', rows: () => 1 },
44
45
  deleteWhere: { verb: 'delete', rows: counted },
45
46
  } as const satisfies Record<string, Reported>;
@@ -17,7 +17,12 @@ import { cursorFor, kindOf, valueAt } from './cursor';
17
17
  import { projectRow } from './driver-rows';
18
18
  import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
19
19
  import { invariantViolated, notFound } from './errors';
20
- import { assertedRowsTooMany, hasJsOnlyInvariant, MAX_ASSERTED_ROWS } from './invariants';
20
+ import {
21
+ assertedRowsTooMany,
22
+ hasJsOnlyInvariant,
23
+ MAX_ASSERTED_ROWS,
24
+ returnedBound,
25
+ } from './invariants';
21
26
  import { holdInOrder, lockKeyInput, lockKeysInput } from './lock-key';
22
27
  import { memoryAggregates } from './memory-aggregates';
23
28
  import { undoingBatch } from './memory-batch';
@@ -35,7 +40,7 @@ import { memoryUpsertAll } from './memory-upsert';
35
40
  import { registerMemoryScan, resolveMemoryVias } from './memory-via';
36
41
  import { assertPageBytes } from './page-bytes';
37
42
  import { idPlan, readPlan, singleKeyOf } from './plan';
38
- import type { FindManyArgs, MemoryRepo, RepoOptions } from './repo';
43
+ import type { FilteredWriteOptions, FindManyArgs, MemoryRepo, RepoOptions } from './repo';
39
44
  import { rowKey } from './row-key';
40
45
  import { sealedFields } from './sealed';
41
46
  import { sealedRepo } from './sealed-repo';
@@ -235,6 +240,47 @@ export const memoryRepo = <Row>(
235
240
  if (rows > MAX_ASSERTED_ROWS) throw assertedRowsTooMany(entity.$name, operation, rows);
236
241
  };
237
242
 
243
+ /** `updateWhere`'s whole path, answering the rows it wrote: the count is their length. */
244
+ const updated = async (
245
+ op: 'updateWhere' | 'updateWhereReturning',
246
+ filter: RowPatch<Row>,
247
+ given: RowPatch<Row>,
248
+ options: FilteredWriteOptions | undefined,
249
+ ): Promise<Row[]> => {
250
+ const patch = entity.$parsePatch(given);
251
+ const plan = updateWherePlan(entity, filter, patch, options, op);
252
+ // The PATCH, judged whole and before the rows are read — the same call `postgresRepo` makes
253
+ // before its statement exists. Inside the loop below it is judged only where a row was
254
+ // matched, so a patch handing rows to another tenant was refused or accepted depending on
255
+ // what the table happened to hold: `updateWhere(filter, { orgId: theirs })` over a filter
256
+ // matching nothing answered `0` here and threw there, from one call.
257
+ assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
258
+ // `rowsOf` again, so a soft-deleted row is as unreachable here as it is through
259
+ // `addressed()` — patching a row the app has already deleted is not an update, it is a
260
+ // resurrection nobody asked for. `write` re-asserts the invariants on each result.
261
+ const found = rowsOf(plan, {});
262
+ // The same ceiling `postgresRepo` applies from its own count, and for the same reason: this
263
+ // is the one write whose result size is the caller's FILTER rather than a page, and a rule
264
+ // only the app can judge is what forces every matched row through `$assert`. Without it a
265
+ // sweep of twelve million rows was green here and `X_INVARIANT_VIOLATED` there, from one
266
+ // call — a test proving a call production refuses. Before the loop, so a refusal never
267
+ // writes the rows it declined to judge.
268
+ if (hasJsOnlyInvariant(entity.$invariants)) assertedBound(found.length, op);
269
+ if (op === 'updateWhereReturning') returnedBound(entity.$name, found.length);
270
+ // The WHOLE batch is judged before any row of it lands — the same statement Postgres sends,
271
+ // which refuses as one. A row this batch refuses used to leave the rows before it stored:
272
+ // the write was a loop, and the loop stopped half way through.
273
+ const merged = judgeUpdate(entity, found, patch, untouched(found), storeKey);
274
+ for (const row of merged) judgeReferences(row);
275
+ // Judged whole, yet each row still meets the rows stored as it lands: one refused undoes the
276
+ // rows before it, as `deleteWhere`'s loop does and as Postgres rolls its statement back.
277
+ const written = undoingBatch(options?.tx, (tx) =>
278
+ merged.map((row, at) => write(row, { ...options, tx }, op, storeKey(found[at]))),
279
+ );
280
+ if (written.length <= MAX_ASSERTED_ROWS) writtenRowsSink()?.(written);
281
+ return written;
282
+ };
283
+
238
284
  // Every method is async: a repository call that fails must reject, never throw
239
285
  // synchronously, or half the call sites would need two error paths. Every write asks
240
286
  // `refuseAbandoned()` first, as `postgresRepo`'s `writing()` does (`write-abandon.test.ts`).
@@ -369,39 +415,8 @@ export const memoryRepo = <Row>(
369
415
  return doomed.length;
370
416
  }),
371
417
 
372
- updateWhere: writing(async (filter, given, options) => {
373
- const patch = entity.$parsePatch(given);
374
- const plan = updateWherePlan(entity, filter, patch, options, 'updateWhere');
375
- // The PATCH, judged whole and before the rows are read — the same call `postgresRepo` makes
376
- // before its statement exists. Inside the loop below it is judged only where a row was
377
- // matched, so a patch handing rows to another tenant was refused or accepted depending on
378
- // what the table happened to hold: `updateWhere(filter, { orgId: theirs })` over a filter
379
- // matching nothing answered `0` here and threw there, from one call.
380
- assertRowTenant(entity.$name, entity.$tenantColumn, 'updateWhere', patch);
381
- // `rowsOf` again, so a soft-deleted row is as unreachable here as it is through
382
- // `addressed()` — patching a row the app has already deleted is not an update, it is a
383
- // resurrection nobody asked for. `write` re-asserts the invariants on each result.
384
- const found = rowsOf(plan, {});
385
- // The same ceiling `postgresRepo` applies from its own count, and for the same reason: this
386
- // is the one write whose result size is the caller's FILTER rather than a page, and a rule
387
- // only the app can judge is what forces every matched row through `$assert`. Without it a
388
- // sweep of twelve million rows was green here and `X_INVARIANT_VIOLATED` there, from one
389
- // call — a test proving a call production refuses. Before the loop, so a refusal never
390
- // writes the rows it declined to judge.
391
- if (hasJsOnlyInvariant(entity.$invariants)) assertedBound(found.length, 'updateWhere');
392
- // The WHOLE batch is judged before any row of it lands — the same statement Postgres sends,
393
- // which refuses as one. A row this batch refuses used to leave the rows before it stored:
394
- // the write was a loop, and the loop stopped half way through.
395
- const merged = judgeUpdate(entity, found, patch, untouched(found), storeKey);
396
- for (const row of merged) judgeReferences(row);
397
- // Judged whole, yet each row still meets the rows stored as it lands: one refused undoes the
398
- // rows before it, as `deleteWhere`'s loop does and as Postgres rolls its statement back.
399
- const written = undoingBatch(options?.tx, (tx) =>
400
- merged.map((row, at) => write(row, { ...options, tx }, 'updateWhere', storeKey(found[at]))),
401
- );
402
- if (written.length <= MAX_ASSERTED_ROWS) writtenRowsSink()?.(written);
403
- return found.length;
404
- }),
418
+ updateWhere: writing(async (...args) => (await updated('updateWhere', ...args)).length),
419
+ updateWhereReturning: writing((...args) => updated('updateWhereReturning', ...args)),
405
420
 
406
421
  // Nothing is decoded in memory, so a count is the rows' length: the same judging, one answer.
407
422
  insertAllCount: async (given, options) => (await repo.insertAll(given, options)).length,
package/src/pg-driver.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  type SqlFragment,
16
16
  sql,
17
17
  withStatementAttribution,
18
+ withTransaction,
18
19
  } from '@ultimat3/db';
19
20
  import { appendOnlyRepo } from './append-only';
20
21
  import { asInvariantRefusal } from './check-refusal';
@@ -26,7 +27,12 @@ import { noteDriverStore } from './driver-registry';
26
27
  import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
27
28
  import { notFound, repoClientPinned } from './errors';
28
29
  import { stampHistoryActor } from './history-actor';
29
- import { assertedRowsTooMany, hasJsOnlyInvariant, MAX_ASSERTED_ROWS } from './invariants';
30
+ import {
31
+ assertedRowsTooMany,
32
+ hasJsOnlyInvariant,
33
+ MAX_ASSERTED_ROWS,
34
+ returnedBound,
35
+ } from './invariants';
30
36
  import { forgetPreloaded, tagSiblings } from './jit-preload';
31
37
  import { judgedWrite } from './judged-write';
32
38
  import { assertPageBytes } from './page-bytes';
@@ -39,13 +45,14 @@ import { countStatement, type ReadShape, selectStatement } from './pg-sql';
39
45
  import { postgresTransactor } from './pg-transactor';
40
46
  import { deleteStatement, updateStatement } from './pg-write-sql';
41
47
  import { idPlan, readPlan } from './plan';
42
- import type { FindManyArgs, Repo } from './repo';
48
+ import type { FilteredWriteOptions, FindManyArgs, Repo } from './repo';
43
49
  import { rowKey } from './row-key';
44
50
  import { sealedRepo } from './sealed-repo';
45
51
  import { deletionStamp } from './search-index-version';
46
52
  import { writtenRowsSink } from './search-written-rows';
47
53
  import type { QueryPlan } from './tenancy';
48
54
  import { assertRowTenant } from './tenancy';
55
+ import type { RowPatch } from './types';
49
56
  import { assertVersionedUpdate, staleOrNotFound, versionOf } from './version-lock';
50
57
  import { taggedWrite } from './write-tag';
51
58
  import { updateWherePlan, writeWherePlan } from './write-where';
@@ -151,6 +158,14 @@ export const postgresRepo = <Row>(
151
158
  ? sql`${deleteStatement(entity, plan)} returning *`
152
159
  : deleteStatement(entity, plan);
153
160
 
161
+ /** How many rows a plan matches now: what bounds a write that answers or judges its rows. */
162
+ const matching = async (op: string, plan: QueryPlan, shape: ReadShape): Promise<number> => {
163
+ const matched = await attributed(op, () =>
164
+ client().one<{ count: unknown }>(countStatement(entity, plan, shape)),
165
+ );
166
+ return Number(matched?.count ?? 0);
167
+ };
168
+
154
169
  /**
155
170
  * A count, or — when the search mirror asked (`search-written-rows.ts`) — the same statement with
156
171
  * `returning *`, its rows handed over and counted. The rows ride only for a searchable entity
@@ -165,15 +180,7 @@ export const postgresRepo = <Row>(
165
180
  statement: (returning: boolean) => SqlFragment,
166
181
  ): Promise<number> => {
167
182
  const sink = writtenRowsSink();
168
- const fits =
169
- sink !== undefined &&
170
- Number(
171
- (
172
- await attributed(op, () =>
173
- client().one<{ count: unknown }>(countStatement(entity, plan, shape)),
174
- )
175
- )?.count ?? 0,
176
- ) <= MAX_ASSERTED_ROWS;
183
+ const fits = sink !== undefined && (await matching(op, plan, shape)) <= MAX_ASSERTED_ROWS;
177
184
  if (sink === undefined || !fits) {
178
185
  return attributed(op, () => writing(() => client().execute(statement(false))));
179
186
  }
@@ -207,27 +214,29 @@ export const postgresRepo = <Row>(
207
214
 
208
215
  /**
209
216
  * Only an entity with a JS-only rule comes here: rows ARE needed, so how many is a memory bound.
210
- * Counted BEFORE the write, because a refusal after `returning *` has already allocated what it
211
- * refuses; a concurrent writer can drift the count, which moves a bound, never a decision.
217
+ * Counted before the write. Returning updates also cap the rows sent back and judge the cap in
218
+ * the transaction, because concurrent changes can invalidate the preliminary count.
212
219
  */
213
220
  const judgedRows = async (
214
221
  op: string,
215
222
  plan: QueryPlan,
216
223
  values: ReadonlyMap<string, unknown>,
217
224
  shape: ReadShape,
218
- ): Promise<number> => {
219
- const matched = await attributed(op, () =>
220
- client().one<{ count: unknown }>(countStatement(entity, plan, shape)),
221
- );
222
- const rows = Number(matched?.count ?? 0);
225
+ ): Promise<Row[]> => {
226
+ const rows = await matching(op, plan, shape);
223
227
  if (rows > MAX_ASSERTED_ROWS) throw assertedRowsTooMany(entity.$name, op, rows);
224
- const statement = updateStatement(entity, plan, values, shape, true);
228
+ const update = updateStatement(entity, plan, values, shape, true);
229
+ const statement =
230
+ op === 'updateWhereReturning'
231
+ ? sql`with updated as (${update}) select * from updated limit ${MAX_ASSERTED_ROWS + 1}`
232
+ : update;
225
233
  return judged(async (send) => {
226
234
  const written = await attributed(op, () => writing(() => send.query<PhysicalRow>(statement)));
235
+ if (op === 'updateWhereReturning') returnedBound(entity.$name, written.length);
227
236
  const decoded = written.map((row) => decodeRow(entity, row));
228
237
  for (const row of decoded) entity.$assert(row);
229
238
  writtenRowsSink()?.(decoded);
230
- return written.length;
239
+ return decoded;
231
240
  });
232
241
  };
233
242
 
@@ -237,9 +246,28 @@ export const postgresRepo = <Row>(
237
246
  */
238
247
  const removed = (op: string, plan: QueryPlan): Promise<number> =>
239
248
  entity.$softDelete && hasJsOnlyInvariant(entity.$invariants)
240
- ? judgedRows(op, plan, softDeletion(), shapeOf({}))
249
+ ? judgedRows(op, plan, softDeletion(), shapeOf({})).then((rows) => rows.length)
241
250
  : counted(op, plan, removalShape(), (returning) => removal(plan, returning));
242
251
 
252
+ /**
253
+ * What `updateWhere` and `updateWhereReturning` share before a statement exists: the plan (filter
254
+ * and patch refused as `updateWherePlan` refuses them), the tenant the patch may hand rows to, and
255
+ * the bound values. `shapeOf({})` keeps the `deleted_at is null` clause `update(id, patch)`
256
+ * already carries, so a soft-deleted row is not silently patched back into shape.
257
+ */
258
+ const filteredPatch = (
259
+ op: 'updateWhere' | 'updateWhereReturning',
260
+ filter: RowPatch<Row>,
261
+ given: RowPatch<Row>,
262
+ options: FilteredWriteOptions | undefined,
263
+ ) => {
264
+ const patch = entity.$parsePatch(given);
265
+ const plan = updateWherePlan(entity, filter, patch, options, op);
266
+ // The same move, filtered: one statement can hand away every row it matches.
267
+ assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
268
+ return { plan, values: bindValues(entity, patch), shape: shapeOf({}) };
269
+ };
270
+
243
271
  const repo: Repo<Row> = {
244
272
  async findById(id, options) {
245
273
  const op = 'findById';
@@ -366,15 +394,8 @@ export const postgresRepo = <Row>(
366
394
  },
367
395
 
368
396
  async updateWhere(filter, given, options) {
369
- const patch = entity.$parsePatch(given);
370
397
  const op = 'updateWhere';
371
- const plan = updateWherePlan(entity, filter, patch, options, op);
372
- // The same move, filtered: one statement can hand away every row it matches.
373
- assertRowTenant(entity.$name, entity.$tenantColumn, op, patch);
374
- const values = bindValues(entity, patch);
375
- // `shapeOf({})` keeps the `deleted_at is null` clause `update(id, patch)` already carries,
376
- // so a soft-deleted row is not silently patched back into shape.
377
- const shape = shapeOf({});
398
+ const { plan, values, shape } = filteredPatch(op, filter, given, options);
378
399
  // The rows come back only when something here can still refuse them. A `check` or a `unique`
379
400
  // invariant is a constraint Postgres enforced on the statement itself, so the answer is
380
401
  // already a count; only a JS-only rule (`kind: 'assert'`, `sql: null`) has to be judged on
@@ -387,7 +408,38 @@ export const postgresRepo = <Row>(
387
408
  updateStatement(entity, plan, values, shape, returning),
388
409
  );
389
410
  }
390
- return judgedRows(op, plan, values, shape);
411
+ return (await judgedRows(op, plan, values, shape)).length;
412
+ },
413
+
414
+ // The same plan, patch and judging as `updateWhere`, and the rows ARE the answer: the one
415
+ // `update … returning *` decides them, with no lock around it. They are also all held at once,
416
+ // so how many is a memory bound. A non-keyed write checks it again inside its transaction:
417
+ // the preliminary count can drift. A primary key names at most one row.
418
+ async updateWhereReturning(filter, given, options) {
419
+ const op = 'updateWhereReturning';
420
+ const { plan, values, shape } = filteredPatch(op, filter, given, options);
421
+ if (hasJsOnlyInvariant(entity.$invariants)) return judgedRows(op, plan, values, shape);
422
+ const keyed = entity.$primaryKey.every((key) =>
423
+ plan.where.some(({ column, op: test }) => column === key && test === 'eq'),
424
+ );
425
+ if (!keyed) returnedBound(entity.$name, await matching(op, plan, shape));
426
+ const statement = updateStatement(entity, plan, values, shape, true);
427
+ if (keyed) {
428
+ const rows = await attributed(op, () =>
429
+ writing(() => client().query<PhysicalRow>(statement)),
430
+ );
431
+ return rows.map((row) => decodeRow(entity, row));
432
+ }
433
+ client();
434
+ return withTransaction(
435
+ async (tx) => {
436
+ const bounded = sql`with updated as (${statement}) select * from updated limit ${MAX_ASSERTED_ROWS + 1}`;
437
+ const rows = await attributed(op, () => writing(() => tx.query<PhysicalRow>(bounded)));
438
+ returnedBound(entity.$name, rows.length);
439
+ return rows.map((row) => decodeRow(entity, row));
440
+ },
441
+ config.client === undefined ? {} : { client: config.client },
442
+ );
391
443
  },
392
444
 
393
445
  async count(args = {}) {
package/src/query.ts CHANGED
@@ -12,6 +12,7 @@ import { assertBatchable, type BatchIterator, batchIterator } from './batch';
12
12
  import { shrinkingPages } from './batch-bytes';
13
13
  import type { EntityCore } from './entity';
14
14
  import { searchUndeclared } from './feature-errors';
15
+ import { returningUnsupported } from './invariants';
15
16
  import { latestByRows, type ReadLatest } from './latest-by';
16
17
  import { checkedPredicate, type Operator } from './operator';
17
18
  import { assertFinitePageSize, DEFAULT_PAGE_SIZE } from './plan';
@@ -206,6 +207,25 @@ export interface Table<Row, C extends ColumnMap = ColumnMap>
206
207
  * `X_PATCH_EMPTY`. `onUpdateNow()` columns are stamped exactly as `update(id, patch)` stamps them.
207
208
  */
208
209
  updateWhere(filter: RowPatch<Row>, patch: RowPatch<Row>, options?: RepoOptions): Promise<number>;
210
+ /**
211
+ * `updateWhere` that resolves with the rows it wrote, as stored — on Postgres one `update … where
212
+ * … returning *`, so "update if it is still open" and "which rows did THIS call move" are decided
213
+ * by one statement and need no explicit lock. A filter matching nothing (the row was already
214
+ * moved, deleted or is another tenant's) resolves `[]`, never `X_NOT_FOUND`. Every guard
215
+ * `updateWhere` has is this call's: the filter and patch refusals (`X_WRITE_UNFILTERED`,
216
+ * `X_PATCH_EMPTY`), tenancy, soft-delete, invariants, the `onUpdateNow()` stamp and the version
217
+ * column, sealing, the search mirror and the `entity.bulk` report. The rows are held at once, so a
218
+ * result past `MAX_ASSERTED_ROWS` is refused (`X_INVARIANT_VIOLATED`), including when concurrent
219
+ * changes increase it after the pre-write count. A filter
220
+ * that does not name the whole primary key is counted first, and so is a write under an invariant
221
+ * only the app can judge. A `defineDriver` store and a repository without
222
+ * `updateWhereReturning` refuse the call with nothing written.
223
+ */
224
+ updateWhereReturning(
225
+ filter: RowPatch<Row>,
226
+ patch: RowPatch<Row>,
227
+ options?: RepoOptions,
228
+ ): Promise<readonly Row[]>;
209
229
  }
210
230
 
211
231
  interface State {
@@ -423,6 +443,11 @@ export const tableFor = <Row, C extends ColumnMap>(
423
443
  deleteWhere: async (filter, options) => repo.deleteWhere(filter, options),
424
444
  updateWhere: async (filter, patch, options) =>
425
445
  repo.updateWhere(filter, touch(entity, patch), options),
446
+ updateWhereReturning: async (filter, patch, options) => {
447
+ // No fallback through `updateWhere`: its count names no rows, and by then they are written.
448
+ if (repo.updateWhereReturning === undefined) throw returningUnsupported(entity.$name);
449
+ return repo.updateWhereReturning(filter, touch(entity, patch), options);
450
+ },
426
451
  // `touch` is passed rather than applied here: a transition IS an update, so an `onUpdateNow()`
427
452
  // column has to move exactly as `update(id, patch)` moves it — which is also the audit of WHEN
428
453
  // the row moved, using the stamp already declared instead of a second one beside it.
package/src/repo.ts CHANGED
@@ -155,6 +155,19 @@ export interface Repo<T = unknown> {
155
155
  patch: RowPatch<T>,
156
156
  options?: FilteredWriteOptions,
157
157
  ): Promise<number>;
158
+ /**
159
+ * `updateWhere` answering the rows it wrote, as stored: `update … where <filter> returning *`, so
160
+ * no explicit lock. The call for "update if it is still open" that must learn which rows this
161
+ * call (not a concurrent one) moved. Every guard `updateWhere` has applies unchanged, a match past
162
+ * `MAX_ASSERTED_ROWS` is refused, including when concurrent changes increase the Postgres result
163
+ * after its pre-write count. A filter matching nothing resolves `[]`.
164
+ * Optional: the typed handle refuses the call, before any write, on a repository without it.
165
+ */
166
+ updateWhereReturning?(
167
+ filter: RowPatch<T>,
168
+ patch: RowPatch<T>,
169
+ options?: FilteredWriteOptions,
170
+ ): Promise<readonly T[]>;
158
171
  /**
159
172
  * A different patch per row, by id, resolving with how many rows were written — the bulk form of a
160
173
  * loop of `update(id, patch)`. Every patch names the same columns. Optional: the typed handle
@@ -370,7 +370,16 @@ export function observedRepo<Row>(
370
370
  * Each is present only where the repository has it, so the typed handle's fallback still sees
371
371
  * an absence.
372
372
  */
373
- const { insertAllCount, upsertAllCount, copyAll, updateMany } = repo;
373
+ const { insertAllCount, upsertAllCount, copyAll, updateMany, updateWhereReturning } = repo;
374
+ if (updateWhereReturning !== undefined) {
375
+ // `updateWhere`'s report, over the rows it answered.
376
+ observed.updateWhereReturning = async (filter, patch, options) => {
377
+ const rows = await updateWhereReturning.call(repo, filter, patch, options);
378
+ bulk('update', rows.length, options);
379
+ await counted?.filtered(asRecord(filter), asRecord(patch) ?? {}, rows.length, options);
380
+ return rows;
381
+ };
382
+ }
374
383
  if (insertAllCount !== undefined) {
375
384
  observed.insertAllCount = async (rows, options) =>
376
385
  subscribed(ROW)
@@ -263,7 +263,24 @@ export const sealedRepo = <Row, R extends Repo<Row>>(entity: SealedSource, repo:
263
263
  // where the inner repository has them, so the typed handle's fallback still sees an absence.
264
264
  const sealAll = <T>(rows: readonly T[], keys: SealKeys): Promise<T[]> =>
265
265
  Promise.all(rows.map((row) => sealRow(entity, fields, row, keys, true)));
266
- const { insertAllCount, upsertAllCount, copyAll, updateMany } = repo;
266
+ const { insertAllCount, upsertAllCount, copyAll, updateMany, updateWhereReturning } = repo;
267
+ if (updateWhereReturning !== undefined) {
268
+ // `updateWhere`'s refusals and sealing, then the rows opened as `update`'s are.
269
+ sealing.updateWhereReturning = async (filter, patch, options) => {
270
+ refuseNamed(entity, fields, filterOf(filter), "a filtered write's filter");
271
+ const keys = sealKeysOnce();
272
+ return openRows(
273
+ fields,
274
+ await updateWhereReturning.call(
275
+ repo,
276
+ filter,
277
+ await sealRow(entity, fields, patch, keys),
278
+ await chainArgs(options, keys),
279
+ ),
280
+ keys,
281
+ );
282
+ };
283
+ }
267
284
  if (insertAllCount !== undefined) {
268
285
  sealing.insertAllCount = async (rows, options) =>
269
286
  insertAllCount.call(repo, await sealAll(rows, sealKeysOnce()), options);
@@ -65,8 +65,17 @@ export function searchMirroredRepo<Row>(entity: EntityCore<Row>, repo: Repo<Row>
65
65
  * installed it runs as its returning counterpart — the same judging, the rows mirrored, their
66
66
  * length answered. With none installed it is the count path, untouched.
67
67
  */
68
- const { insertAllCount, upsertAllCount, copyAll, updateMany } = repo;
68
+ const { insertAllCount, upsertAllCount, copyAll, updateMany, updateWhereReturning } = repo;
69
69
  const counts: Partial<Repo<Row>> = {
70
+ // Its rows are its answer, so the mirror is told them directly: no collecting context.
71
+ ...(updateWhereReturning === undefined
72
+ ? {}
73
+ : {
74
+ updateWhereReturning: (filter, patch, options) =>
75
+ stored(core, 'updateWhereReturning', options, () =>
76
+ updateWhereReturning.call(repo, filter, patch, options),
77
+ ),
78
+ }),
70
79
  ...(insertAllCount === undefined
71
80
  ? {}
72
81
  : {
package/src/view-repo.ts CHANGED
@@ -14,6 +14,7 @@ const WRITES = [
14
14
  'delete',
15
15
  'deleteWhere',
16
16
  'updateWhere',
17
+ 'updateWhereReturning',
17
18
  'insertAllCount',
18
19
  'upsertAllCount',
19
20
  'copyAll',