effect-dynamodb 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 (74) hide show
  1. package/dist/Aggregate.d.ts.map +1 -1
  2. package/dist/Aggregate.js +312 -338
  3. package/dist/Aggregate.js.map +1 -1
  4. package/dist/Batch.d.ts.map +1 -1
  5. package/dist/Batch.js +72 -191
  6. package/dist/Batch.js.map +1 -1
  7. package/dist/Collection.d.ts.map +1 -1
  8. package/dist/Collection.js +15 -16
  9. package/dist/Collection.js.map +1 -1
  10. package/dist/DynamoClient.d.ts +22 -8
  11. package/dist/DynamoClient.d.ts.map +1 -1
  12. package/dist/DynamoClient.js +57 -80
  13. package/dist/DynamoClient.js.map +1 -1
  14. package/dist/Entity.d.ts +9 -84
  15. package/dist/Entity.d.ts.map +1 -1
  16. package/dist/Entity.js +1079 -2664
  17. package/dist/Entity.js.map +1 -1
  18. package/dist/EventStore.d.ts +2 -2
  19. package/dist/EventStore.d.ts.map +1 -1
  20. package/dist/EventStore.js +179 -289
  21. package/dist/EventStore.js.map +1 -1
  22. package/dist/Query.d.ts +70 -32
  23. package/dist/Query.d.ts.map +1 -1
  24. package/dist/Query.js +501 -80
  25. package/dist/Query.js.map +1 -1
  26. package/dist/Table.d.ts +8 -2
  27. package/dist/Table.d.ts.map +1 -1
  28. package/dist/Table.js +7 -0
  29. package/dist/Table.js.map +1 -1
  30. package/dist/Transaction.d.ts +2 -18
  31. package/dist/Transaction.d.ts.map +1 -1
  32. package/dist/Transaction.js +1 -58
  33. package/dist/Transaction.js.map +1 -1
  34. package/dist/index.d.ts +1 -1
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +1 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/internal/BoundQuery.d.ts +11 -8
  39. package/dist/internal/BoundQuery.d.ts.map +1 -1
  40. package/dist/internal/BoundQuery.js +6 -2
  41. package/dist/internal/BoundQuery.js.map +1 -1
  42. package/dist/internal/Cursor.d.ts +9 -4
  43. package/dist/internal/Cursor.d.ts.map +1 -1
  44. package/dist/internal/Cursor.js +12 -2
  45. package/dist/internal/Cursor.js.map +1 -1
  46. package/dist/internal/ProjectionEngine.d.ts +2 -16
  47. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  48. package/dist/internal/ProjectionEngine.js +44 -229
  49. package/dist/internal/ProjectionEngine.js.map +1 -1
  50. package/dist/internal/RangePlanner.d.ts +0 -76
  51. package/dist/internal/RangePlanner.d.ts.map +1 -1
  52. package/dist/internal/RangePlanner.js +2 -206
  53. package/dist/internal/RangePlanner.js.map +1 -1
  54. package/dist/internal/Rekey.d.ts +28 -6
  55. package/dist/internal/Rekey.d.ts.map +1 -1
  56. package/dist/internal/Rekey.js +46 -10
  57. package/dist/internal/Rekey.js.map +1 -1
  58. package/dist/internal/ShardMerge.d.ts +83 -0
  59. package/dist/internal/ShardMerge.d.ts.map +1 -0
  60. package/dist/internal/ShardMerge.js +182 -0
  61. package/dist/internal/ShardMerge.js.map +1 -0
  62. package/dist/internal/TransactPlan.d.ts +1 -8
  63. package/dist/internal/TransactPlan.d.ts.map +1 -1
  64. package/dist/internal/TransactPlan.js +2 -9
  65. package/dist/internal/TransactPlan.js.map +1 -1
  66. package/dist/internal/TransactWriteOps.d.ts +6 -9
  67. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  68. package/dist/internal/TransactWriteOps.js +3 -79
  69. package/dist/internal/TransactWriteOps.js.map +1 -1
  70. package/dist/internal/TransactableOps.d.ts +8 -6
  71. package/dist/internal/TransactableOps.d.ts.map +1 -1
  72. package/dist/internal/TransactableOps.js +13 -9
  73. package/dist/internal/TransactableOps.js.map +1 -1
  74. package/package.json +4 -2
package/dist/Aggregate.js CHANGED
@@ -17,6 +17,7 @@ import { buildDateTransform, containsWireTransform, matchDateRepresentation, opt
17
17
  import * as KeyText136 from "@effect-dynamodb/schema/internal/KeyText136.js";
18
18
  import { isDispatchEligible } from "@effect-dynamodb/schema/internal/PackedCodec.js";
19
19
  import { extractArrayElement, getSchemaFields, hasEncodingTransformation, } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
20
+ import { refuseAggregateKeyInTableKey } from "@effect-dynamodb/schema/internal/SharedKeyAttribute.js";
20
21
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
21
22
  import { DateTime, Effect, Equal, Option, Schema, SchemaAST, } from "effect";
22
23
  import * as Batch from "./Batch.js";
@@ -549,6 +550,17 @@ const makeAggregate = (schema, config) => {
549
550
  `\`collection.index\` naming the GSI partitioned by "${config.pk.field}".`);
550
551
  }
551
552
  }
553
+ refuseAggregateKeyInTableKey(aggregateName, [config.pk.field, "sk", tablePrimary?.pk, tablePrimary?.sk], [
554
+ ...(config.collection.index === undefined || config.collection.sk === undefined
555
+ ? []
556
+ : [["its collection sort key", config.collection.sk.field]]),
557
+ ...(config.list === undefined
558
+ ? []
559
+ : [
560
+ ["its list partition key", config.list.pk.field],
561
+ ["its list sort key", config.list.sk.field],
562
+ ]),
563
+ ]);
552
564
  if ((config.collection.index === undefined) !== (config.collection.sk === undefined)) {
553
565
  throw new Error(`[EDD-9043] Aggregate "${aggregateName}": \`collection.index\` and \`collection.sk\` must ` +
554
566
  `be supplied together. The collection SK exists only to give the index something to ` +
@@ -649,50 +661,37 @@ const makeAggregate = (schema, config) => {
649
661
  "Drop `consistentRead` from the aggregate, or key it on the table's primary " +
650
662
  "partition key so assembly reads the base table.", original);
651
663
  /** Compose the PK and query all items; a rejected read fails as `rejected` names it. */
652
- const readPartition = (key, rejected, force = false, stored) => Effect.flatMap(readPartitionRaw(key, rejected, force, stored), (read) =>
664
+ const readPartition = (key, rejected, rekeyRead) => Effect.flatMap(readPartitionRaw(key, rejected, rekeyRead), (read) =>
653
665
  // Packed edge attributes, read by their stored form (#147).
654
666
  Effect.as(unpackAggregateItems(read.allItems, dispatchByType, aggregateName), read));
655
- /**
656
- * The collection partition key 1.36 composed for `record` (#171, DESIGN.md
657
- * §7 "Rows written by 1.36"), when its text is not `pkValue`'s: a numeric
658
- * partition composite. `undefined` when the text is the same, or the
659
- * schema's `legacyKeys` is off — unless `force`d: `rekey` moves rows
660
- * whatever it is set to.
661
- */
662
- const collectionPk136 = (record, pkValue, force = false) => {
663
- if (!force && !KeyText136.enabled(config.schema))
664
- return undefined;
665
- const pk136 = composeCollectionKey(config.schema, config.collection.name, KeyText136.extractComposites(config.pk.composite, keyRecord(record)));
666
- return pk136 === pkValue ? undefined : pk136;
667
- };
667
+ /** The collection partition key `record`'s values compose under `under`. */
668
+ const collectionPkUnder = (under, record) => composeCollectionKey(config.schema, config.collection.name, KeyComposer.extractKeyComposites(under, {}, config.pk.composite, keyRecord(record)));
668
669
  /** {@link readPartition} without unpacking — `delete` needs only the keys. */
669
- const readPartitionRaw = (key, rejected, force = false,
670
- /** Each item as stored, too ({@link queryAllItems}). */
671
- stored) => Effect.gen(function* () {
670
+ const readPartitionRaw = (key, rejected, rekeyRead) => Effect.gen(function* () {
672
671
  const client = yield* Capacity.client;
673
672
  const tableConfig = yield* config.table.Tag;
674
- const composites = KeyComposer.extractComposites(config.pk.composite, keyRecord(key));
673
+ const composites = KeyComposer.extractKeyComposites(config.schema, {}, config.pk.composite, keyRecord(key));
675
674
  const pkValue = composeCollectionKey(config.schema, config.collection.name, composites);
676
- const read = (partition) => queryAllItems(client, tableConfig.name, config.collection.index, config.pk.field, partition, consistentRead, rejected, stored);
677
- // An aggregate 1.36 wrote under its 1.36 partition text is read there
678
- // too, until `update` or `rekey` moves its rows (#171). Its rows come
679
- // first: they are the older ones.
680
- const pk136 = collectionPk136(key, pkValue, force);
681
- const allItems = pk136 === undefined
675
+ const read = (partition) => queryAllItems(client, tableConfig.name, config.collection.index, config.pk.field, partition, consistentRead, rejected, rekeyRead?.stored);
676
+ const from = rekeyRead?.from;
677
+ const allItems = from === undefined
682
678
  ? yield* read(pkValue)
683
- : [...(yield* read(pk136)), ...(yield* read(pkValue))];
684
- return { client, tableConfig, pkValue, pk136, composites, allItems };
679
+ : [...(yield* read(from)), ...(rekeyRead?.fromOnly === true ? [] : yield* read(pkValue))];
680
+ return { client, tableConfig, pkValue, composites, allItems };
685
681
  });
686
682
  /** Shared: compose PK and query all items, a rejected read a `ValidationError`. */
687
- const fetchPartition = (key, operation, force = false, stored) => readPartition(key, (diagnosis, original) => new ValidationError({
683
+ const fetchPartition = (key, operation, rekeyRead) => readPartition(key, (diagnosis, original) => new ValidationError({
688
684
  entityType: aggregateName,
689
685
  operation: `${operation}.consistentRead`,
690
686
  cause: assemblyReadCause(operation, diagnosis, original),
691
- }), force, stored);
687
+ }), rekeyRead);
692
688
  const derivedSchemas = deriveAggregateSchemas(schema, config.edges, config.pk.composite);
693
689
  /** A stored row's position: its partition and sort key. */
694
690
  const positionOf = (pk, sk) => `${pk}\u0000${sk}`;
695
- /** Attributes holding index keys the aggregate composes: the collection SK mirror, the list keys. */
691
+ /**
692
+ * Attributes holding index keys the aggregate composes: the collection SK mirror, the list
693
+ * keys. Never a table key attribute, which `make` refuses (`EDD-9112`).
694
+ */
696
695
  const indexFields = [
697
696
  ...(config.collection.index !== undefined && config.collection.sk !== undefined
698
697
  ? [config.collection.sk.field]
@@ -705,27 +704,32 @@ const makeAggregate = (schema, config) => {
705
704
  return text !== undefined && text !== stored[field];
706
705
  });
707
706
  /**
708
- * Where the aggregate's rows are stored (#171, DESIGN.md §7 "Rows written by
709
- * 1.36"): for each decomposed item, its current key and its 1.36 key — the
710
- * 1.36 partition text, and the sort key 1.36 composed from its
711
- * discriminator and `many`-edge composites — the rows stored at each, and
712
- * where the item is ({@link placeRows}).
707
+ * Where a row may be under the partition's old text: at the sort key the other setting composes,
708
+ * or the current one, where 1.37.0 and 1.38.0 wrote it (its partition key unescaped, its sort key escaped).
709
+ * Under a partition whose text didn't change, the current sort key is where the row belongs.
710
+ */
711
+ const oldPosition = (pk, pkNow, skOther, sk, storedAt) => pk !== pkNow && !storedAt.has(positionOf(pk, skOther)) && storedAt.has(positionOf(pk, sk))
712
+ ? { pk, sk }
713
+ : { pk, sk: skOther };
714
+ /**
715
+ * `rekey`'s view of where the aggregate's rows are stored (#183, DESIGN.md §7 "`rekey`"): for
716
+ * each decomposed item, its current key and its old one — the partition the row was found in
717
+ * and the sort key text of the other setting — the rows stored at each, and where the item is
718
+ * ({@link placeRows}).
713
719
  */
714
- const locateRows = (groups, composed, allItems, pkValue, pk136) => {
720
+ const locateRows = (groups, composed, allItems, pkValue, from) => {
715
721
  const storedAt = new Map();
716
722
  for (const item of allItems) {
717
723
  storedAt.set(positionOf(String(item[config.pk.field]), String(item.sk)), item);
718
724
  }
719
725
  const rows = groups.flatMap((group, g) => group.items.map((item, i) => {
720
726
  const built = composed[g].items[i];
727
+ const sk = built.sk?.S ?? "";
721
728
  return {
722
729
  group: group.name,
723
730
  built,
724
- current: { pk: pkValue, sk: built.sk?.S ?? "" },
725
- old: {
726
- pk: pk136 ?? pkValue,
727
- sk: composeKey(config.schema, item.entityType, [...item.skComposites136]),
728
- },
731
+ current: { pk: pkValue, sk },
732
+ old: oldPosition(from ?? pkValue, pkValue, otherSortKey(config.schema, item, sk), sk, storedAt),
729
733
  };
730
734
  }));
731
735
  const placements = placeRows(rows.map((row) => ({
@@ -740,7 +744,7 @@ const makeAggregate = (schema, config) => {
740
744
  }));
741
745
  };
742
746
  const updateCore = (key, mutationFn) => Effect.gen(function* () {
743
- const { client, tableConfig, pkValue, pk136, allItems } = yield* fetchPartition(key, "update");
747
+ const { client, tableConfig, pkValue, allItems } = yield* fetchPartition(key, "update");
744
748
  if (allItems.length === 0) {
745
749
  return yield* new AggregateAssemblyError({
746
750
  aggregate: aggregateName,
@@ -800,43 +804,12 @@ const makeAggregate = (schema, config) => {
800
804
  // PUTs and would otherwise clobber it. The old set is only mined for
801
805
  // (pk, sk) delete keys, so it is never stamped.
802
806
  const now = yield* DateTime.now;
803
- const oldDynamo = buildDynamoItems(oldGroups, config, pkValue, sortKeyComposites(config.schema, KeyComposer.extractComposites(config.collection.sk?.composite ?? [], keyRecord(assembledOld))), keyRecord);
807
+ const oldDynamo = buildDynamoItems(oldGroups, config, pkValue, KeyComposer.extractKeyComposites(config.schema, {}, config.collection.sk?.composite ?? [], keyRecord(assembledOld)), keyRecord);
804
808
  const skOf = (item) => item.sk?.S ?? "";
805
- // Rows still under their 1.36 key (#171, DESIGN.md §7 "Rows written by
806
- // 1.36"): the 1.36 partition text, or a sort key whose discriminator or
807
- // `many`-edge composite text changed ({@link locateRows}). Each moves in
808
- // its own group's transaction — the group is rewritten at the current
809
- // keys and the row's stored key deleted beside the Put — keeping its
810
- // `created`. A row at its current key whose list or collection index key
811
- // holds 1.36 text (a list sort key composite whose text changed) has its
812
- // group rewritten too, which recomposes the index keys. A row under both
813
- // keys is taken as current; `rekey` reports it.
814
809
  const existingCreated = new Map(readExistingCreated(allItems));
815
- const moved = new Map();
816
- const movedSks = new Set();
817
- const relisted = new Set();
818
- if (KeyText136.enabled(config.schema)) {
819
- const createdField = stampFields?.createdAt ?? null;
820
- for (const row of locateRows(oldGroups, oldDynamo, allItems, pkValue, pk136)) {
821
- if (row.placement === "old") {
822
- const keys = moved.get(row.group) ?? [];
823
- keys.push(toAttributeMap({ [config.pk.field]: row.old.pk, sk: row.old.sk }));
824
- moved.set(row.group, keys);
825
- movedSks.add(row.current.sk);
826
- const created = createdField === null ? undefined : row.atOld?.[createdField];
827
- if (created !== undefined)
828
- existingCreated.set(row.current.sk, created);
829
- }
830
- else if ((row.placement === "current" || row.placement === "both") &&
831
- row.atCurrent !== undefined &&
832
- staleIndexFields(row.built, row.atCurrent).length > 0) {
833
- relisted.add(row.group);
834
- }
835
- }
836
- }
837
810
  // Packed AFTER the group diff above compared the decomposed values, so
838
811
  // an unchanged packed value is never rewritten (#147).
839
- const newDynamo = buildDynamoItems(yield* packAggregateGroups(newGroups, packedByType, aggregateName, "update"), config, pkValue, sortKeyComposites(config.schema, KeyComposer.extractComposites(config.collection.sk?.composite ?? [], keyRecord(assembledNew))), keyRecord, stampFor(now, existingCreated));
812
+ const newDynamo = buildDynamoItems(yield* packAggregateGroups(newGroups, packedByType, aggregateName, "update"), config, pkValue, KeyComposer.extractKeyComposites(config.schema, {}, config.collection.sk?.composite ?? [], keyRecord(assembledNew)), keyRecord, stampFor(now, existingCreated));
840
813
  const newItemsByGroup = new Map(newDynamo.map((g) => [g.group, g.items]));
841
814
  const oldItemsByGroup = new Map(oldDynamo.map((g) => [g.group, g.items]));
842
815
  // Every sk that survives anywhere in the new decomposition — an old item is
@@ -855,28 +828,16 @@ const makeAggregate = (schema, config) => {
855
828
  const changed = contextChanged ||
856
829
  oldGroup === undefined ||
857
830
  newGroup === undefined ||
858
- !deepEqualGroups(oldGroup, newGroup) ||
859
- moved.has(name) ||
860
- relisted.has(name) ||
861
- (newItemsByGroup.get(name) ?? []).some((item) => movedSks.has(skOf(item)));
831
+ !deepEqualGroups(oldGroup, newGroup);
862
832
  if (!changed)
863
833
  continue;
864
834
  const puts = newItemsByGroup.get(name) ?? [];
865
- // A row under its 1.36 key is deleted there — removed from the
866
- // aggregate or moved — never at a current key it does not have. A
867
- // 1.36 key that is another row's current key (#171: 1.36 did not
868
- // escape) is that row's Put, which overwrites it: the same item can't
869
- // be written twice in one transaction.
870
- const deletes = [
871
- ...(oldItemsByGroup.get(name) ?? [])
872
- .filter((item) => !survivingSks.has(skOf(item)) && !movedSks.has(skOf(item)))
873
- .map((item) => ({
874
- [config.pk.field]: item[config.pk.field],
875
- sk: item.sk,
876
- })),
877
- ...(moved.get(name) ?? []).filter((key) => !(key[config.pk.field]?.S === pkValue &&
878
- survivingSks.has(key.sk?.S ?? ""))),
879
- ];
835
+ const deletes = (oldItemsByGroup.get(name) ?? [])
836
+ .filter((item) => !survivingSks.has(skOf(item)))
837
+ .map((item) => ({
838
+ [config.pk.field]: item[config.pk.field],
839
+ sk: item.sk,
840
+ }));
880
841
  if (puts.length === 0 && deletes.length === 0)
881
842
  continue;
882
843
  groupWrites.push({ group: name, puts, deletes });
@@ -889,26 +850,35 @@ const makeAggregate = (schema, config) => {
889
850
  /** How many times `rekey` reads an aggregate again after a write changed it in between. */
890
851
  const REKEY_ATTEMPTS = 3;
891
852
  /**
892
- * `rekey`'s move of the aggregate at `key` (#171, DESIGN.md §7 "`rekey`"):
893
- * read as `update` reads it, whatever `legacyKeys` is set to, and placed
894
- * ({@link locateRows}). Each row under its 1.36 key moves — a Put of the
895
- * row `update` would write at its current key, keeping its `created` and
896
- * `updated`, beside a Delete of the 1.36 row — and a row at its current key
897
- * whose list or collection index key holds 1.36 text has those keys
898
- * rewritten. Nothing else is written, and every write is conditional: the
899
- * Put only where nothing is, the Delete and the rewrite only while the row
900
- * is as read (`asReadGuard`). Rows whose keys chain move in order, the
901
- * one whose current key is free first, so no write lands on a row still to
902
- * move. A write that loses to a concurrent one reads the aggregate again; a
903
- * row stored under both keys leaves the aggregate as it is, reported. A dry
904
- * run writes nothing.
853
+ * `rekey`'s move of the aggregate at `key` (#183, DESIGN.md §7 "`rekey`"): read from the
854
+ * partition its root was found in and its current one, and placed ({@link locateRows}). Each row
855
+ * under its old key moves — a Put of the row `update` would write at its current key, keeping
856
+ * its `created` and `updated`, beside a Delete of the old row — and a row at its current key
857
+ * whose list or collection index key holds other text has those keys rewritten. Nothing else is
858
+ * written, and every write is conditional: the Put only where nothing is, the Delete and the
859
+ * rewrite only while the row is as read (`asReadGuard`). Rows whose keys chain move in order, the
860
+ * one whose current key is free first, so no write lands on a row still to move, and the root
861
+ * moves last, so a move cut short is found by the next run. A write that loses to a concurrent
862
+ * one reads the aggregate again; a row stored under both keys leaves the aggregate as it is,
863
+ * reported. A dry run writes nothing.
864
+ */
865
+ const rekeyCore = (key, dryRun,
866
+ /** The old partition the aggregate's root was found in, when it isn't the current one. */
867
+ from,
868
+ /**
869
+ * Leave the current partition unread: a dry run's, while another aggregate still to move
870
+ * holds it, whose rows this one's move would find gone by then.
905
871
  */
906
- const rekeyCore = (key, dryRun) => Effect.gen(function* () {
872
+ fromOnly) => Effect.gen(function* () {
907
873
  let movedRows = 0;
908
874
  let rewrittenRows = 0;
909
875
  for (let attempt = 0; attempt < REKEY_ATTEMPTS; attempt++) {
910
876
  const stored = [];
911
- const { client, tableConfig, pkValue, pk136, allItems } = yield* fetchPartition(key, "rekey", true, stored);
877
+ const { client, tableConfig, pkValue, allItems } = yield* fetchPartition(key, "rekey", {
878
+ stored,
879
+ from,
880
+ fromOnly,
881
+ });
912
882
  const done = (rows) => {
913
883
  const unchanged = Math.max(0, rows - movedRows - rewrittenRows);
914
884
  return {
@@ -922,25 +892,25 @@ const makeAggregate = (schema, config) => {
922
892
  return done(0);
923
893
  // A write moving the aggregate between the reads of its two partitions shows its
924
894
  // rows under both, and they can't be assembled or placed: with rows in both, read
925
- // again, and while a row read under the 1.36 partition has gone from it, retry.
926
- const at136 = allItems.filter((item) => item[config.pk.field] === pk136);
927
- if (pk136 !== undefined && at136.length > 0 && at136.length < allItems.length) {
928
- const again = yield* fetchPartition(key, "rekey", true);
895
+ // again, and while a row read under the old partition has gone from it, retry.
896
+ const atFrom = allItems.filter((item) => item[config.pk.field] === from);
897
+ if (from !== undefined && atFrom.length > 0 && atFrom.length < allItems.length) {
898
+ const again = yield* fetchPartition(key, "rekey", { from, fromOnly });
929
899
  const held = new Set(again.allItems
930
- .filter((item) => item[config.pk.field] === pk136)
900
+ .filter((item) => item[config.pk.field] === from)
931
901
  .map((item) => String(item.sk)));
932
- if (at136.some((item) => !held.has(String(item.sk))))
902
+ if (atFrom.some((item) => !held.has(String(item.sk))))
933
903
  continue;
934
904
  }
935
905
  const current = yield* assembleAggregate(decodeSchema, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
936
906
  const assembled = { ...current };
937
907
  const groups = yield* decomposeAggregate(assembled, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
938
- const rootComposites = sortKeyComposites(config.schema, KeyComposer.extractComposites(config.collection.sk?.composite ?? [], keyRecord(assembled)));
939
- const rows = locateRows(groups, buildDynamoItems(groups, config, pkValue, rootComposites, keyRecord), allItems, pkValue, pk136);
908
+ const rootComposites = KeyComposer.extractKeyComposites(config.schema, {}, config.collection.sk?.composite ?? [], keyRecord(assembled));
909
+ const rows = locateRows(groups, buildDynamoItems(groups, config, pkValue, rootComposites, keyRecord), allItems, pkValue, from);
940
910
  const doubled = rows.filter((row) => row.placement === "both" || row.placement === "ambiguous");
941
911
  if (doubled.length > 0) {
942
912
  // In one partition, a move during the read shows a row at both keys too: it's
943
- // only under both while it's still under its 1.36 key.
913
+ // only under both while it's still under its old key.
944
914
  const held = yield* Effect.forEach(doubled, (row) => client
945
915
  .getItem({
946
916
  TableName: tableConfig.name,
@@ -959,9 +929,8 @@ const makeAggregate = (schema, config) => {
959
929
  target: { [config.pk.field]: row.current.pk, sk: row.current.sk },
960
930
  message: row.placement === "both"
961
931
  ? "The row is also stored under its current key: the aggregate is left as it is."
962
- : "Its rows' keys alias across 1.36 and 1.37 text, and which row is stored " +
963
- "under which key can't be told from the keys held: the aggregate is left " +
964
- "as it is.",
932
+ : "Its rows' keys overlap across key text, and which row is stored under which " +
933
+ "key can't be told from the keys held: the aggregate is left as it is.",
965
934
  })),
966
935
  };
967
936
  }
@@ -971,14 +940,14 @@ const makeAggregate = (schema, config) => {
971
940
  const keptCreated = new Map();
972
941
  const keptUpdated = new Map();
973
942
  for (const row of rows) {
974
- const from = row.placement === "old" ? row.atOld : row.atCurrent;
975
- if (from === undefined)
943
+ const was = row.placement === "old" ? row.atOld : row.atCurrent;
944
+ if (was === undefined)
976
945
  continue;
977
- if (createdField !== null && from[createdField] !== undefined) {
978
- keptCreated.set(row.current.sk, from[createdField]);
946
+ if (createdField !== null && was[createdField] !== undefined) {
947
+ keptCreated.set(row.current.sk, was[createdField]);
979
948
  }
980
- if (updatedField !== null && from[updatedField] !== undefined) {
981
- keptUpdated.set(row.current.sk, from[updatedField]);
949
+ if (updatedField !== null && was[updatedField] !== undefined) {
950
+ keptUpdated.set(row.current.sk, was[updatedField]);
982
951
  }
983
952
  }
984
953
  const built = buildDynamoItems(yield* packAggregateGroups(groups, packedByType, aggregateName, "update"), config, pkValue, rootComposites, keyRecord, stampFor(yield* DateTime.now, keptCreated, keptUpdated)).flatMap((group) => group.items);
@@ -1047,14 +1016,16 @@ const makeAggregate = (schema, config) => {
1047
1016
  return done(rows.length);
1048
1017
  }
1049
1018
  // In waves: a row moves once no row still to move is stored at its
1050
- // current key. Each move's Put and Delete share a transaction; up to
1051
- // TRANSACT_LIMIT items go in one.
1019
+ // current key, and the root once nothing else is left: while it's under the old partition
1020
+ // the next run finds the aggregate there. Each move's Put and Delete share a transaction;
1021
+ // up to TRANSACT_LIMIT items go in one.
1052
1022
  const units = rewrites.map((items) => ({ kind: "rewrite", items }));
1053
1023
  let pending = moves;
1054
1024
  let lost = false;
1055
1025
  while (!lost && (pending.length > 0 || units.length > 0)) {
1056
1026
  const sources = new Set(pending.map((move) => positionOf(move.from.pk, move.from.sk)));
1057
- const wave = pending.filter((move) => !sources.has(positionOf(move.to.pk, move.to.sk)));
1027
+ const wave = pending.filter((move) => !sources.has(positionOf(move.to.pk, move.to.sk)) &&
1028
+ (pending.length === 1 || move.from.sk !== rekeyRootSk));
1058
1029
  // Moves whose keys cycle: `placeRows` leaves such rows ambiguous, so
1059
1030
  // none reach here — reported below if one ever does.
1060
1031
  if (wave.length === 0 && units.length === 0)
@@ -1117,10 +1088,10 @@ const makeAggregate = (schema, config) => {
1117
1088
  ],
1118
1089
  };
1119
1090
  });
1120
- // rekey (#171): the aggregate's part in `db.tables.<Table>.rekey()`. Its
1121
- // rows move together ({@link rekeyCore}): the scan's root row — under the
1122
- // current or the 1.36 partition text — runs the move once per run; a row
1123
- // below the root moves with it.
1091
+ // rekey (#171, #183): the aggregate's part in `db.tables.<Table>.rekey()`. Its rows move together
1092
+ // ({@link rekeyCore}): the scan's root row runs the move, once per partition per run. A row below
1093
+ // the root moves with it; with no root in its partition there's no aggregate to move it with, and
1094
+ // it's reported ({@link rekeyFinish}).
1124
1095
  const rekeyTypes = (() => {
1125
1096
  const types = new Set();
1126
1097
  const walk = (node) => {
@@ -1133,27 +1104,132 @@ const makeAggregate = (schema, config) => {
1133
1104
  })();
1134
1105
  const rekeyPrefix = composeCollectionKey(config.schema, config.collection.name, []);
1135
1106
  const rekeyRootSk = composeKey(config.schema, config.root.entityType, []);
1136
- const rekeyHandler = {
1137
- name: aggregateName,
1138
- types: rekeyTypes,
1139
- row: (row, ctx) => Effect.gen(function* () {
1140
- const pk = row[config.pk.field]?.S;
1141
- if (pk === undefined || (pk !== rekeyPrefix && !pk.startsWith(`${rekeyPrefix}#`))) {
1142
- return undefined;
1143
- }
1144
- if (row.sk?.S !== rekeyRootSk || row.__edd_e__?.S !== config.root.entityType)
1145
- return {};
1146
- const key = fromAttributeMap(row);
1147
- let current;
1148
- try {
1149
- current = composeCollectionKey(config.schema, config.collection.name, KeyComposer.extractComposites(config.pk.composite, keyRecord(key)));
1150
- }
1151
- catch {
1152
- return { skipped: { unrecognizedKey: 1 } };
1107
+ const rekeyUnit = (pk) => `${aggregateName}\u0000${pk}`;
1108
+ const rootItemAt = (tableName, pk) => Effect.flatMap(Capacity.client, (client) => client.getItem({
1109
+ TableName: tableName,
1110
+ Key: toAttributeMap({ [config.pk.field]: pk, sk: rekeyRootSk }),
1111
+ ConsistentRead: true,
1112
+ }));
1113
+ /** The partition key a row's values compose under `under`; none if they compose no key. */
1114
+ const partitionUnder = (under, row) => {
1115
+ try {
1116
+ return collectionPkUnder(under, row);
1117
+ }
1118
+ catch {
1119
+ return undefined;
1120
+ }
1121
+ };
1122
+ /**
1123
+ * The root of another aggregate at `pk`, stored there under text its values no longer compose:
1124
+ * it moves first, or this move's rows would land in its partition.
1125
+ */
1126
+ const staleRootAt = (tableName, pk) => Effect.map(rootItemAt(tableName, pk), ({ Item }) => Item === undefined || partitionUnder(config.schema, fromAttributeMap(Item)) === pk
1127
+ ? undefined
1128
+ : Item);
1129
+ /**
1130
+ * What a run has learned: the partitions holding a root or about to, so each edge row in one costs
1131
+ * no read of its own, and the rows found in a partition with no root.
1132
+ */
1133
+ const rekeyRuns = new WeakMap();
1134
+ const rekeyRunOf = (ctx) => {
1135
+ const known = rekeyRuns.get(ctx) ?? { rooted: new Set(), rootless: [] };
1136
+ rekeyRuns.set(ctx, known);
1137
+ return known;
1138
+ };
1139
+ const rekeyRowBelowRoot = (row, pk, ctx) => Effect.gen(function* () {
1140
+ const { rooted, rootless } = rekeyRunOf(ctx);
1141
+ if (rooted.has(pk))
1142
+ return {};
1143
+ const { Item } = yield* rootItemAt(ctx.tableName, pk);
1144
+ if (Item !== undefined) {
1145
+ rooted.add(pk);
1146
+ return {};
1147
+ }
1148
+ rootless.push(row);
1149
+ return {};
1150
+ });
1151
+ /**
1152
+ * A row with no root in its partition, once everything is scanned: a root may have moved it on,
1153
+ * or be on its way to it (a run cut short moves the root last), in any order the scan met them,
1154
+ * and a dry run decides the same. Its values don't say whose it is unless the aggregate's context
1155
+ * holds them, so with no root at all there's no aggregate to move it with, and it's reported.
1156
+ */
1157
+ const rekeyFinish = (ctx) => Effect.gen(function* () {
1158
+ const { rooted, rootless } = rekeyRunOf(ctx);
1159
+ const client = yield* Capacity.client;
1160
+ let left = 0;
1161
+ for (const row of rootless) {
1162
+ if (rooted.has(row[config.pk.field].S))
1163
+ continue;
1164
+ const { Item } = yield* client.getItem({
1165
+ TableName: ctx.tableName,
1166
+ Key: { [config.pk.field]: row[config.pk.field], sk: row.sk },
1167
+ ConsistentRead: true,
1168
+ });
1169
+ if (Item !== undefined)
1170
+ left++;
1171
+ }
1172
+ return left > 0 ? { skipped: { unrecognizedKey: left } } : {};
1173
+ });
1174
+ const rekeyRow = (row, ctx, depth) => Effect.gen(function* () {
1175
+ const pk = row[config.pk.field]?.S;
1176
+ if (pk === undefined || (pk !== rekeyPrefix && !pk.startsWith(`${rekeyPrefix}#`))) {
1177
+ return undefined;
1178
+ }
1179
+ if (row.sk?.S !== rekeyRootSk || row.__edd_e__?.S !== config.root.entityType) {
1180
+ return yield* rekeyRowBelowRoot(row, pk, ctx);
1181
+ }
1182
+ const key = fromAttributeMap(row);
1183
+ const current = partitionUnder(config.schema, key);
1184
+ // Under none of the keys its values have had: nothing here can place it.
1185
+ if (current === undefined ||
1186
+ ![
1187
+ current,
1188
+ partitionUnder(KeyText136.schema136(config.schema), key),
1189
+ partitionUnder(KeyText136.schema137(config.schema), key),
1190
+ partitionUnder(KeyText136.schemaEscaped(config.schema), key),
1191
+ ].includes(pk)) {
1192
+ return { skipped: { unrecognizedKey: 1 } };
1193
+ }
1194
+ const { rooted } = rekeyRunOf(ctx);
1195
+ rooted.add(pk);
1196
+ rooted.add(current);
1197
+ return yield* ctx.once(rekeyUnit(pk), Effect.gen(function* () {
1198
+ const from = pk === current ? undefined : pk;
1199
+ // The chain: another aggregate may still be stored where this one goes (`foo%20bar`'s
1200
+ // old row where `foo bar`'s current one belongs). It moves first; it leaves no row in
1201
+ // this one's way, and nothing is overwritten or merged whichever the scan reached first.
1202
+ let first = {};
1203
+ let fromOnly = false;
1204
+ if (from !== undefined) {
1205
+ const stale = yield* staleRootAt(ctx.tableName, current);
1206
+ if (stale !== undefined) {
1207
+ const tooDeep = depth >= Rekey.DISPLACE_DEPTH;
1208
+ first = tooDeep
1209
+ ? {}
1210
+ : yield* Rekey.displace(ctx, (under) => rekeyRow(stale, under, depth + 1));
1211
+ // A dry run moved nothing: what would stop that aggregate is what would leave it.
1212
+ const stillThere = ctx.dryRun
1213
+ ? tooDeep || (first.conflicts ?? []).length > 0
1214
+ : (yield* staleRootAt(ctx.tableName, current)) !== undefined;
1215
+ if (stillThere) {
1216
+ return Rekey.mergeTallies(first, {
1217
+ conflicts: [
1218
+ {
1219
+ member: aggregateName,
1220
+ kind: "aggregate",
1221
+ reason: "taken",
1222
+ key: { [config.pk.field]: pk, sk: rekeyRootSk },
1223
+ target: { [config.pk.field]: current, sk: rekeyRootSk },
1224
+ message: "Another aggregate's root is stored where this one's belongs.",
1225
+ },
1226
+ ],
1227
+ });
1228
+ }
1229
+ fromOnly = ctx.dryRun;
1230
+ }
1153
1231
  }
1154
- if (!ctx.claim(`${aggregateName}\u0000${current}`))
1155
- return {};
1156
- return yield* rekeyCore(key, ctx.dryRun).pipe(Effect.catch((error) => {
1232
+ const moved = yield* rekeyCore(key, ctx.dryRun, from, fromOnly).pipe(Effect.catch((error) => {
1157
1233
  if (Rekey.isDynamoClientError(error))
1158
1234
  return Effect.fail(error);
1159
1235
  const assembly = error._tag === "AggregateAssemblyError" ? error.reason : undefined;
@@ -1178,7 +1254,14 @@ const makeAggregate = (schema, config) => {
1178
1254
  ],
1179
1255
  });
1180
1256
  }));
1181
- }),
1257
+ return Rekey.mergeTallies(first, moved);
1258
+ }));
1259
+ });
1260
+ const rekeyHandler = {
1261
+ name: aggregateName,
1262
+ types: rekeyTypes,
1263
+ row: (row, ctx) => rekeyRow(row, ctx, 0),
1264
+ finish: rekeyFinish,
1182
1265
  };
1183
1266
  return Rekey.carry(rekeyHandler, withOperations(aggregateName, {
1184
1267
  [TypeId]: TypeId,
@@ -1229,7 +1312,7 @@ const makeAggregate = (schema, config) => {
1229
1312
  })));
1230
1313
  const assembled = { ...decoded };
1231
1314
  // 3. Compose PK
1232
- const composites = KeyComposer.extractComposites(config.pk.composite, keyRecord(assembled));
1315
+ const composites = KeyComposer.extractKeyComposites(config.schema, {}, config.pk.composite, keyRecord(assembled));
1233
1316
  const pkValue = composeCollectionKey(config.schema, config.collection.name, composites);
1234
1317
  // 4. Decompose into items grouped by sub-aggregate transaction boundaries
1235
1318
  const groups = yield* decomposeAggregate(assembled, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
@@ -1237,7 +1320,7 @@ const makeAggregate = (schema, config) => {
1237
1320
  // form — `update` already did (see `newDynamo` / `oldDynamo` below), so
1238
1321
  // leaving `create` raw made the two write paths mirror the collection SK
1239
1322
  // differently for a transformed composite.
1240
- const collectionSkComposites = sortKeyComposites(config.schema, KeyComposer.extractComposites(config.collection.sk?.composite ?? [], keyRecord(assembled)));
1323
+ const collectionSkComposites = KeyComposer.extractKeyComposites(config.schema, {}, config.collection.sk?.composite ?? [], keyRecord(assembled));
1241
1324
  // 6. Build DynamoDB items with composed keys (create only ever PUTs).
1242
1325
  // Every row is new, so `created` has nothing to carry forward.
1243
1326
  const now = yield* DateTime.now;
@@ -1256,14 +1339,10 @@ const makeAggregate = (schema, config) => {
1256
1339
  puts: [...g.items].sort((a, b) => Number(isRoot(b)) - Number(isRoot(a))),
1257
1340
  deletes: [],
1258
1341
  }));
1259
- // An aggregate 1.36 created under its 1.36 partition text exists too:
1260
- // its root is checked absent in the same transaction (#171).
1261
- const pk136 = collectionPk136(assembled, pkValue);
1262
1342
  yield* writeTransactionGroups(client, tableConfig.name, ordered, aggregateName, groupKeys, {
1263
1343
  pkField: config.pk.field,
1264
1344
  entityType: config.root.entityType,
1265
1345
  key: { [config.pk.field]: pkValue, sk: rootSk },
1266
- ...(pk136 === undefined ? {} : { key136: { [config.pk.field]: pk136, sk: rootSk } }),
1267
1346
  });
1268
1347
  return decoded;
1269
1348
  }),
@@ -1317,73 +1396,20 @@ const makeAggregate = (schema, config) => {
1317
1396
  // DOMAIN record, so it goes through the same key form the write side
1318
1397
  // used — otherwise `list` composes a key `create` never wrote and
1319
1398
  // silently returns nothing (#111).
1320
- const listPkComposites = KeyComposer.extractComposites(listConfig.pk.composite, keyRecord(filter ?? {}));
1399
+ const listPkComposites = KeyComposer.extractKeyComposites(config.schema, {}, listConfig.pk.composite, keyRecord(filter ?? {}));
1321
1400
  // Build SK prefix from contiguous filter values matching SK composites.
1322
- // `serializeSortKeyValue`, NOT `String(v)` — the write side encodes
1401
+ // `keyValueText`, NOT `String(v)` — the write side encodes
1323
1402
  // numerics, so `String(5)` would look for `5` where `0000000000000005`
1324
- // is stored, and escapes the sort key's text.
1403
+ // is stored, and escapes the key's text.
1325
1404
  const skValues = [];
1326
1405
  const listSkFilter = keyRecord(filter ?? {});
1327
1406
  for (const attr of listConfig.sk.composite) {
1328
1407
  if (listSkFilter[attr] !== undefined)
1329
- skValues.push(KeyComposer.serializeSortKeyValue(listSkFilter[attr], config.schema.casing));
1408
+ skValues.push(KeyComposer.keyValueText(config.schema, listSkFilter[attr], config.schema.casing));
1330
1409
  else
1331
1410
  break; // Stop at first gap (prefix matching)
1332
1411
  }
1333
1412
  const skComplete = skValues.length === listConfig.sk.composite.length;
1334
- // The list keys 1.36 composed for the filter (#171, DESIGN.md §7 "Rows
1335
- // written by 1.36"): when their text differs, the root items 1.36
1336
- // wrote are listed too, until `update` or `rekey` moves them — under
1337
- // the same equality / prefix rule, ahead of the current key's (behind
1338
- // it under `reverse`).
1339
- const legacy = (() => {
1340
- if (!KeyText136.enabled(config.schema))
1341
- return undefined;
1342
- const pkComposites = KeyText136.extractComposites(listConfig.pk.composite, keyRecord(filter ?? {}));
1343
- const skValues136 = [];
1344
- for (const attr of listConfig.sk.composite) {
1345
- if (listSkFilter[attr] !== undefined)
1346
- skValues136.push(KeyText136.serializeValue(listSkFilter[attr]));
1347
- else
1348
- break;
1349
- }
1350
- // Compared as the keys spell them: cased.
1351
- const text = (values) => composeCollectionKey(config.schema, listConfig.name, values);
1352
- const samePk = text(pkComposites) === text(listPkComposites);
1353
- const sameSk = text(skValues136) === text(skValues);
1354
- return samePk && sameSk ? undefined : { pkComposites, skValues: skValues136, samePk };
1355
- })();
1356
- const current = { pkComposites: listPkComposites, skValues, samePk: true };
1357
- // Under a shared partition, a row the current key condition matches is
1358
- // read by the current pass only.
1359
- const skMatcher = (pass) => {
1360
- const text = composeCollectionKey(config.schema, listConfig.name, pass.skValues);
1361
- return (sk) => pass.skValues.length === 0 ||
1362
- (typeof sk === "string" &&
1363
- (skComplete ? sk === text : sk.startsWith(`${text}${KEY_DELIMITER}`)));
1364
- };
1365
- const inCurrent = skMatcher(current);
1366
- // A root item the current composer keys under the 1.36 condition too
1367
- // (a value holding `#`, or `%` and two hex digits, spelled as another
1368
- // value's escaped text) is not a 1.36 row: its list sort key is the
1369
- // one its values compose now.
1370
- const unmoved = (item) => {
1371
- try {
1372
- const sk = composeCollectionKey(config.schema, listConfig.name, sortKeyComposites(config.schema, KeyComposer.extractComposites(listConfig.sk.composite, keyRecord(item))));
1373
- return item[listConfig.sk.field] !== sk;
1374
- }
1375
- catch {
1376
- return true;
1377
- }
1378
- };
1379
- const acceptFor = (pass) => {
1380
- const filterBy = options?.filterBy;
1381
- if (pass === current || pass.samePk === false)
1382
- return filterBy;
1383
- return (item) => !inCurrent(item[listConfig.sk.field]) &&
1384
- unmoved(item) &&
1385
- (filterBy === undefined || filterBy(item));
1386
- };
1387
1413
  let rootItems;
1388
1414
  let nextKey;
1389
1415
  if (listConfig.cardinality) {
@@ -1407,27 +1433,21 @@ const makeAggregate = (schema, config) => {
1407
1433
  });
1408
1434
  }
1409
1435
  // Fan out across shards and merge. `limit` bounds each shard too — no
1410
- // single shard can contribute more than the whole page. The 1.36
1411
- // keys' shards are read too, first (#171).
1412
- const passes = legacy === undefined ? [current] : [legacy, current];
1413
- const cardinality = listConfig.cardinality;
1414
- const shardQueries = passes.flatMap((pass) => Array.from({ length: cardinality }, (_, shard) => {
1415
- const shardPkValue = composeCollectionKey(config.schema, listConfig.name, [
1416
- ...pass.pkComposites,
1436
+ // single shard can contribute more than the whole page.
1437
+ const shardQueries = Array.from({ length: listConfig.cardinality }, (_, shard) => queryListPartition(client, tableConfig, listConfig, config.schema, {
1438
+ pkValue: composeCollectionKey(config.schema, listConfig.name, [
1439
+ ...listPkComposites,
1417
1440
  String(shard),
1418
- ]);
1419
- return queryListPartition(client, tableConfig, listConfig, config.schema, {
1420
- pkValue: shardPkValue,
1421
- skValues: pass.skValues,
1422
- skComplete,
1423
- limit,
1424
- pageSize,
1425
- filter: rootFilter,
1426
- accept: acceptFor(pass),
1427
- reverse: options?.reverse === true,
1428
- keyFields: listKeyFields,
1429
- }, aggregateName);
1430
- }));
1441
+ ]),
1442
+ skValues,
1443
+ skComplete,
1444
+ limit,
1445
+ pageSize,
1446
+ filter: rootFilter,
1447
+ accept: options?.filterBy,
1448
+ reverse: options?.reverse === true,
1449
+ keyFields: listKeyFields,
1450
+ }, aggregateName));
1431
1451
  const shardResults = yield* Effect.all(shardQueries);
1432
1452
  const merged = shardResults.flatMap((r) => r.items);
1433
1453
  // Truncate the merged fan-out to `limit`. Previously the option was
@@ -1436,55 +1456,22 @@ const makeAggregate = (schema, config) => {
1436
1456
  nextKey = undefined;
1437
1457
  }
1438
1458
  else {
1439
- let startKey = options?.cursor
1440
- ? JSON.parse(atob(options.cursor))
1441
- : undefined;
1442
- const passes = legacy === undefined
1443
- ? [current]
1444
- : options?.reverse === true
1445
- ? [current, legacy]
1446
- : [legacy, current];
1447
- const pkOf = (pass) => composeCollectionKey(config.schema, listConfig.name, pass.pkComposites);
1448
- // A cursor resumes the pass its key is in (a cursor names a row).
1449
- let at = 0;
1450
- if (startKey !== undefined && legacy !== undefined) {
1451
- const inLegacy = legacy.samePk === false
1452
- ? startKey[listConfig.pk.field]?.S === pkOf(legacy)
1453
- : !inCurrent(startKey[listConfig.sk.field]?.S);
1454
- at = passes.indexOf(inLegacy ? legacy : current);
1455
- }
1456
- rootItems = [];
1457
- nextKey = undefined;
1458
- for (; at < passes.length; at++) {
1459
- const pass = passes[at];
1460
- const result = yield* queryListPartition(client, tableConfig, listConfig, config.schema, {
1461
- pkValue: pkOf(pass),
1462
- skValues: pass.skValues,
1463
- skComplete,
1464
- limit: limit === undefined ? undefined : limit - rootItems.length,
1465
- pageSize,
1466
- startKey,
1467
- filter: rootFilter,
1468
- accept: acceptFor(pass),
1469
- reverse: options?.reverse === true,
1470
- keyFields: listKeyFields,
1471
- }, aggregateName);
1472
- rootItems.push(...result.items);
1473
- startKey = undefined;
1474
- if (result.lastKey !== undefined) {
1475
- nextKey = result.lastKey;
1476
- break;
1477
- }
1478
- if (limit !== undefined && rootItems.length >= limit) {
1479
- // The page ends where this pass does: resume after its last
1480
- // row, which reads the rest of the pass (nothing) and goes on.
1481
- const last = rootItems[rootItems.length - 1];
1482
- if (at < passes.length - 1 && last !== undefined) {
1483
- nextKey = listKeyFromItem(toAttributeMap(last), listKeyFields);
1484
- }
1485
- break;
1486
- }
1487
- }
1459
+ const result = yield* queryListPartition(client, tableConfig, listConfig, config.schema, {
1460
+ pkValue: composeCollectionKey(config.schema, listConfig.name, listPkComposites),
1461
+ skValues,
1462
+ skComplete,
1463
+ limit,
1464
+ pageSize,
1465
+ startKey: options?.cursor
1466
+ ? JSON.parse(atob(options.cursor))
1467
+ : undefined,
1468
+ filter: rootFilter,
1469
+ accept: options?.filterBy,
1470
+ reverse: options?.reverse === true,
1471
+ keyFields: listKeyFields,
1472
+ }, aggregateName);
1473
+ rootItems = result.items;
1474
+ nextKey = result.lastKey;
1488
1475
  }
1489
1476
  // Extract PK composite values from each root item and assemble
1490
1477
  const aggregates = [];
@@ -2329,13 +2316,13 @@ const decomposeAggregate = (assembled, rootNode, contextFields, encoders, aggreg
2329
2316
  keyAttributes: rootKeyAttrs,
2330
2317
  transactionGroup: "root",
2331
2318
  skComposites: [],
2332
- skComposites136: [],
2319
+ skCompositesOther: () => [],
2333
2320
  member: rootNode.entityType,
2334
2321
  });
2335
2322
  // Decompose each edge
2336
2323
  for (const child of rootNode.children) {
2337
2324
  const fieldValue = assembled[child.fieldName];
2338
- yield* decomposeNode(items, child, fieldValue, contextValues, "root", { current: [], legacy: [] }, aggregateName, schema.casing);
2325
+ yield* decomposeNode(items, child, fieldValue, contextValues, "root", { current: [], other: () => [] }, aggregateName, schema);
2339
2326
  }
2340
2327
  // Two items composing the same sort key are two writes to one row. DynamoDB
2341
2328
  // rejects the whole TransactWriteItems with a ValidationException ("Transaction
@@ -2380,24 +2367,35 @@ const mergeContextValues = (attrs, contextValues) => {
2380
2367
  attrs[key] = value;
2381
2368
  }
2382
2369
  };
2370
+ /** A sort key value in the text of the setting `schema` isn't using. */
2371
+ const otherKeyText = (schema, value) => KeyComposer.keyValueText(schema.escapeKeys === true ? KeyText136.schema136(schema) : KeyText136.schemaEscaped(schema), value, schema.casing);
2372
+ /** A decomposed row's sort key under the other setting; `sk`, if a value has no text there. */
2373
+ const otherSortKey = (schema, item, sk) => {
2374
+ try {
2375
+ return composeKey(schema, item.entityType, [...item.skCompositesOther()]);
2376
+ }
2377
+ catch {
2378
+ return sk;
2379
+ }
2380
+ };
2383
2381
  /** A node's own static discriminator values as {@link DiscriminatorValues}. */
2384
- const ownDiscriminatorValues = (node, casing) => {
2382
+ const ownDiscriminatorValues = (node, schema) => {
2385
2383
  const entries = node.ownDiscriminator === undefined
2386
2384
  ? []
2387
2385
  : Object.entries(node.ownDiscriminator).filter(([, v]) => typeof v !== "function");
2388
2386
  return {
2389
- current: entries.flatMap(([k, v]) => [k, KeyComposer.serializeSortKeyValue(v, casing)]),
2390
- legacy: entries.flatMap(([k, v]) => [k, KeyText136.serializeValue(v)]),
2387
+ current: entries.flatMap(([k, v]) => [k, KeyComposer.keyValueText(schema, v, schema.casing)]),
2388
+ other: () => entries.flatMap(([k, v]) => [k, otherKeyText(schema, v)]),
2391
2389
  };
2392
2390
  };
2393
2391
  /**
2394
2392
  * Recursively decompose a node's value into DynamoDB items. Sort key values
2395
- * are escaped with the schema's `casing` (`KeyComposer.sortKeyText`); the
2393
+ * are escaped with the schema's `casing` (`KeyComposer.keyText`); the
2396
2394
  * discriminator names between them are field names, kept as they are.
2397
2395
  */
2398
2396
  const decomposeNode = (items, node, value, contextValues, parentGroup,
2399
2397
  /** The parent's discriminator values, in today's text and in 1.36's (#171). */
2400
- parentDiscriminators, aggregateName, casing) => Effect.gen(function* () {
2398
+ parentDiscriminators, aggregateName, schema) => Effect.gen(function* () {
2401
2399
  // Optional edges may have null/undefined values — skip decomposition
2402
2400
  if (value == null)
2403
2401
  return;
@@ -2411,10 +2409,10 @@ parentDiscriminators, aggregateName, casing) => Effect.gen(function* () {
2411
2409
  // Discriminator values for SK composition: the parent sub-aggregate's
2412
2410
  // (name#value pairs, empty at the top level) then this node's own, so a
2413
2411
  // nested sub-aggregate's rows are keyed apart per binding of its parent.
2414
- const own = ownDiscriminatorValues(node, casing);
2412
+ const own = ownDiscriminatorValues(node, schema);
2415
2413
  const discValues = {
2416
2414
  current: [...parentDiscriminators.current, ...own.current],
2417
- legacy: [...parentDiscriminators.legacy, ...own.legacy],
2415
+ other: () => [...parentDiscriminators.other(), ...own.other()],
2418
2416
  };
2419
2417
  // Sub-aggregate root item: fields not claimed by child edges
2420
2418
  const childEdgeNames = new Set(node.children.map((c) => c.fieldName).filter(Boolean));
@@ -2439,13 +2437,13 @@ parentDiscriminators, aggregateName, casing) => Effect.gen(function* () {
2439
2437
  attributes: subRootAttrs,
2440
2438
  transactionGroup: txGroup,
2441
2439
  skComposites: discValues.current,
2442
- skComposites136: discValues.legacy,
2440
+ skCompositesOther: discValues.other,
2443
2441
  member: node.fieldName ?? node.entityType,
2444
2442
  });
2445
2443
  // Decompose children within this sub-aggregate
2446
2444
  for (const child of node.children) {
2447
2445
  const childValue = subValue[child.fieldName];
2448
- yield* decomposeNode(items, child, childValue, contextValues, txGroup, discValues, aggregateName, casing);
2446
+ yield* decomposeNode(items, child, childValue, contextValues, txGroup, discValues, aggregateName, schema);
2449
2447
  }
2450
2448
  }
2451
2449
  else if (node.cardinality === "one") {
@@ -2461,13 +2459,13 @@ parentDiscriminators, aggregateName, casing) => Effect.gen(function* () {
2461
2459
  }
2462
2460
  }
2463
2461
  // Own discriminator values as name#value pairs for SK composition
2464
- const own = ownDiscriminatorValues(node, casing);
2462
+ const own = ownDiscriminatorValues(node, schema);
2465
2463
  items.push({
2466
2464
  entityType: node.entityType,
2467
2465
  attributes: attrs,
2468
2466
  transactionGroup: parentGroup,
2469
2467
  skComposites: [...parentDiscriminators.current, ...own.current],
2470
- skComposites136: [...parentDiscriminators.legacy, ...own.legacy],
2468
+ skCompositesOther: () => [...parentDiscriminators.other(), ...own.other()],
2471
2469
  member: node.fieldName ?? node.entityType,
2472
2470
  });
2473
2471
  }
@@ -2508,11 +2506,11 @@ parentDiscriminators, aggregateName, casing) => Effect.gen(function* () {
2508
2506
  transactionGroup: parentGroup,
2509
2507
  skComposites: [
2510
2508
  ...parentDiscriminators.current,
2511
- ...values.map((value) => KeyComposer.serializeSortKeyValue(value, casing)),
2509
+ ...values.map((value) => KeyComposer.keyValueText(schema, value, schema.casing)),
2512
2510
  ],
2513
- skComposites136: [
2514
- ...parentDiscriminators.legacy,
2515
- ...values.map((value) => KeyText136.serializeValue(value)),
2511
+ skCompositesOther: () => [
2512
+ ...parentDiscriminators.other(),
2513
+ ...values.map((value) => otherKeyText(schema, value)),
2516
2514
  ],
2517
2515
  member: node.fieldName ?? node.entityType,
2518
2516
  });
@@ -2538,13 +2536,6 @@ const readCompositePath = (attrs, path) => {
2538
2536
  }
2539
2537
  return current;
2540
2538
  };
2541
- /**
2542
- * A collection or list sort key's composites as the key holds them: each
2543
- * serialized value (`KeyComposer.extractComposites` over the key-form record)
2544
- * cased and escaped (`KeyComposer.sortKeyText`), so the key's text sorts as
2545
- * its values and a value never holds the delimiter.
2546
- */
2547
- const sortKeyComposites = (schema, composites) => composites.map((text) => KeyComposer.sortKeyText(text, schema.casing));
2548
2539
  /**
2549
2540
  * Whether a resolved composite value can be a sort-key segment.
2550
2541
  *
@@ -2700,7 +2691,7 @@ keyRecord, stamp) => groups.map((group) => ({
2700
2691
  }
2701
2692
  // List collection GSI keys (root items only)
2702
2693
  if (isRootItem && config.list) {
2703
- const listPkComposites = KeyComposer.extractComposites(config.list.pk.composite, keyRecord(item.keyAttributes ?? item.attributes));
2694
+ const listPkComposites = KeyComposer.extractKeyComposites(config.schema, {}, config.list.pk.composite, keyRecord(item.keyAttributes ?? item.attributes));
2704
2695
  if (config.list.cardinality) {
2705
2696
  const shard = hashToShard(pkValue, config.list.cardinality);
2706
2697
  attrs[config.list.pk.field] = composeCollectionKey(config.schema, config.list.name, [
@@ -2711,7 +2702,7 @@ keyRecord, stamp) => groups.map((group) => ({
2711
2702
  else {
2712
2703
  attrs[config.list.pk.field] = composeCollectionKey(config.schema, config.list.name, listPkComposites);
2713
2704
  }
2714
- const listSkComposites = sortKeyComposites(config.schema, KeyComposer.extractComposites(config.list.sk.composite, keyRecord(item.keyAttributes ?? item.attributes)));
2705
+ const listSkComposites = KeyComposer.extractKeyComposites(config.schema, {}, config.list.sk.composite, keyRecord(item.keyAttributes ?? item.attributes));
2715
2706
  attrs[config.list.sk.field] = composeCollectionKey(config.schema, config.list.name, listSkComposites);
2716
2707
  }
2717
2708
  // System timestamps — last, so a generated value wins over the same-named
@@ -2765,31 +2756,15 @@ function writeTransactionGroups(client, tableName, groups, aggregateName, keys,
2765
2756
  },
2766
2757
  })),
2767
2758
  ...group.deletes.map((key) => ({ Delete: { TableName: tableName, Key: key } })),
2768
- ...(rootGuard?.key136 !== undefined && rootIndex >= 0
2769
- ? [
2770
- {
2771
- ConditionCheck: {
2772
- TableName: tableName,
2773
- Key: toAttributeMap(rootGuard.key136),
2774
- ConditionExpression: "attribute_not_exists(#pk)",
2775
- ExpressionAttributeNames: { "#pk": rootGuard.pkField },
2776
- },
2777
- },
2778
- ]
2779
- : []),
2780
2759
  ];
2781
- // The 1.36 root's check, last in the transaction.
2782
- const root136Index = rootGuard?.key136 !== undefined && rootIndex >= 0 ? itemCount : -1;
2783
2760
  // Named once, for both diagnoses below.
2784
2761
  const sent = () => ({
2785
2762
  _tag: "Transaction",
2786
2763
  items: transactItems,
2787
2764
  targets: () => transactItems.map((item) => {
2788
2765
  const entityType = item.Put?.Item?.__edd_e__?.S ?? aggregateName;
2789
- return transactItemTarget(item, tableName, [keys.pkField, "sk"], entityType, item.ConditionCheck !== undefined
2790
- ? `the 1.36 key of the root item of sub-aggregate "${group.group}"`
2791
- : `the ${item.Put !== undefined ? entityType : "removed"} item of ` +
2792
- `sub-aggregate "${group.group}"`);
2766
+ return transactItemTarget(item, tableName, [keys.pkField, "sk"], entityType, `the ${item.Put !== undefined ? entityType : "removed"} item of ` +
2767
+ `sub-aggregate "${group.group}"`);
2793
2768
  }),
2794
2769
  });
2795
2770
  const already = [...committed];
@@ -2829,8 +2804,7 @@ function writeTransactionGroups(client, tableName, groups, aggregateName, keys,
2829
2804
  const reasons = cancelled.CancellationReasons;
2830
2805
  if (rootGuard !== undefined &&
2831
2806
  rootIndex >= 0 &&
2832
- (reasons?.[rootIndex]?.Code === "ConditionalCheckFailed" ||
2833
- (root136Index >= 0 && reasons?.[root136Index]?.Code === "ConditionalCheckFailed"))) {
2807
+ reasons?.[rootIndex]?.Code === "ConditionalCheckFailed") {
2834
2808
  return new ConditionalCheckFailed({
2835
2809
  entityType: rootGuard.entityType,
2836
2810
  key: rootGuard.key,
@@ -2855,17 +2829,17 @@ function writeTransactionGroups(client, tableName, groups, aggregateName, keys,
2855
2829
  });
2856
2830
  }
2857
2831
  // ---------------------------------------------------------------------------
2858
- // Internal: Rows under their 1.36 keys (#171)
2832
+ // Internal: Rows under other key text (#171, #183)
2859
2833
  // ---------------------------------------------------------------------------
2860
2834
  /** DynamoDB's limit on the items of one `TransactWriteItems`. */
2861
2835
  const TRANSACT_LIMIT = 100;
2862
2836
  /**
2863
2837
  * Place an aggregate's rows from the keys that hold a row (#171). Each row has
2864
- * a `current` and an `old` (1.36) position. 1.36 did not escape sort key text,
2865
- * so in one partition a row's 1.36 key can be another row's current key —
2866
- * `a%20b`'s 1.36 sort key is `a b`'s current one — and the rows' keys chain:
2838
+ * a `current` and an `old` position. Off doesn't escape sort key text,
2839
+ * so in one partition a row's unescaped key can be another row's escaped key —
2840
+ * `a%20b`'s unescaped sort key is `a b`'s escaped one — and the rows' keys chain:
2867
2841
  * `a b` → `a%20b` → `a%2520b`. A chain of n rows has n + 1 keys. With exactly
2868
- * one of them free, the rows before it are under their 1.36 keys and those
2842
+ * one of them free, the rows before it are under their old keys and those
2869
2843
  * after it under their current keys. With every key held, a lone row is
2870
2844
  * stored under `both` keys, and a longer chain is `ambiguous`; with more than
2871
2845
  * one free, a row with neither key held is `missing` and the rest are
@@ -2882,7 +2856,7 @@ const placeRows = (slots, held) => {
2882
2856
  currents.add(slot.current);
2883
2857
  }
2884
2858
  for (const [head, slot] of slots.entries()) {
2885
- // A chain starts at a row whose 1.36 key is no other row's current key.
2859
+ // A chain starts at a row whose old key is no other row's current key.
2886
2860
  if (slot.current === slot.old || currents.has(slot.old))
2887
2861
  continue;
2888
2862
  const chain = [];