effect-dynamodb 1.38.0 → 1.40.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 (152) hide show
  1. package/dist/Aggregate.d.ts +119 -15
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +2286 -670
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/Batch.d.ts +9 -5
  6. package/dist/Batch.d.ts.map +1 -1
  7. package/dist/Batch.js +97 -232
  8. package/dist/Batch.js.map +1 -1
  9. package/dist/Collection.d.ts.map +1 -1
  10. package/dist/Collection.js +27 -21
  11. package/dist/Collection.js.map +1 -1
  12. package/dist/ConsumedCapacity.js +1 -1
  13. package/dist/ConsumedCapacity.js.map +1 -1
  14. package/dist/DynamoClient.d.ts +44 -16
  15. package/dist/DynamoClient.d.ts.map +1 -1
  16. package/dist/DynamoClient.js +299 -166
  17. package/dist/DynamoClient.js.map +1 -1
  18. package/dist/Entity.d.ts +94 -104
  19. package/dist/Entity.d.ts.map +1 -1
  20. package/dist/Entity.js +3673 -3022
  21. package/dist/Entity.js.map +1 -1
  22. package/dist/EventStore.d.ts +39 -17
  23. package/dist/EventStore.d.ts.map +1 -1
  24. package/dist/EventStore.js +392 -366
  25. package/dist/EventStore.js.map +1 -1
  26. package/dist/Marshaller.d.ts +39 -9
  27. package/dist/Marshaller.d.ts.map +1 -1
  28. package/dist/Marshaller.js +421 -70
  29. package/dist/Marshaller.js.map +1 -1
  30. package/dist/Query.d.ts +93 -32
  31. package/dist/Query.d.ts.map +1 -1
  32. package/dist/Query.js +550 -83
  33. package/dist/Query.js.map +1 -1
  34. package/dist/StorageEncoding.d.ts +7 -1
  35. package/dist/StorageEncoding.d.ts.map +1 -1
  36. package/dist/StorageEncoding.js +8 -2
  37. package/dist/StorageEncoding.js.map +1 -1
  38. package/dist/Table.d.ts +71 -4
  39. package/dist/Table.d.ts.map +1 -1
  40. package/dist/Table.js +7 -0
  41. package/dist/Table.js.map +1 -1
  42. package/dist/Transaction.d.ts +2 -18
  43. package/dist/Transaction.d.ts.map +1 -1
  44. package/dist/Transaction.js +11 -62
  45. package/dist/Transaction.js.map +1 -1
  46. package/dist/change-feed/ChangeFeed.d.ts +8 -3
  47. package/dist/change-feed/ChangeFeed.d.ts.map +1 -1
  48. package/dist/change-feed/ChangeFeed.js +76 -9
  49. package/dist/change-feed/ChangeFeed.js.map +1 -1
  50. package/dist/change-feed/CheckpointStore.js +1 -1
  51. package/dist/change-feed/CheckpointStore.js.map +1 -1
  52. package/dist/change-feed/DynamoStreamsClient.d.ts +12 -5
  53. package/dist/change-feed/DynamoStreamsClient.d.ts.map +1 -1
  54. package/dist/change-feed/DynamoStreamsClient.js +15 -9
  55. package/dist/change-feed/DynamoStreamsClient.js.map +1 -1
  56. package/dist/index.d.ts +1 -1
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +1 -1
  59. package/dist/index.js.map +1 -1
  60. package/dist/internal/BoundCrud.d.ts +40 -32
  61. package/dist/internal/BoundCrud.d.ts.map +1 -1
  62. package/dist/internal/BoundCrud.js.map +1 -1
  63. package/dist/internal/BoundQuery.d.ts +12 -9
  64. package/dist/internal/BoundQuery.d.ts.map +1 -1
  65. package/dist/internal/BoundQuery.js +26 -12
  66. package/dist/internal/BoundQuery.js.map +1 -1
  67. package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
  68. package/dist/internal/BoundVectorQuery.js +2 -1
  69. package/dist/internal/BoundVectorQuery.js.map +1 -1
  70. package/dist/internal/Capacity.d.ts +44 -4
  71. package/dist/internal/Capacity.d.ts.map +1 -1
  72. package/dist/internal/Capacity.js +89 -15
  73. package/dist/internal/Capacity.js.map +1 -1
  74. package/dist/internal/ClientOptions.d.ts +72 -0
  75. package/dist/internal/ClientOptions.d.ts.map +1 -0
  76. package/dist/internal/ClientOptions.js +79 -0
  77. package/dist/internal/ClientOptions.js.map +1 -0
  78. package/dist/internal/Cursor.d.ts +28 -14
  79. package/dist/internal/Cursor.d.ts.map +1 -1
  80. package/dist/internal/Cursor.js +37 -12
  81. package/dist/internal/Cursor.js.map +1 -1
  82. package/dist/internal/EntityCombinators.d.ts +22 -7
  83. package/dist/internal/EntityCombinators.d.ts.map +1 -1
  84. package/dist/internal/EntityCombinators.js +6 -2
  85. package/dist/internal/EntityCombinators.js.map +1 -1
  86. package/dist/internal/EntityOps.d.ts +11 -1
  87. package/dist/internal/EntityOps.d.ts.map +1 -1
  88. package/dist/internal/EntityOps.js.map +1 -1
  89. package/dist/internal/EventProjection.d.ts +15 -3
  90. package/dist/internal/EventProjection.d.ts.map +1 -1
  91. package/dist/internal/EventProjection.js +27 -8
  92. package/dist/internal/EventProjection.js.map +1 -1
  93. package/dist/internal/Expr.d.ts.map +1 -1
  94. package/dist/internal/Expr.js +53 -2
  95. package/dist/internal/Expr.js.map +1 -1
  96. package/dist/internal/ExpressionLimits.d.ts +57 -1
  97. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  98. package/dist/internal/ExpressionLimits.js +90 -1
  99. package/dist/internal/ExpressionLimits.js.map +1 -1
  100. package/dist/internal/ItemSize.d.ts +108 -4
  101. package/dist/internal/ItemSize.d.ts.map +1 -1
  102. package/dist/internal/ItemSize.js +190 -3
  103. package/dist/internal/ItemSize.js.map +1 -1
  104. package/dist/internal/MultiProjection.d.ts +7 -2
  105. package/dist/internal/MultiProjection.d.ts.map +1 -1
  106. package/dist/internal/MultiProjection.js +9 -3
  107. package/dist/internal/MultiProjection.js.map +1 -1
  108. package/dist/internal/PathBuilder.d.ts +15 -4
  109. package/dist/internal/PathBuilder.d.ts.map +1 -1
  110. package/dist/internal/PathBuilder.js +20 -10
  111. package/dist/internal/PathBuilder.js.map +1 -1
  112. package/dist/internal/ProjectionEngine.d.ts +78 -18
  113. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  114. package/dist/internal/ProjectionEngine.js +402 -257
  115. package/dist/internal/ProjectionEngine.js.map +1 -1
  116. package/dist/internal/RangePlanner.d.ts +0 -76
  117. package/dist/internal/RangePlanner.d.ts.map +1 -1
  118. package/dist/internal/RangePlanner.js +2 -206
  119. package/dist/internal/RangePlanner.js.map +1 -1
  120. package/dist/internal/Rekey.d.ts +49 -7
  121. package/dist/internal/Rekey.d.ts.map +1 -1
  122. package/dist/internal/Rekey.js +113 -10
  123. package/dist/internal/Rekey.js.map +1 -1
  124. package/dist/internal/RoundTrip.d.ts +36 -0
  125. package/dist/internal/RoundTrip.d.ts.map +1 -0
  126. package/dist/internal/RoundTrip.js +79 -0
  127. package/dist/internal/RoundTrip.js.map +1 -0
  128. package/dist/internal/SentRequest.d.ts +14 -0
  129. package/dist/internal/SentRequest.d.ts.map +1 -0
  130. package/dist/internal/SentRequest.js +31 -0
  131. package/dist/internal/SentRequest.js.map +1 -0
  132. package/dist/internal/ShardMerge.d.ts +83 -0
  133. package/dist/internal/ShardMerge.d.ts.map +1 -0
  134. package/dist/internal/ShardMerge.js +182 -0
  135. package/dist/internal/ShardMerge.js.map +1 -0
  136. package/dist/internal/TransactPlan.d.ts +1 -8
  137. package/dist/internal/TransactPlan.d.ts.map +1 -1
  138. package/dist/internal/TransactPlan.js +2 -9
  139. package/dist/internal/TransactPlan.js.map +1 -1
  140. package/dist/internal/TransactWriteOps.d.ts +75 -24
  141. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  142. package/dist/internal/TransactWriteOps.js +147 -186
  143. package/dist/internal/TransactWriteOps.js.map +1 -1
  144. package/dist/internal/TransactableOps.d.ts +123 -29
  145. package/dist/internal/TransactableOps.d.ts.map +1 -1
  146. package/dist/internal/TransactableOps.js +255 -87
  147. package/dist/internal/TransactableOps.js.map +1 -1
  148. package/dist/internal/WriteDiagnosis.d.ts +31 -3
  149. package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
  150. package/dist/internal/WriteDiagnosis.js +128 -11
  151. package/dist/internal/WriteDiagnosis.js.map +1 -1
  152. package/package.json +4 -2
@@ -49,20 +49,25 @@ import { isPackedConfig } from "@effect-dynamodb/schema/DynamoModel.js";
49
49
  import * as DynamoSchema from "@effect-dynamodb/schema/DynamoSchema.js";
50
50
  import { normalizeTtlSeconds } from "@effect-dynamodb/schema/Entity.js";
51
51
  import { AdditionalItemConditionFailed, AppendTooLarge, DuplicateCommand, isAwsConditionalCheckFailed, isAwsTransactionCancelled, isAwsValidationError, StreamSealed, TransactionCancelled, ValidationError, VersionConflict, } from "@effect-dynamodb/schema/Errors.js";
52
+ import { readingStreamValues, writingTuplePositions, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
53
+ import { decodingAsBefore } from "@effect-dynamodb/schema/internal/FailingAsBefore.js";
52
54
  import * as KeyText136 from "@effect-dynamodb/schema/internal/KeyText136.js";
53
55
  import { isDispatchEligible, packedShape, packValue, unpackStoredSync, } from "@effect-dynamodb/schema/internal/PackedCodec.js";
56
+ import { refuseUnreadable } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
54
57
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
55
- import { Context, DateTime, Effect, Function, Option, Pipeable, Result, Schedule, Schema, } from "effect";
58
+ import { Context, DateTime, Effect, Exit, Function, Option, Pipeable, Result, Schedule, Schema, } from "effect";
56
59
  import { attributeValueEquals } from "./internal/AttributeValueEquals.js";
57
60
  import * as Capacity from "./internal/Capacity.js";
58
61
  import { ProjectionRoutes } from "./internal/EventProjection.js";
59
- import { eq, or } from "./internal/Expr.js";
60
- import { asReadGuard } from "./internal/ExpressionLimits.js";
61
- import { itemBytes, transactItemBytes } from "./internal/ItemSize.js";
62
+ import { eq } from "./internal/Expr.js";
63
+ import { asReadGuard, wholeRowGuard } from "./internal/ExpressionLimits.js";
64
+ import { itemBytes, jsonBytes, transactItemBytes, transactWriteBodyBytes, } from "./internal/ItemSize.js";
62
65
  import { isMultiProjection, } from "./internal/MultiProjection.js";
63
66
  import { codecRequirements, currentRegistry, decodeImage, imageEntityType, runtimeCodecCheck, unregisteredCodecError, withRegistry, } from "./internal/Packed.js";
64
67
  import { createPathBuilder } from "./internal/PathBuilder.js";
65
68
  import * as Rekey from "./internal/Rekey.js";
69
+ import { notReadBack, readBackOf } from "./internal/RoundTrip.js";
70
+ import { marshalOrFail } from "./internal/TransactableOps.js";
66
71
  import { buildTransactWriteItems, GUARDED_TRANSACTION_ATTEMPTS, isStreamAppendOp, judgeCancellation, opConditionFailed, StreamAppendTypeId, transactItemTarget, } from "./internal/TransactWriteOps.js";
67
72
  import { diagnosedValidationError, diagnoseFailure, mergeKeyAttributes, withCause, } from "./internal/WriteDiagnosis.js";
68
73
  import { fromAttributeMap, toAttributeMap } from "./Marshaller.js";
@@ -166,12 +171,9 @@ const SEALED_ATTRIBUTE = "__edd_sealed__";
166
171
  */
167
172
  const WRITE_TOKEN_ATTRIBUTE = "__edd_wt__";
168
173
  /**
169
- * @internal Set by `rekey` (#171) on the first event of a stream it moved
170
- * from its 1.36 partition key, once every row is copied to the current one:
171
- * the stream lives there from then on. `locateStream` reads it; an append
172
- * located at the 1.36 key checks it is absent (`AppendParts.locationCheck`),
173
- * so a writer that located the stream before the move fails with
174
- * `VersionConflict` instead of writing where nothing reads.
174
+ * @internal Set by `rekey` on the first event of a stream it moved, once every
175
+ * row is copied to its current partition key: what is left under the old key
176
+ * is then deleted, and a run stopped partway resumes from there.
175
177
  */
176
178
  const MOVED_ATTRIBUTE = "__edd_moved__";
177
179
  /** @internal The write token's length in hex digits: 128 random bits. */
@@ -256,7 +258,7 @@ const putItemReason = (cause) => {
256
258
  };
257
259
  /**
258
260
  * @internal What a cancelled append means for one stream, from the reasons of
259
- * its own items: `[0, guardCount)` the contiguity and location checks,
261
+ * its own items: `[0, guardCount)` the contiguity check,
260
262
  * `[guardCount, guardCount + eventCount)` the event puts, and the snapshot at
261
263
  * `snapshotIndex` (`-1`: none). `StreamSealed` when the contiguity check, the
262
264
  * first event put or the snapshot failed and returned a sealed item (#166);
@@ -333,12 +335,7 @@ const STREAM_INDEX_CONFIG_KEYS = [
333
335
  * stream index several streams (or stream ids) share (#149). The table's `pk`
334
336
  * is projected into every index, whatever its projection.
335
337
  */
336
- const streamPkFilter = (streamPk, streamPk136) => {
337
- const pk = createPathBuilder().pk;
338
- // A stream still under its 1.36 key (#171) has its items there: either
339
- // key, since a stream is never split across the two.
340
- return streamPk136 === undefined ? eq(pk, streamPk) : or(eq(pk, streamPk), eq(pk, streamPk136));
341
- };
338
+ const streamPkFilter = (streamPk) => eq(createPathBuilder().pk, streamPk);
342
339
  /**
343
340
  * @internal Validate `makeStream({ indexes })` at definition time.
344
341
  *
@@ -840,6 +837,28 @@ export const makeStream = (config) => {
840
837
  // Snapshot config validation (EDD-9027, EDD-9062) — fail fast at definition time.
841
838
  // -------------------------------------------------------------------------
842
839
  const snapshot = config.snapshot;
840
+ // What a stream stores has to read back (EDD-9125): an append that succeeds and a read that
841
+ // can't decode leaves events nobody can read.
842
+ const streamLabel = `EventStream "${config.streamName}"`;
843
+ config.events.forEach((event, position) => {
844
+ const identifier = event.identifier;
845
+ const named = typeof identifier === "string" ? `event "${identifier}"` : `events[${position}]`;
846
+ refuseUnreadable(`${streamLabel}, ${named}`, "schema", event, { whole: "the event" });
847
+ });
848
+ if (config.events.length > 1) {
849
+ // Read through one union, so what one event stores can be what another reads.
850
+ refuseUnreadable(streamLabel, "schema", Schema.Union(config.events), { whole: "the union of its events" });
851
+ }
852
+ if (config.metadata !== undefined) {
853
+ refuseUnreadable(`${streamLabel}, metadata`, "schema", config.metadata, {
854
+ whole: "the metadata",
855
+ });
856
+ }
857
+ if (snapshot !== undefined) {
858
+ refuseUnreadable(`${streamLabel}, snapshot state`, "schema", snapshot.schema, {
859
+ whole: "the state",
860
+ });
861
+ }
843
862
  if (snapshot !== undefined && snapshot.every !== undefined) {
844
863
  if (!Number.isInteger(snapshot.every) || snapshot.every <= 0) {
845
864
  throw new Error(`[EDD-9027] EventStream "${config.streamName}": snapshot.every must be a positive integer; ` +
@@ -922,68 +941,12 @@ export const makeStream = (config) => {
922
941
  // ---------------------------------------------------------------------------
923
942
  // Key helpers
924
943
  // ---------------------------------------------------------------------------
925
- const composeStreamPk = (streamId) => {
926
- const composites = KeyComposer.extractComposites(compositeFields, streamId);
927
- return DynamoSchema.composeKey(schema, keyLabel, composites, keyOptions);
928
- };
929
- /**
930
- * The partition key 1.36 composed for `streamId`, when the 1.36 key
931
- * fallback is on and its text differs from {@link composeStreamPk}'s — a
932
- * number stream id composite whose text changed (#171). `force` answers
933
- * with the fallback off too: `rekey` moves streams whatever it is set to.
934
- */
935
- const composeStreamPk136 = (streamId, force = false) => {
936
- if (!force && !KeyText136.enabled(schema))
937
- return undefined;
938
- const composites = KeyText136.extractComposites(compositeFields, streamId);
939
- const pk136 = DynamoSchema.composeKey(schema, keyLabel, composites, keyOptions);
940
- return pk136 === composeStreamPk(streamId) ? undefined : pk136;
941
- };
942
- /**
943
- * The partition key a stream lives under (#171, DESIGN.md §7 "Rows written
944
- * by 1.36"): its current key, unless that key's text changed since 1.36 and
945
- * the stream's first event is under its 1.36 key. A stream 1.36 started is
946
- * read and appended there — its events, snapshot, seal and command
947
- * sentinels — until `rekey` moves it whole (and marks its first event
948
- * there moved); a stream is never split across the two keys, and a new one
949
- * starts under its current key. A stream whose key text did not change
950
- * costs no request; one whose did, one consistent `GetItem` of the first
951
- * event's key.
952
- */
953
- const locateStream = (streamId) => composeStreamPk136(streamId) === undefined
954
- ? Effect.succeed(composeStreamPk(streamId))
955
- : Effect.gen(function* () {
956
- const { name: tableName } = yield* config.table.Tag;
957
- return yield* locateStreamIn(tableName, streamId);
958
- });
959
- /** {@link locateStream} in the table named `tableName`. */
960
- const locateStreamIn = (tableName, streamId) => {
961
- const current = composeStreamPk(streamId);
962
- const pk136 = composeStreamPk136(streamId);
963
- if (pk136 === undefined)
964
- return Effect.succeed(current);
965
- return Effect.gen(function* () {
966
- const client = yield* Capacity.client;
967
- const first = yield* client.getItem({
968
- TableName: tableName,
969
- Key: toAttributeMap({ pk: pk136, sk: composeEventSk(1) }),
970
- ConsistentRead: true,
971
- ProjectionExpression: "#pk, #moved",
972
- ExpressionAttributeNames: { "#pk": "pk", "#moved": MOVED_ATTRIBUTE },
973
- });
974
- return first.Item === undefined || first.Item[MOVED_ATTRIBUTE] !== undefined ? current : pk136;
975
- });
944
+ const composeStreamPkUnder = (under, streamId) => {
945
+ // A stream's own casing, if it has one: its escapes' hex digits are in it too.
946
+ const composites = KeyComposer.extractKeyComposites(under, { casing: config.casing }, compositeFields, streamId);
947
+ return DynamoSchema.composeKey(under, keyLabel, composites, keyOptions);
976
948
  };
977
- /**
978
- * The `prepare` step of a query of the stream's partition: read it where
979
- * the stream lives ({@link locateStream}). Only a stream whose key text
980
- * changed has one.
981
- */
982
- const locatedPrepare = (streamId) => composeStreamPk136(streamId) === undefined
983
- ? {}
984
- : {
985
- prepare: (tableName) => Effect.map(locateStreamIn(tableName, streamId), (pkValue) => ({ pkValue })),
986
- };
949
+ const composeStreamPk = (streamId) => composeStreamPkUnder(schema, streamId);
987
950
  const composeEventSk = (version) => DynamoSchema.composeEventVersionKey(schema, eventKeyLabel, version, keyOptions);
988
951
  /** Sort key of a command's idempotency sentinel. */
989
952
  const composeCommandSk = (commandId) => DynamoSchema.composeKey(schema, commandKeyLabel, [commandId], keyOptions);
@@ -1029,19 +992,62 @@ export const makeStream = (config) => {
1029
992
  }
1030
993
  return eventUnion;
1031
994
  };
995
+ const writableCodecs = new Map();
996
+ /** A codec refusing a tuple position its stored list can't keep. Built once per schema. */
997
+ const writableCodec = (declared) => {
998
+ const known = writableCodecs.get(declared);
999
+ if (known !== undefined)
1000
+ return known;
1001
+ const writable = writingTuplePositions(declared);
1002
+ writableCodecs.set(declared, writable);
1003
+ return writable;
1004
+ };
1005
+ /**
1006
+ * What checks a schema's stored values read back (`EDD-9126`), for one holding a custom
1007
+ * declaration. An event is read through the union of the events; anything else through itself.
1008
+ */
1009
+ const readBacks = new Map();
1010
+ const readBackFor = (declared) => {
1011
+ if (readBacks.has(declared))
1012
+ return readBacks.get(declared);
1013
+ const isEvent = declared === eventUnion || config.events.includes(declared);
1014
+ const readBack = readBackOf(declared, () => readingStreamValues(isEvent ? eventUnion : declared));
1015
+ readBacks.set(declared, readBack);
1016
+ return readBack;
1017
+ };
1032
1018
  /**
1033
1019
  * Validate input and produce wire-form output: `Schema.encode` first, with a
1034
- * `decode → encode` fallback for inputs already in encoded shape. Mirrors
1035
- * the Entity write path (`encodeOrDecodeEncode` in `Entity.ts`).
1020
+ * `decode → encode` fallback for inputs already in encoded shape, then refused if it wouldn't read
1021
+ * back. Mirrors the Entity write path (`encodeForWrite` in `Entity.ts`). Everything a stream stores
1022
+ * from its own schemas goes through this.
1036
1023
  */
1037
- const encodeToWire = (codec, input, operation, errorEntityType = entityType) => Schema.encodeUnknownEffect(codec)(input).pipe(Effect.catch((primaryCause) => Schema.decodeUnknownEffect(codec)(input).pipe(Effect.flatMap((decoded) => Schema.encodeUnknownEffect(codec)(decoded)),
1038
- // Surface the original encode error — its message is keyed on the
1039
- // caller's input shape, which is what the user expects to see.
1040
- Effect.catch(() => Effect.fail(new ValidationError({ entityType: errorEntityType, operation, cause: primaryCause }))))));
1024
+ const encodeToWire = (declared, input, operation, errorEntityType = entityType, packed = false) => {
1025
+ const codec = writableCodec(declared);
1026
+ const wire = Schema.encodeUnknownEffect(codec)(input).pipe(Effect.catch((primaryCause) => Schema.decodeUnknownEffect(codec)(input).pipe(Effect.flatMap((decoded) => Schema.encodeUnknownEffect(codec)(decoded)),
1027
+ // Surface the original encode error — its message is keyed on the
1028
+ // caller's input shape, which is what the user expects to see.
1029
+ Effect.catch(() => Effect.fail(new ValidationError({ entityType: errorEntityType, operation, cause: primaryCause }))))));
1030
+ // What's packed doesn't go through the marshaller's map, and packing refuses an instance itself.
1031
+ const readBack = packed ? undefined : readBackFor(declared);
1032
+ return readBack === undefined
1033
+ ? wire
1034
+ : wire.pipe(Effect.tap((encoded) => readBack(encoded).pipe(Effect.mapError((issue) => new ValidationError({
1035
+ entityType: errorEntityType,
1036
+ operation,
1037
+ cause: notReadBack("The value", issue),
1038
+ })))));
1039
+ };
1041
1040
  // ---------------------------------------------------------------------------
1042
1041
  // Decode a raw DynamoDB item → StreamEvent<TEvent>
1043
1042
  // ---------------------------------------------------------------------------
1044
1043
  const decodeEnvelope = Schema.decodeUnknownEffect(EventEnvelope);
1044
+ // `undefined` and an empty set are stored as absent attributes, in an event as
1045
+ // anywhere else, and read back as those values. A decode that dies on one fails as
1046
+ // 1.39.0's did, which decoded through the declared schema (`decodingAsBefore`).
1047
+ const decodingStream = (declared) => decodingAsBefore(readingStreamValues(declared), declared);
1048
+ const decodeEventData = decodingStream(eventUnion);
1049
+ const decodeMetadata = decodingStream(metadataSchema ?? Schema.Unknown);
1050
+ const decodeSnapshotState = decodingStream(snapshot?.schema ?? Schema.Unknown);
1045
1051
  /**
1046
1052
  * An event's stored `data` → its wire form (plain JSON), by the stored
1047
1053
  * form. A native value costs one `typeof` check.
@@ -1075,15 +1081,14 @@ export const makeStream = (config) => {
1075
1081
  // JSON string (`S`) parsed, compressed binary (`B`) decompressed and
1076
1082
  // parsed — whatever the stream's current `storedAs` says.
1077
1083
  const wireData = yield* unpackData(raw.data, "EventStore.decode");
1078
- const decoder = Schema.decodeUnknownEffect(eventUnion);
1079
- const data = yield* decoder(wireData).pipe(Effect.mapError(toValidationError("EventStore.decode")));
1084
+ const data = yield* decodeEventData(wireData).pipe(Effect.mapError(toValidationError("EventStore.decode")));
1080
1085
  // Metadata is decoded through its schema when the stream declares one —
1081
1086
  // the mirror of the encode performed by `append`. Streams without a
1082
1087
  // metadata schema surface the stored attribute map untouched.
1083
1088
  let metadata;
1084
1089
  if (raw.metadata !== undefined) {
1085
1090
  metadata = metadataSchema
1086
- ? yield* Schema.decodeUnknownEffect(metadataSchema)(raw.metadata).pipe(Effect.mapError(toValidationError("EventStore.decode.metadata")))
1091
+ ? yield* decodeMetadata(raw.metadata).pipe(Effect.mapError(toValidationError("EventStore.decode.metadata")))
1087
1092
  : raw.metadata;
1088
1093
  }
1089
1094
  const event = {
@@ -1166,7 +1171,7 @@ export const makeStream = (config) => {
1166
1171
  * accepts as the class type — is decoded into the schema's type first
1167
1172
  * rather than refused with `Expected <Class>`.
1168
1173
  */
1169
- const encodeSnapshotState = (state, operation) => encodeToWire(snapshot.schema, state, operation, snapshotEntityType);
1174
+ const encodeSnapshotState = (state, operation) => encodeToWire(snapshot.schema, state, operation, snapshotEntityType, stateStoredAs !== undefined);
1170
1175
  /**
1171
1176
  * Send an append — see {@link AppendTransaction} for its layout. Resolves to
1172
1177
  * the race a guarded additional put lost (so the transaction is built and
@@ -1429,9 +1434,7 @@ export const makeStream = (config) => {
1429
1434
  * `sealed` writes the seal marker (#166): only a sealing append's inline
1430
1435
  * snapshot carries it.
1431
1436
  */
1432
- const buildSnapshotItem = (streamId,
1433
- /** The partition the stream lives under ({@link locateStream}). */
1434
- pk, state, asOfVersion, now, operation, eventPartitions, sealed = false) => Effect.gen(function* () {
1437
+ const buildSnapshotItem = (streamId, state, asOfVersion, now, operation, eventPartitions, sealed = false) => Effect.gen(function* () {
1435
1438
  const encoded = yield* encodeSnapshotState(state, operation);
1436
1439
  const stored = stateStoredAs === undefined
1437
1440
  ? encoded
@@ -1441,7 +1444,7 @@ export const makeStream = (config) => {
1441
1444
  operation: `${operation}.packed`,
1442
1445
  });
1443
1446
  const item = {
1444
- pk,
1447
+ pk: composeStreamPk(streamId),
1445
1448
  sk: snapshotSk,
1446
1449
  __edd_e__: snapshotEntityType,
1447
1450
  streamId: composeStreamIdString(streamId),
@@ -1472,7 +1475,7 @@ export const makeStream = (config) => {
1472
1475
  // Top-level and native, beside `state`, so packing never touches it.
1473
1476
  if (sealed)
1474
1477
  item[SEALED_ATTRIBUTE] = true;
1475
- return toAttributeMap(item);
1478
+ return yield* marshalOrFail(snapshotEntityType, operation, () => toAttributeMap(item));
1476
1479
  });
1477
1480
  /**
1478
1481
  * The stream's own items of an append — everything but the caller's
@@ -1481,9 +1484,7 @@ export const makeStream = (config) => {
1481
1484
  * the request `append` would send. `undefined` for an append with nothing
1482
1485
  * to write (the historical no-op).
1483
1486
  */
1484
- const buildAppend = (streamId, events, expectedVersion, options,
1485
- /** Where the stream lives ({@link locateStream}); its current key when not given. */
1486
- streamPk) => Effect.gen(function* () {
1487
+ const buildAppend = (streamId, events, expectedVersion, options) => Effect.gen(function* () {
1487
1488
  const additionalOps = options?.additionalItems ?? [];
1488
1489
  const idempotency = options?.idempotency;
1489
1490
  const snapshotState = options?.snapshot;
@@ -1527,8 +1528,8 @@ export const makeStream = (config) => {
1527
1528
  return yield* snapshotUnavailable("append({ snapshot })");
1528
1529
  }
1529
1530
  // The head proof (#164), checked ahead of the no-op fast path, as the
1530
- // per-event options are. An index into `additionalItems` is checked by
1531
- // `append`, which has them (`measureAppend` does not take them).
1531
+ // per-event options are. An index into `additionalItems` is checked
1532
+ // against them by `headProofOp`.
1532
1533
  const headProof = options?.headProof;
1533
1534
  if (headProof !== undefined) {
1534
1535
  const problem = headProofShapeProblem(headProof);
@@ -1633,7 +1634,7 @@ export const makeStream = (config) => {
1633
1634
  "Nothing was written.",
1634
1635
  });
1635
1636
  }
1636
- const pk = streamPk ?? composeStreamPk(streamId);
1637
+ const pk = composeStreamPk(streamId);
1637
1638
  // Clock-backed timestamp (deterministic under TestClock; wall-clock in prod).
1638
1639
  const nowDateTime = yield* DateTime.now;
1639
1640
  const now = DateTime.formatIso(nowDateTime);
@@ -1664,7 +1665,7 @@ export const makeStream = (config) => {
1664
1665
  const evtType = event._tag ??
1665
1666
  event.constructor.identifier ??
1666
1667
  event.constructor.name;
1667
- const wire = yield* encodeToWire(memberSchemaFor(event), event, "EventStore.append");
1668
+ const wire = yield* encodeToWire(memberSchemaFor(event), event, "EventStore.append", entityType, dataStoredAs !== undefined);
1668
1669
  // Inject _tag for plain Schema.Class events; Schema.TaggedClass
1669
1670
  // events already carry _tag in their encoded form, which wins.
1670
1671
  const eventData = { _tag: evtType, ...wire };
@@ -1752,7 +1753,7 @@ export const makeStream = (config) => {
1752
1753
  return {
1753
1754
  Put: {
1754
1755
  TableName: tableName,
1755
- Item: toAttributeMap(item),
1756
+ Item: yield* marshalOrFail(entityType, "EventStore.append", () => toAttributeMap(item)),
1756
1757
  ConditionExpression: "attribute_not_exists(pk)",
1757
1758
  // The first put of a writer one version behind a seal lands on
1758
1759
  // the sealing event: its item tells `StreamSealed` from a
@@ -1799,7 +1800,7 @@ export const makeStream = (config) => {
1799
1800
  // transaction-size and item-size diagnosis count its stored bytes.
1800
1801
  let snapshotPut;
1801
1802
  if (snapshotState !== undefined) {
1802
- const item = yield* buildSnapshotItem(streamId, pk, snapshotState, expectedVersion + events.length, now, "EventStore.append.snapshot", eventPartitions, sealing);
1803
+ const item = yield* buildSnapshotItem(streamId, snapshotState, expectedVersion + events.length, now, "EventStore.append.snapshot", eventPartitions, sealing);
1803
1804
  // As a head proof, a sealed snapshot fails the proof (#166), and
1804
1805
  // returns its item so the failure is reported as `StreamSealed`.
1805
1806
  snapshotPut = {
@@ -1844,64 +1845,33 @@ export const makeStream = (config) => {
1844
1845
  * costs nothing; `ALL_OLD` returns the item on failure (response bytes
1845
1846
  * only), so a sealed one is reported as `StreamSealed`.
1846
1847
  */
1847
- // A stream still under its 1.36 key (#171) must not have been moved
1848
- // since it was located: `rekey` marks its first event once the stream
1849
- // is copied (`MOVED_ATTRIBUTE`). Checked on the first event — by the
1850
- // contiguity check when it reads that event — for an append that
1851
- // writes anything into the stream's partition: events onto the
1852
- // stream, or a command sentinel alone (a command that decided no
1853
- // events, recorded for exactly-once), which would otherwise land where
1854
- // nothing reads it. An append writing events from version 0 needs no
1855
- // check: its first Put fails on its own, the first event being there.
1856
- const located136 = streamPk !== undefined &&
1857
- streamPk !== composeStreamPk(streamId) &&
1858
- (events.length > 0 ? expectedVersion > 0 : sentinelPut !== undefined);
1859
- const foldLocation = located136 && needsContiguityCheck && expectedVersion === 1;
1860
1848
  const contiguityCheck = needsContiguityCheck
1861
1849
  ? {
1862
1850
  ConditionCheck: {
1863
1851
  TableName: tableName,
1864
1852
  Key: toAttributeMap({ pk, sk: composeEventSk(expectedVersion) }),
1865
- ConditionExpression: foldLocation
1866
- ? "attribute_exists(#pk) AND attribute_not_exists(#sealed) AND attribute_not_exists(#moved)"
1867
- : "attribute_exists(#pk) AND attribute_not_exists(#sealed)",
1868
- ExpressionAttributeNames: {
1869
- "#pk": "pk",
1870
- "#sealed": SEALED_ATTRIBUTE,
1871
- ...(foldLocation && { "#moved": MOVED_ATTRIBUTE }),
1872
- },
1853
+ ConditionExpression: "attribute_exists(#pk) AND attribute_not_exists(#sealed)",
1854
+ ExpressionAttributeNames: { "#pk": "pk", "#sealed": SEALED_ATTRIBUTE },
1873
1855
  ReturnValuesOnConditionCheckFailure: "ALL_OLD",
1874
1856
  },
1875
1857
  }
1876
1858
  : undefined;
1877
- const locationCheck = located136 && !foldLocation
1878
- ? {
1879
- ConditionCheck: {
1880
- TableName: tableName,
1881
- Key: toAttributeMap({ pk, sk: composeEventSk(1) }),
1882
- ConditionExpression: "attribute_exists(#pk) AND attribute_not_exists(#moved)",
1883
- ExpressionAttributeNames: { "#pk": "pk", "#moved": MOVED_ATTRIBUTE },
1884
- },
1885
- }
1886
- : undefined;
1887
1859
  const parts = {
1888
1860
  tableName,
1889
1861
  streamIdStr,
1890
1862
  contiguityCheck,
1891
- locationCheck,
1892
1863
  eventItems,
1893
1864
  sentinelPut,
1894
1865
  snapshotPut,
1895
1866
  };
1896
1867
  return parts;
1897
1868
  });
1898
- const append = (streamId, events, expectedVersion, options) => Effect.gen(function* () {
1899
- const additionalOps = options?.additionalItems ?? [];
1900
- const idempotency = options?.idempotency;
1901
- const headProof = options?.headProof;
1902
- // The additional item a head proof names (#164) must exist — checked
1903
- // before anything is read, and ahead of the no-op fast path. Its shape
1904
- // is checked first, by `buildAppend`'s own rule.
1869
+ /**
1870
+ * The additional item a head proof names (#164), which must exist: checked
1871
+ * before anything is read, and ahead of the no-op fast path. Its shape is
1872
+ * checked first, by `buildAppend`'s own rule.
1873
+ */
1874
+ const headProofOp = (headProof, additionalOps) => Effect.gen(function* () {
1905
1875
  const proofOp = typeof headProof === "object" && headProofShapeProblem(headProof) === undefined
1906
1876
  ? headProof.additionalItem
1907
1877
  : undefined;
@@ -1914,17 +1884,21 @@ export const makeStream = (config) => {
1914
1884
  "Nothing was written.",
1915
1885
  });
1916
1886
  }
1917
- // A stream 1.36 started is appended where it lives (#171).
1918
- const pk = yield* locateStream(streamId);
1919
- const parts = yield* buildAppend(streamId, events, expectedVersion, options, pk);
1920
- if (parts === undefined)
1921
- return { version: expectedVersion, events: [] };
1922
- const { tableName, streamIdStr, contiguityCheck, locationCheck, eventItems, sentinelPut, snapshotPut, } = parts;
1923
- const client = yield* Capacity.client;
1887
+ return proofOp;
1888
+ });
1889
+ /**
1890
+ * The append's one transaction, laid out — see {@link AppendTransaction}:
1891
+ * the caller's `additionalItems` compiled through the same builder
1892
+ * `Transaction.transactWrite` uses, so the two APIs cannot drift, and placed
1893
+ * among the stream's own items. `append` builds it for each attempt (a
1894
+ * guarded put among the additional items reads its item) and sends it;
1895
+ * `measureAppend` builds it once and measures it.
1896
+ */
1897
+ const buildAppendTransaction = (parts, additionalOps, expectedVersion, headProof, proofOp) => Effect.gen(function* () {
1898
+ const { tableName, contiguityCheck, eventItems, sentinelPut, snapshotPut } = parts;
1924
1899
  /**
1925
1900
  * Lay out the append's one transaction — see {@link AppendTransaction}:
1926
- * [0, C) version-contiguity ConditionCheck, then the
1927
- * 1.36 location check (#171) — C is 0 to 2
1901
+ * [0, C) version-contiguity ConditionCheck — C is 0 or 1
1928
1902
  * [C, C + E) event puts
1929
1903
  * [C + E, C + E + A) additional ITEMS (caller op order preserved)
1930
1904
  * then idempotency sentinel, then inline snapshot
@@ -1948,9 +1922,6 @@ export const makeStream = (config) => {
1948
1922
  if (contiguityCheck !== undefined) {
1949
1923
  pushStreamItem(contiguityCheck, entityType, "the version-contiguity check");
1950
1924
  }
1951
- if (locationCheck !== undefined) {
1952
- pushStreamItem(locationCheck, entityType, "the check that rekey has not moved the stream");
1953
- }
1954
1925
  const guardCount = items.length;
1955
1926
  for (const [i, item] of eventItems.entries()) {
1956
1927
  pushStreamItem(item, entityType, `the event at version ${expectedVersion + i + 1}`);
@@ -1979,33 +1950,44 @@ export const makeStream = (config) => {
1979
1950
  headProof,
1980
1951
  };
1981
1952
  };
1953
+ // Caller-owned items, compiled through the same builder
1954
+ // `Transaction.transactWrite` uses, so the two APIs cannot drift.
1955
+ // Another stream's append (#166) is accepted here, and only here.
1956
+ const additional = yield* buildTransactWriteItems(additionalOps, "EventStore.append.additionalItems", { streams: true });
1957
+ // An item without a condition of its own proves nothing about the
1958
+ // head: accepting it would drop the gap protection silently. Nor
1959
+ // does another stream's append: its conditions are its stream's.
1960
+ if (proofOp !== undefined && !additional.conditioned.has(proofOp)) {
1961
+ const named = additionalOps[proofOp];
1962
+ return yield* new ValidationError({
1963
+ entityType,
1964
+ operation: "EventStore.append.headProof",
1965
+ cause: isStreamAppendOp(named)
1966
+ ? `headProof names additionalItems[${proofOp}], which is an append of stream ` +
1967
+ `"${named.streamName}" (appendOp): its conditions prove that stream's head, ` +
1968
+ "not this one's. Name an item conditioned on this stream being at " +
1969
+ "expectedVersion. Nothing was written."
1970
+ : `headProof names additionalItems[${proofOp}], which carries no condition of its ` +
1971
+ "own: the proof must be conditioned on the stream being at expectedVersion " +
1972
+ "(`.condition()`, `create()` or `Transaction.check`). Nothing was written.",
1973
+ });
1974
+ }
1975
+ return layout(additional);
1976
+ });
1977
+ const append = (streamId, events, expectedVersion, options) => Effect.gen(function* () {
1978
+ const additionalOps = options?.additionalItems ?? [];
1979
+ const idempotency = options?.idempotency;
1980
+ const headProof = options?.headProof;
1981
+ const proofOp = yield* headProofOp(headProof, additionalOps);
1982
+ const parts = yield* buildAppend(streamId, events, expectedVersion, options);
1983
+ if (parts === undefined)
1984
+ return { version: expectedVersion, events: [] };
1985
+ const client = yield* Capacity.client;
1982
1986
  // A guarded put among the additional items reads its item; a race with
1983
1987
  // that read cancels the append, which is then built and written again.
1984
1988
  let lost;
1985
1989
  for (let attempt = 0; attempt < GUARDED_TRANSACTION_ATTEMPTS; attempt++) {
1986
- // Caller-owned items, compiled through the same builder
1987
- // `Transaction.transactWrite` uses, so the two APIs cannot drift.
1988
- // Another stream's append (#166) is accepted here, and only here.
1989
- const additional = yield* buildTransactWriteItems(additionalOps, "EventStore.append.additionalItems", { streams: true });
1990
- // An item without a condition of its own proves nothing about the
1991
- // head: accepting it would drop the gap protection silently. Nor
1992
- // does another stream's append: its conditions are its stream's.
1993
- if (proofOp !== undefined && !additional.conditioned.has(proofOp)) {
1994
- const named = additionalOps[proofOp];
1995
- return yield* new ValidationError({
1996
- entityType,
1997
- operation: "EventStore.append.headProof",
1998
- cause: isStreamAppendOp(named)
1999
- ? `headProof names additionalItems[${proofOp}], which is an append of stream ` +
2000
- `"${named.streamName}" (appendOp): its conditions prove that stream's head, ` +
2001
- "not this one's. Name an item conditioned on this stream being at " +
2002
- "expectedVersion. Nothing was written."
2003
- : `headProof names additionalItems[${proofOp}], which carries no condition of its ` +
2004
- "own: the proof must be conditioned on the stream being at expectedVersion " +
2005
- "(`.condition()`, `create()` or `Transaction.check`). Nothing was written.",
2006
- });
2007
- }
2008
- const tx = layout(additional);
1990
+ const tx = yield* buildAppendTransaction(parts, additionalOps, expectedVersion, headProof, proofOp);
2009
1991
  // DynamoDB's rules — one operation per item (an additional item
2010
1992
  // repeating an event, the contiguity check, the idempotency sentinel
2011
1993
  // or the inline snapshot, or another additional item), 100 items,
@@ -2013,7 +1995,7 @@ export const makeStream = (config) => {
2013
1995
  // `sendAppendTransaction` diagnoses DynamoDB's rejection (#144). The
2014
1996
  // items carry packed `data` / `state` as stored (#147), so the
2015
1997
  // diagnosis attributes stored bytes.
2016
- const outcome = yield* sendAppendTransaction(client, tx, streamIdStr, idempotency?.commandId);
1998
+ const outcome = yield* sendAppendTransaction(client, tx, parts.streamIdStr, idempotency?.commandId);
2017
1999
  if (outcome === undefined) {
2018
2000
  return { version: expectedVersion + events.length, events };
2019
2001
  }
@@ -2044,7 +2026,7 @@ export const makeStream = (config) => {
2044
2026
  return yield* refuse(`An append op of stream "${config.streamName}" needs at least one event: with none ` +
2045
2027
  "it writes nothing. Nothing was written.");
2046
2028
  }
2047
- const parts = (yield* buildAppend(streamId, events, expectedVersion, options, yield* locateStream(streamId)));
2029
+ const parts = (yield* buildAppend(streamId, events, expectedVersion, options));
2048
2030
  const items = [];
2049
2031
  const sources = [];
2050
2032
  const label = `${source} (stream "${config.streamName}", ${parts.streamIdStr})`;
@@ -2052,10 +2034,6 @@ export const makeStream = (config) => {
2052
2034
  items.push(parts.contiguityCheck);
2053
2035
  sources.push([entityType, `${label}: the version-contiguity check`]);
2054
2036
  }
2055
- if (parts.locationCheck !== undefined) {
2056
- items.push(parts.locationCheck);
2057
- sources.push([entityType, `${label}: the check that rekey has not moved the stream`]);
2058
- }
2059
2037
  const guardCount = items.length;
2060
2038
  for (const [i, item] of parts.eventItems.entries()) {
2061
2039
  items.push(item);
@@ -2096,38 +2074,62 @@ export const makeStream = (config) => {
2096
2074
  // measureAppend / measureSnapshot — caller-side size planning (#147, R1)
2097
2075
  // ---------------------------------------------------------------------------
2098
2076
  const measureAppend = (streamId, events, expectedVersion, options) => Effect.gen(function* () {
2099
- if (options?.additionalItems !== undefined) {
2077
+ const additionalOps = options?.additionalItems;
2078
+ const headProof = options?.headProof;
2079
+ // A `{ additionalItem }` proof is checked against the additional items
2080
+ // when they are given, as `append` checks it. Without them it stands for
2081
+ // an item the caller adds, so the append is a transaction.
2082
+ const proofOp = additionalOps === undefined ? undefined : yield* headProofOp(headProof, additionalOps);
2083
+ const parts = yield* buildAppend(streamId, events, expectedVersion, options);
2084
+ if (parts === undefined) {
2085
+ return {
2086
+ events: [],
2087
+ sentinel: undefined,
2088
+ snapshot: undefined,
2089
+ transactionBytes: 0,
2090
+ requestBytes: 0,
2091
+ };
2092
+ }
2093
+ // The transaction `append` would send, built by the same code: the
2094
+ // stream's items and the items the caller's `additionalItems` build, in
2095
+ // the same places. Nothing is sent: an item `append` reads the table to
2096
+ // build has no size without that read, and fails the measurement.
2097
+ const built = yield* Capacity.withoutRequests(buildAppendTransaction(parts, additionalOps ?? [], expectedVersion, headProof, proofOp));
2098
+ if (built.refused !== undefined) {
2099
+ const { command, input } = built.refused;
2100
2100
  return yield* new ValidationError({
2101
2101
  entityType,
2102
2102
  operation: "EventStore.measureAppend",
2103
- cause: "measureAppend does not measure additionalItems (building a guarded put reads the " +
2104
- "table): measure the stream's own items without them, and add the size of your " +
2105
- "own items.",
2103
+ cause: `an additional item is built from the stored row: append would send ${command}` +
2104
+ (typeof input.TableName === "string" ? ` on table "${input.TableName}"` : "") +
2105
+ " to build it (a put of a versioned or unique-constrained entity, or a create " +
2106
+ "over a projection tombstone, reads its item). measureAppend sends no request, " +
2107
+ "so it has no size to give for this append. Nothing was read or written.",
2106
2108
  });
2107
2109
  }
2108
- const parts = yield* buildAppend(streamId, events, expectedVersion, options);
2109
- if (parts === undefined) {
2110
- return { events: [], sentinel: undefined, snapshot: undefined, transactionBytes: 0 };
2110
+ if (Exit.isFailure(built.exit)) {
2111
+ // No request was refused, so nothing here is a client error.
2112
+ return yield* Effect.failCause(built.exit.cause);
2111
2113
  }
2114
+ const tx = built.exit.value;
2115
+ // An append of one event and nothing else is sent as a `PutItem`
2116
+ // carrying a write token (#173), measured here with a placeholder token
2117
+ // of its length.
2118
+ const single = typeof headProof !== "object" && isSingleEventPut(tx.items, tx.eventCount);
2119
+ const sent = single
2120
+ ? [withWriteToken(tx.items[0], "0".repeat(WRITE_TOKEN_LENGTH))]
2121
+ : tx.items;
2112
2122
  const putBytes = (item) => itemBytes(item.Put?.Item ?? {});
2113
- const laidOut = [
2114
- ...(parts.contiguityCheck === undefined ? [] : [parts.contiguityCheck]),
2115
- ...parts.eventItems,
2116
- ...(parts.sentinelPut === undefined ? [] : [parts.sentinelPut]),
2117
- ...(parts.snapshotPut === undefined ? [] : [parts.snapshotPut]),
2118
- ];
2119
- // A single-item append is sent as a `PutItem` carrying a write token
2120
- // (#173), whose bytes are measured here as a placeholder of its length.
2121
- // A `{ additionalItem }` proof means the append carries that item, so
2122
- // it is a transaction.
2123
- const single = typeof options?.headProof !== "object" && isSingleEventPut(laidOut, parts.eventItems.length);
2124
- const owned = single ? [withWriteToken(laidOut[0], "0".repeat(WRITE_TOKEN_LENGTH))] : laidOut;
2125
- const eventItems = single ? owned : parts.eventItems;
2123
+ // What the client sends beside the items: the request as `append` sends it.
2124
+ const fields = yield* Capacity.requestFields;
2126
2125
  const measurement = {
2127
- events: eventItems.map(putBytes),
2126
+ events: (single ? sent : parts.eventItems).map(putBytes),
2128
2127
  sentinel: parts.sentinelPut === undefined ? undefined : putBytes(parts.sentinelPut),
2129
2128
  snapshot: parts.snapshotPut === undefined ? undefined : putBytes(parts.snapshotPut),
2130
- transactionBytes: owned.reduce((sum, item) => sum + transactItemBytes(item), 0),
2129
+ transactionBytes: sent.reduce((sum, item) => sum + transactItemBytes(item), 0),
2130
+ requestBytes: single
2131
+ ? jsonBytes({ ...sent[0].Put, ...fields })
2132
+ : transactWriteBodyBytes({ TransactItems: sent, ...fields }),
2131
2133
  };
2132
2134
  return measurement;
2133
2135
  });
@@ -2135,7 +2137,7 @@ export const makeStream = (config) => {
2135
2137
  if (snapshot === undefined)
2136
2138
  return yield* snapshotUnavailable("measureSnapshot");
2137
2139
  const now = DateTime.formatIso(yield* DateTime.now);
2138
- const item = yield* buildSnapshotItem(streamId, composeStreamPk(streamId), state, asOfVersion, now, "EventStore.measureSnapshot");
2140
+ const item = yield* buildSnapshotItem(streamId, state, asOfVersion, now, "EventStore.measureSnapshot");
2139
2141
  return itemBytes(item);
2140
2142
  });
2141
2143
  // ---------------------------------------------------------------------------
@@ -2239,69 +2241,29 @@ export const makeStream = (config) => {
2239
2241
  operation: "EventStore.writeSnapshot",
2240
2242
  entityType: snapshotEntityType,
2241
2243
  });
2242
- // A stream located under its 1.36 key (#171) that `rekey` moves after
2243
- // the locate is written at its current key on a second pass.
2244
- for (let pass = 0; pass < 2; pass++) {
2245
- const pk = yield* locateStream(streamId);
2246
- // Packed per `snapshot.storedAs` (#147): the diagnosis below measures
2247
- // the stored bytes.
2248
- const item = yield* buildSnapshotItem(streamId, pk, state, asOfVersion, now, "EventStore.writeSnapshot");
2249
- const put = {
2250
- TableName: tableName,
2251
- Item: item,
2252
- // Monotonic: never regress the cache. Losing this race is a no-op,
2253
- // not an error — the events it summarises are already durable.
2254
- ConditionExpression: "attribute_not_exists(#pk) OR #asOfVersion < :asOfVersion",
2255
- ExpressionAttributeNames: { "#pk": "pk", "#asOfVersion": "asOfVersion" },
2256
- ExpressionAttributeValues: toAttributeMap({ ":asOfVersion": asOfVersion }),
2257
- };
2258
- const target = (written) => () => transactItemTarget(written, tableName, ["pk", "sk"], snapshotEntityType, "the snapshot");
2259
- if (pk === composeStreamPk(streamId)) {
2260
- return yield* client.putItem(put).pipe(Effect.catchIf((error) => isAwsConditionalCheckFailed(error.cause), () => Effect.void),
2261
- // An oversized snapshot is DynamoDB's to reject (#144); named here.
2262
- diagnoseFailure({
2263
- sent: () => ({ _tag: "Item", item: { Put: put }, target: target({ Put: put }) }),
2264
- keys,
2265
- rewrite,
2266
- }));
2267
- }
2268
- // Under its 1.36 key, the snapshot is written there only while the
2269
- // stream is — checked on its first event, as an append checks it.
2270
- const items = [
2271
- { Put: put },
2272
- {
2273
- ConditionCheck: {
2274
- TableName: tableName,
2275
- Key: toAttributeMap({ pk, sk: composeEventSk(1) }),
2276
- ConditionExpression: "attribute_exists(#pk) AND attribute_not_exists(#moved)",
2277
- ExpressionAttributeNames: { "#pk": "pk", "#moved": MOVED_ATTRIBUTE },
2278
- },
2279
- },
2280
- ];
2281
- const moved = yield* client.transactWriteItems({ TransactItems: [...items] }).pipe(Effect.as(false), Effect.catch((error) => {
2282
- if (!isAwsTransactionCancelled(error.cause))
2283
- return Effect.fail(error);
2284
- const reasons = error.cause.CancellationReasons ?? [];
2285
- if (reasons[1]?.Code === "ConditionalCheckFailed")
2286
- return Effect.succeed(true);
2287
- return reasons[0]?.Code === "ConditionalCheckFailed"
2288
- ? Effect.succeed(false)
2289
- : Effect.fail(error);
2290
- }), diagnoseFailure({
2291
- sent: () => ({
2292
- _tag: "Transaction",
2293
- items,
2294
- targets: () => [
2295
- target(items[0])(),
2296
- transactItemTarget(items[1], tableName, ["pk", "sk"], entityType, "the check that rekey has not moved the stream"),
2297
- ],
2298
- }),
2299
- keys,
2300
- rewrite,
2301
- }));
2302
- if (!moved)
2303
- return;
2304
- }
2244
+ // Packed per `snapshot.storedAs` (#147): the diagnosis below measures
2245
+ // the stored bytes.
2246
+ const item = yield* buildSnapshotItem(streamId, state, asOfVersion, now, "EventStore.writeSnapshot");
2247
+ const put = {
2248
+ TableName: tableName,
2249
+ Item: item,
2250
+ // Monotonic: never regress the cache. Losing this race is a no-op,
2251
+ // not an error — the events it summarises are already durable.
2252
+ ConditionExpression: "attribute_not_exists(#pk) OR #asOfVersion < :asOfVersion",
2253
+ ExpressionAttributeNames: { "#pk": "pk", "#asOfVersion": "asOfVersion" },
2254
+ ExpressionAttributeValues: toAttributeMap({ ":asOfVersion": asOfVersion }),
2255
+ };
2256
+ yield* client.putItem(put).pipe(Effect.catchIf((error) => isAwsConditionalCheckFailed(error.cause), () => Effect.void),
2257
+ // An oversized snapshot is DynamoDB's to reject (#144); named here.
2258
+ diagnoseFailure({
2259
+ sent: () => ({
2260
+ _tag: "Item",
2261
+ item: { Put: put },
2262
+ target: () => transactItemTarget({ Put: put }, tableName, ["pk", "sk"], snapshotEntityType, "the snapshot"),
2263
+ }),
2264
+ keys,
2265
+ rewrite,
2266
+ }));
2305
2267
  });
2306
2268
  /**
2307
2269
  * Decode a stored snapshot item. A snapshot that fails to decode through the
@@ -2312,7 +2274,7 @@ export const makeStream = (config) => {
2312
2274
  // `stateDispatch` — then decoded through the state schema as before.
2313
2275
  (stateDispatch && (typeof raw.state === "string" || raw.state instanceof Uint8Array)
2314
2276
  ? withRegistry((registry) => unpackStoredSync(raw.state, registry, { entityType: snapshotEntityType, operation }, "state"))
2315
- : Effect.succeed(raw.state)).pipe(Effect.flatMap((state) => Schema.decodeUnknownEffect(snapshot.schema)(state).pipe(Effect.mapError((cause) => new ValidationError({ entityType: snapshotEntityType, operation, cause })))), Effect.map((state) => ({
2277
+ : Effect.succeed(raw.state)).pipe(Effect.flatMap((state) => decodeSnapshotState(state).pipe(Effect.mapError((cause) => new ValidationError({ entityType: snapshotEntityType, operation, cause })))), Effect.map((state) => ({
2316
2278
  state,
2317
2279
  asOfVersion: raw.asOfVersion,
2318
2280
  timestamp: raw.timestamp,
@@ -2324,7 +2286,7 @@ export const makeStream = (config) => {
2324
2286
  const result = yield* client.getItem({
2325
2287
  TableName: tableName,
2326
2288
  Key: toAttributeMap({
2327
- pk: yield* locateStream(streamId),
2289
+ pk: composeStreamPk(streamId),
2328
2290
  sk: snapshotSk,
2329
2291
  }),
2330
2292
  ...(consistentRead ? { ConsistentRead: true } : {}),
@@ -2338,7 +2300,7 @@ export const makeStream = (config) => {
2338
2300
  const result = yield* client.getItem({
2339
2301
  TableName: tableName,
2340
2302
  Key: toAttributeMap({
2341
- pk: yield* locateStream(streamId),
2303
+ pk: composeStreamPk(streamId),
2342
2304
  sk: composeEventSk(version),
2343
2305
  }),
2344
2306
  ...(consistentRead ? { ConsistentRead: true } : {}),
@@ -2422,7 +2384,7 @@ export const makeStream = (config) => {
2422
2384
  FilterExpression: "#e IN (:eventType, :snapshotType)",
2423
2385
  ExpressionAttributeNames: { "#pk": "pk", "#sk": "sk", "#e": "__edd_e__" },
2424
2386
  ExpressionAttributeValues: toAttributeMap({
2425
- ":pk": yield* locateStream(streamId),
2387
+ ":pk": composeStreamPk(streamId),
2426
2388
  ":first": eventSkPrefix,
2427
2389
  ":snapshot": snapshotSk,
2428
2390
  ":eventType": entityType,
@@ -2509,7 +2471,7 @@ export const makeStream = (config) => {
2509
2471
  const { name: tableName } = yield* config.table.Tag;
2510
2472
  const result = yield* client.getItem({
2511
2473
  TableName: tableName,
2512
- Key: toAttributeMap({ pk: yield* locateStream(streamId), sk: composeCommandSk(commandId) }),
2474
+ Key: toAttributeMap({ pk: composeStreamPk(streamId), sk: composeCommandSk(commandId) }),
2513
2475
  ConsistentRead: true,
2514
2476
  ProjectionExpression: "#pk",
2515
2477
  ExpressionAttributeNames: { "#pk": "pk" },
@@ -2538,8 +2500,6 @@ export const makeStream = (config) => {
2538
2500
  // Consumed capacity reports these queries under the stream name, as
2539
2501
  // every `EventStream.*` operation does (#174).
2540
2502
  operationTarget: config.streamName,
2541
- // A stream 1.36 started is read where it lives (#171).
2542
- ...locatedPrepare(streamId),
2543
2503
  // Bound to the event SK range so non-event items in the stream partition
2544
2504
  // (the snapshot) are excluded at the key-condition level. A caller-supplied
2545
2505
  // `Query.where` replaces this — the `__edd_e__` filter still applies.
@@ -2622,9 +2582,6 @@ export const makeStream = (config) => {
2622
2582
  },
2623
2583
  keyFields: [idx.pk, idx.sk, "pk", "sk"],
2624
2584
  operationTarget: config.streamName,
2625
- // A stream-scoped index of a stream 1.36 started is read in the 1.36
2626
- // partition, as its events are (#171).
2627
- ...(derived ? {} : locatedPrepare(streamId)),
2628
2585
  // A "keys" index holds no events: an LSI has DynamoDB fetch them
2629
2586
  // (`Select: ALL_ATTRIBUTES`), a GSI fetches each page's with
2630
2587
  // `BatchGetItem` on the table key.
@@ -2636,9 +2593,7 @@ export const makeStream = (config) => {
2636
2593
  }
2637
2594
  : {}),
2638
2595
  });
2639
- return derived
2640
- ? Query.filterExpr(query, streamPkFilter(streamPk, composeStreamPk136(streamId)))
2641
- : query;
2596
+ return derived ? Query.filterExpr(query, streamPkFilter(streamPk)) : query;
2642
2597
  };
2643
2598
  /**
2644
2599
  * @internal The decoder of events read through `idx`.
@@ -2717,18 +2672,18 @@ export const makeStream = (config) => {
2717
2672
  // is safe because all operations correctly require DynamoClient | TableConfig at
2718
2673
  // runtime — the user must provide these layers.
2719
2674
  // ---------------------------------------------------------------------------
2720
- // rekey (#171): the stream's part in `db.tables.<Table>.rekey()`
2675
+ // rekey: the stream's part in `db.tables.<Table>.rekey()`
2721
2676
  //
2722
- // A stream 1.36 started under a partition key whose text changed (a number
2723
- // stream id composite) moves whole, while writers keep appending: every row
2724
- // is COPIED to the current key — where nothing is, or a snapshot over an
2725
- // older one; one transaction then FLIPS it — marks its first event moved,
2726
- // conditioned on the head and the snapshot being as copied — so
2727
- // `locateStream` reads the current key from then on, and an append or
2728
- // snapshot write that located the 1.36 key before fails its location
2729
- // check; the 1.36 rows are DELETED last, each while it is as read, the
2730
- // events from the head down and the first event last. A flip or delete
2731
- // that loses to a write reads again.
2677
+ // A stream under a partition key other text composed for its id moves whole:
2678
+ // every row is COPIED to the current key, where nothing is, or a snapshot over
2679
+ // an older one; one transaction then FLIPS it, marking its first event moved,
2680
+ // conditioned on the head and the snapshot being as copied, so a run stopped
2681
+ // after that resumes by finishing the delete; the old rows are DELETED last,
2682
+ // each while it is as read, the events from the head down and the first event
2683
+ // last. A flip or delete that loses to a write reads again. Another stream's
2684
+ // rows at the current key, themselves under other text, move first. Rows of
2685
+ // another stream id that landed in the same partition are its own: nothing is
2686
+ // merged.
2732
2687
  // ---------------------------------------------------------------------------
2733
2688
  /** Attributes holding the stream's partition key: a GSI index's partition. */
2734
2689
  const partitionAttributes = streamIndexes.flatMap((idx) => (idx.type === "gsi" ? [idx.pk] : []));
@@ -2764,7 +2719,7 @@ export const makeStream = (config) => {
2764
2719
  const part = parts[i];
2765
2720
  const values = [part];
2766
2721
  const n = Number(part);
2767
- if (part.trim() !== "" && Number.isFinite(n) && String(n) === part)
2722
+ if (part.trim() !== "" && String(n) === part)
2768
2723
  values.push(n);
2769
2724
  if (/^-?\d+$/.test(part) && String(BigInt(part)) === part)
2770
2725
  values.push(BigInt(part));
@@ -2774,30 +2729,45 @@ export const makeStream = (config) => {
2774
2729
  });
2775
2730
  };
2776
2731
  /**
2777
- * Where a stream row belongs now and where 1.36 put it, from its
2778
- * `streamId`: the readings of the id whose keys hold the row's partition
2779
- * key. `"ambiguous"` when readings disagree on where it belongs.
2732
+ * Where a stream row belongs now, from its `streamId`: the readings of the id
2733
+ * that compose the row's partition key under some key text. `"ambiguous"` when
2734
+ * readings disagree on where it belongs; `undefined` when none composes it.
2780
2735
  */
2781
2736
  const streamKeys = (row) => {
2782
2737
  const pk = row.pk?.S;
2783
2738
  const text = row.streamId?.S;
2784
2739
  if (pk === undefined || text === undefined)
2785
2740
  return undefined;
2741
+ const undersNow = [
2742
+ KeyText136.schema136(schema),
2743
+ KeyText136.schema137(schema),
2744
+ KeyText136.schemaEscaped(schema),
2745
+ ];
2746
+ const holds = (under, candidate) => {
2747
+ try {
2748
+ return composeStreamPkUnder(under, candidate) === pk;
2749
+ }
2750
+ catch {
2751
+ // No key text for it under this form.
2752
+ return false;
2753
+ }
2754
+ };
2786
2755
  let found;
2787
2756
  for (const candidate of streamIdCandidates(text)) {
2757
+ if (!undersNow.some((under) => holds(under, candidate)))
2758
+ continue;
2759
+ let current;
2788
2760
  try {
2789
- const current = composeStreamPk(candidate);
2790
- const old = composeStreamPk136(candidate, true) ?? current;
2791
- if (pk !== current && pk !== old)
2792
- continue;
2793
- if (found === undefined)
2794
- found = { current, old };
2795
- else if (found.current !== current || found.old !== old)
2796
- return "ambiguous";
2761
+ current = composeStreamPk(candidate);
2797
2762
  }
2798
2763
  catch {
2799
- // Not this reading of the id.
2764
+ // `NaN` under `escapeKeys: true`: no key now.
2765
+ continue;
2800
2766
  }
2767
+ if (found === undefined)
2768
+ found = { current };
2769
+ else if (found.current !== current)
2770
+ return "ambiguous";
2801
2771
  }
2802
2772
  return found;
2803
2773
  };
@@ -2813,15 +2783,16 @@ export const makeStream = (config) => {
2813
2783
  /** How many attempts a stream move makes in all: a flip that loses to a write copies again. */
2814
2784
  const STREAM_MOVE_ATTEMPTS = 8;
2815
2785
  /**
2816
- * Move the stream under `from` to `to` — or, when its first event is no
2817
- * longer under `from` (moved by an earlier run), the rows left there.
2818
- * Command sentinels whose TTL has passed are gone, whether or not DynamoDB
2819
- * has deleted them yet.
2786
+ * Move the stream `streamIdText` under `from` to `to` — or, when its first
2787
+ * event is no longer under `from` (moved by an earlier run), the rows left
2788
+ * there. Command sentinels whose TTL has passed are gone, whether or not
2789
+ * DynamoDB has deleted them yet.
2820
2790
  */
2821
- const moveStream = (ctx, from, to, streamIdText, ttlAttribute) => Effect.gen(function* () {
2791
+ const moveStream = (ctx, from, to, streamIdText, ttlAttribute, depth) => Effect.gen(function* () {
2822
2792
  const client = yield* Capacity.client;
2823
2793
  const firstSk = composeEventSk(1);
2824
2794
  const nowSeconds = DateTime.toEpochSeconds(yield* DateTime.now);
2795
+ const unprovable = Rekey.unprovableRow(ctx);
2825
2796
  const live = (row) => {
2826
2797
  const ttl = row[ttlAttribute]?.N;
2827
2798
  return ttl === undefined || Number(ttl) > nowSeconds;
@@ -2852,6 +2823,13 @@ export const makeStream = (config) => {
2852
2823
  }
2853
2824
  return copy;
2854
2825
  };
2826
+ /** This stream's rows left under the old key: another id's there are its own to move. */
2827
+ const readOwn = Effect.map(readAll(from), (rows) => rows.filter((row) => row.streamId?.S === streamIdText));
2828
+ /** A row at `to` that belongs elsewhere: another stream's, under other key text. */
2829
+ const elsewhere = (row) => {
2830
+ const keys = streamKeys(row);
2831
+ return typeof keys === "object" && keys.current !== to;
2832
+ };
2855
2833
  const skOf = (row) => row.sk?.S ?? "";
2856
2834
  const versionOf = (row) => row.__edd_e__?.S === entityType ? Number(row.version?.N ?? 0) : 0;
2857
2835
  const asOfOf = (row) => Number(row.asOfVersion?.N ?? 0);
@@ -2890,28 +2868,46 @@ export const makeStream = (config) => {
2890
2868
  }),
2891
2869
  })
2892
2870
  .pipe(Effect.as(true), Effect.catch(cancelled));
2893
- /** Delete `row` at `from` while it is as read. `false` when a write changed it. */
2871
+ /**
2872
+ * `row` as read, whole, or, a row too wide for that, the strongest guard that fits, as
2873
+ * 1.39.0 sent: only a stream already part-moved deletes one (`unguardedRows`).
2874
+ */
2875
+ const guardOfRow = (row) => wholeRowGuard(row, "pk", [], [], []) ?? asReadGuard(row, "pk", []);
2876
+ /**
2877
+ * With writes going on (`unprovable`), the rows of a stream nothing of which has moved that
2878
+ * are too wide to guard whole, each reported `unguarded`, before anything is copied: its rows
2879
+ * move together, so one leaves the stream as it is. One already part-moved (a row of it under
2880
+ * `to`, or flipped) is finished under the strongest guard that fits (`guardOfRow`).
2881
+ */
2882
+ const unguardedRows = (rows) => {
2883
+ if (unprovable === "strongest")
2884
+ return undefined;
2885
+ const unguarded = rows.filter((row) => wholeRowGuard(row, "pk", [], [], []) === undefined);
2886
+ if (unguarded.length === 0)
2887
+ return undefined;
2888
+ return Rekey.mergeTallies(...unguarded.map((row) => conflict("unguarded", `${Rekey.UNGUARDED_MESSAGE} The stream's other rows are left with it.`, skOf(row))));
2889
+ };
2890
+ /** Delete `row` at `from` while it is as read (`guardOfRow`). `false` when a write changed it. */
2894
2891
  const remove = (row) => client
2895
2892
  .deleteItem({
2896
2893
  TableName: ctx.tableName,
2897
2894
  Key: toAttributeMap({ pk: from, sk: skOf(row) }),
2898
- ...asReadGuard(row, "pk", []),
2895
+ ...guardOfRow(row),
2899
2896
  })
2900
2897
  .pipe(Effect.as(true), Effect.catch(cancelled));
2901
2898
  /**
2902
2899
  * Bring every row still under `from` over, once the stream lives at
2903
2900
  * `to`: a row `to` lacks is copied (a command sentinel written beside
2904
- * the flip, a row an append that located the stream before the flip
2905
- * wrote), a snapshot newer than `to`'s copied over it, and then each is
2906
- * deleted while it is as read — the events from the head down, the
2907
- * other rows, and the first event last: until it goes, the stream is
2908
- * located here, and an append that located it here fails its check. A
2909
- * row `to` holds differently (an event or sentinel written under both
2910
- * keys) is a conflict, and the rows are left as they are. `undefined`
2911
- * when a write landed in between: read again.
2901
+ * the flip), a snapshot newer than `to`'s copied over it, and then each
2902
+ * is deleted while it is as read — the events from the head down, the
2903
+ * other rows, and the first event last: until it goes, the next run
2904
+ * finds the stream here and finishes the move. A row `to` holds
2905
+ * differently (an event or sentinel written under both keys) is a
2906
+ * conflict, and the rows are left as they are. `undefined` when a write
2907
+ * landed in between: read again.
2912
2908
  */
2913
2909
  const drain = Effect.gen(function* () {
2914
- const left = yield* readAll(from);
2910
+ const left = yield* readOwn;
2915
2911
  const there = new Map((yield* readAll(to)).map((row) => [skOf(row), row]));
2916
2912
  const differing = [];
2917
2913
  for (const row of left) {
@@ -2924,7 +2920,7 @@ export const makeStream = (config) => {
2924
2920
  }
2925
2921
  if (differing.length > 0) {
2926
2922
  return Rekey.mergeTallies(...differing.map((row) => conflict("bothKeys", "a row of it is under both partition keys, and the two differ; the rows " +
2927
- "under its 1.36 key are left as they are.", skOf(row))));
2923
+ "under its old key are left as they are.", skOf(row))));
2928
2924
  }
2929
2925
  for (const row of left) {
2930
2926
  const held = there.get(skOf(row));
@@ -2947,32 +2943,61 @@ export const makeStream = (config) => {
2947
2943
  }
2948
2944
  return { moved: { stream: left.length } };
2949
2945
  });
2946
+ let tally = {};
2950
2947
  for (let attempt = 0; attempt < STREAM_MOVE_ATTEMPTS; attempt++) {
2951
- const rows = yield* readAll(from);
2948
+ const rows = yield* readOwn;
2952
2949
  // Moved since the scan read it.
2953
2950
  if (rows.length === 0)
2954
- return {};
2951
+ return tally;
2955
2952
  const first = rows.find((row) => skOf(row) === firstSk);
2956
2953
  // Flipped by an earlier attempt or run — or never started here: the
2957
2954
  // stream lives at `to`, and the rows left move to it.
2958
2955
  const flipped = first === undefined || first[MOVED_ATTRIBUTE] !== undefined;
2959
2956
  if (!flipped) {
2960
- const there = new Map((yield* readAll(to)).map((row) => [skOf(row), row]));
2957
+ const atTarget = yield* readAll(to);
2958
+ // Nothing of it has moved while no row of it is under `to` (`unguardedRows`).
2959
+ if (!atTarget.some((row) => !elsewhere(row))) {
2960
+ const refused = unguardedRows(rows);
2961
+ if (refused !== undefined)
2962
+ return Rekey.mergeTallies(tally, refused);
2963
+ }
2964
+ // Another stream under other key text moves out first.
2965
+ const stale = atTarget.find(elsewhere);
2966
+ if (stale !== undefined) {
2967
+ if (depth >= Rekey.DISPLACE_DEPTH) {
2968
+ return Rekey.mergeTallies(tally, conflict("contended", "too many streams under other key text hold each other's current keys."));
2969
+ }
2970
+ const displaced = yield* Rekey.displace(ctx, (under) => rekeyStreamRow(stale, under, depth + 1));
2971
+ tally = Rekey.mergeTallies(tally, displaced);
2972
+ // A dry run moved nothing: what would stop that stream is what would leave it there.
2973
+ const stillThere = ctx.dryRun
2974
+ ? (displaced.conflicts ?? []).length > 0
2975
+ : (yield* readAll(to)).some(elsewhere);
2976
+ if (stillThere) {
2977
+ return Rekey.mergeTallies(tally, conflict("taken", "rows of another stream are under its current partition key."));
2978
+ }
2979
+ if (!ctx.dryRun)
2980
+ continue;
2981
+ }
2982
+ const there = new Map(atTarget.filter((row) => !elsewhere(row)).map((row) => [skOf(row), row]));
2961
2983
  const here = new Map(rows.map((row) => [skOf(row), row]));
2962
- // Rows under the current key are copies of an earlier attempt —
2963
- // anything else is another stream's: a row this one does not have,
2964
- // or one it has differently (a snapshot only grows newer).
2984
+ // Rows under the current key are copies of an earlier attempt, or a stream written
2985
+ // there meanwhile: anything else is a conflict, a row this one does not have, or
2986
+ // one it has differently (a snapshot only grows newer).
2965
2987
  for (const [sk, row] of there) {
2966
2988
  const own = here.get(sk);
2967
2989
  if (own === undefined) {
2968
- return conflict("taken", "rows of another stream are under its current partition key.");
2990
+ const same = row.streamId?.S === streamIdText;
2991
+ return Rekey.mergeTallies(tally, conflict(same ? "bothKeys" : "taken", same
2992
+ ? "the stream has rows under both partition keys."
2993
+ : "rows of another stream are under its current partition key."));
2969
2994
  }
2970
2995
  if (sk !== snapshotSk && !sameRow(copyOf(own), row)) {
2971
- return conflict("bothKeys", "rows of another stream are under its current partition key.", sk);
2996
+ return Rekey.mergeTallies(tally, conflict("bothKeys", "the stream has rows under both partition keys, and the two differ.", sk));
2972
2997
  }
2973
2998
  }
2974
2999
  if (ctx.dryRun)
2975
- return { moved: { stream: rows.length } };
3000
+ return Rekey.mergeTallies(tally, { moved: { stream: rows.length } });
2976
3001
  // COPY
2977
3002
  let copiedAll = true;
2978
3003
  for (const row of rows) {
@@ -3060,50 +3085,51 @@ export const makeStream = (config) => {
3060
3085
  continue;
3061
3086
  }
3062
3087
  else if (ctx.dryRun) {
3063
- return { moved: { stream: rows.length } };
3088
+ return Rekey.mergeTallies(tally, { moved: { stream: rows.length } });
3064
3089
  }
3065
3090
  // DELETE
3066
3091
  const drained = yield* drain;
3067
3092
  if (drained !== undefined)
3068
- return drained;
3093
+ return Rekey.mergeTallies(tally, drained);
3094
+ }
3095
+ return Rekey.mergeTallies(tally, conflict("contended", "writes changed it on every attempt to move it."));
3096
+ });
3097
+ /** One scanned row of the stream — or one at a key another stream's move needs. */
3098
+ const rekeyStreamRow = (row, ctx, depth) => Effect.gen(function* () {
3099
+ const tableConfig = yield* config.table.Tag;
3100
+ if (tableConfig.name !== ctx.tableName)
3101
+ return undefined;
3102
+ const keys = streamKeys(row);
3103
+ if (keys === undefined)
3104
+ return { skipped: { unrecognizedKey: 1 } };
3105
+ if (keys === "ambiguous") {
3106
+ return {
3107
+ conflicts: [
3108
+ {
3109
+ member: config.streamName,
3110
+ kind: "stream",
3111
+ reason: "failed",
3112
+ key: { pk: row.pk?.S, sk: row.sk?.S },
3113
+ target: undefined,
3114
+ message: `Stream ${JSON.stringify(row.streamId?.S ?? "")}: its stored stream id reads ` +
3115
+ "as more than one id of the stream's composites, and they disagree on where " +
3116
+ "it belongs.",
3117
+ },
3118
+ ],
3119
+ };
3069
3120
  }
3070
- return conflict("contended", "writes changed it on every attempt to move it.");
3121
+ const from = row.pk.S;
3122
+ if (from === keys.current)
3123
+ return { unchanged: 1 };
3124
+ // A stream moves whole, once per run, from whichever of its rows the scan reaches
3125
+ // first, and rows left there after it moved move after it.
3126
+ const streamIdText = row.streamId?.S ?? "";
3127
+ return yield* ctx.once(`${config.streamName}\u0000${from}\u0000${streamIdText}`, moveStream(ctx, from, keys.current, streamIdText, resolveTtlAttributeName(tableConfig), depth));
3071
3128
  });
3072
3129
  const rekeyHandler = {
3073
3130
  name: config.streamName,
3074
3131
  types: [entityType, snapshotEntityType, commandEntityType],
3075
- row: (row, ctx) => Effect.gen(function* () {
3076
- const tableConfig = yield* config.table.Tag;
3077
- if (tableConfig.name !== ctx.tableName)
3078
- return undefined;
3079
- const keys = streamKeys(row);
3080
- if (keys === undefined)
3081
- return { skipped: { unrecognizedKey: 1 } };
3082
- if (keys === "ambiguous") {
3083
- return {
3084
- conflicts: [
3085
- {
3086
- member: config.streamName,
3087
- kind: "stream",
3088
- reason: "failed",
3089
- key: { pk: row.pk?.S, sk: row.sk?.S },
3090
- target: undefined,
3091
- message: `Stream ${JSON.stringify(row.streamId?.S ?? "")}: its stored stream id reads ` +
3092
- "as more than one id of the stream's composites, and they disagree on where " +
3093
- "it belongs.",
3094
- },
3095
- ],
3096
- };
3097
- }
3098
- if (row.pk?.S === keys.current)
3099
- return { unchanged: 1 };
3100
- // A stream under its 1.36 key moves whole, once per run, from
3101
- // whichever of its rows the scan reaches first — and rows left there
3102
- // after it moved move after it.
3103
- if (!ctx.claim(`${config.streamName}\u0000${keys.old}`))
3104
- return {};
3105
- return yield* moveStream(ctx, keys.old, keys.current, row.streamId?.S ?? "", resolveTtlAttributeName(tableConfig));
3106
- }),
3132
+ row: (row, ctx) => rekeyStreamRow(row, ctx, 0),
3107
3133
  };
3108
3134
  return {
3109
3135
  [EventStreamTypeId]: EventStreamTypeId,