@ultimat3/entity 31.48.0 → 31.49.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
@@ -34,6 +34,11 @@ A rule marked `†` has its full text in [`docs/history/entity-rules.md`](../../
34
34
  - **A numeric key has one spelling** (`keyOf`): batches, conflict targets and memory's uniques. **A null test on a whole money property reads `<p>.minor`; any other predicate on it, or an unknown operator, is refused at plan time (`predicate-screen.ts`).** Why: `docs/history/entity.md` (31.0.0).
35
35
  - **A PREDICATE's meaning is decided by the column's KIND** (`memory-match.ts`; `compareByKind` /
36
36
  `sameValueOfKind` exported for query); ONE numeric comparison, `numericOrder`; `LIKE` never a regex. †
37
+ - **An operand Postgres would refuse is decided in `operandFor`, never bound** (`As of 2026-11`): text
38
+ that is no uuid equals no row (`equalsNoValue`, `uuid-text.ts`); `like` is text/char/bytea only; an
39
+ instant crosses in years 0001–9999 (writes too, `instant-range.ts` — never on read); an `in` list
40
+ ≥ `IN_LIST_AS_ARRAY_FROM` is one array bind (`pg-sql-in.ts`). `readByIds` isolates a class-22 id.
41
+ - **`avg` is `averageSql`** — `averageDecimalText`'s integer arithmetic; never `round(avg())`.
37
42
  - **The Postgres driver is proved against a real Postgres** (`pg-driver.live.test.ts`, skipped without
38
43
  `TEST_DATABASE_URL`). A new operator, kind or write path is not done until it round-trips.
39
44
  - **A repository call rejects, never throws synchronously** (`tableFor`'s writes are `async`).
package/README.md CHANGED
@@ -331,7 +331,10 @@ is `kind: 'check'` and emits `slug ~ '^[a-z0-9]+(?:-[a-z0-9]+)*$'`. The **same s
331
331
  places — nothing is translated — so a construct the two engines read differently is REFUSED where it
332
332
  is written, with the portable spelling in the `fix` where one exists (`\w` -> `[A-Za-z0-9_]`, `.` ->
333
333
  `[^\n\r]`) and the app-only predicate where none does (`\b` is a word boundary to `.test()` and a
334
- BACKSPACE to Postgres). `i` becomes `~*`; every other flag is refused.
334
+ BACKSPACE to Postgres). `i` becomes `~*`; every other flag is refused. Also refused, because
335
+ Postgres rejects the CHECK or answers it differently: an astral character (Bun writes `/😀/` as a
336
+ surrogate pair `\uD83D\uDE00`), a repetition bound past 255 (`{256}`), a `-` straight after a range
337
+ or `\d` inside a class unless it is last (`[a-z-9]`), and a quantified lookahead (`(?=a)*`).
335
338
 
336
339
  `isNull()` / `isNotNull()` are the only pair in the vocabulary TOTAL over NULL — `IS NULL` answers
337
340
  true or false for every input, and the app side reads an ABSENT key and a stored `null` as one value.
@@ -519,7 +522,7 @@ visibility, never its page.
519
522
  |---|---|
520
523
  | Never a float | `sum`/`avg` answer decimal **text** whatever the column was (the sum of a million `integer` rows is not an `integer`, and `Number()` past 2^53 loses digits); money answers `MoneyValue` in integer minor units; `min`/`max` answer the row's own type |
521
524
  | Empty set | `null` in every function, which is what SQL answers — a `0` would claim rows were seen. `count()` is `0`, and that is the distinction |
522
- | `avg` | one fixed scale (6 digits), rounded half away from zero from the exact rational, so both drivers land on one number |
525
+ | `avg` | one fixed scale (6 digits), rounded half away from zero from the exact rational, so both drivers land on one number — at any magnitude: Postgres' own `avg(bigint)` keeps about sixteen significant digits, so the statement does the integer arithmetic itself (`averageSql`, `As of 2026-11`) |
523
526
  | Refused | `min`/`max` on `text` (ordering is the database's collation there and JS code-unit order here); `avg` over money (every answer would be a silent rounding of a fraction of a minor unit — `sum()` and `count()` instead, dividing where the rounding is a decision); an amount covering more than one currency **or scale**; a money total past ±2^53 minor units |
524
527
  | `approximateCount()` | `reltuples` out of `pg_class`, constant time, because `count(*)` walks every visible row and no index can make it cheaper. The whole **table** — a filtered chain, every tenant-scoped entity and every soft-deleting one (`reltuples` counts the deleted rows) are `X_APPROXIMATE_COUNT_FILTERED`, and `null` means the table has never been analysed |
525
528
 
@@ -540,9 +543,13 @@ An operand is read by the column's kind, once for both drivers (`predicate-opera
540
543
  | `timestamp()` | a `Date` or ISO text with `Z`/an offset | compared as that instant |
541
544
  | `timestamp()` | zoneless ISO text (`'2026-01-01'`, `'2026-01-01T10:00'`) | read as UTC in both drivers, never the server's `TimeZone` |
542
545
  | `timestamp()` | a number | `X_INVARIANT_VIOLATED` — epoch milliseconds are no instant Postgres parses |
546
+ | `timestamp()` | a `Date` outside years 0001–9999, or text in year `0000` | `X_INVARIANT_VIOLATED` — Postgres reads an instant as ISO text with a four-digit year. A write is refused the same way, at its entry; a row the server already holds outside the range still reads (`As of 2026-11`) |
543
547
  | `date()` | a `Date` | its UTC calendar date (`plainDateUtc`), as `$parse` writes one |
544
548
  | `integer()` / `bigint()` | a fraction (`1.5`, `'1.5'`, `'1e1'`) | `X_INVARIANT_VIOLATED` — round it to the bound you mean |
545
- | `integer()` / `bigint()` / `decimal()` | any `like` | `X_INVARIANT_VIOLATED` — a number is matched by range |
549
+ | every kind but `text()` / `char()` / `bytes()` | any `like` | `X_INVARIANT_VIOLATED` — a pattern matches text; a number is matched by range, a `uuid`, `boolean`, instant, date, `jsonb` or array by value (`As of 2026-11`) |
550
+ | `uuid()` | any spelling Postgres parses — upper case, no hyphens, `{braces}` | the one value it names, in `eq`/`neq`/`in`, `findById` and a batched lookup |
551
+ | `uuid()` | text that is no uuid, under `eq`/`neq`/`in` | a value no row equals: `eq`/`in` match nothing, `neq` every row; `findById` is `null`, `update`/`delete` are `X_NOT_FOUND` — never `22P02`. It is not bound, so the statement reads `1 = 0` (`As of 2026-11`) |
552
+ | any | an `in` list of 32,768 values or more | one array parameter (`= any($1)`) on Postgres, so a list past the 65,535-bind limit answers. `bytes()`, `json()` and `arrayOf()` have no array form: past 65,535 values they are `X_INVARIANT_VIOLATED` in both drivers (`As of 2026-11`) |
546
553
  | `arrayOf()` | a list, under `eq`/`neq`/`in` | element by element, in order (`array_eq`) |
547
554
 
548
555
  ## A predicate tree: `andWhereNode`
@@ -767,7 +774,7 @@ export const find = async (orgId: string, q: string) => {
767
774
 
768
775
  | Rule | Detail |
769
776
  |---|---|
770
- | `.search(term)` asks the installed index | built-in: the `matches` predicate in the statement (today's SQL). Any other: ids first — 10,000 (`MAX_PAGE_SIZE`) or more hits are refused with `X_INVARIANT_VIOLATED`, never truncated — then the chain reads those rows with its own tenancy, soft delete, order and cursor |
777
+ | `.search(term)` asks the installed index | built-in: the `matches` predicate in the statement (today's SQL). Any other: ids first — 10,000 (`MAX_PAGE_SIZE`) or more hits are refused with `X_INVARIANT_VIOLATED`, never truncated — then the chain reads those rows with its own tenancy, soft delete, order and cursor. The index is asked per tenant: the chain's `eq` on the tenant column, else the actor's org — and inside `crossTenant()` each tenant of an `andWhere('<tenant>', 'in', [...])`, never the actor's alone; a `crossTenant` search naming neither is refused (`X_INVARIANT_VIOLATED`) |
771
778
  | a document has a **version** | the row's `onUpdateNow()` instant, epoch ms. A searchable entity indexed by anything declares one — `updatedAt: timestamp().defaultNow().onUpdateNow()` — or `searchDocumentOf` and `reindex()` refuse (`X_INVARIANT_VIOLATED`) |
772
779
  | the version is STRICTLY increasing per row | a write of a searchable entity — a soft delete included — stores its version no earlier than the stored one + 1 ms: Postgres `greatest($now, updated_at + interval '1 millisecond')` in the `update` and the upsert's `on conflict` set; the memory driver in its merge (`advanceVersion`); a `defineDriver` store in ITS write, atomically per row — `DriverRepo.update`'s `advance` argument, and `advanceVersion(entity, stored, merged, (p) => plan.set.includes(p))` in its own `upsert` (`entityDriverConformance` refuses a store that skips either). So two writes inside one millisecond are two versions, and the index keeps the second. The column may run ahead of the clock by a millisecond per same-ms write. Other entities' `onUpdateNow()` columns are the clock's reading, unchanged |
773
780
  | keep only newer | an index applies a document only when its version is newer than what it holds for that id: a document, or the tombstone `remove(scope, ids, version)` leaves (a delete's: past the row's last version and no earlier than its instant). Equal = replay. EXCEPT a `committed` document — the write path's, `index(docs, { committed: true })` — which replaces a tombstone whatever its version: a key deleted and written again is live at once, inside one millisecond too. `reindex`'s reads are not `committed`, so a stale read never brings a deleted row back |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/entity",
3
- "version": "31.48.0",
3
+ "version": "31.49.0",
4
4
  "description": "A table + its domain type + invariants the database also enforces",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -26,6 +26,7 @@
26
26
  "exports": {
27
27
  ".": "./src/index.ts",
28
28
  "./adapter": "./src/adapter.ts",
29
+ "./internal/memory-tx": "./src/memory-tx-entry.ts",
29
30
  "./record": "./src/record.ts"
30
31
  },
31
32
  "files": [
@@ -44,9 +45,9 @@
44
45
  "test": "bun test"
45
46
  },
46
47
  "dependencies": {
47
- "@ultimat3/core": "31.48.0",
48
- "@ultimat3/db": "31.48.0",
49
- "@ultimat3/schema": "31.48.0",
50
- "@ultimat3/time": "31.48.0"
48
+ "@ultimat3/core": "31.49.0",
49
+ "@ultimat3/db": "31.49.0",
50
+ "@ultimat3/schema": "31.49.0",
51
+ "@ultimat3/time": "31.49.0"
51
52
  }
52
53
  }
package/src/aggregate.ts CHANGED
@@ -159,9 +159,10 @@ export const sumDecimalText = (values: readonly string[]): string | null => {
159
159
  };
160
160
 
161
161
  /**
162
- * `sum / count`, rounded half away from zero at `AVG_SCALE` — which is what Postgres' `round()`
163
- * does to a `numeric`, and the reason the statement asks for `round(avg(...), 6)` rather than the
164
- * server's own default scale: two drivers rounding at different places answer two numbers.
162
+ * `sum / count`, rounded half away from zero at `AVG_SCALE`. The statement spells the same integer
163
+ * arithmetic (`averageSql`, `pg-sql-aggregate.ts`) rather than taking the server's own scale: two
164
+ * drivers rounding at different places answer two numbers, and `avg(bigint)` past sixteen digits
165
+ * rounds at none.
165
166
  */
166
167
  export const averageDecimalText = (total: string | null, count: number): string | null => {
167
168
  if (total === null || count === 0) return null;
package/src/batch-read.ts CHANGED
@@ -3,12 +3,13 @@
3
3
  // answers them. The microtask coalescer and the sibling-aware preload both read ids through here,
4
4
  // so the two can never disagree about when a shared statement is legal.
5
5
 
6
- import type { DbClient } from '@ultimat3/db';
6
+ import { type DbClient, sqlState } from '@ultimat3/db';
7
7
  import type { EntityCore } from './entity';
8
8
  import { canonicalDecimal, canonicalInteger } from './numeric-compare';
9
9
  import { decodeRow, type PhysicalRow } from './pg-row';
10
10
  import { type ReadShape, selectStatement } from './pg-sql';
11
11
  import type { QueryPlan } from './tenancy';
12
+ import { canonicalUuid } from './uuid-text';
12
13
 
13
14
  /**
14
15
  * Postgres binds at most 65535 parameters, so a batch wider than this becomes several statements
@@ -36,14 +37,15 @@ export type Answer = { readonly row: unknown } | { readonly error: unknown };
36
37
  * The string both sides of a batch are filed under — the requested id, and the key of a row that
37
38
  * came back. Postgres compares a `uuid` as a value and prints it lower-cased, so an id handed in
38
39
  * upper case matches the row *there* and would miss it here, which would make an answer depend on
39
- * whether some other lookup shared the microtask. An integer or `numeric` is compared by value too:
40
+ * whether some other lookup shared the microtask; braces and missing hyphens are the same value
41
+ * there too (`uuid-text.ts`). An integer or `numeric` is compared by value too:
40
42
  * `'007'` matched the row and missed its answer here, filed under `'7'`. One the column could not
41
43
  * hold stays as written, so the statement still carries it and Postgres answers its own refusal.
42
44
  * Every other kind compares by its bytes, and lower-casing a text key would merge two rows
43
45
  * Postgres keeps apart.
44
46
  */
45
47
  export const keyOf = (kind: string, value: unknown): string => {
46
- if (kind === 'uuid') return String(value).toLowerCase();
48
+ if (kind === 'uuid') return canonicalUuid(value) ?? String(value).toLowerCase();
47
49
  if (kind === 'integer' || kind === 'bigint') return canonicalInteger(value) ?? String(value);
48
50
  if (kind === 'numeric') return canonicalDecimal(value) ?? String(value);
49
51
  if (kind === 'timestamptz') return canonicalInstant(value) ?? String(value);
@@ -117,7 +119,7 @@ export interface PointRead<Row> {
117
119
  }
118
120
 
119
121
  /** The one statement, filed by key — the same builder, the same scope, `in` instead of `=`. */
120
- export const readByIds = async <Row>(
122
+ const readStatement = async <Row>(
121
123
  read: PointRead<Row>,
122
124
  ids: readonly unknown[],
123
125
  ): Promise<ReadonlyMap<string, Answer>> => {
@@ -144,6 +146,62 @@ export const readByIds = async <Row>(
144
146
  return answers;
145
147
  };
146
148
 
149
+ /** `in_failed_transaction`: a statement sent after the first refusal aborted the transaction. */
150
+ const IN_FAILED_TRANSACTION = '25P02';
151
+
152
+ /** SQLSTATE class 22, data exception: the server refused a VALUE, not the statement's shape. */
153
+ const isDataError = (error: unknown): boolean => sqlState(error)?.startsWith('22') === true;
154
+
155
+ /**
156
+ * `readStatement`, with a value the server refuses failing only the id that carried it. One key
157
+ * the column cannot hold (`'abc'` against a `bigint`) is a class 22 refusal of the WHOLE statement,
158
+ * so every lookup widened into it was failed by an id it never asked for — rows the single
159
+ * statement each would have sent answers. The ids are re-sent in halves until the refused one
160
+ * stands alone: about `2k·log2(n)` statements for `k` bad ids, never one per id.
161
+ *
162
+ * Anything else — a dropped connection, a timeout, a stale schema — is the statement's own failure
163
+ * and is rethrown for every caller, as before; a half that fails that way answers its ids with its
164
+ * own failure. Only a half sent into a transaction the first refusal aborted (`25P02`) gets the
165
+ * FIRST refusal, the one the unsplit statement gave them.
166
+ */
167
+ export const readByIds = async <Row>(
168
+ read: PointRead<Row>,
169
+ ids: readonly unknown[],
170
+ ): Promise<ReadonlyMap<string, Answer>> => {
171
+ try {
172
+ return await readStatement(read, ids);
173
+ } catch (error) {
174
+ if (!isDataError(error) || ids.length < 2) throw error;
175
+ const answers = new Map<string, Answer>();
176
+ await isolate(read, ids, error, answers);
177
+ return answers;
178
+ }
179
+ };
180
+
181
+ /** `ids` is known to fail together with `refusal`: halve, and file what each half answers. */
182
+ const isolate = async <Row>(
183
+ read: PointRead<Row>,
184
+ ids: readonly unknown[],
185
+ refusal: unknown,
186
+ answers: Map<string, Answer>,
187
+ ): Promise<void> => {
188
+ const middle = Math.ceil(ids.length / 2);
189
+ for (const half of [ids.slice(0, middle), ids.slice(middle)]) {
190
+ try {
191
+ for (const [key, answer] of await readStatement(read, half)) answers.set(key, answer);
192
+ } catch (error) {
193
+ if (isDataError(error) && half.length > 1) {
194
+ await isolate(read, half, error, answers);
195
+ continue;
196
+ }
197
+ // Only a transaction the first refusal ABORTED inherits it; a half's own failure (a pool
198
+ // timeout, a failover's 57P01) is that half's answer, never "invalid input syntax".
199
+ const own = sqlState(error) === IN_FAILED_TRANSACTION ? refusal : error;
200
+ for (const id of half) answers.set(keyOf(read.key.kind, id), { error: own });
201
+ }
202
+ }
203
+ };
204
+
147
205
  /** One statement's worth at a time — a batch too wide for the bind count is several, never one. */
148
206
  export const statementChunks = <T>(values: readonly T[]): readonly (readonly T[])[] => {
149
207
  const chunks: T[][] = [];
package/src/bulk-write.ts CHANGED
@@ -9,7 +9,7 @@ import { keyOf } from './batch-read';
9
9
  import { columnFor } from './column';
10
10
  import { valueAt } from './cursor';
11
11
  import { type EntityCore, SOFT_DELETE_COLUMN } from './entity';
12
- import { EntityError, invariantViolated } from './errors';
12
+ import { crossTenantUpsert, EntityError, invariantViolated } from './errors';
13
13
  import { allColumns, columnsOf } from './pg-row';
14
14
  import type { RowPatch } from './types';
15
15
  import { uniqueConstraints } from './unique-constraints';
@@ -134,24 +134,6 @@ const unevenBatch = (entityName: string, position: number, missing: string): Ent
134
134
  fix: `${entityName}.upsertAll(rows.map((row) => ({ ...row, ${missing}: <value> })), args) # every row of an updating batch names the same columns`,
135
135
  });
136
136
 
137
- /**
138
- * A cross-tenant upsert is not a batching mistake, it is a write into another tenant's row, so it
139
- * gets tenancy's own code. `X_TENANCY_UNSCOPED`'s own factory sends the reader to the request
140
- * context the tenant is derived from, which is not what repairs this: an upsert builds no read
141
- * plan, so nothing derives anything onto it — the scope has to be part of the constraint the
142
- * collision is judged against, or the row that comes back was never in scope to begin with.
143
- */
144
- const crossTenantUpsert = (
145
- entityName: string,
146
- tenant: string,
147
- on: readonly string[],
148
- ): EntityError =>
149
- new EntityError({
150
- code: 'X_TENANCY_UNSCOPED',
151
- cause: `${entityName}.upsertAll() resolves a collision on (${on.join(', ')}), which does not include the tenant column "${tenant}" — a row stored by another tenant would match and be overwritten`,
152
- fix: `${entityName}.upsertAll(rows, { onConflict: ['${tenant}', '${on.join("', '")}'] }) # or onMatch: 'nothing', which writes nothing to a row it does not own`,
153
- });
154
-
155
137
  /**
156
138
  * Every conflict target Postgres could infer an index for: the primary key, and every non-partial
157
139
  * unique the entity declares by either spelling (`unique-constraints.ts`).
package/src/coalesce.ts CHANGED
@@ -107,8 +107,9 @@ const flush = async (batch: Batch): Promise<void> => {
107
107
  else entry.settle(answer.row);
108
108
  }
109
109
  } catch (error) {
110
- // The statement failed, so everyone in it gets the failure the single statement would
111
- // have handed them. Every one was returned to a caller, so none goes unhandled.
110
+ // The statement failed for a reason that is the statement's — a refused VALUE never
111
+ // reaches here: `readByIds` re-sends around it and files that failure under its own id
112
+ // (`batch-read.ts`). Every entry was returned to a caller, so none goes unhandled.
112
113
  for (const entry of chunk) entry.fail(error);
113
114
  }
114
115
  }
package/src/columns.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  makeTimestamp,
21
21
  } from './column';
22
22
  import { got, oneOf, refuseNul } from './column-values';
23
+ import { assertInstantsCross } from './instant-range';
23
24
  import { refuseColumn } from './refuse';
24
25
  import type {
25
26
  Column,
@@ -443,8 +444,10 @@ const narrowUuid = <Row>(columns: ColumnMap, row: Row): Row => {
443
444
  * nowhere. The `as` is the one assertion this file is for — every money property is a `MoneyValue`
444
445
  * once `narrowMoney` has returned, and `parseMinor` threw for anything that could not become one.
445
446
  */
446
- export const narrowRow = <Row>(columns: ColumnMap, values: RowWrite<Row>): Row =>
447
- narrowUuid(columns, narrowMoney(columns, values)) as Row;
447
+ export const narrowRow = <Row>(columns: ColumnMap, values: RowWrite<Row>): Row => {
448
+ assertInstantsCross(columns, values);
449
+ return narrowUuid(columns, narrowMoney(columns, values)) as Row;
450
+ };
448
451
 
449
452
  /**
450
453
  * The CHECK that stops a psql session writing a currency the app would refuse — the app's own
@@ -62,7 +62,8 @@ export function crossTenant<T>(reason: string, fn: () => T): T {
62
62
 
63
63
  /**
64
64
  * The innermost enclosing reason, or `undefined` outside every scope — which is every query in an
65
- * app that never calls `crossTenant`. Read by the tenant guard, and by nothing else.
65
+ * app that never calls `crossTenant`. Read by the tenant guard, and by `search-repo.ts`, which must
66
+ * know the chain spans tenants before it asks an external index for one.
66
67
  */
67
68
  export const crossTenantReason = (): string | undefined => storage.get();
68
69
 
@@ -3,6 +3,7 @@
3
3
  // would rewrite every column it did not name.
4
4
 
5
5
  import { invariantViolated } from './errors';
6
+ import { assertInstantsCross } from './instant-range';
6
7
  import { holdsJsonNull } from './json-null';
7
8
  import { copyRow } from './sealed';
8
9
  import type { AnyColumn } from './types';
@@ -40,5 +41,7 @@ export const parseEntityPatch = <Patch>(
40
41
  configurable: true,
41
42
  });
42
43
  }
44
+ // A patch is a write: an instant Postgres would refuse is refused here, for both drivers.
45
+ assertInstantsCross(columns, parsed);
43
46
  return parsed as Patch;
44
47
  };
package/src/errors.ts CHANGED
@@ -61,17 +61,43 @@ export const tenancyUnscoped = (
61
61
  entityName: string,
62
62
  operation: string,
63
63
  actorOrg?: string,
64
+ ): EntityError =>
65
+ // Two constructions, never one with a ternary in its `fix:`. `x errors explain` quotes the first
66
+ // throw site whose fix is ONE literal, and a ternary is none: it skipped this factory and
67
+ // answered a read's question with the upsert's fix below. The no-context branch is first because
68
+ // it is the code's general cause — its registered title, "a tenant-scoped query has no org
69
+ // predicate" — and both other fixes are narrower than that.
70
+ actorOrg === undefined
71
+ ? new EntityError({
72
+ code: 'X_TENANCY_UNSCOPED',
73
+ cause: `${entityName}.${operation}() was built without an org predicate but the entity has an orgId column, and no request context carried an actor to take the tenant from`,
74
+ fix: `runWithContext(ctxOf({ actor: userActor({ id, orgId }) }), fn) // the actor's org scopes the plan — or name the tenant: ${entityName}.${operation}({ orgId }), which orgScoped(plan, orgId) is the plan-level form of`,
75
+ })
76
+ : new EntityError({
77
+ code: 'X_TENANCY_UNSCOPED',
78
+ cause: `${entityName}.${operation}() was checked against a plan with no org predicate, though the acting actor's tenant is ${renderValue(actorOrg)} — a plan is verified here, never rewritten, so the tenant had to be on it already`,
79
+ fix: `scopedPlan('${entityName}', tenantColumn, '${operation}', plan) // applies the actor's tenant — or add the predicate first: orgScoped(plan, ${asLiteral(actorOrg, "'<org>'")})`,
80
+ });
81
+
82
+ /**
83
+ * A cross-tenant upsert is not a batching mistake, it is a write into another tenant's row, so it
84
+ * gets tenancy's own code. `tenancyUnscoped` sends the reader to the request context the tenant is
85
+ * derived from, which is not what repairs this: an upsert builds no read plan, so nothing derives
86
+ * anything onto it — the scope has to be part of the constraint the collision is judged against,
87
+ * or the row that comes back was never in scope to begin with.
88
+ *
89
+ * Declared HERE, below the general factory, and not beside its one caller in `bulk-write.ts`:
90
+ * that file sorts first, so its fix was the one `x errors explain X_TENANCY_UNSCOPED` printed.
91
+ */
92
+ export const crossTenantUpsert = (
93
+ entityName: string,
94
+ tenant: string,
95
+ on: readonly string[],
64
96
  ): EntityError =>
65
97
  new EntityError({
66
98
  code: 'X_TENANCY_UNSCOPED',
67
- cause:
68
- actorOrg === undefined
69
- ? `${entityName}.${operation}() was built without an org predicate but the entity has an orgId column, and no request context carried an actor to take the tenant from`
70
- : `${entityName}.${operation}() was checked against a plan with no org predicate, though the acting actor's tenant is ${renderValue(actorOrg)} — a plan is verified here, never rewritten, so the tenant had to be on it already`,
71
- fix:
72
- actorOrg === undefined
73
- ? `runWithContext(ctxOf({ actor: userActor({ id, orgId }) }), fn) // the actor's org scopes the plan — or name the tenant: ${entityName}.${operation}({ orgId }), which orgScoped(plan, orgId) is the plan-level form of`
74
- : `scopedPlan('${entityName}', tenantColumn, '${operation}', plan) // applies the actor's tenant — or add the predicate first: orgScoped(plan, ${asLiteral(actorOrg, "'<org>'")})`,
99
+ cause: `${entityName}.upsertAll() resolves a collision on (${on.join(', ')}), which does not include the tenant column "${tenant}" — a row stored by another tenant would match and be overwritten`,
100
+ fix: `${entityName}.upsertAll(rows, { onConflict: ['${tenant}', '${on.join("', '")}'] }) # or onMatch: 'nothing', which writes nothing to a row it does not own`,
75
101
  });
76
102
 
77
103
  /**
package/src/index.ts CHANGED
@@ -86,6 +86,7 @@ export { MAX_LATEST_GROUPS } from './latest-by';
86
86
  export { MAX_LOCK_KEYS } from './lock-key';
87
87
  export type { CountByOptions, Measure, MeasureFn, MeasureMap } from './measures';
88
88
  export { MAX_MEASURES } from './measures';
89
+ // Whether a memory transaction has ended: `@ultimat3/action`'s settle scope asks it, never a probe.
89
90
  export { memoryJournal } from './memory-journal';
90
91
  // How Postgres compares two values of one column, decided by the column's declared KIND. Exported
91
92
  // because `@ultimat3/query`'s matcher and in-memory source ask the same question — and a second
@@ -0,0 +1,38 @@
1
+ // Single responsibility: refuse, at a WRITE's entry, a `timestamp()` value Postgres cannot be
2
+ // handed. Never on read: an instant the server already holds — a sentinel a psql session wrote past
3
+ // year 9999 — still decodes, exactly as it did.
4
+
5
+ import { got } from './column-values';
6
+ import { instantCrosses } from './instant';
7
+ import { refuseColumn } from './refuse';
8
+ import type { AnyColumn } from './types';
9
+
10
+ const outOfRange = (value: unknown): boolean => value instanceof Date && !instantCrosses(value);
11
+
12
+ /**
13
+ * A `Date` is bound as its ISO text, and outside years 0001–9999 the server refuses that text
14
+ * (`22008`, `22007`, `22009`) while memory stored the row: one only a single driver could hold.
15
+ * Refused by both, before either — the same place a malformed `uuid` is (`narrowUuid`). Only a
16
+ * `Date` is judged: a repository write is asserted, not parsed, and `timestamp()`'s own parser has
17
+ * made every other spelling a `Date` before a row reaches here.
18
+ */
19
+ export const assertInstantsCross = (
20
+ columns: Readonly<Record<string, AnyColumn>>,
21
+ row: unknown,
22
+ ): void => {
23
+ if (typeof row !== 'object' || row === null) return;
24
+ const record = row as Readonly<Record<string, unknown>>;
25
+ for (const [property, column] of Object.entries(columns)) {
26
+ const kind =
27
+ column.$meta.kind === 'array' ? column.$meta.element?.$meta.kind : column.$meta.kind;
28
+ if (kind !== 'timestamptz') continue;
29
+ const value = record[property];
30
+ const refusedValue = Array.isArray(value) ? value.find(outOfRange) : value;
31
+ if (!outOfRange(refusedValue)) continue;
32
+ refuseColumn(
33
+ 'format',
34
+ `${property}: expected an instant in years 0001–9999, ${got(refusedValue)}`,
35
+ "new Date('2026-03-14T09:00:00Z') // timestamp() crosses to Postgres as ISO text with a four-digit year; store null on a .nullable() column for 'never', not a far-off sentinel",
36
+ );
37
+ }
38
+ };
package/src/instant.ts CHANGED
@@ -131,6 +131,20 @@ const isoInstantMicros = (text: string): bigint | undefined => {
131
131
  return local - offset * MICROS_PER_MINUTE;
132
132
  };
133
133
 
134
+ /** The first and last milliseconds `toISOString()` writes with a four-digit year, 0001 to 9999. */
135
+ const FIRST_INSTANT_MS = -62_135_596_800_000;
136
+ const LAST_INSTANT_MS = 253_402_300_799_999;
137
+
138
+ /**
139
+ * Whether a `Date` crosses to Postgres. It is bound as its ISO text, and outside years 0001–9999
140
+ * that text is one the server refuses (`22008` for year 0000, `22007`/`22009` for a signed year)
141
+ * while memory stored and compared the value: a row only one driver could hold.
142
+ */
143
+ export const instantCrosses = (value: Date): boolean => {
144
+ const ms = value.getTime();
145
+ return ms >= FIRST_INSTANT_MS && ms <= LAST_INSTANT_MS;
146
+ };
147
+
134
148
  /**
135
149
  * The microsecond epoch of whatever a sort key or an operand is holding: a decoded row's `Date`
136
150
  * (milliseconds, so the last three digits are zero), a value already counted in microseconds, the
@@ -201,8 +201,9 @@ const fill = async <Row>(
201
201
  try {
202
202
  answers = await readByIds(read, chunk);
203
203
  } catch (error) {
204
- // The statement failed, so it fails for everyone it was widened to cover — which is what
205
- // the single statement each of them would have sent would have done.
204
+ // The statement failed for a reason that is the statement's, so it fails for everyone it was
205
+ // widened to cover. A refused VALUE is not that: `readByIds` isolates the id that carried it
206
+ // (`batch-read.ts`), so the rest are answered as their own statement would have been.
206
207
  for (const id of chunk) settlers.get(keyOf(read.key.kind, id))?.({ error });
207
208
  continue;
208
209
  }
@@ -44,6 +44,14 @@ export const enrolMemoryScope = (scope: Tx, tx: Tx | undefined): void => {
44
44
  if (parent !== undefined) scopes.set(scope, parent);
45
45
  };
46
46
 
47
+ /**
48
+ * Whether a memory `tx` may still take a write — its root has neither committed nor rolled back. A
49
+ * `Tx` the memory transactor never handed out has no root here, so it answers `true`, the same pass
50
+ * `refuseIfMemoryTxClosed` gives it. Off the barrel: `@ultimat3/entity/internal/memory-tx`.
51
+ */
52
+ export const memoryTxOpen = (tx: Tx): boolean =>
53
+ (scopes.get(tx)?.outcome.value ?? 'open') === 'open';
54
+
47
55
  /** The root a memory `tx` belongs to — what a lock is held to — or `tx` itself for any other. */
48
56
  export const memoryRoot = (tx: Tx): Tx => scopes.get(tx)?.root ?? tx;
49
57
 
@@ -391,12 +391,13 @@ export const memoryRepo = <Row>(
391
391
  if (hasJsOnlyInvariant(entity.$invariants)) assertedBound(found.length, 'updateWhere');
392
392
  // The WHOLE batch is judged before any row of it lands — the same statement Postgres sends,
393
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. Postgres rolls that
395
- // statement back; here nothing was written yet, so nothing has to be undone.
394
+ // the write was a loop, and the loop stopped half way through.
396
395
  const merged = judgeUpdate(entity, found, patch, untouched(found), storeKey);
397
396
  for (const row of merged) judgeReferences(row);
398
- const written = merged.map((row, at) =>
399
- write(row, options, 'updateWhere', storeKey(found[at])),
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]))),
400
401
  );
401
402
  if (written.length <= MAX_ASSERTED_ROWS) writtenRowsSink()?.(written);
402
403
  return found.length;
@@ -422,8 +423,10 @@ export const memoryRepo = <Row>(
422
423
  });
423
424
  const merged = judgeUpdateMany(entity, plan, found, untouched(found), storeKey);
424
425
  for (const row of merged) judgeReferences(row);
425
- const written = merged.map((row, at) =>
426
- write(row, options, 'updateMany', storeKey(found[at])),
426
+ // A batch whose END state is unique can still meet a stored value part way — `c` takes `b`'s
427
+ // slug before `b` lets it go — and Postgres refuses that statement whole: so is this loop.
428
+ const written = undoingBatch(options?.tx, (tx) =>
429
+ merged.map((row, at) => write(row, { ...options, tx }, 'updateMany', storeKey(found[at]))),
427
430
  );
428
431
  if (written.length <= MAX_ASSERTED_ROWS) writtenRowsSink()?.(written);
429
432
  return written.length;
@@ -0,0 +1,5 @@
1
+ // `@ultimat3/entity/internal/memory-tx` — whether a memory transaction's root is still open, for
2
+ // `@ultimat3/action`'s settle scope. INTERNAL and a leaf on purpose: the barrel is an app's, and
3
+ // `/adapter` (the driver kit) put ten modules into every role's serve graph; this costs one.
4
+
5
+ export { memoryTxOpen } from './memory-journal';