@effect-dynamodb/schema 1.38.0 → 1.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/Aggregate.d.ts.map +1 -1
  2. package/dist/Aggregate.js +12 -0
  3. package/dist/Aggregate.js.map +1 -1
  4. package/dist/DynamoSchema.d.ts +28 -17
  5. package/dist/DynamoSchema.d.ts.map +1 -1
  6. package/dist/DynamoSchema.js +19 -13
  7. package/dist/DynamoSchema.js.map +1 -1
  8. package/dist/Entity.d.ts +64 -14
  9. package/dist/Entity.d.ts.map +1 -1
  10. package/dist/Entity.js +59 -0
  11. package/dist/Entity.js.map +1 -1
  12. package/dist/Errors.d.ts +0 -27
  13. package/dist/Errors.d.ts.map +1 -1
  14. package/dist/Errors.js +0 -24
  15. package/dist/Errors.js.map +1 -1
  16. package/dist/KeyComposer.d.ts +212 -12
  17. package/dist/KeyComposer.d.ts.map +1 -1
  18. package/dist/KeyComposer.js +488 -86
  19. package/dist/KeyComposer.js.map +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +1 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/internal/KeyText136.d.ts +56 -131
  25. package/dist/internal/KeyText136.d.ts.map +1 -1
  26. package/dist/internal/KeyText136.js +123 -264
  27. package/dist/internal/KeyText136.js.map +1 -1
  28. package/dist/internal/NumericKey.d.ts +8 -0
  29. package/dist/internal/NumericKey.d.ts.map +1 -1
  30. package/dist/internal/NumericKey.js +45 -0
  31. package/dist/internal/NumericKey.js.map +1 -1
  32. package/dist/internal/Shards.d.ts +47 -0
  33. package/dist/internal/Shards.d.ts.map +1 -0
  34. package/dist/internal/Shards.js +60 -0
  35. package/dist/internal/Shards.js.map +1 -0
  36. package/dist/internal/SharedKeyAttribute.d.ts +48 -0
  37. package/dist/internal/SharedKeyAttribute.d.ts.map +1 -0
  38. package/dist/internal/SharedKeyAttribute.js +173 -0
  39. package/dist/internal/SharedKeyAttribute.js.map +1 -0
  40. package/package.json +2 -1
@@ -8,6 +8,7 @@
8
8
  import { DateTime } from "effect";
9
9
  import { applyCasing, composeClusteredSortKey, composeCollectionKey, composeIsolatedSortKey, composeKey, KEY_DELIMITER, } from "./DynamoSchema.js";
10
10
  import { encodeBigInt, encodeNumber } from "./internal/NumericKey.js";
11
+ import { MAX_SHARD_COUNT, ShardSourceError, shardMarker, shardOf } from "./internal/Shards.js";
11
12
  import { concatBytes, interleave, prefixSegment, toBytes, } from "./internal/ZOrderCurve.js";
12
13
  import { declareDimension } from "./internal/ZOrderDimension.js";
13
14
  /** Is this sort key half a Z-order one? */
@@ -28,6 +29,61 @@ export const assertCollectionCasingAgreement = (collectionName, members) => {
28
29
  `\`casing\` on every member.`);
29
30
  }
30
31
  };
32
+ /**
33
+ * Fail when a collection's members would read different partitions (#183). They
34
+ * share one physical index and one logical key, so they must agree on how many
35
+ * partitions it is spread over and on the layout being migrated from. `by` may
36
+ * differ: each member hashes its own source, into the same partitions.
37
+ */
38
+ export const assertCollectionShardsAgreement = (collectionName, members) => {
39
+ const layout = (member) => `${member.index.shards?.count ?? "unsharded"}/${member.index.shards?.previous ?? "none"}`;
40
+ if (new Set(members.map(layout)).size > 1) {
41
+ const shown = members.map((member) => {
42
+ const { count, previous } = member.index.shards ?? {};
43
+ return `${member.key}: ${count === undefined ? "unsharded" : `count ${count}`}${previous === undefined ? "" : `, previous ${previous}`}`;
44
+ });
45
+ throw new Error(`[EDD-9103] Collection "${collectionName}" members spread its index differently ` +
46
+ `(${shown.join("; ")}). They share one logical partition, so a query has to read one ` +
47
+ `set of partitions: give the collection's index the same \`shards\` count and \`previous\` ` +
48
+ `on every member.`);
49
+ }
50
+ };
51
+ const shardsMalformed = (index, why) => new Error(`[EDD-9099] Index "${index}" declares malformed shards: ${why}`);
52
+ /** Normalise and check a declared `shards` (the rest is `Entity.make`'s, which has the model). */
53
+ const normalizeShards = (index, declared) => {
54
+ const config = typeof declared === "number" ? { count: declared } : declared;
55
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
56
+ throw shardsMalformed(index, "pass a count, or { count, by?, previous? }.");
57
+ }
58
+ const unknownKeys = Object.keys(config).filter((key) => key !== "count" && key !== "by" && key !== "previous");
59
+ if (unknownKeys.length > 0) {
60
+ throw shardsMalformed(index, `unknown option ${unknownKeys.map((key) => `"${key}"`).join(", ")}: it takes count, by and previous.`);
61
+ }
62
+ const { count, by, previous } = config;
63
+ if (typeof count !== "number" ||
64
+ !Number.isInteger(count) ||
65
+ count < 2 ||
66
+ count > MAX_SHARD_COUNT) {
67
+ throw shardsMalformed(index, `count ${JSON.stringify(count)} must be an integer from 2 to ${MAX_SHARD_COUNT}.`);
68
+ }
69
+ if (previous !== undefined) {
70
+ if (typeof previous !== "number" || !Number.isInteger(previous) || previous < 1) {
71
+ throw shardsMalformed(index, `previous ${JSON.stringify(previous)} must be a positive integer: 1 for the unsharded key, or the old count.`);
72
+ }
73
+ if (previous === count) {
74
+ throw shardsMalformed(index, `previous ${previous} equals count: it names the layout being migrated from, which has to differ.`);
75
+ }
76
+ if (previous > MAX_SHARD_COUNT) {
77
+ throw shardsMalformed(index, `previous ${previous} is above ${MAX_SHARD_COUNT}.`);
78
+ }
79
+ }
80
+ return {
81
+ count,
82
+ by: by === undefined ? undefined : [...by],
83
+ previous,
84
+ source: undefined,
85
+ };
86
+ };
31
87
  /** Normalize a GsiConfig (entity input) to an IndexDefinition (internal format). */
32
88
  export const normalizeGsiConfig = (config) => {
33
89
  // Detect old format and give helpful migration error
@@ -54,6 +110,7 @@ export const normalizeGsiConfig = (config) => {
54
110
  : { field: sk.field, composite: [...sk.composite] },
55
111
  ...(config.casing !== undefined && { casing: config.casing }),
56
112
  ...(config.indexPolicy !== undefined && { indexPolicy: config.indexPolicy }),
113
+ ...(config.shards !== undefined && { shards: normalizeShards(config.name, config.shards) }),
57
114
  };
58
115
  };
59
116
  const zorderMalformed = (index, why) => new Error(`[EDD-9086] Index "${index}" declares a malformed Z-order sort key: ${why}`);
@@ -141,8 +198,28 @@ export const tryExtractComposites = (composite, record) => {
141
198
  }
142
199
  return values;
143
200
  };
201
+ /** A value's composite text, its numbers by `number` and `bigint`. */
202
+ const serializeWith = (value, number, bigint) => {
203
+ if (typeof value === "string")
204
+ return value;
205
+ if (typeof value === "number")
206
+ return number(value);
207
+ if (typeof value === "bigint")
208
+ return bigint(value);
209
+ if (typeof value === "boolean")
210
+ return value ? "true" : "false";
211
+ // DateTime types → ISO string (Zoned normalized to UTC for sort order)
212
+ if (typeof value === "object" && value !== null && DateTime.isDateTime(value)) {
213
+ return DateTime.formatIso(value);
214
+ }
215
+ // Native Date
216
+ if (value instanceof Date)
217
+ return value.toISOString();
218
+ return String(value);
219
+ };
144
220
  /**
145
- * Serialize a value for use in a composite key.
221
+ * Serialize a value for a composite key under `escapeKeys: true`. {@link compositeText} is the
222
+ * text under a schema's setting.
146
223
  *
147
224
  * Numeric values are encoded so their key text sorts in numeric order
148
225
  * (`internal/NumericKey.ts` has the format):
@@ -159,33 +236,27 @@ export const tryExtractComposites = (composite, record) => {
159
236
  * - DateTime.Utc → ISO string
160
237
  * - Date → ISO string
161
238
  */
162
- export const serializeValue = (value) => {
163
- if (typeof value === "string")
164
- return value;
165
- if (typeof value === "number")
166
- return encodeNumber(value);
167
- if (typeof value === "bigint")
168
- return encodeBigInt(value);
169
- if (typeof value === "boolean")
170
- return value ? "true" : "false";
171
- // DateTime types → ISO string (Zoned normalized to UTC for sort order)
172
- if (typeof value === "object" && value !== null && DateTime.isDateTime(value)) {
173
- return DateTime.formatIso(value);
174
- }
175
- // Native Date
176
- if (value instanceof Date)
177
- return value.toISOString();
178
- return String(value);
179
- };
180
- /** The highest code point a sort key composite's text escapes: `%`. */
239
+ export const serializeValue = (value) => serializeWith(value, encodeNumber, encodeBigInt);
240
+ /**
241
+ * A composite value's text with `escapeKeys` off, the text 1.36 composed: a number zero-padded to
242
+ * 16 characters and a bigint to 38 (`String(n)` padded, so `-3` is `00000000000000-3` and `2.5` is
243
+ * `00000000000002.5`). Never throws: `NaN` is `0000000000000NaN`.
244
+ */
245
+ export const serializeValue136 = (value) => serializeWith(value, (n) => String(n).padStart(16, "0"), (n) => String(n).padStart(38, "0"));
246
+ /** A composite value's serialized text under the schema's setting, before casing and escaping. */
247
+ export const compositeText = (schema, value) => schema.escapeKeys === true || schema.numericKeyText === true
248
+ ? serializeValue(value)
249
+ : serializeValue136(value);
250
+ /** The highest code point a key composite's text escapes: `%`. */
181
251
  const ESCAPED_MAX = 0x25;
182
252
  /**
183
- * A composite value's serialized text as a sort key holds it (#171): cased,
253
+ * A composite value's serialized text as a key holds it (#171, #183): cased,
184
254
  * then each code point U+0000–U+0025 — control characters, space, `!`, `"`,
185
255
  * `#`, `$` and `%` — escaped as `%` and two hex digits (space → `%20`, `#` →
186
256
  * `%23`, `%` → `%25`), the hex digits in upper case, or lower case under
187
257
  * `"lowercase"` casing. Any other text is unchanged, so a value without such a
188
- * character keeps its 1.36 key text.
258
+ * character keeps its 1.36 key text. The same rule holds in a partition key and
259
+ * a sort key, so the two build identical text from identical values.
189
260
  *
190
261
  * Every escaped value sorts as its cased value and starts with its cased
191
262
  * prefixes' text: an unescaped character sorts above `%`, and an escape starts
@@ -197,7 +268,7 @@ const ESCAPED_MAX = 0x25;
197
268
  * Casing comes first so the hex digits are the only text it can't reach: the
198
269
  * composer cases the key again, which leaves cased text as it is.
199
270
  */
200
- export const sortKeyText = (text, casing) => {
271
+ export const escapeKeyText = (text, casing) => {
201
272
  const cased = applyCasing(text, casing);
202
273
  let escaped = "";
203
274
  let from = 0;
@@ -211,10 +282,33 @@ export const sortKeyText = (text, casing) => {
211
282
  }
212
283
  return from === 0 ? cased : `${escaped}${cased.slice(from)}`;
213
284
  };
214
- /** A composite value's text in a sort key: {@link serializeValue}, then {@link sortKeyText}. */
215
- export const serializeSortKeyValue = (value, casing) => sortKeyText(serializeValue(value), casing);
216
- /** {@link extractComposites} for a sort key half: each value's {@link sortKeyText}. */
217
- const extractSortKeyComposites = (composite, record, casing) => extractComposites(composite, record).map((text) => sortKeyText(text, casing));
285
+ /** The text {@link escapeKeyText} escaped back, cased: for `rekey`, reading a value out of a key. */
286
+ export const unescapeKeyText = (text) => text.replace(/%([0-9a-fA-F]{2})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
287
+ /**
288
+ * @deprecated since 1.39.0: escaping is `escapeKeys: true`'s, in every key. Use {@link keyText},
289
+ * which follows the setting, or {@link escapeKeyText}, the same function under its new name.
290
+ */
291
+ export const sortKeyText = (text, casing) => escapeKeyText(text, casing);
292
+ /**
293
+ * @deprecated since 1.39.0: escaping is `escapeKeys: true`'s, in every key. Use
294
+ * {@link keyValueText}, which follows the setting.
295
+ */
296
+ export const serializeSortKeyValue = (value, casing) => escapeKeyText(serializeValue(value), casing);
297
+ /**
298
+ * A composite's serialized text in a key: cased, and with `escapeKeys: true`
299
+ * {@link escapeKeyText}. Every key composite passes through here, in every key.
300
+ */
301
+ export const keyText = (schema, text, casing) => (schema.escapeKeys === true ? escapeKeyText(text, casing) : applyCasing(text, casing));
302
+ /** A composite value's text in a key: {@link compositeText}, then {@link keyText}. */
303
+ export const keyValueText = (schema, value, casing) => keyText(schema, compositeText(schema, value), casing);
304
+ /** {@link extractComposites} under the schema's setting, each value's {@link keyValueText}. */
305
+ export const extractKeyComposites = (schema, index, composite, record) => composite.map((attr) => {
306
+ const value = record[attr];
307
+ if (value === undefined || value === null) {
308
+ throw new Error(`Missing composite attribute "${attr}" in record`);
309
+ }
310
+ return keyValueText(schema, value, index.casing ?? schema.casing);
311
+ });
218
312
  /**
219
313
  * Compose a partition key for an entity index.
220
314
  *
@@ -222,16 +316,172 @@ const extractSortKeyComposites = (composite, record, casing) => extractComposite
222
316
  * For collection indexes: `$schema#v<version>#collectionName#attr1#attr2`
223
317
  */
224
318
  export const composePk = (schema, entityType, index, record) => {
225
- const composites = extractComposites(index.pk.composite, record);
226
- const names = [...index.pk.composite];
319
+ const composites = extractKeyComposites(schema, index, index.pk.composite, record);
320
+ return composePkText(schema, entityType, index, composites, index.pk.composite, composedShardMarker(entityType, index, record));
321
+ };
322
+ /**
323
+ * The text of a partition key: the entity type or collection name, the marker
324
+ * of a sharded index (design §2), then the composites.
325
+ */
326
+ const composePkText = (schema, entityType, index, composites, names, marker) => {
227
327
  const collection = index.collection;
228
- if (collection !== undefined) {
229
- // Collection index — PK uses collection name
230
- const collectionName = Array.isArray(collection) ? collection[0] : collection;
231
- return composeCollectionKey(schema, collectionName, composites, { casing: index.casing, names });
328
+ // Collection index — PK uses collection name; regular index — entity type.
329
+ const label = collection === undefined
330
+ ? entityType
331
+ : Array.isArray(collection)
332
+ ? collection[0]
333
+ : collection;
334
+ const spelled = marker === undefined ? label : `${label}${KEY_DELIMITER}${marker}`;
335
+ const options = { casing: index.casing, names: [...names] };
336
+ return collection === undefined
337
+ ? composeKey(schema, spelled, composites, options)
338
+ : composeCollectionKey(schema, spelled, composites, options);
339
+ };
340
+ /**
341
+ * The marker of the shard `record` hashes to; `undefined` on an unsharded index.
342
+ * Throws `[EDD-9100]` when the source is missing: a sharded index never composes
343
+ * an unsharded partition key, so a write can't go wrong by forgetting it.
344
+ */
345
+ const composedShardMarker = (entityType, index, record) => {
346
+ const shards = index.shards;
347
+ if (shards === undefined)
348
+ return undefined;
349
+ const source = boundShardSource(index, shards);
350
+ const absent = source.filter((attr) => record[attr] === undefined || record[attr] === null);
351
+ if (absent.length > 0) {
352
+ throw new ShardSourceError({
353
+ message: `[EDD-9100] Entity "${entityType}": index "${index.index}" is sharded, and its partition ` +
354
+ `key can't be composed without the shard source: ${absent.map((attr) => `"${attr}"`).join(", ")} ` +
355
+ `missing. A sharded index never composes an unsharded key, so nothing was written. ` +
356
+ `Include ${absent.length === 1 ? "it" : "them"} in the write.`,
357
+ });
232
358
  }
233
- // Regular entity index — PK uses entity type
234
- return composeKey(schema, entityType, composites, { casing: index.casing, names });
359
+ return shardMarker(shards.count, shardOf(source.map((attr) => serializeValue(record[attr])), shards.count));
360
+ };
361
+ /**
362
+ * `index` as its unsharded layout: what a `previous: 1` migration reads, and the
363
+ * only layout rows under another setting's key text can be in. Reads only.
364
+ */
365
+ export const unshardedView = (index) => {
366
+ if (index.shards === undefined)
367
+ return index;
368
+ const { shards: _shards, ...view } = index;
369
+ return view;
370
+ };
371
+ /**
372
+ * The partition key a stored row's values compose now, for `rekey` (#183): by the
373
+ * structural rule an update composes with, truncated included. `undefined` when
374
+ * they can't compose one: a hole, no leading composite, or the source missing.
375
+ */
376
+ export const composeStoredPk = (schema, entityType, index, record) => {
377
+ const outcome = classifyHalf(index.pk.composite, record, "sparse", false);
378
+ if (outcome.kind !== "set")
379
+ return undefined;
380
+ const shards = index.shards;
381
+ if (shards !== undefined &&
382
+ !boundShardSource(index, shards).every((attr) => hasValue(record[attr]))) {
383
+ return undefined;
384
+ }
385
+ return outcome.length === index.pk.composite.length
386
+ ? composePk(schema, entityType, index, record)
387
+ : composePkPrefixUpTo(schema, entityType, index, record, outcome.length);
388
+ };
389
+ /**
390
+ * The index key a row's values compose now, truncating a half whose trailing
391
+ * composites are absent as the structural rule does (`DESIGN.md §7`). `undefined`
392
+ * when a half can't compose (a hole, or no leading value) or the sort key is a
393
+ * binary Z-order address.
394
+ */
395
+ export const tryComposeStructuralKeys = (schema, entityType, entityVersion, index, record) => {
396
+ if (isZOrderHalf(index.sk))
397
+ return undefined;
398
+ const pk = classifyHalf(index.pk.composite, record, "sparse", false);
399
+ const sk = classifyHalf(index.sk.composite, record, "sparse", false);
400
+ if (pk.kind !== "set" || sk.kind !== "set")
401
+ return undefined;
402
+ return {
403
+ pk: pk.length === index.pk.composite.length
404
+ ? composePk(schema, entityType, index, record)
405
+ : composePkPrefixUpTo(schema, entityType, index, record, pk.length),
406
+ sk: sk.length === index.sk.composite.length
407
+ ? composeSk(schema, entityType, entityVersion, index, record)
408
+ : composeSkPrefixUpTo(schema, entityType, entityVersion, index, record, sk.length),
409
+ };
410
+ };
411
+ /**
412
+ * Does stored partition key text lie in `index`'s current layout (#183): shard
413
+ * marker with this count, whatever shard? A row whose values can't compose its key
414
+ * can only be left alone when this holds.
415
+ */
416
+ export const isCurrentShardLayout = (schema, entityType, index, stored) => index.shards !== undefined &&
417
+ stored.startsWith(composePkText(schema, entityType, index, [], [], `!${index.shards.count}.`));
418
+ const boundShardSource = (index, shards) => {
419
+ if (shards.source === undefined) {
420
+ throw new Error(`KeyComposer: sharded index "${index.index}" was never bound to an entity — Entity.make ` +
421
+ `binds a sharded index's source to the primary key composites or \`by\`.`);
422
+ }
423
+ return shards.source;
424
+ };
425
+ /**
426
+ * Do the pins in `record` name every attribute of the shard source? A pin is a
427
+ * partition key composite or part of the sort key's leading run of present values:
428
+ * what a key condition can select. A value elsewhere in `record` selects nothing,
429
+ * and reading one shard for it would lose the rows of the others.
430
+ */
431
+ const pinsShardSource = (index, source, record) => {
432
+ const pins = new Set(index.pk.composite);
433
+ if (!isZOrderHalf(index.sk)) {
434
+ for (const attr of index.sk.composite) {
435
+ if (!hasValue(record[attr]))
436
+ break;
437
+ pins.add(attr);
438
+ }
439
+ }
440
+ return source.every((attr) => pins.has(attr) && hasValue(record[attr]));
441
+ };
442
+ /**
443
+ * The partitions a query of `index` reads for the pinned composites in `record`,
444
+ * in merge order: the current layout's by shard number (one, when every attribute
445
+ * of the shard source is pinned, whether that source is `by` or the primary key),
446
+ * then the `previous` layout's, which are never pruned: the old source isn't
447
+ * recorded. Every read path uses this; {@link composePk} composes the one key a
448
+ * write stores.
449
+ */
450
+ export const composeReadPartitions = (schema, entityType, index, record,
451
+ /** `false`: read every shard, whatever is pinned (a collection's members may differ). */
452
+ options) => {
453
+ const shards = index.shards;
454
+ if (shards === undefined) {
455
+ return { partitions: [composePk(schema, entityType, index, record)], fanOut: undefined };
456
+ }
457
+ const source = boundShardSource(index, shards);
458
+ const composites = extractKeyComposites(schema, index, index.pk.composite, record);
459
+ const partition = (count, shard) => composePkText(schema, entityType, index, composites, index.pk.composite, shardMarker(count, shard));
460
+ const layout = (count) => Array.from({ length: count }, (_, i) => partition(count, i));
461
+ const pruned = options?.prune !== false && pinsShardSource(index, source, record);
462
+ const current = pruned
463
+ ? [
464
+ partition(shards.count, shardOf(source.map((attr) => serializeValue(record[attr])), shards.count)),
465
+ ]
466
+ : layout(shards.count);
467
+ const unsharded = shards.previous === 1
468
+ ? composePkText(schema, entityType, index, composites, index.pk.composite, undefined)
469
+ : undefined;
470
+ const previous = unsharded !== undefined
471
+ ? [unsharded]
472
+ : shards.previous === undefined
473
+ ? []
474
+ : layout(shards.previous);
475
+ return {
476
+ partitions: [...current, ...previous],
477
+ fanOut: {
478
+ count: shards.count,
479
+ source,
480
+ previous: shards.previous,
481
+ pruned,
482
+ everyPartition: pruned ? [...layout(shards.count), ...previous] : undefined,
483
+ },
484
+ };
235
485
  };
236
486
  /**
237
487
  * Compose a sort key for an entity index.
@@ -242,7 +492,7 @@ export const composePk = (schema, entityType, index, record) => {
242
492
  */
243
493
  export const composeSk = (schema, entityType, entityVersion, index, record) => {
244
494
  assertStringHalf(index, "composeSk");
245
- const composites = extractSortKeyComposites(index.sk.composite, record, effectiveCasing(schema, index));
495
+ const composites = extractKeyComposites(schema, index, index.sk.composite, record);
246
496
  const names = [...index.sk.composite];
247
497
  const collection = index.collection;
248
498
  const collectionType = index.type ?? "isolated";
@@ -301,7 +551,7 @@ export const composeZOrderSk = (schema, index, record) => {
301
551
  if (value === undefined || value === null) {
302
552
  throw new Error(`Missing composite attribute "${part.field}" in record`);
303
553
  }
304
- return prefixSegment(serializeSortKeyValue(value, casing), part.hash);
554
+ return prefixSegment(keyValueText(schema, value, casing), part.hash);
305
555
  });
306
556
  const levels = layout.dimensions.map((dim) => {
307
557
  const value = record[dim.field];
@@ -384,19 +634,7 @@ export const composeAllKeys = (schema, entityType, entityVersion, indexes, recor
384
634
  */
385
635
  const composePkPrefixUpTo = (schema, entityType, index, record, stopBefore) => {
386
636
  const slice = index.pk.composite.slice(0, stopBefore);
387
- const composites = extractComposites(slice, record);
388
- const collection = index.collection;
389
- if (collection !== undefined) {
390
- const collectionName = Array.isArray(collection) ? collection[0] : collection;
391
- return composeCollectionKey(schema, collectionName, composites, {
392
- casing: index.casing,
393
- names: [...slice],
394
- });
395
- }
396
- return composeKey(schema, entityType, composites, {
397
- casing: index.casing,
398
- names: [...slice],
399
- });
637
+ return composePkText(schema, entityType, index, extractKeyComposites(schema, index, slice, record), slice, composedShardMarker(entityType, index, record));
400
638
  };
401
639
  /**
402
640
  * Compose a sort key from the leading prefix `[sk_0, ..., sk_(stopBefore-1)]`
@@ -414,7 +652,7 @@ const composePkPrefixUpTo = (schema, entityType, index, record, stopBefore) => {
414
652
  export const composeSkPrefixUpTo = (schema, entityType, entityVersion, index, record, stopBefore) => {
415
653
  assertStringHalf(index, "composeSkPrefixUpTo");
416
654
  const slice = index.sk.composite.slice(0, stopBefore);
417
- const composites = extractSortKeyComposites(slice, record, effectiveCasing(schema, index));
655
+ const composites = extractKeyComposites(schema, index, slice, record);
418
656
  const collection = index.collection;
419
657
  const collectionType = index.type ?? "isolated";
420
658
  if (collection !== undefined) {
@@ -518,6 +756,79 @@ const classifyZOrderHalf = (fields, record, policy, halfHasRemoved) => {
518
756
  return "drop";
519
757
  return "noop";
520
758
  };
759
+ const hasValue = (value) => value !== undefined && value !== null;
760
+ /**
761
+ * The per-half gate's question for a half with composites: does this writer name
762
+ * none of them, while the half can't be recomposed from what it knows? Then the
763
+ * half belongs to some other writer, and its stored key stays as it is.
764
+ */
765
+ const writerLeavesHalf = (composites, updatePayload, keyRecord) => composites.every((attr) => !(attr in updatePayload)) &&
766
+ composites.some((attr) => !hasValue(keyRecord[attr]));
767
+ /**
768
+ * The PK half's outcome on a sharded index, from what {@link classifyHalf} says
769
+ * of its composites and what the update did to the shard source (design §5). On
770
+ * an unsharded index, that outcome as it is.
771
+ *
772
+ * A write that would leave the shard stale or need an unsharded key throws
773
+ * `[EDD-9100]`; a `by` attribute explicitly gone drops the entry, which writes no
774
+ * unsharded key; and an update that doesn't touch the source leaves the stored
775
+ * key alone.
776
+ */
777
+ const shardedPkOutcome = (entityType, index, outcome, update) => {
778
+ const shards = index.shards;
779
+ if (shards === undefined)
780
+ return outcome;
781
+ const { merged, updatePayload, policy } = update;
782
+ const pkComposites = index.pk.composite;
783
+ const refuse = () => {
784
+ if (update.onMissing === "keep")
785
+ return { kind: "noop" };
786
+ const absent = boundShardSource(index, shards).filter((attr) => !hasValue(merged[attr]));
787
+ const missing = absent.length > 0 ? absent : pkComposites.filter((a) => !hasValue(merged[a]));
788
+ throw new ShardSourceError({
789
+ message: `[EDD-9100] Entity "${entityType}": this update changes what index "${index.index}" is ` +
790
+ `sharded by, and its partition key can't be composed without ` +
791
+ `${missing.map((attr) => `"${attr}"`).join(", ")}. The stored shard would go stale, so ` +
792
+ `nothing was written. Include ${missing.length === 1 ? "it" : "them"} in the update.`,
793
+ });
794
+ };
795
+ if (update.byRemoved)
796
+ return { kind: "drop" };
797
+ if (outcome.kind === "drop") {
798
+ const pkExplicitlyGone = update.pkHasRemoved ||
799
+ pkComposites.some((attr) => attr in updatePayload && !hasValue(updatePayload[attr]));
800
+ return update.byTouched && !pkExplicitlyGone ? refuse() : outcome;
801
+ }
802
+ if (outcome.kind === "noop")
803
+ return update.byTouched ? refuse() : outcome;
804
+ if (boundShardSource(index, shards).every((attr) => hasValue(merged[attr]))) {
805
+ // The shard follows `by`, and the sort key would stay at the old value: no pin
806
+ // could reach the row, since each searches the shard its own value hashes to and
807
+ // only the old value's text is stored. The update may name the value the row
808
+ // already holds, but nothing was read to tell.
809
+ if (update.byTouched && update.skKept) {
810
+ if (update.onMissing === "keep")
811
+ return { kind: "noop" };
812
+ const missing = index.sk.composite.filter((attr) => !hasValue(merged[attr]));
813
+ throw new ShardSourceError({
814
+ message: `[EDD-9100] Entity "${entityType}": this update changes what index "${index.index}" is ` +
815
+ `sharded by, and its sort key can't be composed without ` +
816
+ `${missing.map((attr) => `"${attr}"`).join(", ")}. The stored sort key would stay at ` +
817
+ `the old value in the new value's shard, where no query could find it, so nothing was ` +
818
+ `written. Include ${missing.length === 1 ? "it" : "them"} in the update, or .remove() ` +
819
+ `${missing.length === 1 ? "it" : "them"} to take the item out of the index.`,
820
+ });
821
+ }
822
+ return outcome;
823
+ }
824
+ if (update.byCleared && policy === "sparse")
825
+ return { kind: "drop" };
826
+ // The source is incomplete: an update changing the partition or part of `by`
827
+ // can't compute the shard; any other leaves the stored key alone.
828
+ return update.byTouched || pkComposites.some((attr) => hasValue(updatePayload[attr]))
829
+ ? refuse()
830
+ : { kind: "noop" };
831
+ };
521
832
  /**
522
833
  * Resolve the per-half policy for an index. Defaults each half to `"preserve"`
523
834
  * when omitted (or when `indexPolicy` is omitted entirely).
@@ -537,10 +848,11 @@ const resolveIndexPolicy = (policy) => ({
537
848
  * protection: prevent writer A from clobbering keys for halves it doesn't
538
849
  * own when writer B does own them. The skip-predicate states that purpose
539
850
  * directly: skip iff multi-writer protection actually applies (the half has
540
- * composites, no composite was explicitly removed, and every composite is
541
- * absent from BOTH `updatePayload` AND `keyRecord` — so this writer is
542
- * genuinely not claiming ownership of this half on this call). If the half
543
- * cannot be safely skipped, it is evaluated by the structural rule.
851
+ * composites, no composite was explicitly removed, none is in `updatePayload`,
852
+ * and at least one is unknown to `keyRecord` — so this writer is genuinely not
853
+ * claiming ownership of this half on this call, and can't recompose it to the
854
+ * value it already holds). If the half cannot be safely skipped, it is evaluated
855
+ * by the structural rule.
544
856
  *
545
857
  * Pre-v1.7.3 the predicate was inverted ("list cases for which to evaluate"
546
858
  * as a chain of `||` clauses) and had to enumerate every shape: payload
@@ -550,7 +862,9 @@ const resolveIndexPolicy = (policy) => ({
550
862
  * PK-composites-only case (#43), v1.7.2 then missed the empty-composite-half
551
863
  * case (#46) because every `.some(...)` clause trivially returned `false`
552
864
  * for an empty composite array. The skip-predicate closes the entire class
553
- * of degenerate-case bugs structurally.
865
+ * of degenerate-case bugs structurally. Through v1.37 its `keyRecord` arm asked
866
+ * whether *every* composite was absent, so one entity-PK composite woke a half
867
+ * that mixes it with a mutable composite (#183: `DESIGN.md §7`, shape 10).
554
868
  *
555
869
  * **Two-way payload classification.**
556
870
  * - **present** (`attr: <value>` in payload, or inherited from `keyRecord`)
@@ -607,24 +921,36 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
607
921
  // skipping would just leave a missing key forever — closes #46),
608
922
  // - AND no composite of this half was explicitly removed (cascade
609
923
  // intent must always evaluate),
610
- // - AND every composite is absent from BOTH `updatePayload` AND
611
- // `keyRecord` (so this writer is genuinely not claiming ownership
612
- // of this half on this call — preserves the v1.7.1 multi-writer
613
- // fix #41 and the v1.7.2 PK-composites-only fix #43, since
614
- // entity-PK composites are always present in `keyRecord`).
924
+ // - AND no composite is in `updatePayload` (this writer names none of
925
+ // them, so it claims no ownership of this half — #41),
926
+ // - AND some composite is unknown to `keyRecord` (so the half can't be
927
+ // recomposed to the value it already has). Every composite known
928
+ // means a SET the writer can't get wrong: entity-PK composites are
929
+ // immutable, which keeps #43's PK-composites-only half composing on
930
+ // every write. One known composite proves nothing: a half mixing an
931
+ // entity-PK composite with a mutable one is not this writer's to
932
+ // truncate or drop on an unrelated write (see `DESIGN.md §7`, shape 10).
615
933
  //
616
- // The negation `!shouldSkip` is observably equivalent to the previous
617
- // touched-predicate `||`-chain extended with `composites.length === 0`:
618
- // every fix the touched-predicate accumulated falls out of one of the
619
- // skip-predicate's three structural conditions. See `DESIGN.md §7`.
934
+ // See `DESIGN.md §7`.
620
935
  const pkHasRemoved = removedSet !== undefined && pkComposites.some((attr) => removedSet.has(attr));
621
936
  const skHasRemoved = removedSet !== undefined && skComposites.some((attr) => removedSet.has(attr));
622
- const skipPk = pkComposites.length > 0 &&
623
- !pkHasRemoved &&
624
- pkComposites.every((attr) => !(attr in updatePayload) && !(attr in keyRecord));
937
+ // A `by` attribute (#183) is a dependency of the PK half, when the writer
938
+ // touches it: the shard follows its value. Its presence in `keyRecord` is no
939
+ // evidence of a change. The retain path's holds the whole item.
940
+ const by = index.shards?.by ?? [];
941
+ const byTouched = by.some((attr) => hasValue(updatePayload[attr]));
942
+ const byCleared = by.some((attr) => attr in updatePayload && !hasValue(updatePayload[attr]));
943
+ const byRemoved = removedSet !== undefined && by.some((attr) => removedSet.has(attr));
944
+ // An empty PK half is a constant prefix, unless `by` makes its marker vary.
945
+ const skipPk = (pkComposites.length > 0
946
+ ? !pkHasRemoved && writerLeavesHalf(pkComposites, updatePayload, keyRecord)
947
+ : by.length > 0 && by.some((attr) => !hasValue(keyRecord[attr]))) &&
948
+ !byTouched &&
949
+ !byCleared &&
950
+ !byRemoved;
625
951
  const skipSk = skComposites.length > 0 &&
626
952
  !skHasRemoved &&
627
- skComposites.every((attr) => !(attr in updatePayload) && !(attr in keyRecord));
953
+ writerLeavesHalf(skComposites, updatePayload, keyRecord);
628
954
  if (skipPk && skipSk)
629
955
  continue;
630
956
  // Build merged record for value extraction. Two-way classification: any
@@ -647,8 +973,22 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
647
973
  }
648
974
  }
649
975
  const policy = resolveIndexPolicy(index.indexPolicy);
976
+ // A Z-order half is never a `by` source, so only a text half can disagree.
977
+ const skKept = !skipSk &&
978
+ !isZOrderHalf(index.sk) &&
979
+ classifyHalf(skComposites, merged, policy.sk, skHasRemoved).kind === "noop";
650
980
  if (!skipPk) {
651
- const pkOutcome = classifyHalf(pkComposites, merged, policy.pk, pkHasRemoved);
981
+ const pkOutcome = shardedPkOutcome(entityType, index, classifyHalf(pkComposites, merged, policy.pk, pkHasRemoved), {
982
+ merged,
983
+ updatePayload,
984
+ policy: policy.pk,
985
+ pkHasRemoved,
986
+ byTouched,
987
+ byCleared,
988
+ byRemoved,
989
+ onMissing: options?.onMissingShardSource ?? "fail",
990
+ skKept,
991
+ });
652
992
  if (pkOutcome.kind === "drop") {
653
993
  removes.push(index.pk.field);
654
994
  }
@@ -683,7 +1023,21 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
683
1023
  // noop — emit nothing for this half.
684
1024
  }
685
1025
  }
686
- return { sets, removes };
1026
+ // No part of the primary key is ever set or removed by an update, whatever the index
1027
+ // structure (`DESIGN.md §7`). A half stored in a table key attribute (a local index's
1028
+ // partition key, an inverted index, a sort key shared with the table) composes the
1029
+ // table's text from what an update can't change, so there is nothing to write; dropping
1030
+ // the entry takes only the other half. A half reads as dropped here only for a row an
1031
+ // earlier release's `.remove()` left without a composite, which a move from other key text
1032
+ // recomposes from: it keeps its key.
1033
+ const primary = indexes.primary;
1034
+ if (primary === undefined)
1035
+ return { sets, removes };
1036
+ const tableKey = new Set([primary.pk.field, primary.sk.field]);
1037
+ return {
1038
+ sets: Object.fromEntries(Object.entries(sets).filter(([field]) => !tableKey.has(field))),
1039
+ removes: removes.filter((field) => !tableKey.has(field)),
1040
+ };
687
1041
  };
688
1042
  // ---------------------------------------------------------------------------
689
1043
  // Vector index partition composition
@@ -703,13 +1057,9 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
703
1057
  * sparse index semantics leave it out of the index.
704
1058
  */
705
1059
  export const tryComposeVectorPartition = (schema, entityType, index, record) => {
706
- const composites = tryExtractComposites(index.partition, record);
707
- if (composites === undefined)
1060
+ if (tryExtractComposites(index.partition, record) === undefined)
708
1061
  return undefined;
709
- return composeKey(schema, entityType, composites, {
710
- casing: index.casing,
711
- names: [...index.partition],
712
- });
1062
+ return composeVectorPartition(schema, entityType, index, record);
713
1063
  };
714
1064
  /**
715
1065
  * Throwing variant of {@link tryComposeVectorPartition}. Used on the search
@@ -717,7 +1067,7 @@ export const tryComposeVectorPartition = (schema, entityType, index, record) =>
717
1067
  * sparse-index outcome.
718
1068
  */
719
1069
  export const composeVectorPartition = (schema, entityType, index, record) => {
720
- const composites = extractComposites(index.partition, record);
1070
+ const composites = extractKeyComposites(schema, index, index.partition, record);
721
1071
  return composeKey(schema, entityType, composites, {
722
1072
  casing: index.casing,
723
1073
  names: [...index.partition],
@@ -778,6 +1128,38 @@ export const composeSortKeyBeginsWith = (schema, entityType, entityVersion, inde
778
1128
  const complete = availableSkCount(index, record) === index.sk.composite.length;
779
1129
  return complete ? prefix : `${prefix}${KEY_DELIMITER}`;
780
1130
  };
1131
+ /**
1132
+ * Above every key below a complete sort key prefix: the delimiter is followed by
1133
+ * a composite's label, and no label reaches U+FFFF.
1134
+ */
1135
+ export const SORT_KEY_MAX = "\uFFFF";
1136
+ /**
1137
+ * The condition selecting a complete sort key prefix on a secondary index, with
1138
+ * `escapeKeys: true`: the key itself, where the structural rule truncates a row whose
1139
+ * trailing composites are absent (`DESIGN.md §7`), and every key below it. A longer sibling
1140
+ * value stays out: its text extends the prefix with a character above the delimiter (escaping
1141
+ * puts everything up to `%` out of reach of a value).
1142
+ *
1143
+ * With `escapeKeys` off that range would hold `new york` for `new`, so a pin sends 1.36's
1144
+ * `begins_with` on the prefix and the delimiter, and a row truncated at the prefix isn't among
1145
+ * what it reads, as in 1.36.
1146
+ */
1147
+ export const pinCondition = (schema, prefix) => schema.escapeKeys === true
1148
+ ? subtreeCondition(prefix)
1149
+ : { beginsWith: `${prefix}${KEY_DELIMITER}` };
1150
+ /** The range {@link pinCondition} sends with `escapeKeys: true`. */
1151
+ export const subtreeCondition = (prefix) => ({
1152
+ between: [prefix, `${prefix}${KEY_DELIMITER}${SORT_KEY_MAX}`],
1153
+ });
1154
+ /** The prefix a {@link subtreeCondition} selects; `undefined` for any other condition. */
1155
+ export const subtreePrefix = (condition) => {
1156
+ if (!("between" in condition))
1157
+ return undefined;
1158
+ const [lower, upper] = condition.between;
1159
+ return typeof lower === "string" && upper === `${lower}${KEY_DELIMITER}${SORT_KEY_MAX}`
1160
+ ? lower
1161
+ : undefined;
1162
+ };
781
1163
  /**
782
1164
  * The sort key condition a query accessor sends for the leading SK composites
783
1165
  * present in `record` (the caller has checked at least one is):
@@ -788,15 +1170,21 @@ export const composeSortKeyBeginsWith = (schema, entityType, entityVersion, inde
788
1170
  * matching `"ab"`, and `seq: 3` matching 3.14 and 3.5, whose key text
789
1171
  * extends 3's. On the primary index `=` also leaves out the item's history
790
1172
  * rows, whose keys extend the current one.
791
- * - **Partial prefix** — `{ beginsWith }` on {@link composeSortKeyBeginsWith}:
792
- * the prefix and the delimiter, so it stops on a segment boundary.
1173
+ * - **Partial prefix, secondary index** — {@link pinCondition}: with `escapeKeys: true` a row
1174
+ * truncated at this prefix belongs to these pins, and `begins_with` on the
1175
+ * prefix and delimiter can't reach it (the key ends where the operand goes on).
1176
+ * - **Partial prefix, primary index** — `{ beginsWith }` on
1177
+ * {@link composeSortKeyBeginsWith}: the prefix and the delimiter, so it stops on
1178
+ * a segment boundary. Primary keys are never truncated.
793
1179
  */
794
1180
  export const composeSortKeyCondition = (schema, entityType, entityVersion, index, record) => {
795
1181
  assertStringHalf(index, "composeSortKeyCondition");
796
1182
  const prefix = composeSortKeyPrefix(schema, entityType, entityVersion, index, record);
797
- return availableSkCount(index, record) === index.sk.composite.length
798
- ? { eq: prefix }
799
- : { beginsWith: `${prefix}${KEY_DELIMITER}` };
1183
+ if (availableSkCount(index, record) === index.sk.composite.length)
1184
+ return { eq: prefix };
1185
+ return index.index === undefined
1186
+ ? { beginsWith: `${prefix}${KEY_DELIMITER}` }
1187
+ : pinCondition(schema, prefix);
800
1188
  };
801
1189
  /**
802
1190
  * Compose a partial sort key prefix for query operations.
@@ -819,7 +1207,7 @@ export const composeSortKeyPrefix = (schema, entityType, entityVersion, index, r
819
1207
  const value = record[attr];
820
1208
  if (value === undefined || value === null)
821
1209
  break;
822
- available.push(serializeSortKeyValue(value, casing));
1210
+ available.push(keyValueText(schema, value, casing));
823
1211
  names.push(attr);
824
1212
  }
825
1213
  const collection = index.collection;
@@ -845,7 +1233,7 @@ export const composeSortKeyPrefix = (schema, entityType, entityVersion, index, r
845
1233
  // Event item SK format: `<currentSk>#e#<orderBy value's sort key text>`.
846
1234
  // Casing is applied to both the `#e#` infix and the value for consistency with
847
1235
  // the rest of the SK — matches how every other composite segment is cased —
848
- // and the value is escaped as every sort key composite is (`sortKeyText`).
1236
+ // and the value is escaped as every key composite is (`keyText`).
849
1237
  // ---------------------------------------------------------------------------
850
1238
  const EVENT_SK_INFIX = "e";
851
1239
  /**
@@ -853,8 +1241,22 @@ const EVENT_SK_INFIX = "e";
853
1241
  *
854
1242
  * Given `currentSk = "$app#v1#telemetry_1"` and `orderByValue = 42`, returns
855
1243
  * `"$app#v1#telemetry_1#e#0000000000000042"` (with default lowercase casing).
1244
+ * `orderByValue` is what {@link eventOrderByValue} picks for the schema's setting.
1245
+ */
1246
+ export const composeEventSk = (first, ...rest) => {
1247
+ if (typeof first === "string") {
1248
+ const casing = (rest[1] ?? "lowercase");
1249
+ return `${first}#${applyCasing(EVENT_SK_INFIX, casing)}#${escapeKeyText(serializeValue(rest[0]), casing)}`;
1250
+ }
1251
+ const casing = (rest[2] ?? first.casing);
1252
+ return `${rest[0]}#${applyCasing(EVENT_SK_INFIX, casing)}#${keyValueText(first, rest[1], casing)}`;
1253
+ };
1254
+ /**
1255
+ * The value of the `orderBy` attribute an event's sort key holds: its key form with numeric key
1256
+ * text, its encoded value (a `NumberFromString` `"10"` as the string `10`) with `escapeKeys` off,
1257
+ * as 1.36 composed it.
856
1258
  */
857
- export const composeEventSk = (currentSk, orderByValue, casing = "lowercase") => `${currentSk}#${applyCasing(EVENT_SK_INFIX, casing)}#${serializeSortKeyValue(orderByValue, casing)}`;
1259
+ export const eventOrderByValue = (schema, encoded, keyForm) => (schema.escapeKeys === true || schema.numericKeyText === true ? keyForm : encoded);
858
1260
  /**
859
1261
  * Compose the prefix used to scope `.history()` queries to event items only.
860
1262
  *