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
package/dist/Aggregate.js CHANGED
@@ -10,32 +10,39 @@
10
10
  */
11
11
  import { TypeId as SchemaAggregateTypeId } from "@effect-dynamodb/schema/Aggregate.js";
12
12
  import * as DynamoModel from "@effect-dynamodb/schema/DynamoModel.js";
13
- import { composeCollectionKey, composeKey, KEY_DELIMITER, } from "@effect-dynamodb/schema/DynamoSchema.js";
14
- import { AggregateAssemblyError, AggregateDecompositionError, AggregateTransactionOverflow, ConditionalCheckFailed, DynamoError, DynamoValidationError, isAwsTransactionCancelled, RefNotFound, TransactionCancelled, ValidationError, } from "@effect-dynamodb/schema/Errors.js";
15
- import { makeCompositeKeyForm, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
13
+ import { composeCollectionKey, composeKey, composeUniqueKey, KEY_DELIMITER, } from "@effect-dynamodb/schema/DynamoSchema.js";
14
+ import { AggregateAssemblyError, AggregateDecompositionError, AggregateTransactionOverflow, ConditionalCheckFailed, DynamoError, DynamoValidationError, isAwsTransactionCancelled, RefNotFound, TRANSACT_WRITE_ITEMS_LIMIT, TransactionCancelled, ValidationError, } from "@effect-dynamodb/schema/Errors.js";
15
+ import { fieldAtPath, kindReadingOf, kindTargets, makeCompositeKeyForm, readBackAs, readBackUnsure, readsBackOtherwise, refuseInexact, storedNaNKeyForm, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
16
16
  import { buildDateTransform, containsWireTransform, matchDateRepresentation, optionalField, resolveSystemFields, substituteSchemaDeep, validateNoTransformOverride, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
17
+ import { failingAsBefore, issueDecoding } from "@effect-dynamodb/schema/internal/FailingAsBefore.js";
18
+ import { readingInstances } from "@effect-dynamodb/schema/internal/InstanceReads.js";
17
19
  import * as KeyText136 from "@effect-dynamodb/schema/internal/KeyText136.js";
20
+ import { KeyValueError } from "@effect-dynamodb/schema/internal/NumericKey.js";
18
21
  import { isDispatchEligible } from "@effect-dynamodb/schema/internal/PackedCodec.js";
19
- import { extractArrayElement, getSchemaFields, hasEncodingTransformation, } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
22
+ import { extractArrayElement, extractKeyedValue, getSchemaFields, hasEncodingTransformation, holdsCustomDeclaration, refuseUnreadable, } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
23
+ import { refuseAggregateKeyInTableKey } from "@effect-dynamodb/schema/internal/SharedKeyAttribute.js";
20
24
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
21
- import { DateTime, Effect, Equal, Option, Schema, SchemaAST, } from "effect";
25
+ import { DateTime, Effect, Equal, Exit, Option, Schema, SchemaAST, } from "effect";
22
26
  import * as Batch from "./Batch.js";
23
27
  import { fromDefinition as entityFromDefinition } from "./Entity.js";
24
28
  import * as Capacity from "./internal/Capacity.js";
29
+ import { decodeKeyCursor, encodeKeyCursor } from "./internal/Cursor.js";
25
30
  import { compileExpr, createConditionOps, emptyPartProblem, isEmptyExpr, parseSimpleShorthand, } from "./internal/Expr.js";
26
- import { asReadGuard } from "./internal/ExpressionLimits.js";
31
+ import { asReadGuard, preferredGuard, wholeRowGuard, } from "./internal/ExpressionLimits.js";
32
+ import { packRequests, transactWriteShape, transactWriteUnit } from "./internal/ItemSize.js";
27
33
  import { hasStoredForm, packItemSync, unpackItemSync, withRegistry } from "./internal/Packed.js";
28
34
  import { createPathBuilder } from "./internal/PathBuilder.js";
29
35
  import * as Rekey from "./internal/Rekey.js";
30
- import { generateTimestampPrimitive } from "./internal/TransactableOps.js";
36
+ import { asRead, notReadBack, notStoredForm, readBackRefusal } from "./internal/RoundTrip.js";
37
+ import { composePrimaryKeyOrFail, generateTimestampPrimitive, INCARNATION_TOKEN, KEY_TEXT, marshalOrFail, OUTBOX_CLAIM, OUTBOX_CLAIMED_UNTIL, OUTBOX_ROW_PK, OUTBOX_ROW_SK, } from "./internal/TransactableOps.js";
31
38
  import { diagnosedValidationError, diagnoseFailure, explainDiagnosis, mergeKeyAttributes, transactItemTarget, withCause, } from "./internal/WriteDiagnosis.js";
32
- import { fromAttributeMap, toAttributeMap, toAttributeValue } from "./Marshaller.js";
39
+ import { fromAttributeMap, toAttributeMap, toAttributeValue, } from "./Marshaller.js";
33
40
  import { resolvePrimaryKey } from "./Table.js";
34
41
  // Internal modules (decomposed from Aggregate.ts)
35
42
  export { isManyEdge, isOneEdge, isRefEdge, many, one, ref, } from "@effect-dynamodb/schema/internal/AggregateEdges.js";
36
43
  export { deriveAggregateSchemas, deriveElementInputSchema, deriveEntityFieldName, extractArrayElement, getSchemaFields, isFieldOptional, isSchemaMatchingEntity, unwrapModel, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
37
44
  import { makeCursor, } from "@effect-dynamodb/schema/internal/AggregateCursor.js";
38
- import { deriveAggregateSchemas, deriveEntityFieldName, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
45
+ import { deriveAggregateSchemas, deriveEntityFieldName, elementHoldsRef, given, holdsRefId, isEntityElement, isFieldOptional, manyEdgePaths, manyElementFields, manyElementSchema, refIdField, refIdValue, refKeyComposite, refKeyComposites, refuseAggregateKeyOverMovingValue, refuseAggregateKeysOverBothKinds, refuseManySortKeysOverMovingValue, resolveAggregateStamps, unwrapModel, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
39
46
  // ---------------------------------------------------------------------------
40
47
  // TypeId
41
48
  // ---------------------------------------------------------------------------
@@ -47,6 +54,9 @@ import { deriveAggregateSchemas, deriveEntityFieldName, } from "@effect-dynamodb
47
54
  // that dual-package hazard.
48
55
  export const TypeId = SchemaAggregateTypeId;
49
56
  export function make(schema, config) {
57
+ refuseUnreadable(`Aggregate "${config.root.entityType}"`, "aggregate", unwrapModel(schema), {
58
+ manyEdges: manyEdgePaths(config.edges),
59
+ });
50
60
  if (!("table" in config) || config.table === undefined) {
51
61
  // Sub-aggregate form
52
62
  return makeSubAggregate(schema, config);
@@ -72,43 +82,38 @@ const makeSubAggregate = (schema, config) => {
72
82
  return sub;
73
83
  };
74
84
  /**
75
- * Infer date encoding from a schema AST, handling Schema.optional() wrappers.
85
+ * The date encodings a schema AST holds, handling Schema.optional() wrappers: one, or one per date
86
+ * member of a union, in the order they're declared.
76
87
  * Optional fields have Union AST with [InnerType, Undefined] — unwrap to find dates.
77
88
  */
78
- const inferDateEncoding = (ast) => {
89
+ const inferDateEncodings = (ast) => {
79
90
  // Try SchemaAST.resolve first (works for non-optional date fields)
80
91
  const resolved = SchemaAST.resolve(ast);
81
92
  if (resolved) {
82
93
  const direct = matchDateRepresentation(resolved);
83
94
  if (direct)
84
- return direct;
95
+ return [direct];
85
96
  }
86
97
  // Handle optional wrapper: Union with Undefined + inner type.
87
98
  // SchemaAST.resolve returns undefined for Union ASTs, so check the raw AST.
88
99
  const rawAst = ast;
89
- if (rawAst._tag === "Union" && rawAst.types) {
90
- for (const member of rawAst.types) {
91
- if (member._tag === "Undefined")
92
- continue;
93
- // Try SchemaAST.resolve on the inner member (e.g., Declaration for Schema.Date)
94
- const memberResolved = SchemaAST.resolve(member);
95
- if (memberResolved) {
96
- const enc = matchDateRepresentation(memberResolved);
97
- if (enc)
98
- return enc;
99
- }
100
- // Fallback: check raw member annotations (same record shape, nested under .annotations)
101
- const enc = matchDateRepresentation(member.annotations);
102
- if (enc)
103
- return enc;
104
- }
105
- }
106
- return undefined;
100
+ if (rawAst._tag !== "Union" || !rawAst.types)
101
+ return [];
102
+ return rawAst.types.flatMap((member) => {
103
+ if (member._tag === "Undefined")
104
+ return [];
105
+ // Try SchemaAST.resolve on the inner member (e.g., Declaration for Schema.Date)
106
+ const memberResolved = SchemaAST.resolve(member);
107
+ // Fallback: check raw member annotations (same record shape, nested under .annotations)
108
+ const encoding = (memberResolved ? matchDateRepresentation(memberResolved) : undefined) ??
109
+ matchDateRepresentation(member.annotations);
110
+ return encoding ? [encoding] : [];
111
+ });
107
112
  };
108
113
  /**
109
114
  * A union that holds a date member alongside a member that is neither a date
110
115
  * nor `Undefined` / `Null` — `Union([DateTimeUtcFromString, Number])`.
111
- * `inferDateEncoding` looks through unions to find the date in `optional(date)`,
116
+ * `inferDateEncodings` looks through unions to find the date in `optional(date)`,
112
117
  * so it reports such a field as a date, and encoding a `5` through a date
113
118
  * transform throws. Its stored form is the union's own business: it is encoded
114
119
  * member by member through the substituted union instead.
@@ -132,19 +137,45 @@ const isMixedDateUnion = (ast) => {
132
137
  const dateAttrEncoder = (fieldSchema, options) => {
133
138
  if (options?.mixedUnions !== true && isMixedDateUnion(fieldSchema.ast))
134
139
  return undefined;
135
- const encoding = DynamoModel.getEncoding(fieldSchema) ?? inferDateEncoding(fieldSchema.ast);
136
- if (!encoding)
140
+ const encodings = storedDateEncodings(fieldSchema);
141
+ const last = encodings.at(-1);
142
+ if (!last)
137
143
  return undefined;
138
- const encode = Schema.encodeUnknownSync(buildDateTransform(encoding));
139
- return (value) => encode(value);
144
+ // A union of dates of different kinds: a value is stored in the form of the kind it is.
145
+ const earlier = encodings
146
+ .slice(0, -1)
147
+ .map((encoding) => Schema.encodeUnknownOption(buildDateTransform(encoding)));
148
+ const encode = Schema.encodeUnknownSync(buildDateTransform(last));
149
+ return (value) => {
150
+ for (const encodeEarlier of earlier) {
151
+ const encoded = encodeEarlier(value);
152
+ if (Option.isSome(encoded))
153
+ return encoded.value;
154
+ }
155
+ return encode(value);
156
+ };
157
+ };
158
+ /**
159
+ * The encodings a date field's values are stored in, the last for a value of no earlier one's kind:
160
+ * the field's own annotation, else those its schema's dates imply. Read off the field as declared, so
161
+ * an annotation inside `Schema.optional`'s union isn't seen, and such a field's values are stored as
162
+ * its date's default, ISO text, as 1.39.0 stored them. A stamp in a field a row declares is stored
163
+ * the same way (`rowStampsOf`).
164
+ */
165
+ const storedDateEncodings = (fieldSchema) => {
166
+ const explicit = DynamoModel.getEncoding(fieldSchema);
167
+ return explicit ? [explicit] : inferDateEncodings(fieldSchema.ast);
168
+ };
169
+ /** Whether a value is a date field's stored form: one its date encodings decode. */
170
+ const storedDateForm = (fieldSchema) => {
171
+ const decoders = storedDateEncodings(fieldSchema).map((encoding) => Schema.decodeUnknownOption(buildDateTransform(encoding)));
172
+ return (value) => decoders.some((decode) => Option.isSome(decode(value)));
140
173
  };
141
174
  /**
142
175
  * The field's own encode, with `decode -> encode` as the fallback so a caller
143
176
  * who already supplied wire form round-trips to itself (the same strategy
144
- * `Entity.put` uses). Neither working means the value is neither Type nor
145
- * Encoded for this field; it is stored unchanged rather than introducing a
146
- * write-time failure mode — that shape is already unreadable, and the tolerant
147
- * read path reports it.
177
+ * `Entity.put` uses). `None` when neither works: the value is neither Type nor
178
+ * Encoded for this field, and what's stored is the caller's to decide.
148
179
  */
149
180
  const ownAttrEncoder = (fieldSchema) => {
150
181
  const codec = fieldSchema;
@@ -153,14 +184,70 @@ const ownAttrEncoder = (fieldSchema) => {
153
184
  return (value) => {
154
185
  const direct = encode(value);
155
186
  if (Option.isSome(direct))
156
- return direct.value;
157
- const decoded = decode(value);
158
- if (Option.isSome(decoded)) {
159
- const reencoded = encode(decoded.value);
160
- if (Option.isSome(reencoded))
161
- return reencoded.value;
162
- }
163
- return value;
187
+ return direct;
188
+ return Option.flatMap(decode(value), encode);
189
+ };
190
+ };
191
+ /**
192
+ * Whether a caller's object holds `field`: as its own property or one its class gives it (a
193
+ * getter, a prototype's property), as `in` says, but never as a member every object inherits
194
+ * (`toString`, `constructor`).
195
+ */
196
+ const holdsField = (holder, field) => {
197
+ for (let at = holder; at !== null && at !== Object.prototype; at = Object.getPrototypeOf(at)) {
198
+ if (Object.hasOwn(at, field))
199
+ return true;
200
+ }
201
+ return false;
202
+ };
203
+ /** The caller's value of `field`, under `written`. */
204
+ const writtenField = (written, field) => {
205
+ if (written === undefined)
206
+ return undefined;
207
+ const holder = written.present ? written.value : undefined;
208
+ const present = holder !== null && typeof holder === "object" && holdsField(holder, field);
209
+ return {
210
+ present,
211
+ value: present ? holder[field] : undefined,
212
+ update: written.update,
213
+ };
214
+ };
215
+ /**
216
+ * What a `many` edge's custom `decompose` is handed on a write: the caller's own value of the edge
217
+ * read stored form first, once, as 1.39.0 read every write's input. A write's value is otherwise
218
+ * taken as the domain value a caller holds, but a `decompose` written for 1.39.0 was handed this,
219
+ * and what it returns is stored and keyed as it is: handed the domain value instead, a `decompose`
220
+ * that returns a field's stored form (`f / 10` on a field that multiplies by 10) has that encoded
221
+ * once more, its sort key moves, and every `update` compounds the value and adds a row. Handed
222
+ * this, its rows store, key and read exactly as on 1.39.0, and an `update` of a row 1.39.0 wrote
223
+ * finds it. A `decompose` that hands such a field back unchanged stores it decoded once more, as
224
+ * on 1.39.0.
225
+ *
226
+ * It reads what the caller gave, never the value the write already decoded: read again, a decoding
227
+ * default (`5`, read as 50) or a stored form the domain side refuses (`"5"`, read as 50) would be
228
+ * decoded twice, to 500. Only a transformation with one type on both sides reads differently, and
229
+ * a class whose fields hold none reads as given, so undefined when the field holds no
230
+ * transformation beneath its classes: nothing is read again. What was read (update's old state,
231
+ * `rekey`) is handed to `decompose` as it was read, as 1.39.0 did. None where the caller's value
232
+ * doesn't read, and `decompose` is handed the decoded value.
233
+ */
234
+ const storedFormFirst = (field, fieldSchema, resolveRef) => {
235
+ if (fieldSchema === undefined || !containsWireTransform(fieldSchema, { throughClasses: true })) {
236
+ return undefined;
237
+ }
238
+ const reader = (update) => Schema.decodeUnknownOption(substituteSchemaDeep(Schema.Struct({ [field]: fieldSchema }), {
239
+ tolerantTransforms: true,
240
+ decodeOnly: true,
241
+ resolveRef,
242
+ // A mutation's plain state holds a set as a list and an `Option` as a tagged object.
243
+ ...(update && { plainStateForms: true }),
244
+ }));
245
+ const readers = {};
246
+ return (written) => {
247
+ const which = written.update ? "update" : "create";
248
+ const read = readers[which] ?? reader(written.update);
249
+ readers[which] = read;
250
+ return Option.map(read(written.present ? { [field]: written.value } : {}), (asRead) => asRead[field]);
164
251
  };
165
252
  };
166
253
  /**
@@ -176,7 +263,8 @@ const ownAttrEncoder = (fieldSchema) => {
176
263
  *
177
264
  * Exactly ONE encoder per field, so nothing is ever encoded twice:
178
265
  *
179
- * 1. **A date encoding** — see {@link dateAttrEncoder}.
266
+ * 1. **A date encoding** — see {@link dateAttrEncoder}. With `storedDates`, a value already in
267
+ * the field's stored form is stored as it is ({@link storedDateForm}).
180
268
  * 2. **Anything that holds a wire transform AT ANY DEPTH** — a leaf transform, a
181
269
  * `Schema.Class`, and also an `Array` / `Struct` / `Union` containing one, or
182
270
  * a self date or `Redacted` nested anywhere ({@link containsWireTransform}).
@@ -185,7 +273,11 @@ const ownAttrEncoder = (fieldSchema) => {
185
273
  * `tolerantTransforms`, with the aggregate's ref resolver), so the stored
186
274
  * form is exactly what assembly reads back — nested date leaves included —
187
275
  * and a `DynamoModel.ref`-annotated field is encoded through the ref
188
- * target's model. The field's own encode is the fallback.
276
+ * target's model. The field's own encode is the fallback. A value none of
277
+ * them takes is stored as given, and reported through `asGiven`: the write
278
+ * then stores it only if its rows read back (`refuseNotReadBack`,
279
+ * `EDD-9127`). A schema that can't encode a value it decodes to, such as a
280
+ * transformation over itself, gets here with every value a caller holds.
189
281
  *
190
282
  * Gating on the TOP-LEVEL node instead (as before #133) skipped every
191
283
  * container, because an `Arrays` / `Objects` node carries no encoding of its
@@ -198,36 +290,69 @@ const ownAttrEncoder = (fieldSchema) => {
198
290
  * Type-side values (`numericTypeWithStringEncoding`), so the aggregate is never
199
291
  * encoded as a whole before it is decomposed.
200
292
  */
201
- const buildAttrEncoders = (fields, resolveRef) => {
293
+ const buildAttrEncoders = (fields, resolveRef,
294
+ /**
295
+ * A keyed (`Schema.Record`) `many` edge without an `entity` only: 1.39.0 gave it no encoders, so
296
+ * it stored a date its custom `decompose` returned in the field's stored form as it was.
297
+ */
298
+ storedDates = false) => {
202
299
  const encoders = {};
203
300
  if (!fields)
204
301
  return encoders;
205
302
  for (const field of Object.keys(fields)) {
206
303
  const fieldSchema = fields[field];
207
- // 1. Date encoding.
304
+ // 1. Date encoding. With `storedDates`, a value already in the field's stored form (a custom
305
+ // `decompose` that returns the ISO text of a `DateTimeUtcFromString`) is stored as it is, as
306
+ // 1.39.0 stored it there; anything else is stored as given, and the write refuses it unless
307
+ // it reads back. Elsewhere a value the encoding doesn't take fails the write, as on 1.39.0.
208
308
  const date = dateAttrEncoder(fieldSchema);
209
- if (date) {
309
+ if (date && !storedDates) {
210
310
  encoders[field] = date;
211
311
  continue;
212
312
  }
313
+ if (date) {
314
+ const stored = storedDateForm(fieldSchema);
315
+ encoders[field] = (value, asGiven) => {
316
+ try {
317
+ return date(value);
318
+ }
319
+ catch {
320
+ if (!stored(value))
321
+ asGiven?.();
322
+ return value;
323
+ }
324
+ };
325
+ continue;
326
+ }
213
327
  // 3. Nothing anywhere in the value has a wire form distinct from its domain form.
214
328
  if (!containsWireTransform(fieldSchema))
215
329
  continue;
216
330
  // 2. Encode through the read path's own (substituted, tolerant) schema. A
217
331
  // one-field struct carries the field's optionality and lets `resolveRef`
218
332
  // re-point the field itself, exactly as it does inside `decodeSchema`.
219
- const substituted = substituteSchemaDeep(Schema.Struct({ [field]: fieldSchema }), {
220
- tolerantTransforms: true,
221
- resolveRef,
222
- });
223
- const encodeSubstituted = Schema.encodeUnknownOption(substituted);
224
- const own = ownAttrEncoder(fieldSchema);
225
- encoders[field] = (value) => {
226
- const encoded = encodeSubstituted({ [field]: value });
227
- if (Option.isSome(encoded))
228
- return encoded.value[field];
229
- return own(value);
333
+ const encoderOver = (options) => {
334
+ const encode = Schema.encodeUnknownOption(substituteSchemaDeep(Schema.Struct({ [field]: fieldSchema }), {
335
+ ...options,
336
+ tolerantTransforms: true,
337
+ resolveRef,
338
+ }));
339
+ return (value) => {
340
+ const encoded = encode({ [field]: value });
341
+ return Option.isSome(encoded)
342
+ ? Option.some(encoded.value[field])
343
+ : Option.none();
344
+ };
230
345
  };
346
+ const encodeSubstituted = encoderOver({});
347
+ // A read reaches beneath a decoding default and this doesn't, and what it takes there isn't
348
+ // always what the field's own schema takes: a redacted value of another label. What's stored
349
+ // is the first's; this only keeps such a value from being marshalled as it is.
350
+ const encodeAsRead = encoderOver({ decodeOnly: true });
351
+ const own = ownAttrEncoder(fieldSchema);
352
+ encoders[field] = (value, asGiven) => encodeSubstituted(value).pipe(Option.orElse(() => encodeAsRead(value)), Option.orElse(() => own(value)), Option.getOrElse(() => {
353
+ asGiven?.();
354
+ return value;
355
+ }));
231
356
  }
232
357
  return encoders;
233
358
  };
@@ -265,8 +390,11 @@ const buildKeyAttrEncoders = (fields) => {
265
390
  }
266
391
  };
267
392
  }
268
- else if (hasEncodingTransformation(fieldSchema))
269
- encoders[field] = ownAttrEncoder(fieldSchema);
393
+ else if (hasEncodingTransformation(fieldSchema)) {
394
+ // A key composed from a value no encoder takes is composed from the value as it is.
395
+ const own = ownAttrEncoder(fieldSchema);
396
+ encoders[field] = (value) => Option.getOrElse(own(value), () => value);
397
+ }
270
398
  }
271
399
  return encoders;
272
400
  };
@@ -298,17 +426,6 @@ const isOpaqueRefField = (field) => {
298
426
  const inner = unwrapOptionalField(field);
299
427
  return getSchemaFields(inner) === undefined && SchemaAST.isDeclaration(inner.ast);
300
428
  };
301
- /**
302
- * The fields of a `many` edge's ELEMENT, read off the parent model's array
303
- * field (`players: Schema.Array(PlayerSheet)` → `PlayerSheet`'s fields).
304
- * `undefined` when the field is not array-shaped (a custom `decompose`) or its
305
- * element exposes no fields (a scalar, or an opaque ref).
306
- */
307
- const manyElementFields = (parentFields, edgeName) => {
308
- const field = parentFields?.[edgeName];
309
- const element = field === undefined ? undefined : extractArrayElement(field);
310
- return element === undefined ? undefined : getSchemaFields(element);
311
- };
312
429
  /**
313
430
  * A sub-aggregate nested in another inherits its parent's discriminator, and
314
431
  * its rows carry both (#133). Re-using an inherited attribute name would
@@ -434,15 +551,19 @@ const collectRefTargets = (rootFields, rootEdges) => {
434
551
  * Apply a node's attribute encoders in place — puts each attribute into its
435
552
  * stored form before the decomposed item is marshalled (#72, #133: without
436
553
  * this, a `DateTime` marshals to a `{ epochMilliseconds, … }` map that the
437
- * read path cannot decode as the wire form).
554
+ * read path cannot decode as the wire form). Returns the fields stored as
555
+ * given (see {@link AttrEncoder}).
438
556
  */
439
557
  const applyNodeAttrEncoders = (attrs, encoders) => {
558
+ const asGiven = [];
440
559
  if (!encoders)
441
- return;
560
+ return asGiven;
442
561
  for (const [field, encode] of Object.entries(encoders)) {
443
- if (field in attrs && attrs[field] != null)
444
- attrs[field] = encode(attrs[field]);
562
+ if (field in attrs && attrs[field] != null) {
563
+ attrs[field] = encode(attrs[field], () => asGiven.push(field));
564
+ }
445
565
  }
566
+ return asGiven;
446
567
  };
447
568
  // ---------------------------------------------------------------------------
448
569
  // Top-level aggregate construction
@@ -486,17 +607,97 @@ const makeAggregate = (schema, config) => {
486
607
  // same-named field anywhere in the model.
487
608
  const refTargets = collectRefTargets(schemaFields, config.edges);
488
609
  const resolveRef = (_name, field) => refTargets.get(field);
610
+ // System timestamps (#98). Aggregates compose their DynamoDB items directly
611
+ // rather than routing through Entity write ops, so Entity's timestamp
612
+ // machinery never reached these rows. Resolution goes through the SAME
613
+ // resolver as Entity, which means field names, `DynamoModel` storage
614
+ // annotations and the EDD-9044 guard on an un-annotated `schema` all behave
615
+ // identically here. Passing the root schema's fields also inherits Entity's
616
+ // collision rule: a date-compatible root field of the same name supplies the
617
+ // encoding, and a non-date one means the user owns the attribute outright, on
618
+ // every row. As on an entity, `Schema.optional` wraps the value that's read.
619
+ const resolveStampsOver = (fields) => resolveAggregateStamps(config.timestamps, fields, `Aggregate "${aggregateName}"`);
620
+ const timestampFields = resolveStampsOver(schemaFields);
621
+ refuseAggregateKeyOverMovingValue(aggregateName, config.timestamps, schemaFields, config.pk.composite);
622
+ // The form a stamp is stored in: on a row declaring its field, the form the row stores any value of
623
+ // that field in ({@link storedDateEncodings}, as `buildAttrEncoders` reads it), else the stamp's
624
+ // own encoding. A row that doesn't declare it holds what the root's would.
625
+ const storedIn = (fields, name, declared, encoding) => {
626
+ const field = declared && name !== null ? fields?.[name] : undefined;
627
+ return (field === undefined ? undefined : storedDateEncodings(field).at(-1)) ?? encoding;
628
+ };
629
+ const stampFields = timestampFields.createdAt !== null || timestampFields.updatedAt !== null
630
+ ? {
631
+ createdAt: timestampFields.createdAt,
632
+ createdEncoding: storedIn(schemaFields, timestampFields.createdAt, timestampFields.createdAtCollision, timestampFields.createdAtEncoding),
633
+ updatedAt: timestampFields.updatedAt,
634
+ updatedEncoding: storedIn(schemaFields, timestampFields.updatedAt, timestampFields.updatedAtCollision, timestampFields.updatedAtEncoding),
635
+ }
636
+ : undefined;
637
+ // What the read path may drop before decoding: each node drops those its rows
638
+ // don't declare ({@link stampsToStrip}). Declared, it belongs to the domain object.
639
+ const systemAttrs = new Set([timestampFields.createdAt, timestampFields.updatedAt].filter((name) => name !== null));
640
+ const requiredIn = (fields, name) => name !== null && fields?.[name] !== undefined && !isFieldOptional(fields[name]);
641
+ // On `create`, a stamp replaces a value the input holds, as on 1.39.0, except under a date the root
642
+ // declares `Schema.optional`: 1.39.0 left that field the caller's and stored a value passed for it.
643
+ // That is 1.39.0's verdict, the resolver's over the root's fields as declared: `Schema.optional`'s
644
+ // union isn't a date there, while a required date and a `Schema.optionalKey` one are the library's.
645
+ const asDeclared = resolveSystemFields(config.timestamps, undefined, undefined, schemaFields, {}, `Aggregate "${aggregateName}"`);
646
+ const createdReplaces = !timestampFields.createdAtCollision || asDeclared.createdAtCollision;
647
+ const updatedReplaces = !timestampFields.updatedAtCollision || asDeclared.updatedAtCollision;
648
+ /**
649
+ * What the rows of a value with these fields do with each timestamp, as an entity's do: a date the
650
+ * value declares is the library's, under the field's encoding, and `create` stamps it over what the
651
+ * input holds unless the root declares it `Schema.optional` ({@link fillStamps}), where an `update`
652
+ * takes a value the mutation changed; any other field of that name is the caller's and the row
653
+ * isn't stamped. Undeclared, the row is stamped.
654
+ */
655
+ const rowStampsOf = (fields) => {
656
+ if (stampFields === undefined)
657
+ return undefined;
658
+ const own = resolveStampsOver(fields);
659
+ return {
660
+ createdAt: stampFields.createdAt === null ? null : own.createdAt,
661
+ createdEncoding: own.createdAtCollision ? own.createdAtEncoding : stampFields.createdEncoding,
662
+ createdStored: own.createdAtCollision
663
+ ? storedIn(fields, own.createdAt, true, own.createdAtEncoding)
664
+ : stampFields.createdEncoding,
665
+ createdDeclared: own.createdAtCollision,
666
+ createdRequired: own.createdAtCollision && requiredIn(fields, own.createdAt),
667
+ createdReplaces,
668
+ updatedAt: stampFields.updatedAt === null ? null : own.updatedAt,
669
+ updatedEncoding: own.updatedAtCollision ? own.updatedAtEncoding : stampFields.updatedEncoding,
670
+ updatedStored: own.updatedAtCollision
671
+ ? storedIn(fields, own.updatedAt, true, own.updatedAtEncoding)
672
+ : stampFields.updatedEncoding,
673
+ updatedDeclared: own.updatedAtCollision,
674
+ updatedRequired: own.updatedAtCollision && requiredIn(fields, own.updatedAt),
675
+ updatedReplaces,
676
+ };
677
+ };
678
+ refuseManySortKeysOverMovingValue(aggregateName, config.timestamps, schemaFields, config.edges);
679
+ refuseAggregateKeysOverBothKinds(aggregateName, schemaFields, config, config.edges);
680
+ const withRowStamps = (node) => ({
681
+ ...node,
682
+ rowStamps: rowStampsOf(node.ownFields),
683
+ children: node.children.map(withRowStamps),
684
+ });
489
685
  // Build resolved graph by walking edges recursively. Each node's attribute
490
686
  // encoders come from the schema its decomposed values actually have — for a
491
687
  // `many` edge that is the aggregate model's array ELEMENT (#133).
492
- const rootNode = resolveNode({
688
+ const rootNode = withRowStamps(resolveNode({
493
689
  fieldName: null,
494
690
  entityType: config.root.entityType,
495
691
  cardinality: "root",
496
692
  edges: config.edges,
497
693
  parentFields: schemaFields,
498
694
  resolveRef,
499
- });
695
+ }));
696
+ // Rows that hold a stamp in the domain object: what `update` returns has to say what it wrote.
697
+ const declaresStamp = (node) => node.rowStamps?.createdDeclared === true ||
698
+ node.rowStamps?.updatedDeclared === true ||
699
+ node.children.some(declaresStamp);
700
+ const returnsStamps = declaresStamp(rootNode);
500
701
  // Packed edge attributes, and those read by stored form, by item entity type (#147).
501
702
  const packedByType = collectPackedByType(rootNode);
502
703
  const dispatchByType = collectDispatchByType(rootNode);
@@ -517,22 +718,55 @@ const makeAggregate = (schema, config) => {
517
718
  // - update re-decodes the mutated state, which carries domain `DateTime`
518
719
  // values → accepted as-is (a strict `*FromString` decoder would reject
519
720
  // them). It is decode-only, so making transforms tolerant is safe — the
520
- // stored wire format is still produced by the attribute encoders.
721
+ // stored wire format is still produced by the attribute encoders;
722
+ // - an absent attribute reads as the value it stands for: `undefined`, or an
723
+ // empty set, neither of which DynamoDB can store (`absentReading`).
521
724
  // Nested edge / ref classes round-trip with their class instance identity
522
725
  // preserved (Option A). Returns the raw `schema` unchanged when it carries no
523
726
  // such leaf at all (zero overhead).
524
727
  const decodeSchema = substituteSchemaDeep(schema, {
525
728
  tolerantTransforms: true,
729
+ decodeOnly: true,
526
730
  resolveRef,
731
+ absentReads: true,
527
732
  });
733
+ // What assembly decodes the rows with: `decodeSchema`, with each of Effect's look-alike
734
+ // declarations (a `BigDecimal`, a `Duration`, a date in an `Option`, ...) reading back as a real
735
+ // instance (`readingInstances`). Reads only: the plain state `update` hands a mutation
736
+ // (`readToPlain`) is `decodeSchema`'s.
737
+ //
738
+ // A read that dies on an absent attribute fails as 1.39.0's did, with the issue `decodeSchema`
739
+ // without its absent reads gives (`failingAsBefore`), built only once a read has died.
740
+ let asBefore;
741
+ const assembly = {
742
+ schema: readingInstances(decodeSchema),
743
+ before: () => (asBefore ??= substituteSchemaDeep(schema, {
744
+ tolerantTransforms: true,
745
+ decodeOnly: true,
746
+ resolveRef,
747
+ })),
748
+ };
528
749
  // The same schema for WRITES — `create` input and `update`'s mutated state —
529
750
  // with the container `.check()` refinements the substitution rebuilds kept, so
530
- // a write that breaks one is rejected (#133). Assembly keeps `decodeSchema`:
751
+ // a write that breaks one is rejected (#133), and a value is asked as the domain
752
+ // value first, since that's what a caller holds. Assembly keeps `decodeSchema`:
531
753
  // a row written while those checks were not enforced must stay readable.
532
754
  const writeSchema = substituteSchemaDeep(schema, {
533
755
  tolerantTransforms: true,
756
+ decodeOnly: true,
534
757
  resolveRef,
535
758
  enforceChecks: true,
759
+ domainValues: true,
760
+ });
761
+ // `update`'s mutated state: the plain state a mutation is handed holds a set as a list and
762
+ // an `Option` as a tagged object (`Schema.toIso`), and it can hand that straight back.
763
+ const mutatedStateSchema = substituteSchemaDeep(schema, {
764
+ tolerantTransforms: true,
765
+ decodeOnly: true,
766
+ resolveRef,
767
+ enforceChecks: true,
768
+ plainStateForms: true,
769
+ domainValues: true,
536
770
  });
537
771
  // Validate the collection index against the table's primary key. Best effort: a
538
772
  // table registering only aggregates has no primary key to resolve, in which case
@@ -549,35 +783,23 @@ const makeAggregate = (schema, config) => {
549
783
  `\`collection.index\` naming the GSI partitioned by "${config.pk.field}".`);
550
784
  }
551
785
  }
786
+ refuseAggregateKeyInTableKey(aggregateName, [config.pk.field, "sk", tablePrimary?.pk, tablePrimary?.sk], [
787
+ ...(config.collection.index === undefined || config.collection.sk === undefined
788
+ ? []
789
+ : [["its collection sort key", config.collection.sk.field]]),
790
+ ...(config.list === undefined
791
+ ? []
792
+ : [
793
+ ["its list partition key", config.list.pk.field],
794
+ ["its list sort key", config.list.sk.field],
795
+ ]),
796
+ ]);
552
797
  if ((config.collection.index === undefined) !== (config.collection.sk === undefined)) {
553
798
  throw new Error(`[EDD-9043] Aggregate "${aggregateName}": \`collection.index\` and \`collection.sk\` must ` +
554
799
  `be supplied together. The collection SK exists only to give the index something to ` +
555
800
  `sort by — declare both to assemble through an index, or neither to assemble off the ` +
556
801
  `base table.`);
557
802
  }
558
- // System timestamps (#98). Aggregates compose their DynamoDB items directly
559
- // rather than routing through Entity write ops, so Entity's timestamp
560
- // machinery never reached these rows. Resolution goes through the SAME
561
- // resolver as Entity, which means field names, `DynamoModel` storage
562
- // annotations and the EDD-9044 guard on an un-annotated `schema` all behave
563
- // identically here. Passing the root schema's fields also inherits Entity's
564
- // collision rule: a date-compatible root field of the same name supplies the
565
- // encoding, and a non-date one means the user owns the attribute outright.
566
- const timestampFields = resolveSystemFields(config.timestamps, undefined, undefined, schemaFields ?? {}, {}, `Aggregate "${aggregateName}"`);
567
- const stampFields = timestampFields.createdAt !== null || timestampFields.updatedAt !== null
568
- ? {
569
- createdAt: timestampFields.createdAt,
570
- createdEncoding: timestampFields.createdAtEncoding,
571
- updatedAt: timestampFields.updatedAt,
572
- updatedEncoding: timestampFields.updatedAtEncoding,
573
- }
574
- : undefined;
575
- // Attributes the read path must drop before decoding. A field the root model
576
- // declares itself is NOT stripped — it belongs to the domain object.
577
- const systemAttrs = new Set([
578
- timestampFields.createdAtCollision ? null : timestampFields.createdAt,
579
- timestampFields.updatedAtCollision ? null : timestampFields.updatedAt,
580
- ].filter((name) => name !== null));
581
803
  /** Read stored `created` values back, keyed by sk, so a rewrite preserves them. */
582
804
  const readExistingCreated = (allItems) => {
583
805
  const createdField = stampFields?.createdAt;
@@ -593,9 +815,11 @@ const makeAggregate = (schema, config) => {
593
815
  return map;
594
816
  };
595
817
  /** Bind the per-write stamp: config + the Clock-backed instant + carry-forward. */
596
- const stampFor = (now, existingCreated, existingUpdated) => stampFields === undefined
597
- ? undefined
598
- : { fields: stampFields, now, existingCreated, existingUpdated };
818
+ const stampFor = (now, existingCreated, existingUpdated, updatedBefore) => stampFields === undefined ? undefined : { now, existingCreated, existingUpdated, updatedBefore };
819
+ /** Compose keys and marshal rows: a value it can't place is a `ValidationError`, not a defect. */
820
+ const composeOrFail = (operation, compose) => marshalOrFail(aggregateName, `aggregate.${operation}`, compose);
821
+ /** The partition key `record` composes. Throws what {@link composeOrFail} turns into its failure. */
822
+ const collectionPkOf = (record) => composeCollectionKey(config.schema, config.collection.name, keyCompositesOrThrow(aggregateName, "its partition key", config.schema, config.pk.composite, keyRecord(record)));
599
823
  // Build optics at construction time (once per aggregate definition)
600
824
  const classToPlain = Schema.toIso(schema);
601
825
  const opticRoot = Schema.toIsoFocus(schema);
@@ -617,12 +841,21 @@ const makeAggregate = (schema, config) => {
617
841
  // domain objects, so without this a `DateEpochMs` composite would key on its
618
842
  // ISO form here and its epoch form on the entity path, and a numeric
619
843
  // composite with a string encoding would not be zero-padded on either.
620
- const compositeKeyForm = makeCompositeKeyForm(schema, (attr, value) => {
844
+ //
845
+ // 1.39.0's form (`text139`): a codec `encode` takes on its own output (a
846
+ // number scaled, `x:` prepended) is encoded whatever it's given. The
847
+ // aggregate's keys are its own — `create`, `get`, `list` and `rekey` all
848
+ // compose them here, from domain values, encoded once — so no other path
849
+ // missed what it wrote, and they keep every byte.
850
+ const compositeKeyForm = makeCompositeKeyForm(schema, (attr, value, reason) => {
851
+ if (reason !== undefined) {
852
+ return refuseInexact(`Composite "${attr}" on aggregate "${aggregateName}"`, value, reason);
853
+ }
621
854
  throw new Error(`[EDD-9050] Composite "${attr}" on aggregate "${aggregateName}" could not be put into ` +
622
855
  `its key form. The attribute's schema carries an encoding transformation, but ` +
623
856
  `${JSON.stringify(String(value))} resolves under neither encode nor decode->encode. ` +
624
857
  `Supply a value of the attribute's own type.`);
625
- });
858
+ }, { text139: true });
626
859
  // Only the attributes a key is ever composed from are put into key form. The
627
860
  // rest of the record is never read off the result, and normalising it could
628
861
  // only fail: a stored value that breaks a field's `.check()` (#133) made
@@ -649,50 +882,255 @@ const makeAggregate = (schema, config) => {
649
882
  "Drop `consistentRead` from the aggregate, or key it on the table's primary " +
650
883
  "partition key so assembly reads the base table.", original);
651
884
  /** 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) =>
885
+ const readPartition = (key, rejected, rekeyRead) => Effect.flatMap(readPartitionRaw(key, rejected, rekeyRead), (read) =>
653
886
  // Packed edge attributes, read by their stored form (#147).
654
887
  Effect.as(unpackAggregateItems(read.allItems, dispatchByType, aggregateName), read));
888
+ // A root row's partition key composites as a read takes them: decoded through their fields, as
889
+ // assembly decodes the root row. `create` composes the key from the value it holds, so a key
890
+ // composed again from a stored row (`list`, `rekey`) is composed from these, never from the
891
+ // stored form: a transformation that isn't its own inverse on the other side (a value stored
892
+ // divided by ten, an `Option` holding one) keys the stored form elsewhere.
893
+ const decodeRootKey = (() => {
894
+ const fields = {};
895
+ for (const attr of config.pk.composite) {
896
+ const field = schemaFields?.[attr];
897
+ if (field !== undefined)
898
+ fields[attr] = field;
899
+ }
900
+ return Schema.decodeUnknownOption(substituteSchemaDeep(Schema.Struct(fields), {
901
+ tolerantTransforms: true,
902
+ decodeOnly: true,
903
+ resolveRef,
904
+ absentReads: true,
905
+ }));
906
+ })();
655
907
  /**
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.
908
+ * `row` (a stored root row) with its partition key composites as a read takes them. A row whose
909
+ * composites a read can't take is left as it is: its key composes as the stored form does, and its
910
+ * read fails as assembly's does.
661
911
  */
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;
912
+ const rootKeyAsRead = (row) => {
913
+ const composites = {};
914
+ for (const attr of config.pk.composite) {
915
+ if (attr in row)
916
+ composites[attr] = row[attr];
917
+ }
918
+ const read = decodeRootKey(composites);
919
+ return Option.isSome(read) ? { ...row, ...read.value } : row;
667
920
  };
921
+ /** The collection partition key `record`'s values compose under `under`. */
922
+ const collectionPkUnder = (under, record) => composeCollectionKey(config.schema, config.collection.name, KeyComposer.extractKeyComposites(under, {}, config.pk.composite, keyRecord(record)));
668
923
  /** {@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* () {
924
+ const readPartitionRaw = (key, rejected, rekeyRead) => Effect.gen(function* () {
672
925
  const client = yield* Capacity.client;
673
926
  const tableConfig = yield* config.table.Tag;
674
- const composites = KeyComposer.extractComposites(config.pk.composite, keyRecord(key));
675
- 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
927
+ const pkValue = yield* composeOrFail("key", () => collectionPkOf(key));
928
+ const read = (partition) => queryAllItems(client, tableConfig.name, config.collection.index, config.pk.field, partition, consistentRead, rejected, rekeyRead?.stored);
929
+ const from = rekeyRead?.from;
930
+ const allItems = from === undefined
682
931
  ? yield* read(pkValue)
683
- : [...(yield* read(pk136)), ...(yield* read(pkValue))];
684
- return { client, tableConfig, pkValue, pk136, composites, allItems };
932
+ : [...(yield* read(from)), ...(rekeyRead?.fromOnly === true ? [] : yield* read(pkValue))];
933
+ return { client, tableConfig, pkValue, allItems };
685
934
  });
935
+ const holdsCustom = holdsCustomDeclaration(schema.ast);
936
+ /**
937
+ * Refuses the rows of a write that wouldn't read back: the rows it's about to write, through the read
938
+ * path a `get` takes. Only two kinds of write pay for it: one of an aggregate holding a custom
939
+ * declaration (`EDD-9126`), and one that stored a value as given, which no encoder of its field
940
+ * takes (`asGiven`, `EDD-9127`). Every other write has nothing to do here.
941
+ */
942
+ const refuseNotReadBack = (groups, key, operation, asGiven) => !holdsCustom && asGiven.length === 0
943
+ ? Effect.void
944
+ : Effect.gen(function* () {
945
+ const rows = groups.flatMap((group) => group.items.map((item) => fromAttributeMap(item)));
946
+ yield* unpackAggregateItems(rows, dispatchByType, aggregateName);
947
+ yield* assembleAggregate(assembly, rootNode, rows, contextFields, key, aggregateName, systemAttrs).pipe(Effect.mapError((error) => new ValidationError({
948
+ entityType: aggregateName,
949
+ operation,
950
+ cause: asGiven.length > 0
951
+ ? notStoredForm(asGiven, error.cause ?? error)
952
+ : notReadBack("The aggregate", error.cause ?? error),
953
+ })));
954
+ });
955
+ /**
956
+ * `[EDD-9128]`, by value: each key composite whose numeric kinds can't be read at load
957
+ * (`Schema.Unknown`, `Schema.Any`, a declaration, or a transformation from one), with what composes
958
+ * it and the test of a stored value that reads back otherwise (`readsBackOtherwise`), per node
959
+ * whose key composes it. A composite that's a path into a value (`nested.n`) is followed to the
960
+ * field it names (`fieldAtPath`). A declared one is refused at load. Empty for an aggregate with
961
+ * none, which pays nothing more on a write.
962
+ */
963
+ const otherKindKeys = (() => {
964
+ // A composite judged by the value at its path alone.
965
+ const leafJudge = (path, readsOther) => (item) => {
966
+ const held = readCompositePath(item.attributes, path);
967
+ const readsAs = held == null ? undefined : readsOther(held);
968
+ return readsAs === undefined ? undefined : { held, readsAs };
969
+ };
970
+ // A dotted composite of `node`'s sort key (`nested.n`), judged through the field holding it:
971
+ // the text `node` composes for it from the element written against the text composed again
972
+ // from the row as a read takes it, its field decoded as assembly decodes it and its key read
973
+ // off the result as `decompose` reads it. A transformation of what holds the value (a struct
974
+ // decoded to another) is a read's too, so the value at the path alone isn't what a key read
975
+ // back is composed from.
976
+ const throughFieldJudge = (node, fields, path) => {
977
+ const top = path.slice(0, path.indexOf("."));
978
+ const decode = Schema.decodeUnknownOption(substituteSchemaDeep(Schema.Struct({ [top]: fields[top] }), {
979
+ tolerantTransforms: true,
980
+ decodeOnly: true,
981
+ resolveRef,
982
+ absentReads: true,
983
+ }));
984
+ const keyEncoder = node.keyAttrEncoders?.[top];
985
+ // The value at the path of a top-level value decoded, as `decompose` reads a key off it.
986
+ const leafOf = (value) => Option.map(decode({ [top]: value }), (decoded) => {
987
+ const held = decoded[top];
988
+ return readCompositePath({ [top]: keyEncoder === undefined ? held : keyEncoder(held) }, path);
989
+ });
990
+ return (item) => {
991
+ const stored = item.attributes[top];
992
+ if (stored == null)
993
+ return undefined;
994
+ // Only a `many` element has a sort key `node` composes from it.
995
+ const written = item.skTextFor?.(node, path);
996
+ if (written === undefined)
997
+ return undefined;
998
+ let returned;
999
+ try {
1000
+ returned = asRead(stored);
1001
+ }
1002
+ catch {
1003
+ // A value the marshaller refuses is the write's own marshalling's to report.
1004
+ return undefined;
1005
+ }
1006
+ const read = Option.filter(leafOf(returned), (leaf) => leaf != null);
1007
+ if (Option.isSome(read) &&
1008
+ isScalarComposite(read.value) &&
1009
+ KeyComposer.keyValueText(config.schema, read.value, config.schema.casing) === written) {
1010
+ return undefined;
1011
+ }
1012
+ const was = Option.getOrUndefined(leafOf(stored));
1013
+ return {
1014
+ held: was ?? readCompositePath(item.attributes, path),
1015
+ readsAs: readBackAs(read, was),
1016
+ };
1017
+ };
1018
+ };
1019
+ // The text the root's key composes from a composite's value, written and read back alike: the
1020
+ // key form takes a value read back as its field reads it.
1021
+ const rootKeyText = (path) => (value) => {
1022
+ try {
1023
+ return KeyComposer.compositeText(config.schema, compositeKeyForm(path, value));
1024
+ }
1025
+ catch {
1026
+ return undefined;
1027
+ }
1028
+ };
1029
+ const checksOf = (fields, into, composites, root = false) => composites.flatMap((path) => {
1030
+ const fieldSchema = fieldAtPath(fields, path);
1031
+ const text = rootKeyText(path);
1032
+ const readsOther = fieldSchema === undefined
1033
+ ? undefined
1034
+ : readsBackOtherwise(fieldSchema, {
1035
+ asRead,
1036
+ texts: root ? [{ written: text, read: text }] : [],
1037
+ });
1038
+ return readsOther === undefined ? [] : [{ path, into, judge: leafJudge(path, readsOther) }];
1039
+ });
1040
+ // An edge's sort key: a dotted composite is judged through the field holding it when that field's
1041
+ // read-back can't be guaranteed at load, and any other composite by its value.
1042
+ const edgeChecksOf = (node, composites) => {
1043
+ const into = `edge "${node.fieldName}"'s sort key`;
1044
+ const fields = node.ownFields;
1045
+ return composites.flatMap((path) => {
1046
+ const top = fields?.[path.slice(0, path.indexOf("."))];
1047
+ const leaf = fieldAtPath(fields, path);
1048
+ return fields !== undefined &&
1049
+ top !== undefined &&
1050
+ path.includes(".") &&
1051
+ (readBackUnsure(top) || (leaf !== undefined && readBackUnsure(leaf)))
1052
+ ? [{ path, into, judge: throughFieldJudge(node, fields, path) }]
1053
+ : checksOf(fields, into, [path]);
1054
+ });
1055
+ };
1056
+ // Each node's own checks: a row is judged by every node assembly hands it to (`assemblyWalk`).
1057
+ const byNode = new Map();
1058
+ const add = (node, checks) => {
1059
+ if (checks.length > 0)
1060
+ byNode.set(node, checks);
1061
+ };
1062
+ add(rootNode, [
1063
+ ...checksOf(schemaFields, "its partition key", config.pk.composite, true),
1064
+ ...checksOf(schemaFields, "its collection sort key", config.collection.sk?.composite ?? [], true),
1065
+ ...(config.list === undefined
1066
+ ? []
1067
+ : [
1068
+ ...checksOf(schemaFields, "its list partition key", config.list.pk.composite, true),
1069
+ ...checksOf(schemaFields, "its list sort key", config.list.sk.composite, true),
1070
+ ]),
1071
+ ]);
1072
+ const walk = (node) => {
1073
+ if (node.cardinality === "many" && node.skComposite !== undefined) {
1074
+ add(node, edgeChecksOf(node, node.skComposite));
1075
+ }
1076
+ for (const child of node.children)
1077
+ walk(child);
1078
+ };
1079
+ walk(rootNode);
1080
+ return byNode;
1081
+ })();
1082
+ /**
1083
+ * Refuses a write storing, for a key composite whose numeric kinds can't be read at load, a value
1084
+ * that reads back otherwise: a stored row would compose other key text (`EDD-9128`). `groups` is
1085
+ * the whole decomposition of the value stored, rows a diff leaves alone included: a read of the
1086
+ * aggregate takes them all. A row is judged by the checks of each node a read hands it to
1087
+ * (`assemblyWalk`), its composites read off its stored attributes, a path into a value followed.
1088
+ */
1089
+ const refuseOtherKindKeys = (groups, operation) => {
1090
+ if (otherKindKeys.size === 0)
1091
+ return Effect.void;
1092
+ const reached = assemblyWalk(rootNode, groups.flatMap((group) => group.items),
1093
+ // An attribute as a read has it: a discriminator is matched against what's read back.
1094
+ (node, item) => takesRow(node, item.entityType, (attr) => {
1095
+ try {
1096
+ return asRead(item.attributes[attr]);
1097
+ }
1098
+ catch {
1099
+ return undefined;
1100
+ }
1101
+ }));
1102
+ for (const [node, taken] of reached) {
1103
+ const checks = otherKindKeys.get(node);
1104
+ if (checks === undefined)
1105
+ continue;
1106
+ for (const item of taken) {
1107
+ for (const { path, into, judge } of checks) {
1108
+ const refused = judge(item);
1109
+ if (refused === undefined)
1110
+ continue;
1111
+ return Effect.fail(new ValidationError({
1112
+ entityType: aggregateName,
1113
+ operation,
1114
+ cause: readBackRefusal(`Field "${path}" of "${item.member}" is composed into ${into}`, refused.held, refused.readsAs),
1115
+ }));
1116
+ }
1117
+ }
1118
+ }
1119
+ return Effect.void;
1120
+ };
686
1121
  /** 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({
1122
+ const fetchPartition = (key, operation, rekeyRead) => readPartition(key, (diagnosis, original) => new ValidationError({
688
1123
  entityType: aggregateName,
689
1124
  operation: `${operation}.consistentRead`,
690
1125
  cause: assemblyReadCause(operation, diagnosis, original),
691
- }), force, stored);
692
- const derivedSchemas = deriveAggregateSchemas(schema, config.edges, config.pk.composite);
1126
+ }), rekeyRead);
1127
+ const derivedSchemas = deriveAggregateSchemas(schema, config.edges, config.pk.composite, config.timestamps);
693
1128
  /** A stored row's position: its partition and sort key. */
694
1129
  const positionOf = (pk, sk) => `${pk}\u0000${sk}`;
695
- /** Attributes holding index keys the aggregate composes: the collection SK mirror, the list keys. */
1130
+ /**
1131
+ * Attributes holding index keys the aggregate composes: the collection SK mirror, the list
1132
+ * keys. Never a table key attribute, which `make` refuses (`EDD-9112`).
1133
+ */
696
1134
  const indexFields = [
697
1135
  ...(config.collection.index !== undefined && config.collection.sk !== undefined
698
1136
  ? [config.collection.sk.field]
@@ -705,27 +1143,258 @@ const makeAggregate = (schema, config) => {
705
1143
  return text !== undefined && text !== stored[field];
706
1144
  });
707
1145
  /**
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}).
1146
+ * Where a row may be under the partition's old text: at the sort key the other setting composes,
1147
+ * or the current one, where 1.37.0 and 1.38.0 wrote it (its partition key unescaped, its sort key escaped).
1148
+ * Under a partition whose text didn't change, the current sort key is where the row belongs.
1149
+ */
1150
+ const oldPosition = (pk, pkNow, skOther, sk, storedAt, otherKind) => {
1151
+ if (storedAt.has(positionOf(pk, skOther)))
1152
+ return { pk, sk: skOther };
1153
+ if (storedAt.has(positionOf(pk, sk)))
1154
+ return { pk, sk: pk === pkNow ? skOther : sk };
1155
+ // A sort key holding a numeric composite's other kind's text. Looked for only for a row at
1156
+ // neither key: one at its current key under the other kind's text too would have been read
1157
+ // back as a second element composing that key, which the decomposition refuses.
1158
+ return { pk, sk: otherKind(pk) ?? skOther };
1159
+ };
1160
+ // ---------------------------------------------------------------------------
1161
+ // Which rows of its partition are the aggregate's (DESIGN.md §7 "Which rows in its partition
1162
+ // are an aggregate's")
1163
+ // ---------------------------------------------------------------------------
1164
+ /** Every entity type a node of the aggregate's rows carries. */
1165
+ const nodeTypes = (() => {
1166
+ const types = new Set();
1167
+ const walk = (node) => {
1168
+ types.add(node.entityType);
1169
+ for (const child of node.children)
1170
+ walk(child);
1171
+ };
1172
+ walk(rootNode);
1173
+ return [...types];
1174
+ })();
1175
+ /** The fixed text every partition key the aggregate composes begins with. */
1176
+ const partitionHead = composeCollectionKey(config.schema, config.collection.name, []);
1177
+ /**
1178
+ * `ownsRows`: every row of the aggregate's types in its partition is its own, so `update` deletes
1179
+ * the rows of them it reads beyond the ones its value keys, and `rekey` reports them.
1180
+ */
1181
+ const ownsRows = config.ownsRows === true;
1182
+ const ownedTypes = new Set(nodeTypes);
1183
+ /**
1184
+ * Each node a row can be handed to, as `assembleNode` hands rows: its entity type and its static
1185
+ * discriminator (an enclosing sub-aggregate's merged in at resolve time). With the transaction
1186
+ * group its rows are written in and the discriminator values its sort key holds.
1187
+ */
1188
+ const nodeSlots = (() => {
1189
+ const slots = [{ node: rootNode, group: "root", keyDiscriminators: { current: [], other: () => [] } }];
1190
+ const visit = (node, parentGroup, parent) => {
1191
+ if (node.cardinality === "one" && node.children.length > 0) {
1192
+ const ownName = node.fieldName ?? node.entityType;
1193
+ const group = parentGroup === "root" ? ownName : `${parentGroup}.${ownName}`;
1194
+ const own = ownDiscriminatorValues(node, config.schema);
1195
+ const values = {
1196
+ current: [...parent.current, ...own.current],
1197
+ other: () => [...parent.other(), ...own.other()],
1198
+ };
1199
+ slots.push({ node, group, keyDiscriminators: values });
1200
+ for (const child of node.children)
1201
+ visit(child, group, values);
1202
+ return;
1203
+ }
1204
+ if (node.cardinality === "one") {
1205
+ const own = ownDiscriminatorValues(node, config.schema);
1206
+ slots.push({
1207
+ node,
1208
+ group: parentGroup,
1209
+ keyDiscriminators: {
1210
+ current: [...parent.current, ...own.current],
1211
+ other: () => [...parent.other(), ...own.other()],
1212
+ },
1213
+ });
1214
+ return;
1215
+ }
1216
+ slots.push({ node, group: parentGroup, keyDiscriminators: parent });
1217
+ };
1218
+ for (const child of rootNode.children)
1219
+ visit(child, "root", { current: [], other: () => [] });
1220
+ return slots;
1221
+ })();
1222
+ /** The nodes `item` is handed to by its entity type and static discriminator. */
1223
+ const slotsOf = (item) => nodeSlots.filter(({ node }) => item.__edd_e__ === node.entityType &&
1224
+ Object.entries(node.discriminator ?? {}).every(([attr, value]) => typeof value === "function" || (Object.hasOwn(item, attr) && item[attr] === value)));
1225
+ /**
1226
+ * `update`'s cleanup with `ownsRows` (DESIGN.md §7 "Which rows in its partition are an
1227
+ * aggregate's"): the rows read of each changed node, keyed where the new value writes nothing and
1228
+ * the update's groups delete nothing (`written`, `deleted`). A node changed when the update writes
1229
+ * its group (`writtenGroups`) and its items of the old value and of the new one differ by the
1230
+ * comparison that decides that ({@link sameItems}: types and attributes in order, not keys). A row
1231
+ * is a node's as assembly hands it ({@link slotsOf}); one handed to two nodes is left. Each row
1232
+ * once.
1233
+ */
1234
+ const ownedRowsLeft = (allItems, pkValue, oldGroups, newGroups, writtenGroups, written, deleted) => {
1235
+ const inWrittenGroup = new Set();
1236
+ const byNode = (groups) => {
1237
+ const items = new Map();
1238
+ for (const group of groups) {
1239
+ for (const item of group.items) {
1240
+ if (writtenGroups.has(group.name))
1241
+ inWrittenGroup.add(item.node);
1242
+ const list = items.get(item.node) ?? [];
1243
+ list.push(item);
1244
+ items.set(item.node, list);
1245
+ }
1246
+ }
1247
+ return items;
1248
+ };
1249
+ const before = byNode(oldGroups);
1250
+ const after = byNode(newGroups);
1251
+ const changed = new Set(nodeSlots
1252
+ .map(({ node }) => node)
1253
+ .filter((node) => inWrittenGroup.has(node) && !sameItems(before.get(node) ?? [], after.get(node) ?? [])));
1254
+ if (changed.size === 0)
1255
+ return [];
1256
+ const taken = new Set(deleted);
1257
+ const left = [];
1258
+ for (const item of allItems) {
1259
+ const sk = String(item.sk);
1260
+ if (item[config.pk.field] !== pkValue || written.has(sk) || taken.has(sk))
1261
+ continue;
1262
+ const slots = slotsOf(item);
1263
+ if (slots.length !== 1 || !changed.has(slots[0].node))
1264
+ continue;
1265
+ taken.add(sk);
1266
+ left.push({ pk: pkValue, sk, entityType: String(item.__edd_e__) });
1267
+ }
1268
+ return left;
1269
+ };
1270
+ /**
1271
+ * The attributes the aggregate writes on its rows, for another aggregate declaring `ownsRows` to
1272
+ * check at bind (DESIGN.md §7 "Which rows in its partition are an aggregate's"), as each row holds
1273
+ * them after the last write of each: its partition key, `sk` and the collection index's sort key
1274
+ * on every row, its list keys on its root row, its timestamps, written last, and its rows' own
1275
+ * attributes (their fields, discriminators and context, or what a custom `decompose` returns):
1276
+ * any name holding any text, but the ones the library writes after them.
713
1277
  */
714
- const locateRows = (groups, composed, allItems, pkValue, pk136) => {
1278
+ const attributeWriters = (() => {
1279
+ const table = config.table.Tag;
1280
+ const labelled = (type) => ({
1281
+ type,
1282
+ label: composeKey(config.schema, type, []),
1283
+ });
1284
+ const all = nodeTypes.map(labelled);
1285
+ const root = labelled(config.root.entityType);
1286
+ const mirror = config.collection.index !== undefined && config.collection.sk !== undefined
1287
+ ? config.collection.sk.field
1288
+ : undefined;
1289
+ const writers = [
1290
+ {
1291
+ field: config.pk.field,
1292
+ head: partitionHead,
1293
+ exact: config.pk.composite.length === 0,
1294
+ types: all,
1295
+ table,
1296
+ channel: "its partition key",
1297
+ },
1298
+ ...all.map((type) => ({
1299
+ field: "sk",
1300
+ head: type.label,
1301
+ types: [type],
1302
+ table,
1303
+ channel: "its sort key",
1304
+ })),
1305
+ ];
1306
+ if (mirror !== undefined) {
1307
+ writers.push({
1308
+ field: mirror,
1309
+ head: partitionHead,
1310
+ types: [root],
1311
+ table,
1312
+ channel: "its collection index's sort key",
1313
+ });
1314
+ for (const type of all) {
1315
+ writers.push({
1316
+ field: mirror,
1317
+ head: type.label,
1318
+ types: [type],
1319
+ table,
1320
+ channel: "its collection index's sort key",
1321
+ });
1322
+ }
1323
+ }
1324
+ if (config.list !== undefined) {
1325
+ const head = composeCollectionKey(config.schema, config.list.name, []);
1326
+ for (const field of [config.list.pk.field, config.list.sk.field]) {
1327
+ writers.push({ field, head, types: [root], table, channel: "its list index's keys" });
1328
+ }
1329
+ }
1330
+ // Its timestamps, written after everything else: one named as a key replaces it.
1331
+ for (const name of systemAttrs) {
1332
+ writers.push({ field: name, head: undefined, types: all, table, channel: `its "${name}"` });
1333
+ }
1334
+ // Its rows' own attributes. Whatever a schema declares, these are any name holding any text, but
1335
+ // the ones the library writes after them.
1336
+ const library = [config.pk.field, "sk", "__edd_e__", ...(mirror === undefined ? [] : [mirror])];
1337
+ writers.push({
1338
+ field: undefined,
1339
+ except: library,
1340
+ head: undefined,
1341
+ types: all,
1342
+ table,
1343
+ channel: "its rows' own attributes",
1344
+ });
1345
+ return withTypeOverwrites(writers);
1346
+ })();
1347
+ /** What `DynamoClient.make` checks an aggregate declaring `ownsRows` against. */
1348
+ const ownership = {
1349
+ pkField: config.pk.field,
1350
+ pkComposite: config.pk.composite,
1351
+ partitionHead,
1352
+ schema: config.schema,
1353
+ table: config.table.Tag,
1354
+ types: nodeTypes.map((type) => ({ type, label: composeKey(config.schema, type, []) })),
1355
+ declared: [
1356
+ ...Object.entries((config.table.entities ?? {})),
1357
+ ...Object.entries((config.table.aggregates ?? {})),
1358
+ ].map(([name, member]) => ({ name, member })),
1359
+ };
1360
+ /**
1361
+ * `rekey`'s view of where the aggregate's rows are stored (#183, DESIGN.md §7 "`rekey`"): for
1362
+ * each decomposed item, its current key and its old one — the partition the row was found in
1363
+ * and the sort key text of the other setting — the rows stored at each, and where the item is
1364
+ * ({@link placeRows}).
1365
+ */
1366
+ const locateRows = (groups, composed, allItems, pkValue, from) => {
715
1367
  const storedAt = new Map();
716
1368
  for (const item of allItems) {
717
1369
  storedAt.set(positionOf(String(item[config.pk.field]), String(item.sk)), item);
718
1370
  }
1371
+ /** The sort keys stored in a partition, other than `sk` ({@link oldPosition}). */
1372
+ const partitions = new Map();
1373
+ const sortKeysIn = (pk, sk) => {
1374
+ let held = partitions.get(pk);
1375
+ if (held === undefined) {
1376
+ held = kindTargets(allItems
1377
+ .filter((item) => String(item[config.pk.field]) === pk)
1378
+ .map((item) => String(item.sk)));
1379
+ partitions.set(pk, held);
1380
+ }
1381
+ const inPartition = held;
1382
+ return {
1383
+ has: (text) => text !== sk && inPartition.has(text),
1384
+ hasPrefix: inPartition.hasPrefix,
1385
+ };
1386
+ };
719
1387
  const rows = groups.flatMap((group, g) => group.items.map((item, i) => {
720
1388
  const built = composed[g].items[i];
1389
+ const sk = built.sk?.S ?? "";
721
1390
  return {
722
1391
  group: group.name,
1392
+ item,
723
1393
  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
- },
1394
+ /** An element of a `many` edge with a custom `decompose`: its row moves as stored. */
1395
+ custom: item.node.decompose !== undefined,
1396
+ current: { pk: pkValue, sk },
1397
+ old: oldPosition(from ?? pkValue, pkValue, otherSortKey(config.schema, item, sk), sk, storedAt, (pk) => item.otherKindSortKey?.(sortKeysIn(pk, sk))),
729
1398
  };
730
1399
  }));
731
1400
  const placements = placeRows(rows.map((row) => ({
@@ -740,7 +1409,7 @@ const makeAggregate = (schema, config) => {
740
1409
  }));
741
1410
  };
742
1411
  const updateCore = (key, mutationFn) => Effect.gen(function* () {
743
- const { client, tableConfig, pkValue, pk136, allItems } = yield* fetchPartition(key, "update");
1412
+ const { client, tableConfig, pkValue, allItems } = yield* fetchPartition(key, "update");
744
1413
  if (allItems.length === 0) {
745
1414
  return yield* new AggregateAssemblyError({
746
1415
  aggregate: aggregateName,
@@ -749,7 +1418,8 @@ const makeAggregate = (schema, config) => {
749
1418
  });
750
1419
  }
751
1420
  // 1. Assemble current state
752
- const current = yield* assembleAggregate(decodeSchema, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
1421
+ const current = yield* assembleAggregate(assembly, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
1422
+ const now = yield* DateTime.now;
753
1423
  // 2. Apply mutation — provide optics context for composable updates
754
1424
  const state = toPlainState(current);
755
1425
  const updated = mutationFn({
@@ -758,12 +1428,15 @@ const makeAggregate = (schema, config) => {
758
1428
  optic: opticRoot,
759
1429
  current: current,
760
1430
  });
761
- // 3. Validate the mutated state via `decodeSchema` — its tolerant date
762
- // transforms accept the domain `DateTime` values the mutation yields
763
- // for every date field (root + nested edges, Pattern A and Pattern B),
764
- // so update no longer trips the "Expected string, got DateTime" decode
765
- // that a strict `*FromString` schema would raise (#72 update path).
766
- const decoded = yield* Schema.decodeUnknownEffect(writeSchema)(updated).pipe(Effect.mapError((cause) => new ValidationError({
1431
+ // 3. Validate the mutated state — its tolerant transforms take the domain
1432
+ // values the mutation yields as what they are, for every field (root +
1433
+ // nested edges), so update no longer trips the "Expected string, got
1434
+ // DateTime" decode that a strict `*FromString` schema would raise (#72
1435
+ // update path), and a transformation with one type on both sides isn't
1436
+ // applied again to a value it already made.
1437
+ // A row the mutation added doesn't need the dates the library stamps.
1438
+ const written = fillStamps(rootNode, updated, now, "required");
1439
+ const decoded = yield* Schema.decodeUnknownEffect(mutatedStateSchema)(written).pipe(Effect.mapError((cause) => new ValidationError({
767
1440
  entityType: aggregateName,
768
1441
  operation: "aggregate.update",
769
1442
  cause,
@@ -772,7 +1445,7 @@ const makeAggregate = (schema, config) => {
772
1445
  const assembledNew = { ...decoded };
773
1446
  // 4. Decompose both old and new
774
1447
  const oldGroups = yield* decomposeAggregate(assembledOld, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
775
- const newGroups = yield* decomposeAggregate(assembledNew, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
1448
+ const newGroups = yield* decomposeAggregate(assembledNew, rootNode, contextFields, rootEncoders, aggregateName, config.schema, { present: true, value: written, update: true });
776
1449
  // 5. Diff at the ITEM (primary-key) level, not just the group level.
777
1450
  // A `many`-edge element — and a cleared `one` edge — lives in its PARENT's
778
1451
  // transaction group, so removing it SHRINKS a group rather than dropping a
@@ -792,51 +1465,30 @@ const makeAggregate = (schema, config) => {
792
1465
  }
793
1466
  }
794
1467
  // 6. Build the full new + old DynamoDB item sets (with composed keys). The
795
- // collection SK composites only affect the LSI/GSI mirror attributes,
796
- // never the (pk, sk) identity used to PUT or DELETE, so the old set's
797
- // composites are irrelevant — we read only its (pk, sk) for deletes.
1468
+ // collection SK and list keys are mirror attributes, never the (pk, sk)
1469
+ // identity used to PUT or DELETE, and the old set is read only for its
1470
+ // (pk, sk) delete keys, so it composes neither and is never stamped.
798
1471
  // Rewritten rows are stamped `updated`; their stored `created` is read
799
1472
  // back off the fetched partition and re-emitted verbatim, since these are
800
- // PUTs and would otherwise clobber it. The old set is only mined for
801
- // (pk, sk) delete keys, so it is never stamped.
802
- const now = yield* DateTime.now;
803
- const oldDynamo = buildDynamoItems(oldGroups, config, pkValue, sortKeyComposites(config.schema, KeyComposer.extractComposites(config.collection.sk?.composite ?? [], keyRecord(assembledOld))), keyRecord);
1473
+ // PUTs and would otherwise clobber it.
1474
+ const oldDynamo = buildDynamoItems(oldGroups, config, pkValue, undefined, keyRecord);
804
1475
  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
1476
  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);
1477
+ // Each row's declared `updated` as the mutation found it: if it changed it, it's the caller's.
1478
+ const updatedBefore = new Map();
1479
+ if (stampFields?.updatedAt) {
1480
+ for (const group of oldGroups) {
1481
+ for (const item of group.items) {
1482
+ updatedBefore.set(composeKey(config.schema, item.entityType, [...item.skComposites]), item.attributes[stampFields.updatedAt]);
834
1483
  }
835
1484
  }
836
1485
  }
837
1486
  // Packed AFTER the group diff above compared the decomposed values, so
838
1487
  // 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));
1488
+ const newPacked = yield* packAggregateGroups(newGroups, packedByType, aggregateName, "update");
1489
+ const newDynamo = yield* composeOrFail("update", () => buildDynamoItems(newPacked, config, pkValue, assembledNew, keyRecord, stampFor(now, existingCreated, undefined, updatedBefore)));
1490
+ yield* refuseOtherKindKeys(newGroups, "aggregate.update");
1491
+ yield* refuseNotReadBack(newDynamo, key, "aggregate.update", storedAsGivenIn(newGroups));
840
1492
  const newItemsByGroup = new Map(newDynamo.map((g) => [g.group, g.items]));
841
1493
  const oldItemsByGroup = new Map(oldDynamo.map((g) => [g.group, g.items]));
842
1494
  // Every sk that survives anywhere in the new decomposition — an old item is
@@ -855,60 +1507,142 @@ const makeAggregate = (schema, config) => {
855
1507
  const changed = contextChanged ||
856
1508
  oldGroup === undefined ||
857
1509
  newGroup === undefined ||
858
- !deepEqualGroups(oldGroup, newGroup) ||
859
- moved.has(name) ||
860
- relisted.has(name) ||
861
- (newItemsByGroup.get(name) ?? []).some((item) => movedSks.has(skOf(item)));
1510
+ !deepEqualGroups(oldGroup, newGroup);
862
1511
  if (!changed)
863
1512
  continue;
864
1513
  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
- ];
1514
+ const deletes = (oldItemsByGroup.get(name) ?? [])
1515
+ .filter((item) => !survivingSks.has(skOf(item)))
1516
+ .map((item) => ({
1517
+ [config.pk.field]: item[config.pk.field],
1518
+ sk: item.sk,
1519
+ }));
880
1520
  if (puts.length === 0 && deletes.length === 0)
881
1521
  continue;
882
1522
  groupWrites.push({ group: name, puts, deletes });
883
1523
  }
1524
+ // With `ownsRows`, every row of its types in the partition is the aggregate's (DESIGN.md §7
1525
+ // "Which rows in its partition are an aggregate's"). After the update's groups, the rows read
1526
+ // of each node whose decomposition changed that the new value doesn't write are deleted too
1527
+ // (`ownedRowsLeft`): a node's rows are what its decomposition writes.
1528
+ const cleanup = ownsRows
1529
+ ? ownedRowsLeft(allItems, pkValue, oldGroups, newGroups, new Set(groupWrites.map(({ group }) => group)), survivingSks, groupWrites.flatMap(({ deletes }) => deletes.map((item) => skOf(item))))
1530
+ : [];
884
1531
  if (groupWrites.length > 0) {
885
1532
  yield* writeTransactionGroups(client, tableConfig.name, groupWrites, aggregateName, groupKeys);
886
1533
  }
887
- return decoded;
1534
+ if (cleanup.length > 0) {
1535
+ yield* deleteOwnedRows(client, tableConfig.name, config.pk.field, cleanup);
1536
+ }
1537
+ if (!returnsStamps) {
1538
+ return decoded;
1539
+ }
1540
+ // A stamp the domain object holds: what's returned is what's stored, as `get` would read it,
1541
+ // and no read is needed to know that. The partition as read, with these writes applied.
1542
+ const stored = new Map(allItems.map((item) => [String(item.sk), item]));
1543
+ for (const { sk } of cleanup)
1544
+ stored.delete(sk);
1545
+ for (const { deletes, puts } of groupWrites) {
1546
+ for (const item of deletes)
1547
+ stored.delete(String(item.sk.S));
1548
+ const written = puts.map((item) => fromAttributeMap(item));
1549
+ yield* unpackAggregateItems(written, dispatchByType, aggregateName);
1550
+ for (const item of written)
1551
+ stored.set(String(item.sk), item);
1552
+ }
1553
+ return (yield* assembleAggregate(assembly, rootNode, [...stored.values()], contextFields, key, aggregateName, systemAttrs));
888
1554
  });
889
1555
  /** How many times `rekey` reads an aggregate again after a write changed it in between. */
890
1556
  const REKEY_ATTEMPTS = 3;
891
1557
  /**
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.
1558
+ * Every attribute a row of each entity type can hold, the table key aside: its node's own fields
1559
+ * (an edge field is its own rows'), the context fields and discriminators a row beneath the root
1560
+ * carries, the index keys, the timestamps and `__edd_e__`. A row `rekey` moves is guarded on each
1561
+ * one it didn't have still being absent, so a write that adds one cancels the move.
1562
+ */
1563
+ const writableAttributes = (() => {
1564
+ const shared = [
1565
+ "__edd_e__",
1566
+ ...indexFields,
1567
+ ...[timestampFields.createdAt, timestampFields.updatedAt].filter((name) => name !== null),
1568
+ ];
1569
+ const byType = new Map();
1570
+ const walk = (node) => {
1571
+ const names = byType.get(node.entityType) ?? new Set(shared);
1572
+ const edges = new Set(node.children.map((child) => child.fieldName));
1573
+ for (const field of Object.keys(node.ownFields ?? {})) {
1574
+ if (!edges.has(field))
1575
+ names.add(field);
1576
+ }
1577
+ if (node.cardinality !== "root") {
1578
+ for (const field of contextFields)
1579
+ names.add(field);
1580
+ for (const [field, value] of Object.entries(node.discriminator ?? {})) {
1581
+ if (typeof value !== "function")
1582
+ names.add(field);
1583
+ }
1584
+ }
1585
+ byType.set(node.entityType, names);
1586
+ for (const child of node.children)
1587
+ walk(child);
1588
+ };
1589
+ walk(rootNode);
1590
+ return new Map([...byType].map(([entityType, names]) => [entityType, [...names].sort()]));
1591
+ })();
1592
+ /**
1593
+ * The entity types the library stamps an `updatedAt` on, every row of every node holding them. A
1594
+ * node declaring a field of that name other than a date holds the caller's value there
1595
+ * (`rowStampsOf`), which a write of the library leaves as it was, so it proves nothing of the row.
905
1596
  */
906
- const rekeyCore = (key, dryRun) => Effect.gen(function* () {
1597
+ const stampsUpdated = (() => {
1598
+ const stamped = new Set();
1599
+ const unstamped = new Set();
1600
+ const walk = (node) => {
1601
+ const updated = node.rowStamps?.updatedAt ?? null;
1602
+ (updated === null ? unstamped : stamped).add(node.entityType);
1603
+ for (const child of node.children)
1604
+ walk(child);
1605
+ };
1606
+ walk(rootNode);
1607
+ return new Set([...stamped].filter((entityType) => !unstamped.has(entityType)));
1608
+ })();
1609
+ /**
1610
+ * `rekey`'s move of the aggregate at `key` (#183, DESIGN.md §7 "`rekey`"): read from the
1611
+ * partition its root was found in and its current one, and placed ({@link locateRows}). Each row
1612
+ * under its old key moves — a Put of the row `update` would write at its current key, keeping
1613
+ * its `created` and `updated`, beside a Delete of the old row — and a row at its current key
1614
+ * whose list or collection index key holds other text has those keys rewritten. Nothing else is
1615
+ * written, and every write is conditional: the Put only where nothing is, the Delete and the
1616
+ * rewrite only while the row is as read, whole, with each attribute its entity type can hold and
1617
+ * it didn't still absent (`wholeRowGuard`; a row too wide for that, on its `updatedAt` when the
1618
+ * library stamps one on it, `preferredGuard`, or else as `unprovable` decides: under `"report"` an
1619
+ * aggregate nothing of which has moved is left as it is, every row, and each such row is reported
1620
+ * `unguarded`, dry run or not; one already part-moved is finished under the strongest guard that
1621
+ * fits, as 1.39.0 finished it). Rows whose keys chain move in order, the one whose current key is
1622
+ * free first, so no write lands on a row still to move, and the root moves last, so a move cut
1623
+ * short is found by the next run. A write that loses to a concurrent one reads the aggregate
1624
+ * again; a row stored under both keys leaves the aggregate as it is, reported. A dry run writes
1625
+ * nothing.
1626
+ */
1627
+ const rekeyCore = (key, dryRun,
1628
+ /** The old partition the aggregate's root was found in, when it isn't the current one. */
1629
+ from,
1630
+ /**
1631
+ * Leave the current partition unread: a dry run's, while another aggregate still to move
1632
+ * holds it, whose rows this one's move would find gone by then.
1633
+ */
1634
+ fromOnly,
1635
+ /** What a row too wide to guard whole, with no `updatedAt` to stand in, gets. */
1636
+ unprovable) => Effect.gen(function* () {
907
1637
  let movedRows = 0;
908
1638
  let rewrittenRows = 0;
909
1639
  for (let attempt = 0; attempt < REKEY_ATTEMPTS; attempt++) {
910
1640
  const stored = [];
911
- const { client, tableConfig, pkValue, pk136, allItems } = yield* fetchPartition(key, "rekey", true, stored);
1641
+ const { client, tableConfig, pkValue, allItems } = yield* fetchPartition(key, "rekey", {
1642
+ stored,
1643
+ from,
1644
+ fromOnly,
1645
+ });
912
1646
  const done = (rows) => {
913
1647
  const unchanged = Math.max(0, rows - movedRows - rewrittenRows);
914
1648
  return {
@@ -922,25 +1656,24 @@ const makeAggregate = (schema, config) => {
922
1656
  return done(0);
923
1657
  // A write moving the aggregate between the reads of its two partitions shows its
924
1658
  // 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);
1659
+ // again, and while a row read under the old partition has gone from it, retry.
1660
+ const atFrom = allItems.filter((item) => item[config.pk.field] === from);
1661
+ if (from !== undefined && atFrom.length > 0 && atFrom.length < allItems.length) {
1662
+ const again = yield* fetchPartition(key, "rekey", { from, fromOnly });
929
1663
  const held = new Set(again.allItems
930
- .filter((item) => item[config.pk.field] === pk136)
1664
+ .filter((item) => item[config.pk.field] === from)
931
1665
  .map((item) => String(item.sk)));
932
- if (at136.some((item) => !held.has(String(item.sk))))
1666
+ if (atFrom.some((item) => !held.has(String(item.sk))))
933
1667
  continue;
934
1668
  }
935
- const current = yield* assembleAggregate(decodeSchema, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
1669
+ const current = yield* assembleAggregate(assembly, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
936
1670
  const assembled = { ...current };
937
1671
  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);
1672
+ const rows = locateRows(groups, buildDynamoItems(groups, config, pkValue, undefined, keyRecord), allItems, pkValue, from);
940
1673
  const doubled = rows.filter((row) => row.placement === "both" || row.placement === "ambiguous");
941
1674
  if (doubled.length > 0) {
942
1675
  // 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.
1676
+ // only under both while it's still under its old key.
944
1677
  const held = yield* Effect.forEach(doubled, (row) => client
945
1678
  .getItem({
946
1679
  TableName: tableConfig.name,
@@ -959,41 +1692,133 @@ const makeAggregate = (schema, config) => {
959
1692
  target: { [config.pk.field]: row.current.pk, sk: row.current.sk },
960
1693
  message: row.placement === "both"
961
1694
  ? "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.",
1695
+ : "Its rows' keys overlap across key text, and which row is stored under which " +
1696
+ "key can't be told from the keys held: the aggregate is left as it is.",
965
1697
  })),
966
1698
  };
967
1699
  }
1700
+ // With `ownsRows`, every row of its types it reads is the aggregate's (DESIGN.md §7 "Which
1701
+ // rows in its partition are an aggregate's"), and it moves exactly what it moves without the
1702
+ // option: the rows its value decomposes to. Where any other row of its types would go can't
1703
+ // be told from what's stored, so it isn't moved. One whose own partition key changes would
1704
+ // be left behind in the old partition: the aggregate is left as it is, reported `failed`.
1705
+ // Otherwise the row stays where the aggregate reads it, counted `unrecognizedKey`. Without
1706
+ // `ownsRows`, nothing here applies.
1707
+ const placed = new Set();
1708
+ for (const row of rows) {
1709
+ if (row.placement === "old")
1710
+ placed.add(positionOf(row.old.pk, row.old.sk));
1711
+ if (row.placement === "current")
1712
+ placed.add(positionOf(row.current.pk, row.current.sk));
1713
+ }
1714
+ const unplaced = [];
1715
+ for (const item of ownsRows ? allItems : []) {
1716
+ if (!ownedTypes.has(String(item.__edd_e__)))
1717
+ continue;
1718
+ const at = { pk: String(item[config.pk.field]), sk: String(item.sk) };
1719
+ if (!placed.has(positionOf(at.pk, at.sk)))
1720
+ unplaced.push(at);
1721
+ }
1722
+ const stranded = unplaced.filter((at) => at.pk !== pkValue);
1723
+ if (stranded.length > 0) {
1724
+ return {
1725
+ conflicts: stranded.map((at) => ({
1726
+ member: aggregateName,
1727
+ kind: "aggregate",
1728
+ reason: "failed",
1729
+ key: { [config.pk.field]: at.pk, sk: at.sk },
1730
+ target: undefined,
1731
+ message: "The aggregate owns its rows (`ownsRows`), and this one isn't a row its value " +
1732
+ "decomposes to, so where it goes can't be told. Moving the rest would leave it in " +
1733
+ "the old partition: the aggregate is left as it is.",
1734
+ })),
1735
+ };
1736
+ }
1737
+ const left = unplaced.length > 0 ? { skipped: { unrecognizedKey: unplaced.length } } : {};
1738
+ const tally = (rows) => ({ ...done(rows), ...left });
1739
+ const counted = rows.length;
968
1740
  // Each row's write keeps the `created` and `updated` of the row it moves.
969
1741
  const createdField = stampFields?.createdAt ?? null;
970
1742
  const updatedField = stampFields?.updatedAt ?? null;
971
1743
  const keptCreated = new Map();
972
1744
  const keptUpdated = new Map();
973
1745
  for (const row of rows) {
974
- const from = row.placement === "old" ? row.atOld : row.atCurrent;
975
- if (from === undefined)
1746
+ const was = row.placement === "old" ? row.atOld : row.atCurrent;
1747
+ if (was === undefined)
976
1748
  continue;
977
- if (createdField !== null && from[createdField] !== undefined) {
978
- keptCreated.set(row.current.sk, from[createdField]);
1749
+ if (createdField !== null && was[createdField] !== undefined) {
1750
+ keptCreated.set(row.current.sk, was[createdField]);
979
1751
  }
980
- if (updatedField !== null && from[updatedField] !== undefined) {
981
- keptUpdated.set(row.current.sk, from[updatedField]);
1752
+ if (updatedField !== null && was[updatedField] !== undefined) {
1753
+ keptUpdated.set(row.current.sk, was[updatedField]);
982
1754
  }
983
1755
  }
984
- const built = buildDynamoItems(yield* packAggregateGroups(groups, packedByType, aggregateName, "update"), config, pkValue, rootComposites, keyRecord, stampFor(yield* DateTime.now, keptCreated, keptUpdated)).flatMap((group) => group.items);
1756
+ const packedGroups = yield* packAggregateGroups(groups, packedByType, aggregateName, "update");
1757
+ const rekeyedAt = yield* DateTime.now;
1758
+ const built = (yield* composeOrFail("rekey", () => buildDynamoItems(packedGroups, config, pkValue, assembled, keyRecord, stampFor(rekeyedAt, keptCreated, keptUpdated)))).flatMap((group) => group.items);
985
1759
  const storedAt = new Map(stored.map((item) => [
986
1760
  positionOf(item[config.pk.field]?.S ?? "", item.sk?.S ?? ""),
987
1761
  item,
988
1762
  ]));
989
- const guardOf = (at) => asReadGuard(storedAt.get(positionOf(at.pk, at.sk)) ?? {}, config.pk.field, [
990
- ...(updatedField === null ? [] : [updatedField]),
991
- ]);
1763
+ // An aggregate is left as it is, reported, only while nothing of it has moved. One already
1764
+ // part-moved, in this run or a run cut short, is finished under the strongest guard that
1765
+ // fits, as 1.39.0 finished it: left across two keys, a read under either misses rows.
1766
+ const partMoved = movedRows > 0 ||
1767
+ rows.some((row) => row.placement === "current" &&
1768
+ positionOf(row.old.pk, row.old.sk) !== positionOf(row.current.pk, row.current.sk));
1769
+ const unprovableHere = partMoved ? "strongest" : unprovable;
1770
+ // The row as read, whole, with every attribute its entity type can hold and it didn't
1771
+ // still absent: 1.39.0's guard with those appended. A row too wide for that is guarded on
1772
+ // its `updatedAt` when the library stamps one on it, held or absent (`preferredGuard`),
1773
+ // with what else fits; otherwise `unprovableHere` decides, and `undefined` is a row
1774
+ // reported.
1775
+ const guardOf = (at, r) => {
1776
+ const read = storedAt.get(positionOf(at.pk, at.sk)) ?? {};
1777
+ const entityType = built[r].__edd_e__?.S ?? "";
1778
+ const absent = writableAttributes.get(entityType) ?? [];
1779
+ const prefer = updatedField === null ? [] : [updatedField];
1780
+ const whole = wholeRowGuard(read, config.pk.field, prefer, [], absent);
1781
+ if (whole !== undefined)
1782
+ return whole;
1783
+ if (updatedField !== null && stampsUpdated.has(entityType)) {
1784
+ return preferredGuard(read, config.pk.field, prefer, absent);
1785
+ }
1786
+ switch (unprovableHere) {
1787
+ case "report":
1788
+ return undefined;
1789
+ case "strongest":
1790
+ return asReadGuard(read, config.pk.field, prefer);
1791
+ }
1792
+ };
992
1793
  const keyOf = (at) => toAttributeMap({ [config.pk.field]: at.pk, sk: at.sk });
1794
+ // A custom `decompose`'s row is written as stored, its keys and its collection sort key
1795
+ // copy replaced: decomposing the value read back needn't give the attributes it holds (one
1796
+ // renaming a transformed field would store it decoded once more on every run).
1797
+ const mirror = config.collection.index !== undefined && config.collection.sk !== undefined
1798
+ ? config.collection.sk.field
1799
+ : undefined;
1800
+ const itemOf = (r) => {
1801
+ const row = rows[r];
1802
+ if (!row.custom)
1803
+ return built[r];
1804
+ const at = row.placement === "old" ? row.old : row.current;
1805
+ return {
1806
+ ...storedAt.get(positionOf(at.pk, at.sk)),
1807
+ [config.pk.field]: { S: row.current.pk },
1808
+ sk: { S: row.current.sk },
1809
+ ...(mirror !== undefined && { [mirror]: { S: row.current.sk } }),
1810
+ };
1811
+ };
993
1812
  const moves = [];
994
1813
  const rewrites = [];
1814
+ const unguarded = [];
995
1815
  for (const [r, row] of rows.entries()) {
996
1816
  if (row.placement === "old") {
1817
+ const guard = guardOf(row.old, r);
1818
+ if (guard === undefined) {
1819
+ unguarded.push({ from: row.old, to: row.current });
1820
+ continue;
1821
+ }
997
1822
  moves.push({
998
1823
  from: row.old,
999
1824
  to: row.current,
@@ -1001,13 +1826,17 @@ const makeAggregate = (schema, config) => {
1001
1826
  {
1002
1827
  Put: {
1003
1828
  TableName: tableConfig.name,
1004
- Item: built[r],
1829
+ Item: itemOf(r),
1005
1830
  ConditionExpression: "attribute_not_exists(#pk)",
1006
1831
  ExpressionAttributeNames: { "#pk": config.pk.field },
1007
1832
  },
1008
1833
  },
1009
1834
  {
1010
- Delete: { TableName: tableConfig.name, Key: keyOf(row.old), ...guardOf(row.old) },
1835
+ Delete: {
1836
+ TableName: tableConfig.name,
1837
+ Key: keyOf(row.old),
1838
+ ...guard,
1839
+ },
1011
1840
  },
1012
1841
  ],
1013
1842
  });
@@ -1015,15 +1844,20 @@ const makeAggregate = (schema, config) => {
1015
1844
  }
1016
1845
  if (row.placement !== "current" || row.atCurrent === undefined)
1017
1846
  continue;
1018
- const stale = staleIndexFields(built[r], row.atCurrent);
1847
+ const item = itemOf(r);
1848
+ const stale = staleIndexFields(item, row.atCurrent);
1019
1849
  if (stale.length === 0)
1020
1850
  continue;
1021
- const guard = guardOf(row.current);
1851
+ const guard = guardOf(row.current, r);
1852
+ if (guard === undefined) {
1853
+ unguarded.push({ from: row.current, to: row.current });
1854
+ continue;
1855
+ }
1022
1856
  const names = { ...guard.ExpressionAttributeNames };
1023
1857
  const values = { ...guard.ExpressionAttributeValues };
1024
1858
  const sets = stale.map((field, i) => {
1025
1859
  names[`#x${i}`] = field;
1026
- values[`:x${i}`] = built[r][field];
1860
+ values[`:x${i}`] = item[field];
1027
1861
  return `#x${i} = :x${i}`;
1028
1862
  });
1029
1863
  rewrites.push([
@@ -1039,35 +1873,50 @@ const makeAggregate = (schema, config) => {
1039
1873
  },
1040
1874
  ]);
1041
1875
  }
1876
+ // Nothing of it has moved (`unprovableHere`): an unguarded row leaves the aggregate as is.
1877
+ if (unguarded.length > 0) {
1878
+ return {
1879
+ ...(movedRows > 0 && { moved: { aggregate: movedRows } }),
1880
+ ...(rewrittenRows > 0 && { indexKeysRewritten: rewrittenRows }),
1881
+ ...left,
1882
+ conflicts: unguarded.map((row) => ({
1883
+ member: aggregateName,
1884
+ kind: "aggregate",
1885
+ reason: "unguarded",
1886
+ key: { [config.pk.field]: row.from.pk, sk: row.from.sk },
1887
+ target: { [config.pk.field]: row.to.pk, sk: row.to.sk },
1888
+ message: `${Rekey.UNGUARDED_MESSAGE} Its aggregate's other rows are left with it.`,
1889
+ })),
1890
+ };
1891
+ }
1042
1892
  if (moves.length === 0 && rewrites.length === 0)
1043
- return done(rows.length);
1893
+ return tally(counted);
1044
1894
  if (dryRun) {
1045
1895
  movedRows += moves.length;
1046
1896
  rewrittenRows += rewrites.length;
1047
- return done(rows.length);
1897
+ return tally(counted);
1048
1898
  }
1049
1899
  // 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.
1900
+ // current key, and the root once nothing else is left: while it's under the old partition
1901
+ // the next run finds the aggregate there. Each move's Put and Delete share a transaction;
1902
+ // a transaction takes the units in order while it is within DynamoDB's limits on one
1903
+ // (`packRequests`: 100 actions, 4 MB of item size, 16 MB of body), and at least one.
1904
+ const shape = transactWriteShape(yield* Capacity.requestFields);
1052
1905
  const units = rewrites.map((items) => ({ kind: "rewrite", items }));
1053
1906
  let pending = moves;
1054
1907
  let lost = false;
1055
1908
  while (!lost && (pending.length > 0 || units.length > 0)) {
1056
1909
  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)));
1910
+ const wave = pending.filter((move) => !sources.has(positionOf(move.to.pk, move.to.sk)) &&
1911
+ (pending.length === 1 || move.from.sk !== rekeyRootSk));
1058
1912
  // Moves whose keys cycle: `placeRows` leaves such rows ambiguous, so
1059
1913
  // none reach here — reported below if one ever does.
1060
1914
  if (wave.length === 0 && units.length === 0)
1061
1915
  break;
1062
1916
  pending = pending.filter((move) => !wave.includes(move));
1063
1917
  units.push(...wave.map((move) => ({ kind: "move", items: move.items })));
1064
- while (!lost && units.length > 0) {
1065
- const chunk = [];
1066
- let size = 0;
1067
- while (units.length > 0 && size + units[0].items.length <= TRANSACT_LIMIT) {
1068
- size += units[0].items.length;
1069
- chunk.push(units.shift());
1070
- }
1918
+ const chunks = packRequests(units.splice(0), (unit) => transactWriteUnit(unit.items), shape);
1919
+ for (const chunk of chunks) {
1071
1920
  const written = yield* client
1072
1921
  .transactWriteItems({ TransactItems: chunk.flatMap((unit) => unit.items) })
1073
1922
  .pipe(Effect.as(true), Effect.catch((error) => isAwsTransactionCancelled(error.cause)
@@ -1089,9 +1938,9 @@ const makeAggregate = (schema, config) => {
1089
1938
  if (lost)
1090
1939
  continue;
1091
1940
  if (pending.length === 0)
1092
- return done(rows.length);
1941
+ return tally(counted);
1093
1942
  return {
1094
- ...done(rows.length - pending.length),
1943
+ ...tally(counted - pending.length),
1095
1944
  conflicts: pending.map((move) => ({
1096
1945
  member: aggregateName,
1097
1946
  kind: "aggregate",
@@ -1117,10 +1966,10 @@ const makeAggregate = (schema, config) => {
1117
1966
  ],
1118
1967
  };
1119
1968
  });
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.
1969
+ // rekey (#171, #183): the aggregate's part in `db.tables.<Table>.rekey()`. Its rows move together
1970
+ // ({@link rekeyCore}): the scan's root row runs the move, once per partition per run. A row below
1971
+ // the root moves with it; with no root in its partition there's no aggregate to move it with, and
1972
+ // it's reported ({@link rekeyFinish}).
1124
1973
  const rekeyTypes = (() => {
1125
1974
  const types = new Set();
1126
1975
  const walk = (node) => {
@@ -1133,27 +1982,145 @@ const makeAggregate = (schema, config) => {
1133
1982
  })();
1134
1983
  const rekeyPrefix = composeCollectionKey(config.schema, config.collection.name, []);
1135
1984
  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 } };
1985
+ const rekeyUnit = (pk) => `${aggregateName}\u0000${pk}`;
1986
+ const rootItemAt = (tableName, pk) => Effect.flatMap(Capacity.client, (client) => client.getItem({
1987
+ TableName: tableName,
1988
+ Key: toAttributeMap({ [config.pk.field]: pk, sk: rekeyRootSk }),
1989
+ ConsistentRead: true,
1990
+ }));
1991
+ /** The partition key a row's values compose under `under`; none if they compose no key. */
1992
+ const partitionUnder = (under, row) => {
1993
+ try {
1994
+ return collectionPkUnder(under, row);
1995
+ }
1996
+ catch {
1997
+ return undefined;
1998
+ }
1999
+ };
2000
+ /**
2001
+ * Is `pk` a partition key a root row's values have composed: under each setting's text, and with
2002
+ * a numeric composite as either kind (`CompositeCodec.kindReadingOf`), the other kind read from
2003
+ * the digits the row stored. The current text comes first, and a root under it composes nothing
2004
+ * more.
2005
+ */
2006
+ const holdsPartition = (row, key, pk) => [
2007
+ config.schema,
2008
+ KeyText136.schema136(config.schema),
2009
+ KeyText136.schema137(config.schema),
2010
+ KeyText136.schemaEscaped(config.schema),
2011
+ ].some((under) => kindReadingOf(keyRecord(key), config.pk.composite, (field) => row[field]?.N, ({ record }) => composeCollectionKey(config.schema, config.collection.name, KeyComposer.extractKeyComposites(under, {}, config.pk.composite, record)), pk) !== undefined);
2012
+ /**
2013
+ * The root of another aggregate at `pk`, stored there under text its values no longer compose:
2014
+ * it moves first, or this move's rows would land in its partition.
2015
+ */
2016
+ const staleRootAt = (tableName, pk) => Effect.map(rootItemAt(tableName, pk), ({ Item }) => Item === undefined ||
2017
+ partitionUnder(config.schema, rootKeyAsRead(fromAttributeMap(Item))) === pk
2018
+ ? undefined
2019
+ : Item);
2020
+ /**
2021
+ * What a run has learned: the partitions holding a root or about to, so each edge row in one costs
2022
+ * no read of its own, and the rows found in a partition with no root.
2023
+ */
2024
+ const rekeyRuns = new WeakMap();
2025
+ const rekeyRunOf = (ctx) => {
2026
+ const known = rekeyRuns.get(ctx) ?? { rooted: new Set(), rootless: [] };
2027
+ rekeyRuns.set(ctx, known);
2028
+ return known;
2029
+ };
2030
+ const rekeyRowBelowRoot = (row, pk, ctx) => Effect.gen(function* () {
2031
+ const { rooted, rootless } = rekeyRunOf(ctx);
2032
+ if (rooted.has(pk))
2033
+ return {};
2034
+ const { Item } = yield* rootItemAt(ctx.tableName, pk);
2035
+ if (Item !== undefined) {
2036
+ rooted.add(pk);
2037
+ return {};
2038
+ }
2039
+ rootless.push(row);
2040
+ return {};
2041
+ });
2042
+ /**
2043
+ * A row with no root in its partition, once everything is scanned: a root may have moved it on,
2044
+ * or be on its way to it (a run cut short moves the root last), in any order the scan met them,
2045
+ * and a dry run decides the same. Its values don't say whose it is unless the aggregate's context
2046
+ * holds them, so with no root at all there's no aggregate to move it with, and it's reported.
2047
+ *
2048
+ * A run that hasn't read the whole table can't say there's no root: a root at its old key, on a
2049
+ * page this run didn't read, names this partition only when the scan reaches it. So it reports
2050
+ * the row as unjudged, and a run over the whole table judges it.
2051
+ */
2052
+ const rekeyFinish = (ctx) => Effect.gen(function* () {
2053
+ const { rooted, rootless } = rekeyRunOf(ctx);
2054
+ const client = yield* Capacity.client;
2055
+ let left = 0;
2056
+ for (const row of rootless) {
2057
+ if (rooted.has(row[config.pk.field].S))
2058
+ continue;
2059
+ const { Item } = yield* client.getItem({
2060
+ TableName: ctx.tableName,
2061
+ Key: { [config.pk.field]: row[config.pk.field], sk: row.sk },
2062
+ ConsistentRead: true,
2063
+ });
2064
+ if (Item !== undefined)
2065
+ left++;
2066
+ }
2067
+ if (left === 0)
2068
+ return {};
2069
+ return { skipped: ctx.sawWholeTable() ? { unrecognizedKey: left } : { rootNotSeen: left } };
2070
+ });
2071
+ const rekeyRow = (row, ctx, depth) => Effect.gen(function* () {
2072
+ const pk = row[config.pk.field]?.S;
2073
+ if (pk === undefined || (pk !== rekeyPrefix && !pk.startsWith(`${rekeyPrefix}#`))) {
2074
+ return undefined;
2075
+ }
2076
+ if (row.sk?.S !== rekeyRootSk || row.__edd_e__?.S !== config.root.entityType) {
2077
+ return yield* rekeyRowBelowRoot(row, pk, ctx);
2078
+ }
2079
+ const key = rootKeyAsRead(fromAttributeMap(row));
2080
+ const current = partitionUnder(config.schema, key);
2081
+ // Under none of the keys its values have had: nothing here can place it.
2082
+ if (current === undefined || !holdsPartition(row, key, pk)) {
2083
+ return { skipped: { unrecognizedKey: 1 } };
2084
+ }
2085
+ const { rooted } = rekeyRunOf(ctx);
2086
+ rooted.add(pk);
2087
+ rooted.add(current);
2088
+ return yield* ctx.once(rekeyUnit(pk), Effect.gen(function* () {
2089
+ const from = pk === current ? undefined : pk;
2090
+ // The chain: another aggregate may still be stored where this one goes (`foo%20bar`'s
2091
+ // old row where `foo bar`'s current one belongs). It moves first; it leaves no row in
2092
+ // this one's way, and nothing is overwritten or merged whichever the scan reached first.
2093
+ let first = {};
2094
+ let fromOnly = false;
2095
+ if (from !== undefined) {
2096
+ const stale = yield* staleRootAt(ctx.tableName, current);
2097
+ if (stale !== undefined) {
2098
+ const tooDeep = depth >= Rekey.DISPLACE_DEPTH;
2099
+ first = tooDeep
2100
+ ? {}
2101
+ : yield* Rekey.displace(ctx, (under) => rekeyRow(stale, under, depth + 1));
2102
+ // A dry run moved nothing: what would stop that aggregate is what would leave it.
2103
+ const stillThere = ctx.dryRun
2104
+ ? tooDeep || (first.conflicts ?? []).length > 0
2105
+ : (yield* staleRootAt(ctx.tableName, current)) !== undefined;
2106
+ if (stillThere) {
2107
+ return Rekey.mergeTallies(first, {
2108
+ conflicts: [
2109
+ {
2110
+ member: aggregateName,
2111
+ kind: "aggregate",
2112
+ reason: "taken",
2113
+ key: { [config.pk.field]: pk, sk: rekeyRootSk },
2114
+ target: { [config.pk.field]: current, sk: rekeyRootSk },
2115
+ message: "Another aggregate's root is stored where this one's belongs.",
2116
+ },
2117
+ ],
2118
+ });
2119
+ }
2120
+ fromOnly = ctx.dryRun;
2121
+ }
1153
2122
  }
1154
- if (!ctx.claim(`${aggregateName}\u0000${current}`))
1155
- return {};
1156
- return yield* rekeyCore(key, ctx.dryRun).pipe(Effect.catch((error) => {
2123
+ const moved = yield* rekeyCore(key, ctx.dryRun, from, fromOnly, Rekey.unprovableRow(ctx)).pipe(Effect.catch((error) => {
1157
2124
  if (Rekey.isDynamoClientError(error))
1158
2125
  return Effect.fail(error);
1159
2126
  const assembly = error._tag === "AggregateAssemblyError" ? error.reason : undefined;
@@ -1163,6 +2130,13 @@ const makeAggregate = (schema, config) => {
1163
2130
  // A root under both partition keys (its sort key is fixed, so one
1164
2131
  // partition holds one): neither copy is judged.
1165
2132
  const both = assembly === "Multiple root items found";
2133
+ // What went wrong, as the error says it: a tagged error's own message is empty.
2134
+ const detail = error._tag === "AggregateAssemblyError" ||
2135
+ error._tag === "AggregateDecompositionError"
2136
+ ? error.reason
2137
+ : error._tag === "ValidationError"
2138
+ ? String(error.cause ?? error.message)
2139
+ : error.message;
1166
2140
  return Effect.succeed({
1167
2141
  conflicts: [
1168
2142
  {
@@ -1173,18 +2147,28 @@ const makeAggregate = (schema, config) => {
1173
2147
  target: { [config.pk.field]: current, sk: rekeyRootSk },
1174
2148
  message: both
1175
2149
  ? "The aggregate's root is also stored under its current key."
1176
- : `${error._tag}: ${String(assembly ?? error.message ?? "")}`,
2150
+ : `${error._tag}: ${detail}`,
1177
2151
  },
1178
2152
  ],
1179
2153
  });
1180
2154
  }));
1181
- }),
2155
+ return Rekey.mergeTallies(first, moved);
2156
+ }));
2157
+ });
2158
+ const rekeyHandler = {
2159
+ name: aggregateName,
2160
+ types: rekeyTypes,
2161
+ row: (row, ctx) => rekeyRow(row, ctx, 0),
2162
+ finish: rekeyFinish,
1182
2163
  };
1183
2164
  return Rekey.carry(rekeyHandler, withOperations(aggregateName, {
1184
2165
  [TypeId]: TypeId,
1185
2166
  _tag: "Aggregate",
1186
2167
  _tableTag: config.table.Tag,
1187
2168
  _packedByType: packedByType,
2169
+ _ownsRows: ownsRows,
2170
+ _attributeWriters: attributeWriters,
2171
+ _ownership: ownership,
1188
2172
  schema,
1189
2173
  pkField: config.pk.field,
1190
2174
  collection: {
@@ -1211,38 +2195,40 @@ const makeAggregate = (schema, config) => {
1211
2195
  key,
1212
2196
  });
1213
2197
  }
1214
- const result = yield* assembleAggregate(decodeSchema, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
2198
+ const result = yield* assembleAggregate(assembly, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
1215
2199
  return result;
1216
2200
  }),
1217
2201
  create: (input) => Effect.gen(function* () {
1218
2202
  const client = yield* Capacity.client;
1219
2203
  const tableConfig = yield* config.table.Tag;
1220
2204
  // 1. Hydrate refs from edges
1221
- const hydrated = yield* hydrateAggregateRefs(input, config.edges, aggregateName);
2205
+ const hydrated = yield* hydrateAggregateRefs(
2206
+ // What `create`'s type takes (`CreateArgument`) is judged here, at run time.
2207
+ input, config.edges, schemaFields, aggregateName);
1222
2208
  // 2. Validate via schema decode (decodeSchema substitutes nested edge
1223
2209
  // self-date/Redacted leaves — Option A — and is identical to `schema`
1224
- // when no edge needs it).
1225
- const decoded = yield* Schema.decodeUnknownEffect(writeSchema)(hydrated).pipe(Effect.mapError((cause) => new ValidationError({
2210
+ // when no edge needs it). A date the library stamps is stamped now,
2211
+ // over what the input holds for it unless the root declares it
2212
+ // optional, so what's composed and returned is what's stored.
2213
+ const now = yield* DateTime.now;
2214
+ const written = fillStamps(rootNode, hydrated, now, "declared");
2215
+ const decoded = yield* Schema.decodeUnknownEffect(writeSchema)(written).pipe(Effect.mapError((cause) => new ValidationError({
1226
2216
  entityType: aggregateName,
1227
2217
  operation: "aggregate.create",
1228
2218
  cause,
1229
2219
  })));
1230
2220
  const assembled = { ...decoded };
1231
2221
  // 3. Compose PK
1232
- const composites = KeyComposer.extractComposites(config.pk.composite, keyRecord(assembled));
1233
- const pkValue = composeCollectionKey(config.schema, config.collection.name, composites);
2222
+ const pkValue = yield* composeOrFail("create", () => collectionPkOf(assembled));
1234
2223
  // 4. Decompose into items grouped by sub-aggregate transaction boundaries
1235
- const groups = yield* decomposeAggregate(assembled, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
1236
- // 5. Compose collection SK composites for root item. Through the key
1237
- // form — `update` already did (see `newDynamo` / `oldDynamo` below), so
1238
- // leaving `create` raw made the two write paths mirror the collection SK
1239
- // differently for a transformed composite.
1240
- const collectionSkComposites = sortKeyComposites(config.schema, KeyComposer.extractComposites(config.collection.sk?.composite ?? [], keyRecord(assembled)));
1241
- // 6. Build DynamoDB items with composed keys (create only ever PUTs).
2224
+ const groups = yield* decomposeAggregate(assembled, rootNode, contextFields, rootEncoders, aggregateName, config.schema, { present: true, value: written, update: false });
2225
+ // 5. Build DynamoDB items with composed keys (create only ever PUTs).
1242
2226
  // Every row is new, so `created` has nothing to carry forward.
1243
- const now = yield* DateTime.now;
1244
- const dynamoGroups = buildDynamoItems(yield* packAggregateGroups(groups, packedByType, aggregateName, "create"), config, pkValue, collectionSkComposites, keyRecord, stampFor(now, EMPTY_CREATED));
1245
- // 7. Write via sub-aggregate transactions. The root item goes first in
2227
+ const packedGroups = yield* packAggregateGroups(groups, packedByType, aggregateName, "create");
2228
+ const dynamoGroups = yield* composeOrFail("create", () => buildDynamoItems(packedGroups, config, pkValue, assembled, keyRecord, stampFor(now, EMPTY_CREATED)));
2229
+ yield* refuseOtherKindKeys(groups, "aggregate.create");
2230
+ yield* refuseNotReadBack(dynamoGroups, assembled, "aggregate.create", storedAsGivenIn(groups));
2231
+ // 6. Write via sub-aggregate transactions. The root item goes first in
1246
2232
  // the first transaction, guarded by `attribute_not_exists` (#134):
1247
2233
  // an existing aggregate cancels it before any edge or sub-aggregate
1248
2234
  // row is written. Rows below the root need no guard of their own —
@@ -1256,14 +2242,10 @@ const makeAggregate = (schema, config) => {
1256
2242
  puts: [...g.items].sort((a, b) => Number(isRoot(b)) - Number(isRoot(a))),
1257
2243
  deletes: [],
1258
2244
  }));
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
2245
  yield* writeTransactionGroups(client, tableConfig.name, ordered, aggregateName, groupKeys, {
1263
2246
  pkField: config.pk.field,
1264
2247
  entityType: config.root.entityType,
1265
2248
  key: { [config.pk.field]: pkValue, sk: rootSk },
1266
- ...(pk136 === undefined ? {} : { key136: { [config.pk.field]: pk136, sk: rootSk } }),
1267
2249
  });
1268
2250
  return decoded;
1269
2251
  }),
@@ -1275,7 +2257,13 @@ const makeAggregate = (schema, config) => {
1275
2257
  (diagnosis, original) => new DynamoValidationError({
1276
2258
  operation: "Query",
1277
2259
  cause: assemblyReadCause("delete", diagnosis, original),
1278
- }));
2260
+ })).pipe(
2261
+ // Nor a key with no value: nothing to read, reported as a key that finds nothing.
2262
+ Effect.catchTag("ValidationError", (error) => Effect.fail(new AggregateAssemblyError({
2263
+ aggregate: aggregateName,
2264
+ reason: String(error.cause?.message ?? error.cause),
2265
+ key,
2266
+ }))));
1279
2267
  if (allItems.length === 0) {
1280
2268
  return yield* new AggregateAssemblyError({
1281
2269
  aggregate: aggregateName,
@@ -1317,73 +2305,20 @@ const makeAggregate = (schema, config) => {
1317
2305
  // DOMAIN record, so it goes through the same key form the write side
1318
2306
  // used — otherwise `list` composes a key `create` never wrote and
1319
2307
  // silently returns nothing (#111).
1320
- const listPkComposites = KeyComposer.extractComposites(listConfig.pk.composite, keyRecord(filter ?? {}));
2308
+ const listPkComposites = yield* composeOrFail("list", () => keyCompositesOrThrow(aggregateName, "its list partition key", config.schema, listConfig.pk.composite, keyRecord(filter ?? {})));
1321
2309
  // Build SK prefix from contiguous filter values matching SK composites.
1322
- // `serializeSortKeyValue`, NOT `String(v)` — the write side encodes
2310
+ // `keyValueText`, NOT `String(v)` — the write side encodes
1323
2311
  // numerics, so `String(5)` would look for `5` where `0000000000000005`
1324
- // is stored, and escapes the sort key's text.
2312
+ // is stored, and escapes the key's text.
1325
2313
  const skValues = [];
1326
2314
  const listSkFilter = keyRecord(filter ?? {});
1327
2315
  for (const attr of listConfig.sk.composite) {
1328
2316
  if (listSkFilter[attr] !== undefined)
1329
- skValues.push(KeyComposer.serializeSortKeyValue(listSkFilter[attr], config.schema.casing));
2317
+ skValues.push(KeyComposer.keyValueText(config.schema, listSkFilter[attr], config.schema.casing));
1330
2318
  else
1331
2319
  break; // Stop at first gap (prefix matching)
1332
2320
  }
1333
2321
  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
2322
  let rootItems;
1388
2323
  let nextKey;
1389
2324
  if (listConfig.cardinality) {
@@ -1407,27 +2342,21 @@ const makeAggregate = (schema, config) => {
1407
2342
  });
1408
2343
  }
1409
2344
  // 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,
2345
+ // single shard can contribute more than the whole page.
2346
+ const shardQueries = Array.from({ length: listConfig.cardinality }, (_, shard) => queryListPartition(client, tableConfig, listConfig, config.schema, {
2347
+ pkValue: composeCollectionKey(config.schema, listConfig.name, [
2348
+ ...listPkComposites,
1417
2349
  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
- }));
2350
+ ]),
2351
+ skValues,
2352
+ skComplete,
2353
+ limit,
2354
+ pageSize,
2355
+ filter: rootFilter,
2356
+ accept: options?.filterBy,
2357
+ reverse: options?.reverse === true,
2358
+ keyFields: listKeyFields,
2359
+ }, aggregateName));
1431
2360
  const shardResults = yield* Effect.all(shardQueries);
1432
2361
  const merged = shardResults.flatMap((r) => r.items);
1433
2362
  // Truncate the merged fan-out to `limit`. Previously the option was
@@ -1436,74 +2365,53 @@ const makeAggregate = (schema, config) => {
1436
2365
  nextKey = undefined;
1437
2366
  }
1438
2367
  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
- }
2368
+ // `!== undefined`, as above: an empty string is a cursor no list
2369
+ // returned, not a way of saying "from the start".
2370
+ const startKey = options?.cursor === undefined ? undefined : decodeKeyCursor(options.cursor);
2371
+ if (options?.cursor !== undefined && startKey === undefined) {
2372
+ return yield* new ValidationError({
2373
+ entityType: aggregateName,
2374
+ operation: "list",
2375
+ cause: `[EDD-9094] Aggregate "${aggregateName}": the cursor is not one a list returned. ` +
2376
+ "A cursor is opaque: pass back the text of a previous `list` result's `cursor`, " +
2377
+ "unchanged, to the same list. Nothing was sent.",
2378
+ });
1487
2379
  }
2380
+ const result = yield* queryListPartition(client, tableConfig, listConfig, config.schema, {
2381
+ pkValue: composeCollectionKey(config.schema, listConfig.name, listPkComposites),
2382
+ skValues,
2383
+ skComplete,
2384
+ limit,
2385
+ pageSize,
2386
+ startKey,
2387
+ filter: rootFilter,
2388
+ accept: options?.filterBy,
2389
+ reverse: options?.reverse === true,
2390
+ keyFields: listKeyFields,
2391
+ }, aggregateName);
2392
+ rootItems = result.items;
2393
+ nextKey = result.lastKey;
1488
2394
  }
1489
2395
  // Extract PK composite values from each root item and assemble
1490
2396
  const aggregates = [];
1491
2397
  for (const rootItem of rootItems) {
1492
- const key = {};
2398
+ const stored = {};
1493
2399
  for (const composite of config.pk.composite) {
1494
- key[composite] = rootItem[composite];
2400
+ stored[composite] = rootItem[composite];
1495
2401
  }
2402
+ // The key the root's values compose as a read takes them, as `create` composed it.
2403
+ const key = rootKeyAsRead(stored);
1496
2404
  const assembled = yield* Effect.gen(function* () {
1497
2405
  const { allItems } = yield* fetchPartition(key, "list");
1498
2406
  if (allItems.length === 0)
1499
2407
  return undefined;
1500
- const result = yield* assembleAggregate(decodeSchema, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
2408
+ const result = yield* assembleAggregate(assembly, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
1501
2409
  return result;
1502
2410
  });
1503
2411
  if (assembled !== undefined)
1504
2412
  aggregates.push(assembled);
1505
2413
  }
1506
- const cursor = nextKey ? Option.some(btoa(JSON.stringify(nextKey))) : Option.none();
2414
+ const cursor = nextKey ? Option.some(encodeKeyCursor(nextKey)) : Option.none();
1507
2415
  return { data: aggregates, cursor };
1508
2416
  }),
1509
2417
  }));
@@ -1568,6 +2476,14 @@ const deepEqual = (a, b) => {
1568
2476
  }
1569
2477
  if (Array.isArray(a) || Array.isArray(b))
1570
2478
  return false;
2479
+ // A set has no own keys: compared below, any two would be equal, and a change to one
2480
+ // would never be written. Members are strings, numbers or binary values, by identity.
2481
+ if (a instanceof Set || b instanceof Set) {
2482
+ return (a instanceof Set &&
2483
+ b instanceof Set &&
2484
+ a.size === b.size &&
2485
+ [...a].every((member) => b.has(member)));
2486
+ }
1571
2487
  const aObj = a;
1572
2488
  const bObj = b;
1573
2489
  const aKeys = Object.keys(aObj);
@@ -1576,11 +2492,13 @@ const deepEqual = (a, b) => {
1576
2492
  return false;
1577
2493
  return aKeys.every((k) => deepEqual(aObj[k], bObj[k]));
1578
2494
  };
1579
- const deepEqualGroups = (a, b) => {
1580
- if (a.items.length !== b.items.length)
2495
+ const deepEqualGroups = (a, b) => sameItems(a.items, b.items);
2496
+ /** Whether two decompositions are one: the same items, in order, of the same types and attributes. */
2497
+ const sameItems = (a, b) => {
2498
+ if (a.length !== b.length)
1581
2499
  return false;
1582
- return a.items.every((item, i) => {
1583
- const other = b.items[i];
2500
+ return a.every((item, i) => {
2501
+ const other = b[i];
1584
2502
  if (item.entityType !== other.entityType)
1585
2503
  return false;
1586
2504
  return deepEqual(item.attributes, other.attributes);
@@ -1661,6 +2579,7 @@ const resolveNode = (args) => {
1661
2579
  edges: {},
1662
2580
  discriminator: mergedDisc,
1663
2581
  ownDiscriminator: edge.discriminator,
2582
+ ownFields: valueFields,
1664
2583
  attrEncoders: buildAttrEncoders(valueFields, resolveRef),
1665
2584
  ...edgeStorage(edgePackedFields(field, edge.entity, valueFields, edge.discriminator, undefined), edge.entity, valueFields),
1666
2585
  }));
@@ -1675,6 +2594,11 @@ const resolveNode = (args) => {
1675
2594
  // entity's model, which is what such an element IS.
1676
2595
  const entityFields = fieldsOf(edge.entity?.model);
1677
2596
  const elementFields = manyElementFields(parentFields, field) ?? entityFields;
2597
+ const parentField = parentFields?.[field];
2598
+ const arrayElement = parentField === undefined ? undefined : extractArrayElement(parentField);
2599
+ const keyedValue = parentField === undefined || arrayElement !== undefined
2600
+ ? undefined
2601
+ : extractKeyedValue(parentField);
1678
2602
  children.push(resolveNode({
1679
2603
  fieldName: field,
1680
2604
  entityType: edge.entityType,
@@ -1683,7 +2607,11 @@ const resolveNode = (args) => {
1683
2607
  discriminator,
1684
2608
  assemble: edge.assemble,
1685
2609
  decompose: edge.decompose,
1686
- attrEncoders: buildAttrEncoders(elementFields, resolveRef),
2610
+ decomposeInput: edge.decompose === undefined
2611
+ ? undefined
2612
+ : storedFormFirst(field, parentFields?.[field], resolveRef),
2613
+ ownFields: elementFields,
2614
+ attrEncoders: buildAttrEncoders(elementFields, resolveRef, keyedValue !== undefined && edge.entity === undefined),
1687
2615
  // Sort-key composites keep reading the pre-#133 encoding (the entity
1688
2616
  // model's top-level transforms), so no stored key is re-spelled.
1689
2617
  keyAttrEncoders: buildKeyAttrEncoders(entityFields),
@@ -1724,16 +2652,19 @@ const resolveNode = (args) => {
1724
2652
  }
1725
2653
  }
1726
2654
  }
2655
+ const ownFields = args.ownFields ?? parentFields;
1727
2656
  return {
1728
2657
  fieldName,
1729
2658
  entityType,
1730
2659
  cardinality,
2660
+ ownFields,
1731
2661
  // Absent optionals stay absent under `exactOptionalPropertyTypes`.
1732
2662
  ...(discriminator !== undefined && { discriminator }),
1733
2663
  ...(ownDiscriminator !== undefined && { ownDiscriminator }),
1734
2664
  children,
1735
2665
  ...(assemble !== undefined && { assemble }),
1736
2666
  ...(decompose !== undefined && { decompose }),
2667
+ ...(args.decomposeInput !== undefined && { decomposeInput: args.decomposeInput }),
1737
2668
  ...(skComposite !== undefined && { skComposite }),
1738
2669
  ...(refIdentifierField !== undefined && { refIdentifierField }),
1739
2670
  ...(args.packed !== undefined && { packed: args.packed }),
@@ -1860,14 +2791,12 @@ stored) => Effect.gen(function* () {
1860
2791
  } while (exclusiveStartKey !== undefined);
1861
2792
  return allItems;
1862
2793
  });
1863
- // ---------------------------------------------------------------------------
1864
- // Internal: Assembly algorithm
1865
- // ---------------------------------------------------------------------------
1866
- const assembleAggregate = (decodeSchema, rootNode, allItems, _contextFields, key, aggregateName,
2794
+ const assembleAggregate = (assembly, rootNode, allItems, _contextFields, key, aggregateName,
1867
2795
  /** Library-managed attribute names (system timestamps) to drop before decode. */
1868
2796
  systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
2797
+ const reached = assemblyWalk(rootNode, allItems, (node, item) => takesRow(node, item.__edd_e__, (attr) => item[attr]));
1869
2798
  // Find the root item
1870
- const rootItems = allItems.filter((item) => item.__edd_e__ === rootNode.entityType);
2799
+ const rootItems = reached.get(rootNode) ?? [];
1871
2800
  if (rootItems.length === 0) {
1872
2801
  return yield* new AggregateAssemblyError({
1873
2802
  aggregate: aggregateName,
@@ -1886,7 +2815,7 @@ systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
1886
2815
  // Assemble edge values from the item collection
1887
2816
  const edgeValues = {};
1888
2817
  for (const child of rootNode.children) {
1889
- const assembled = yield* assembleNode(child, allItems, key, aggregateName, systemAttrs);
2818
+ const assembled = yield* assembleNode(child, reached, key, aggregateName, systemAttrs);
1890
2819
  if (child.fieldName !== null && assembled !== undefined) {
1891
2820
  edgeValues[child.fieldName] = assembled;
1892
2821
  }
@@ -1910,7 +2839,7 @@ systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
1910
2839
  "gsi5sk",
1911
2840
  "lsi1sk",
1912
2841
  "lsi2sk",
1913
- ...systemAttrs,
2842
+ ...stampsToStrip(rootNode, systemAttrs),
1914
2843
  ]);
1915
2844
  for (const [fieldKey, value] of Object.entries(rootItem)) {
1916
2845
  if (metaFields.has(fieldKey))
@@ -1924,30 +2853,50 @@ systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
1924
2853
  // Decode through `decodeSchema` — a tolerant clone of the aggregate schema
1925
2854
  // that lifts every date / Redacted leaf (root + nested edges) from the stored
1926
2855
  // wire form to its domain value in a single pass (#72 + Option A).
1927
- const decoded = yield* Schema.decodeUnknownEffect(decodeSchema)(assembled).pipe(Effect.mapError((cause) => new ValidationError({
1928
- entityType: aggregateName,
1929
- operation: "aggregate.assemble",
1930
- cause,
1931
- })));
2856
+ const toValidationError = (cause) => new ValidationError({ entityType: aggregateName, operation: "aggregate.assemble", cause });
2857
+ const decoded = yield* Schema.decodeUnknownEffect(assembly.schema)(assembled).pipe(Effect.mapError(toValidationError), failingAsBefore(() => issueDecoding(assembly.before(), assembled), toValidationError));
1932
2858
  return decoded;
1933
2859
  });
1934
- const assembleNode = (node, allItems, key, aggregateName, systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
1935
- // Find items matching this node's entity type and discriminator
1936
- const matchingItems = allItems.filter((item) => {
1937
- if (item.__edd_e__ !== node.entityType)
2860
+ /**
2861
+ * Whether assembly hands a row to `node`: the row's entity type is the node's, and so is each of
2862
+ * the node's static discriminator values (a computed one, a function, isn't matched). A node's
2863
+ * discriminator already holds every enclosing one (`resolveNode`). `valueOf` reads an attribute of
2864
+ * the row as a read has it.
2865
+ */
2866
+ const takesRow = (node, entityType, valueOf) => {
2867
+ if (entityType !== node.entityType)
2868
+ return false;
2869
+ for (const [attr, value] of Object.entries(node.discriminator ?? {})) {
2870
+ if (typeof value === "function")
2871
+ continue;
2872
+ if (valueOf(attr) !== value)
1938
2873
  return false;
1939
- // If this node has a discriminator, check that item attributes match
1940
- if (node.discriminator) {
1941
- for (const [attr, value] of Object.entries(node.discriminator)) {
1942
- // Skip computed discriminators (functions) — only match on static values
1943
- if (typeof value === "function")
1944
- continue;
1945
- if (item[attr] !== value)
1946
- return false;
1947
- }
1948
- }
1949
- return true;
1950
- });
2874
+ }
2875
+ return true;
2876
+ };
2877
+ /**
2878
+ * Assembly's walk over an aggregate's rows: each node a read reaches, with the rows it takes
2879
+ * (`takesRow`). A node with edges (the root, a sub-aggregate) leads to them only through its one
2880
+ * row: one that takes none is absent, and one that takes more can't be assembled, so a read hands
2881
+ * nothing to the nodes under it. Assembly reads each node's rows off this walk, and the write
2882
+ * check (`EDD-9128`) judges a row only by the nodes it reaches, so the two never disagree on which
2883
+ * node a row is.
2884
+ */
2885
+ const assemblyWalk = (rootNode, rows, takes) => {
2886
+ const reached = new Map();
2887
+ const visit = (node) => {
2888
+ const taken = rows.filter((row) => takes(node, row));
2889
+ reached.set(node, taken);
2890
+ if (node.children.length > 0 && taken.length !== 1)
2891
+ return;
2892
+ for (const child of node.children)
2893
+ visit(child);
2894
+ };
2895
+ visit(rootNode);
2896
+ return reached;
2897
+ };
2898
+ const assembleNode = (node, reached, key, aggregateName, systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
2899
+ const matchingItems = reached.get(node) ?? [];
1951
2900
  if (node.cardinality === "one") {
1952
2901
  // One-to-one: sub-aggregate root or simple one edge
1953
2902
  if (node.children.length > 0) {
@@ -1964,12 +2913,10 @@ const assembleNode = (node, allItems, key, aggregateName, systemAttrs = EMPTY_AT
1964
2913
  }
1965
2914
  const subRootItem = matchingItems[0];
1966
2915
  const edgeValues = {};
2916
+ // Its one row leads to its edges (`assemblyWalk`). Each child's discriminator already holds
2917
+ // this node's (`resolveNode`).
1967
2918
  for (const child of node.children) {
1968
- // For children within a sub-aggregate, propagate the parent's discriminator
1969
- const childNode = node.discriminator
1970
- ? { ...child, discriminator: { ...node.discriminator, ...child.discriminator } }
1971
- : child;
1972
- const assembled = yield* assembleNode(childNode, allItems, key, aggregateName, systemAttrs);
2919
+ const assembled = yield* assembleNode(child, reached, key, aggregateName, systemAttrs);
1973
2920
  if (child.fieldName !== null && assembled !== undefined) {
1974
2921
  edgeValues[child.fieldName] = assembled;
1975
2922
  }
@@ -1977,6 +2924,7 @@ const assembleNode = (node, allItems, key, aggregateName, systemAttrs = EMPTY_AT
1977
2924
  // Build sub-aggregate result: sub-root fields + assembled edges
1978
2925
  const subFields = {};
1979
2926
  const edgeFieldNames = new Set(node.children.map((c) => c.fieldName).filter(Boolean));
2927
+ const stripped = stampsToStrip(node, systemAttrs);
1980
2928
  for (const [fieldKey, value] of Object.entries(subRootItem)) {
1981
2929
  // Skip DynamoDB metadata, discriminator attributes, and edge fields
1982
2930
  if (fieldKey === "__edd_e__")
@@ -1985,7 +2933,7 @@ const assembleNode = (node, allItems, key, aggregateName, systemAttrs = EMPTY_AT
1985
2933
  continue;
1986
2934
  if (fieldKey.startsWith("gsi") || fieldKey.startsWith("lsi"))
1987
2935
  continue;
1988
- if (systemAttrs.has(fieldKey))
2936
+ if (stripped.has(fieldKey))
1989
2937
  continue;
1990
2938
  if (edgeFieldNames.has(fieldKey))
1991
2939
  continue;
@@ -2002,10 +2950,10 @@ const assembleNode = (node, allItems, key, aggregateName, systemAttrs = EMPTY_AT
2002
2950
  return undefined;
2003
2951
  // Return the item (stripped of DynamoDB metadata)
2004
2952
  const item = matchingItems[0];
2005
- return stripMetadata(item, systemAttrs);
2953
+ return stripMetadata(item, stampsToStrip(node, systemAttrs));
2006
2954
  }
2007
2955
  // Many edge: collect all matching items
2008
- const stripped = matchingItems.map((item) => stripMetadata(item, systemAttrs));
2956
+ const stripped = matchingItems.map((item) => stripMetadata(item, stampsToStrip(node, systemAttrs)));
2009
2957
  if (node.assemble) {
2010
2958
  return node.assemble(stripped);
2011
2959
  }
@@ -2015,6 +2963,14 @@ const assembleNode = (node, allItems, key, aggregateName, systemAttrs = EMPTY_AT
2015
2963
  // Internal: Strip DynamoDB metadata from items
2016
2964
  // ---------------------------------------------------------------------------
2017
2965
  const EMPTY_ATTRS = new Set();
2966
+ /** The timestamps a node's rows hold beside its value: those its value doesn't declare. */
2967
+ const stampsToStrip = (node, systemAttrs) => {
2968
+ const own = node.ownFields;
2969
+ if (own === undefined)
2970
+ return systemAttrs;
2971
+ const kept = [...systemAttrs].filter((name) => !(name in own));
2972
+ return kept.length === systemAttrs.size ? systemAttrs : new Set(kept);
2973
+ };
2018
2974
  const stripMetadata = (item, systemAttrs = EMPTY_ATTRS) => {
2019
2975
  const result = {};
2020
2976
  for (const [key, value] of Object.entries(item)) {
@@ -2030,14 +2986,45 @@ const stripMetadata = (item, systemAttrs = EMPTY_ATTRS) => {
2030
2986
  }
2031
2987
  return result;
2032
2988
  };
2989
+ /** An object as given, to name it in an error, whatever its `toString` (a JSON body's may be text). */
2990
+ const describeObject = (value) => {
2991
+ try {
2992
+ const json = JSON.stringify(value);
2993
+ if (json !== undefined)
2994
+ return json;
2995
+ }
2996
+ catch {
2997
+ // A cycle, or a `toJSON` that throws: named by its kind below.
2998
+ }
2999
+ return Object.prototype.toString.call(value);
3000
+ };
3001
+ /** An id as given, to name it in an error. */
3002
+ const describeId = (id) => typeof id === "string"
3003
+ ? JSON.stringify(id)
3004
+ : typeof id === "bigint"
3005
+ ? `${id}n`
3006
+ : id instanceof Date
3007
+ ? `a Date (${Number.isNaN(id.getTime()) ? "invalid" : id.toISOString()})`
3008
+ : typeof id === "object" && id !== null
3009
+ ? `an object (${describeObject(id)})`
3010
+ : typeof id === "function"
3011
+ ? "a function"
3012
+ : String(id);
3013
+ /** An id as `RefNotFound` names it. */
3014
+ const refIdText = (id) => typeof id === "string" ? id : id instanceof Date ? id.toISOString() : String(id);
2033
3015
  /**
2034
3016
  * Walk the input recursively following graph edges, collect ref IDs,
2035
3017
  * fetch referenced entities, and replace IDs with hydrated domain data.
3018
+ *
3019
+ * Every id is judged before anything is fetched: an id of an entity no one id names
3020
+ * (`EDD-9129`), then an id that is no value of the entity's key composite, or one `put` refuses as
3021
+ * DynamoDB can't store it (`EDD-9131`), then one with no key text (`EDD-9096`). Each is then fetched by the key `Entity.put` wrote for it,
3022
+ * composed as `Batch.get` composes an entity's own `get` (`composePrimaryKeyOrFail`), once per key.
2036
3023
  */
2037
- const hydrateAggregateRefs = (input, edges, aggregateName) => Effect.gen(function* () {
3024
+ const hydrateAggregateRefs = (input, edges, fields, aggregateName) => Effect.gen(function* () {
2038
3025
  // Collect all ref IDs from the entire input hierarchy
2039
3026
  const refRequests = [];
2040
- collectRefIdsFromEdges(refRequests, input, edges, []);
3027
+ collectRefIdsFromEdges(refRequests, input, edges, fields, [], "");
2041
3028
  if (refRequests.length === 0)
2042
3029
  return input;
2043
3030
  // Group by entity type for efficient fetching
@@ -2052,57 +3039,150 @@ const hydrateAggregateRefs = (input, edges, aggregateName) => Effect.gen(functio
2052
3039
  byEntityType.set(key, { entity: req.entity, reqs: [req] });
2053
3040
  }
2054
3041
  }
2055
- // Batch-fetch all refs — one Batch.get call per entity type
2056
- const hydratedLookup = new Map();
3042
+ // An entity no one id names (its key has two composites, or none): nothing to fetch it by.
3043
+ // 1.39.0 fetched under its identifier (or `id`), which no key composes from alone, and died.
2057
3044
  for (const [entityType, { entity, reqs }] of byEntityType) {
2058
- const idField = DynamoModel.getIdentifierField(entity.model);
2059
- const identifierName = idField?.name ?? "id";
2060
- // Deduplicate IDs for this entity type
2061
- const uniqueIds = [...new Set(reqs.map((r) => r.id))];
2062
- // `RefEntity` is the pure structural bound (no `get` — issue #66): aggregate
2063
- // edges can be authored from AWS-free `@effect-dynamodb/schema` definitions,
2064
- // which carry no runtime `.get`/operations. Ref hydration is a runtime
2065
- // operation, so promote a pure edge target to a full operational Entity (a
2066
- // thin op-attach over its retained `_data`); runtime-authored targets already
2067
- // carry `.get` and pass through untouched. Mirrors `DynamoClient.make()`'s
2068
- // entity binding. The promoted entity also exposes `.schemas`, used by the
2069
- // encode-back below (issue #72). The loop is already grouped by entity type,
2070
- // so this promotes once per distinct edge entity type per hydrate (issue #71).
2071
- const runtimeEntity = (typeof entity.get === "function"
3045
+ if (refKeyComposite(entity) !== undefined)
3046
+ continue;
3047
+ const composites = refKeyComposites(entity);
3048
+ const named = [...new Set(reqs.map((req) => req.fieldName))];
3049
+ return yield* new ValidationError({
3050
+ entityType: aggregateName,
3051
+ operation: "aggregate.create",
3052
+ cause: new Error(`[EDD-9129] Aggregate "${aggregateName}": ${named.map((name) => `"${name}"`).join(", ")} ` +
3053
+ `${named.length === 1 ? "is" : "are"} given an id of entity "${entityType}", whose ` +
3054
+ `primary key is composed from ${composites.length === 0
3055
+ ? "no attribute"
3056
+ : composites.map((name) => `"${name}"`).join(", ")}, so no one id names one item to fetch. Give "${named[0]}" whole, or key that entity ` +
3057
+ `by one attribute to fetch it by id. Nothing was fetched or written.`),
3058
+ });
3059
+ }
3060
+ // `RefEntity` is the pure structural bound (no `get` — issue #66): aggregate
3061
+ // edges can be authored from AWS-free `@effect-dynamodb/schema` definitions,
3062
+ // which carry no runtime `.get`/operations. Ref hydration is a runtime
3063
+ // operation, so promote a pure edge target to a full operational Entity (a
3064
+ // thin op-attach over its retained `_data`); runtime-authored targets already
3065
+ // carry `.get` and pass through untouched. Mirrors `DynamoClient.make()`'s
3066
+ // entity binding. Promoted once per distinct edge entity type per hydrate (issue #71).
3067
+ const runtimeEntities = new Map();
3068
+ for (const [entityType, { entity }] of byEntityType) {
3069
+ runtimeEntities.set(entityType, (typeof entity.get === "function"
2072
3070
  ? entity
2073
- : entityFromDefinition(entity));
2074
- // Build EntityGet intermediates for batch fetching
2075
- const getOps = uniqueIds.map((id) => runtimeEntity.get({ [identifierName]: id }));
3071
+ : entityFromDefinition(entity)));
3072
+ }
3073
+ // An id that is no value of the key composite names no item: up to 1.39.0 a string was
3074
+ // fetched under a key no `put` writes (`lineid_5` for a number), and anything else was dropped.
3075
+ // Nor does one `put` refuses: one that doesn't encode as the attribute is stored (an infinite
3076
+ // number through a digits-only string codec), or one DynamoDB can't store (an infinite number,
3077
+ // at any depth of a struct, an `Option` or a `Result`), whose key text can name an item of
3078
+ // another value (`{ a: Infinity }` and `{ a: 5 }` compose one key), fetched in its place.
3079
+ // An id given more than once is judged once: one composing the key text of an id already
3080
+ // judged, and equal to it as a value of the key composite (`Schema.toEquivalence`), so three
3081
+ // ISO strings of one instant, each decoded to a `Date` of its own, are judged once. The key
3082
+ // text alone isn't enough: `{ a: Infinity }` composes the key of `{ a: 5 }`, and is refused.
3083
+ // An id whose key isn't composed here is judged, and fails composing below.
3084
+ const judged = new Map();
3085
+ const composed = new Map();
3086
+ for (const req of refRequests) {
3087
+ const composite = refKeyComposite(req.entity);
3088
+ if (Option.isNone(req.id)) {
3089
+ return yield* new ValidationError({
3090
+ entityType: aggregateName,
3091
+ operation: "aggregate.create",
3092
+ cause: new Error(`[EDD-9131] Aggregate "${aggregateName}": "${req.at}" is given ${describeId(req.given)}, ` +
3093
+ `which is no value of "${composite}", the attribute entity ` +
3094
+ `"${req.entity.entityType}" is keyed by, so it names no item to fetch. Give an id of ` +
3095
+ `that attribute's type. Nothing was fetched or written.`),
3096
+ });
3097
+ }
3098
+ const runtimeEntity = runtimeEntities.get(req.entity.entityType);
3099
+ const key = yield* Effect.exit(composePrimaryKeyOrFail(runtimeEntity, { [composite]: req.id.value }, "aggregate.create"));
3100
+ if (Exit.isSuccess(key)) {
3101
+ const keyText = `${req.entity.entityType}:${JSON.stringify(Object.values(key.value))}`;
3102
+ composed.set(req, keyText);
3103
+ const same = judged.get(keyText) ?? [];
3104
+ judged.set(keyText, same);
3105
+ const equivalent = idEquivalence(req.entity);
3106
+ const value = req.id.value;
3107
+ if (same.some((other) => equivalent(other, value)))
3108
+ continue;
3109
+ same.push(value);
3110
+ }
3111
+ const unstorable = yield* runtimeEntity._unstorableKey({ [composite]: req.id.value }).pipe(Effect.mapError((refused) => new ValidationError({
3112
+ entityType: aggregateName,
3113
+ operation: "aggregate.create",
3114
+ cause: new Error(`[EDD-9131] Aggregate "${aggregateName}": "${req.at}" is given ` +
3115
+ `${describeId(req.given)}, which no item of entity "${req.entity.entityType}" ` +
3116
+ `can be keyed by: \`put\` refuses it, as it doesn't encode as "${composite}" ` +
3117
+ `is stored. Give an id that does. Nothing was fetched or written.`, { cause: refused }),
3118
+ })));
3119
+ if (unstorable !== undefined) {
3120
+ return yield* new ValidationError({
3121
+ entityType: aggregateName,
3122
+ operation: "aggregate.create",
3123
+ cause: new Error(`[EDD-9131] Aggregate "${aggregateName}": "${req.at}" is given ${describeId(req.given)}, ` +
3124
+ `which no item of entity "${req.entity.entityType}" can be keyed by: \`put\` ` +
3125
+ `refuses it, as DynamoDB can't store it (${unstorable.describe()}). Give an id ` +
3126
+ `DynamoDB can store. Nothing was fetched or written.`),
3127
+ });
3128
+ }
3129
+ }
3130
+ // Each id's key, composed before anything is fetched: one with no key text (`NaN`,
3131
+ // `EDD-9096`) fails here. An id fetched twice, or two ids composing one key (`"L"` and `"l"`
3132
+ // under lowercase casing), is fetched once: `BatchGetItem` refuses a repeated key.
3133
+ const fetches = [];
3134
+ const lookupKeys = new Map();
3135
+ for (const [entityType, { entity, reqs }] of byEntityType) {
3136
+ const runtimeEntity = runtimeEntities.get(entityType);
3137
+ const composite = refKeyComposite(entity);
3138
+ const ops = [];
3139
+ const seen = new Set();
3140
+ for (const req of reqs) {
3141
+ // Composed while judging the id, unless that failed: then composing fails here.
3142
+ let lookupKey = composed.get(req);
3143
+ if (lookupKey === undefined) {
3144
+ const key = yield* composePrimaryKeyOrFail(runtimeEntity, { [composite]: Option.getOrThrow(req.id) }, "aggregate.create");
3145
+ lookupKey = `${entityType}:${JSON.stringify(Object.values(key))}`;
3146
+ }
3147
+ lookupKeys.set(req, lookupKey);
3148
+ if (!seen.has(lookupKey)) {
3149
+ seen.add(lookupKey);
3150
+ ops.push({ lookupKey, req });
3151
+ }
3152
+ }
3153
+ fetches.push({ entityType, runtimeEntity, ops });
3154
+ }
3155
+ // Batch-fetch all refs — one Batch.get call per entity type
3156
+ const hydratedLookup = new Map();
3157
+ for (const { entityType, runtimeEntity, ops } of fetches) {
3158
+ const composite = refKeyComposite(runtimeEntity);
3159
+ // Build EntityGet intermediates for batch fetching: `Batch.get` composes each key as the
3160
+ // entity's own `get` does, the key `Entity.put` wrote.
3161
+ const getOps = ops.map(({ req }) => runtimeEntity.get({ [composite]: Option.getOrThrow(req.id) }));
2076
3162
  const results = yield* Batch.get(getOps);
2077
3163
  // Map results back to lookup, failing on missing refs.
2078
- for (let i = 0; i < uniqueIds.length; i++) {
2079
- const id = uniqueIds[i];
3164
+ for (let i = 0; i < ops.length; i++) {
3165
+ const { lookupKey, req } = ops[i];
2080
3166
  const result = results[i];
2081
3167
  if (result == null) {
2082
3168
  return yield* new RefNotFound({
2083
3169
  entity: aggregateName,
2084
- field: reqs.find((r) => r.id === id)?.fieldName ?? "",
3170
+ field: req.fieldName,
2085
3171
  refEntity: entityType,
2086
- refId: id,
3172
+ refId: refIdText(req.given),
2087
3173
  });
2088
3174
  }
2089
- // `Batch.get` returns the DECODED record — transform fields are lifted to
2090
- // their domain form (e.g. `Schema.DateTimeUtcFromString` → `DateTime`). The
2091
- // denormalized ref is spliced into `input` and decoded again by the
2092
- // aggregate's strict `schema`, whose nested edge field is the ORIGINAL ref
2093
- // class expecting the wire form. Re-encode through the ref's substituted
2094
- // `recordSchema` so the spliced value is wire-form and decoded exactly once
2095
- // (issue #72) — this also keeps it marshall-safe for decompose.
2096
- const wire = yield* Schema.encodeUnknownEffect(runtimeEntity.schemas.recordSchema)(result).pipe(Effect.mapError((cause) => new ValidationError({
2097
- entityType: aggregateName,
2098
- operation: "aggregate.hydrateRefs.encode",
2099
- cause,
2100
- })));
2101
- hydratedLookup.set(`${entityType}:${id}`, wire);
3175
+ // `Batch.get` returns the decoded record: domain values, as a caller holds, and
3176
+ // `writeSchema` takes them as that. Encoded here, a field with one type on both
3177
+ // sides of a transformation would be taken for a domain value and encoded twice.
3178
+ hydratedLookup.set(lookupKey, result);
2102
3179
  }
2103
3180
  }
2104
3181
  // Walk the input again and replace IDs with hydrated data
2105
- const result = replaceRefIds(input, refRequests, hydratedLookup);
3182
+ const result = replaceRefIds(input, refRequests, (req) => {
3183
+ const lookupKey = lookupKeys.get(req);
3184
+ return lookupKey === undefined ? undefined : hydratedLookup.get(lookupKey);
3185
+ });
2106
3186
  renameInputFields(result, edges);
2107
3187
  return result;
2108
3188
  });
@@ -2128,82 +3208,118 @@ const renameInputFields = (data, edges) => {
2128
3208
  }
2129
3209
  }
2130
3210
  };
3211
+ /** An id given for an edge's entity: the id as given, and as a value of its key composite. */
3212
+ const refId = (entity, given) => ({ given, id: refIdValue(entity, given) });
3213
+ const idEquivalences = new WeakMap();
3214
+ /**
3215
+ * Whether two ids of `entity` are one value of its key composite (`refIdField`), by the field's
3216
+ * own equivalence (`Schema.toEquivalence`: two `Date`s of one instant are one); `Equal.equals`
3217
+ * where the field can't be read or derives none.
3218
+ */
3219
+ const idEquivalence = (entity) => {
3220
+ const field = refIdField(entity);
3221
+ if (field === undefined)
3222
+ return Equal.equals;
3223
+ const cached = idEquivalences.get(field);
3224
+ if (cached !== undefined)
3225
+ return cached;
3226
+ let equivalent;
3227
+ try {
3228
+ equivalent = Schema.toEquivalence(field);
3229
+ }
3230
+ catch {
3231
+ equivalent = Equal.equals;
3232
+ }
3233
+ idEquivalences.set(field, equivalent);
3234
+ return equivalent;
3235
+ };
2131
3236
  /**
2132
3237
  * Recursively walk input following graph edges to collect ref ID references.
2133
3238
  * Edge-driven: entity lookup comes from the edge directly, not from a refs bag.
3239
+ *
3240
+ * An id is anything given where the input takes one (`null` and `undefined` give none), judged
3241
+ * by `hydrateAggregateRefs` before anything is fetched. Up to 1.39.0 only a string was taken,
3242
+ * so a number or bigint id was dropped, and an optional edge was created without it.
2134
3243
  */
2135
- const collectRefIdsFromEdges = (result, input, edges, path) => {
3244
+ const collectRefIdsFromEdges = (result, input, edges,
3245
+ /** The fields of the schema `input` is a value of: a `many` element's schema is read off it. */
3246
+ fields, path,
3247
+ /** Where `input` is, to name an id in an error: `""` at the root, `"sub."` under `sub`. */
3248
+ at) => {
2136
3249
  for (const [edgeName, edge] of Object.entries(edges)) {
2137
3250
  if (!("_tag" in edge))
2138
3251
  continue;
2139
- if (edge._tag === "RefEdge") {
2140
- // RefEdge → ${field}Id in input
3252
+ if (edge._tag === "RefEdge" || (edge._tag === "OneEdge" && edge.entity)) {
3253
+ // RefEdge, and OneEdge with an entity → ${field}Id in input, where it holds an id `create`
3254
+ // fetches (`holdsRefId`): a string as on 1.39.0, an id of another type only where the model's
3255
+ // field is the entity's own model, its id isn't declared, and the entity isn't given whole.
3256
+ const entity = edge.entity;
2141
3257
  const idFieldName = `${edgeName}Id`;
2142
- const idValue = input[idFieldName];
2143
- if (typeof idValue === "string") {
3258
+ const idValue = given(input, idFieldName);
3259
+ if (holdsRefId(fields, edgeName, entity, input)) {
2144
3260
  result.push({
2145
- entity: edge.entity,
2146
- id: idValue,
2147
- path: [...path],
2148
- fieldName: edgeName,
2149
- idFieldName,
2150
- });
2151
- }
2152
- }
2153
- else if (edge._tag === "OneEdge" && edge.entity) {
2154
- // OneEdge with entity → ${field}Id in input
2155
- const idFieldName = `${edgeName}Id`;
2156
- const idValue = input[idFieldName];
2157
- if (typeof idValue === "string") {
2158
- result.push({
2159
- entity: edge.entity,
2160
- id: idValue,
3261
+ entity,
3262
+ ...refId(entity, idValue),
2161
3263
  path: [...path],
2162
3264
  fieldName: edgeName,
2163
3265
  idFieldName,
3266
+ at: `${at}${idFieldName}`,
2164
3267
  });
2165
3268
  }
2166
3269
  }
2167
3270
  else if (edge._tag === "BoundSubAggregate") {
2168
3271
  const bound = edge;
2169
- const subInput = input[edgeName];
3272
+ const subInput = given(input, edgeName);
2170
3273
  if (subInput != null && typeof subInput === "object") {
2171
- collectRefIdsFromEdges(result, subInput, bound.aggregate.edges, [
2172
- ...path,
2173
- edgeName,
2174
- ]);
3274
+ collectRefIdsFromEdges(result, subInput, bound.aggregate.edges, fieldsOf(bound.aggregate.schema), [...path, edgeName], `${at}${edgeName}.`);
2175
3275
  }
2176
3276
  }
2177
3277
  else if (edge._tag === "ManyEdge" && edge.entity) {
2178
3278
  // ManyEdge with entity → walk array elements for ref IDs
3279
+ const entity = edge.entity;
2179
3280
  const inputKey = edge.inputField ?? edgeName;
2180
- const arr = input[inputKey];
3281
+ const arr = given(input, inputKey);
2181
3282
  if (Array.isArray(arr)) {
2182
- const entityFieldName = deriveEntityFieldName(edge.entity);
3283
+ const entityFieldName = deriveEntityFieldName(entity);
3284
+ const element = manyElementSchema(fields, edgeName);
3285
+ const entityElement = isEntityElement(element, entity);
2183
3286
  for (let i = 0; i < arr.length; i++) {
2184
3287
  const elem = arr[i];
2185
- if (typeof elem === "string") {
2186
- // Element IS the ref ID (e.g., Array<string> for Array<Umpire>)
3288
+ if (elem == null)
3289
+ continue;
3290
+ const asId = refId(entity, elem);
3291
+ if (entityElement
3292
+ ? Option.isSome(asId.id) || typeof elem !== "object"
3293
+ : typeof elem === "string") {
3294
+ // Element IS the ref ID. Where the element is the entity (`Array<Umpire>`), an id of
3295
+ // the entity's key composite, or a scalar given for one, which names no item. Any
3296
+ // other element, a string, as on 1.39.0.
2187
3297
  result.push({
2188
- entity: edge.entity,
2189
- id: elem,
3298
+ entity,
3299
+ ...asId,
2190
3300
  path: [...path, inputKey, String(i)],
2191
3301
  fieldName: edgeName,
2192
3302
  idFieldName: String(i),
3303
+ at: `${at}${inputKey}[${i}]`,
2193
3304
  });
2194
3305
  }
2195
- else if (elem != null && typeof elem === "object") {
2196
- // Element wraps entity + attributes — find the entityFieldName + "Id"
3306
+ else if (typeof elem === "object" &&
3307
+ elementHoldsRef(element, entity, elem)) {
3308
+ // Element wraps the entity, given as `${field}Id`, where it holds an id `create`
3309
+ // fetches (`elementHoldsRef`, the rule a `one` edge's id follows): a string as on
3310
+ // 1.39.0, an id of another type only where the element's field of the entity's name is
3311
+ // the entity's own model, its id isn't declared, and the entity isn't given whole.
2197
3312
  const elemObj = elem;
2198
3313
  const idFieldName = `${entityFieldName}Id`;
2199
- const idValue = elemObj[idFieldName];
2200
- if (typeof idValue === "string") {
3314
+ const idValue = given(elemObj, idFieldName);
3315
+ if (idValue != null) {
2201
3316
  result.push({
2202
- entity: edge.entity,
2203
- id: idValue,
3317
+ entity,
3318
+ ...refId(entity, idValue),
2204
3319
  path: [...path, inputKey, String(i)],
2205
3320
  fieldName: entityFieldName,
2206
3321
  idFieldName,
3322
+ at: `${at}${inputKey}[${i}].${idFieldName}`,
2207
3323
  });
2208
3324
  }
2209
3325
  }
@@ -2269,21 +3385,23 @@ const replaceRefIds = (input, refRequests, lookup) => {
2269
3385
  // Deep clone the input for mutation
2270
3386
  const result = cloneInput(input);
2271
3387
  for (const req of refRequests) {
2272
- const lookupKey = `${req.entity.entityType}:${req.id}`;
2273
- const data = lookup.get(lookupKey);
3388
+ const data = lookup(req);
2274
3389
  if (!data)
2275
3390
  continue;
3391
+ // For ManyEdge elements that are direct IDs (element IS the ref), the target is the array
3392
+ // itself: the path ends at the element, which may be an object (a `Date` id).
3393
+ const isElementId = /^\d+$/.test(req.idFieldName);
3394
+ const segments = isElementId ? req.path.slice(0, -1) : req.path;
2276
3395
  // Navigate to the target location in the result
2277
3396
  let target = result;
2278
- for (const segment of req.path) {
3397
+ for (const segment of segments) {
2279
3398
  const next = target[segment];
2280
3399
  if (next == null || typeof next !== "object")
2281
3400
  break;
2282
3401
  target = next;
2283
3402
  }
2284
- // For ManyEdge elements that are direct IDs (element IS the ref),
2285
- // the target is the array itself — replace the element at the index
2286
- if (Array.isArray(target) && /^\d+$/.test(req.idFieldName)) {
3403
+ // Replace the element at the index
3404
+ if (Array.isArray(target) && isElementId) {
2287
3405
  target[Number(req.idFieldName)] = data;
2288
3406
  }
2289
3407
  else {
@@ -2294,15 +3412,24 @@ const replaceRefIds = (input, refRequests, lookup) => {
2294
3412
  }
2295
3413
  return result;
2296
3414
  };
3415
+ /** Each field a decomposition stored as given, once, as `"field" of "member"` (`EDD-9127`). */
3416
+ const storedAsGivenIn = (groups) => [
3417
+ ...new Set(groups.flatMap((group) => group.items.flatMap((item) => item.storedAsGiven.map((field) => `"${field}" of "${item.member}"`)))),
3418
+ ];
2297
3419
  /**
2298
3420
  * Decompose an assembled domain object into DynamoDB items grouped by
2299
3421
  * sub-aggregate transaction boundaries.
2300
3422
  */
2301
- const decomposeAggregate = (assembled, rootNode, contextFields, encoders, aggregateName, schema) => Effect.gen(function* () {
3423
+ const decomposeAggregate = (assembled, rootNode, contextFields, encoders, aggregateName, schema,
3424
+ /**
3425
+ * A write's own value (`create`'s input, the state `update`'s mutation returned), before it was
3426
+ * decoded: a custom `decompose` is handed it read as on 1.39.0. Undefined for what was read.
3427
+ */
3428
+ written) => Effect.gen(function* () {
2302
3429
  const items = [];
2303
- const encodeWith = (set, field, value) => {
3430
+ const encodeWith = (set, field, value, asGiven) => {
2304
3431
  const encode = set[field];
2305
- return encode && value != null ? encode(value) : value;
3432
+ return encode && value != null ? encode(value, asGiven) : value;
2306
3433
  };
2307
3434
  // Extract context values from the root, encoded for DynamoDB storage.
2308
3435
  // Domain Date/DateTime objects must be encoded before toAttributeMap() marshalling,
@@ -2317,10 +3444,12 @@ const decomposeAggregate = (assembled, rootNode, contextFields, encoders, aggreg
2317
3444
  const edgeFieldNames = new Set(rootNode.children.map((c) => c.fieldName).filter(Boolean));
2318
3445
  const rootAttrs = {};
2319
3446
  const rootKeyAttrs = {};
3447
+ // A context field is a root field, so this names it too.
3448
+ const rootAsGiven = [];
2320
3449
  for (const [key, value] of Object.entries(assembled)) {
2321
3450
  if (edgeFieldNames.has(key))
2322
3451
  continue;
2323
- rootAttrs[key] = encodeWith(encoders.stored, key, value);
3452
+ rootAttrs[key] = encodeWith(encoders.stored, key, value, () => rootAsGiven.push(key));
2324
3453
  rootKeyAttrs[key] = encodeWith(encoders.key, key, value);
2325
3454
  }
2326
3455
  items.push({
@@ -2329,13 +3458,16 @@ const decomposeAggregate = (assembled, rootNode, contextFields, encoders, aggreg
2329
3458
  keyAttributes: rootKeyAttrs,
2330
3459
  transactionGroup: "root",
2331
3460
  skComposites: [],
2332
- skComposites136: [],
3461
+ skCompositesOther: () => [],
2333
3462
  member: rootNode.entityType,
3463
+ rowStamps: rootNode.rowStamps,
3464
+ storedAsGiven: rootAsGiven,
3465
+ node: rootNode,
2334
3466
  });
2335
3467
  // Decompose each edge
2336
3468
  for (const child of rootNode.children) {
2337
3469
  const fieldValue = assembled[child.fieldName];
2338
- yield* decomposeNode(items, child, fieldValue, contextValues, "root", { current: [], legacy: [] }, aggregateName, schema.casing);
3470
+ yield* decomposeNode(items, child, fieldValue, contextValues, "root", { current: [], other: () => [] }, aggregateName, schema, writtenField(written, child.fieldName));
2339
3471
  }
2340
3472
  // Two items composing the same sort key are two writes to one row. DynamoDB
2341
3473
  // rejects the whole TransactWriteItems with a ValidationException ("Transaction
@@ -2380,24 +3512,336 @@ const mergeContextValues = (attrs, contextValues) => {
2380
3512
  attrs[key] = value;
2381
3513
  }
2382
3514
  };
3515
+ /**
3516
+ * Whether two keys beginning with these fixed texts can be one text: the texts are equal, or one
3517
+ * continues the other after a `#`. A composite value is taken to be any text (with `escapeKeys`
3518
+ * off one may hold `#`), so this never misses a key that can be the other's.
3519
+ */
3520
+ const headsOverlap = (a, b) => a === b || a.startsWith(`${b}#`) || b.startsWith(`${a}#`);
3521
+ /**
3522
+ * Whether a writer's text can be the aggregate's partition key: any text can, and composed text
3523
+ * can when it and the key can be one text ({@link headsOverlap}). The aggregate's partition key is
3524
+ * its head continued after `#` when it has composites, and exactly its head when it has none (a
3525
+ * singleton): text that continues its own head can be that only when its head and a `#` begin it.
3526
+ */
3527
+ const canBePartitionKey = (writer, ownership) => {
3528
+ const head = writer.head;
3529
+ if (head === undefined)
3530
+ return true;
3531
+ const partition = ownership.partitionHead;
3532
+ if (ownership.pkComposite.length === 0) {
3533
+ const equal = head === partition;
3534
+ const continued = partition.startsWith(`${head}#`);
3535
+ return writer.exact === true ? equal : writer.exact === false ? continued : equal || continued;
3536
+ }
3537
+ return writer.exact === true ? head.startsWith(`${partition}#`) : headsOverlap(head, partition);
3538
+ };
3539
+ /**
3540
+ * Whether a row of `theirs` can be taken for a row of `ours`: it can carry any type, it's the same
3541
+ * type, or keys of the two can be one text, each cased as its member's keys are. A bind-time
3542
+ * comparison only: ownership and assembly match `__edd_e__` exactly.
3543
+ */
3544
+ const typesCollide = (theirs, ours) => theirs.any !== undefined || theirs.type === ours.type || headsOverlap(theirs.label, ours.label);
3545
+ /**
3546
+ * A member's writers, every row type of them made any when one stores an attribute under
3547
+ * `__edd_e__` other than the library's marker, or any attribute: its rows can carry any type. An
3548
+ * aggregate's timestamp so named does, since it's written last. An entity can't (`EDD-9140`).
3549
+ */
3550
+ const withTypeOverwrites = (writers) => {
3551
+ const marker = writers.find((writer) => writer.field === "__edd_e__" ||
3552
+ (writer.field === undefined && writer.except?.includes("__edd_e__") !== true));
3553
+ if (marker === undefined)
3554
+ return writers;
3555
+ const any = { via: `${marker.channel}, stored under "__edd_e__"` };
3556
+ return writers.map((writer) => ({
3557
+ ...writer,
3558
+ types: writer.types.map((type) => ({ ...type, any })),
3559
+ }));
3560
+ };
3561
+ /**
3562
+ * The attributes an entity writes (DESIGN.md §7 "Which rows in its partition are an aggregate's"),
3563
+ * as each row holds them after the last write of each:
3564
+ * - its primary key on every row it writes under it: live rows, version snapshots, soft-delete
3565
+ * tombstones, time-series events, projection tombstones and outbox items;
3566
+ * - each secondary index's partition key on its live rows, and each vector index's partition;
3567
+ * - its unique sentinels, under their own key, with back-pointers to the owning row's key;
3568
+ * - any sort key, its timestamps, `deletedAt`, and the attributes a projection writes on its
3569
+ * tombstones and outbox items, as any text;
3570
+ * - its model attributes, on its rows and kept on its projection tombstones: any name holding any
3571
+ * text, but `__edd_e__` and its table key attributes, which it writes after them (`EDD-9109` and
3572
+ * `EDD-9140` refuse a model attribute stored under them).
3573
+ * None of its rows is an aggregate node's: it composes each composite with its field's name
3574
+ * (`id_p`), which an aggregate never does, and its primary key has at least one. An entity whose
3575
+ * keys can't be read is taken to write any attribute.
3576
+ */
3577
+ const entityWriters = (entity) => {
3578
+ const e = entity;
3579
+ const type = e.entityType;
3580
+ const table = e._tableTag;
3581
+ try {
3582
+ const schema = e._schema;
3583
+ const typed = (name, casing) => ({
3584
+ type: name,
3585
+ label: composeKey(schema, name, [], { casing }),
3586
+ });
3587
+ const labelOf = (index) => {
3588
+ const collection = index.collection;
3589
+ return collection === undefined
3590
+ ? type
3591
+ : Array.isArray(collection)
3592
+ ? collection[0]
3593
+ : collection;
3594
+ };
3595
+ // A partition key with composites, or a shard, continues its head after `#`.
3596
+ const exactOf = (index) => index.pk.composite.length > 0 || index.shards !== undefined ? false : undefined;
3597
+ const primary = e.indexes.primary;
3598
+ const tableKeys = [
3599
+ primary.pk.field,
3600
+ ...(primary.sk?.field === undefined ? [] : [primary.sk.field]),
3601
+ ];
3602
+ const stamps = [e.systemFields?.createdAt, e.systemFields?.updatedAt].filter((name) => typeof name === "string");
3603
+ const writers = [];
3604
+ const anyText = (fields, types, on, channel) => {
3605
+ for (const field of fields) {
3606
+ writers.push({ field, head: undefined, types, table: on, channel: channel(field) });
3607
+ }
3608
+ };
3609
+ const projectionTypes = [];
3610
+ for (const [name, index] of Object.entries(e.indexes)) {
3611
+ const head = composeKey(schema, labelOf(index), [], { casing: index.casing });
3612
+ const exact = exactOf(index);
3613
+ const own = typed(type, index.casing);
3614
+ if (name !== "primary") {
3615
+ // A half on a table key attribute holds the primary key's text (an inverted index): two
3616
+ // halves of one entity share an attribute only with the same fields (`EDD-9106`).
3617
+ if (!tableKeys.includes(index.pk.field)) {
3618
+ writers.push({
3619
+ field: index.pk.field,
3620
+ head,
3621
+ exact,
3622
+ types: [own],
3623
+ table,
3624
+ channel: `its index "${name}"`,
3625
+ });
3626
+ }
3627
+ if (index.sk?.field !== undefined && !tableKeys.includes(index.sk.field)) {
3628
+ writers.push({
3629
+ field: index.sk.field,
3630
+ head: undefined,
3631
+ types: [own],
3632
+ table,
3633
+ channel: `its index "${name}"'s sort key`,
3634
+ });
3635
+ }
3636
+ continue;
3637
+ }
3638
+ // Its live rows, version snapshots, soft-delete tombstones, time-series events and projection
3639
+ // rows. None is an aggregate node's row: an entity composes each composite with its field's
3640
+ // name (`id_p`), which an aggregate never does, and its primary key has at least one.
3641
+ const tombstone = e._projectionTombstones !== undefined ? typed(`${type}#tombstone`, index.casing) : undefined;
3642
+ const outboxConfigs = e._projectionOutboxes ?? [];
3643
+ const outboxHere = outboxConfigs.some((outbox) => outbox.table === undefined)
3644
+ ? typed(`${type}#outbox`, index.casing)
3645
+ : undefined;
3646
+ if (tombstone !== undefined)
3647
+ projectionTypes.push(tombstone);
3648
+ const rows = [
3649
+ own,
3650
+ ...(tombstone === undefined ? [] : [tombstone]),
3651
+ ...(outboxHere === undefined ? [] : [outboxHere]),
3652
+ ];
3653
+ writers.push({
3654
+ field: index.pk.field,
3655
+ head,
3656
+ exact,
3657
+ types: rows,
3658
+ table,
3659
+ channel: "its primary key",
3660
+ });
3661
+ if (index.sk?.field !== undefined) {
3662
+ writers.push({
3663
+ field: index.sk.field,
3664
+ head: undefined,
3665
+ types: rows,
3666
+ table,
3667
+ channel: "its sort key",
3668
+ });
3669
+ }
3670
+ if (e.softDelete !== undefined && e.softDelete !== false) {
3671
+ anyText(["deletedAt"], [own], table, () => "its soft-delete tombstones' `deletedAt`");
3672
+ }
3673
+ if (tombstone !== undefined) {
3674
+ anyText(["__edd_removed__", KEY_TEXT], [tombstone], table, (field) => `its projection tombstones' "${field}"`);
3675
+ }
3676
+ for (const constraint of Object.keys(e.unique ?? {})) {
3677
+ const sentinel = composeUniqueKey(schema, type, constraint, [], {
3678
+ casing: index.casing,
3679
+ }).sk;
3680
+ const rowType = { type: `${type}._unique.${constraint}`, label: sentinel };
3681
+ const channel = `its unique constraint "${constraint}"`;
3682
+ writers.push({
3683
+ field: index.pk.field,
3684
+ head: sentinel,
3685
+ exact: false,
3686
+ types: [rowType],
3687
+ table,
3688
+ channel,
3689
+ });
3690
+ if (index.sk?.field !== undefined) {
3691
+ writers.push({
3692
+ field: index.sk.field,
3693
+ head: sentinel,
3694
+ exact: true,
3695
+ types: [rowType],
3696
+ table,
3697
+ channel,
3698
+ });
3699
+ }
3700
+ // Written after the sentinel's key: one named as a key attribute replaces it.
3701
+ writers.push({
3702
+ field: "_entity_pk",
3703
+ head,
3704
+ exact,
3705
+ types: [rowType],
3706
+ table,
3707
+ channel: `${channel}'s back-pointer "_entity_pk"`,
3708
+ });
3709
+ anyText(["_entity_sk"], [rowType], table, () => `${channel}'s back-pointer "_entity_sk"`);
3710
+ }
3711
+ // Each projection's outbox items: under the row's partition key, on the row table or another.
3712
+ const outboxes = outboxConfigs.map((outbox) => outbox.table === undefined
3713
+ ? { on: table, pk: index.pk.field, sk: index.sk?.field, index: outbox.index }
3714
+ : { on: outbox.table.Tag, pk: outbox.pk, sk: outbox.sk, index: outbox.index });
3715
+ for (const outbox of outboxes) {
3716
+ const outboxType = typed(`${type}#outbox`, index.casing);
3717
+ const channel = "its projection outbox";
3718
+ for (const field of [outbox.pk, OUTBOX_ROW_PK]) {
3719
+ writers.push({ field, head, exact, types: [outboxType], table: outbox.on, channel });
3720
+ }
3721
+ anyText([
3722
+ ...(outbox.sk === undefined ? [] : [outbox.sk]),
3723
+ OUTBOX_ROW_SK,
3724
+ "effect",
3725
+ "source",
3726
+ "streamId",
3727
+ "eventType",
3728
+ KEY_TEXT,
3729
+ OUTBOX_CLAIM,
3730
+ OUTBOX_CLAIMED_UNTIL,
3731
+ ...(outbox.index === undefined ? [] : [outbox.index.pk, outbox.index.sk]),
3732
+ ], [outboxType], outbox.on, (field) => `${channel}'s "${field}"`);
3733
+ }
3734
+ }
3735
+ for (const [name, vector] of Object.entries(e._vectorIndexes ?? {})) {
3736
+ writers.push({
3737
+ field: vector.partitionField,
3738
+ head: vector.compose === undefined
3739
+ ? composeKey(schema, type, [], { casing: vector.casing })
3740
+ : undefined,
3741
+ types: [typed(type)],
3742
+ table,
3743
+ channel: `its vector index "${name}"`,
3744
+ });
3745
+ }
3746
+ anyText([...stamps, INCARNATION_TOKEN], [typed(type)], table, (field) => `its "${field}"`);
3747
+ // Its model attributes: on its rows, and kept on its projection tombstones. Whatever its model
3748
+ // declares, these are any name holding any text, but the ones it writes after them.
3749
+ writers.push({
3750
+ field: undefined,
3751
+ except: ["__edd_e__", ...tableKeys],
3752
+ head: undefined,
3753
+ types: [typed(type), ...projectionTypes],
3754
+ table,
3755
+ channel: "its model attributes",
3756
+ });
3757
+ return withTypeOverwrites(writers);
3758
+ }
3759
+ catch {
3760
+ return [
3761
+ {
3762
+ field: undefined,
3763
+ head: undefined,
3764
+ types: [{ type, label: type, any: { via: "its keys can't be read" } }],
3765
+ table,
3766
+ channel: "its keys, which can't be read",
3767
+ },
3768
+ ];
3769
+ }
3770
+ };
3771
+ /**
3772
+ * The first member that can write a row of one of the aggregate's types into its partition, if
3773
+ * any (DESIGN.md §7 "Which rows in its partition are an aggregate's"): `DynamoClient.make` refuses
3774
+ * an aggregate declaring `ownsRows` for it (`EDD-9130`). A member can when one of its attribute
3775
+ * writers ({@link entityWriters}, an aggregate's own) writes the aggregate's `pk.field` on the same
3776
+ * physical table (`sameTable`), with text that can be the aggregate's partition key
3777
+ * ({@link canBePartitionKey}), on a row whose type collides with one of the aggregate's
3778
+ * ({@link typesCollide}). The aggregate itself isn't one.
3779
+ */
3780
+ export const ownershipConflict = (aggregate, members, sameTable) => {
3781
+ const ownership = aggregate._ownership;
3782
+ if (ownership === undefined)
3783
+ return undefined;
3784
+ const seen = new Set([aggregate]);
3785
+ for (const { name, member } of [...ownership.declared, ...members]) {
3786
+ if (member === null || typeof member !== "object" || seen.has(member))
3787
+ continue;
3788
+ seen.add(member);
3789
+ const writers = member
3790
+ ._attributeWriters ??
3791
+ (member._tag === "Entity" ? entityWriters(member) : []);
3792
+ for (const writer of writers) {
3793
+ if (!sameTable(writer.table))
3794
+ continue;
3795
+ if (writer.field === undefined
3796
+ ? writer.except?.includes(ownership.pkField) === true
3797
+ : writer.field !== ownership.pkField) {
3798
+ continue;
3799
+ }
3800
+ if (!canBePartitionKey(writer, ownership))
3801
+ continue;
3802
+ for (const theirs of writer.types) {
3803
+ const ours = ownership.types.find((type) => typesCollide(theirs, type));
3804
+ if (ours === undefined)
3805
+ continue;
3806
+ return theirs.any === undefined
3807
+ ? { member: name, type: theirs.type, channel: writer.channel }
3808
+ : { member: name, type: ours.type, channel: `${writer.channel}; ${theirs.any.via}` };
3809
+ }
3810
+ }
3811
+ }
3812
+ return undefined;
3813
+ };
3814
+ /** A sort key value in the text of the setting `schema` isn't using. */
3815
+ const otherKeyText = (schema, value) => KeyComposer.keyValueText(schema.escapeKeys === true ? KeyText136.schema136(schema) : KeyText136.schemaEscaped(schema), value, schema.casing);
3816
+ /** A decomposed row's sort key under the other setting; `sk`, if a value has no text there. */
3817
+ const otherSortKey = (schema, item, sk) => {
3818
+ try {
3819
+ return composeKey(schema, item.entityType, [...item.skCompositesOther()]);
3820
+ }
3821
+ catch {
3822
+ return sk;
3823
+ }
3824
+ };
2383
3825
  /** A node's own static discriminator values as {@link DiscriminatorValues}. */
2384
- const ownDiscriminatorValues = (node, casing) => {
3826
+ const ownDiscriminatorValues = (node, schema) => {
2385
3827
  const entries = node.ownDiscriminator === undefined
2386
3828
  ? []
2387
3829
  : Object.entries(node.ownDiscriminator).filter(([, v]) => typeof v !== "function");
2388
3830
  return {
2389
- current: entries.flatMap(([k, v]) => [k, KeyComposer.serializeSortKeyValue(v, casing)]),
2390
- legacy: entries.flatMap(([k, v]) => [k, KeyText136.serializeValue(v)]),
3831
+ current: entries.flatMap(([k, v]) => [k, KeyComposer.keyValueText(schema, v, schema.casing)]),
3832
+ other: () => entries.flatMap(([k, v]) => [k, otherKeyText(schema, v)]),
2391
3833
  };
2392
3834
  };
2393
3835
  /**
2394
3836
  * Recursively decompose a node's value into DynamoDB items. Sort key values
2395
- * are escaped with the schema's `casing` (`KeyComposer.sortKeyText`); the
3837
+ * are escaped with the schema's `casing` (`KeyComposer.keyText`); the
2396
3838
  * discriminator names between them are field names, kept as they are.
2397
3839
  */
2398
3840
  const decomposeNode = (items, node, value, contextValues, parentGroup,
2399
3841
  /** The parent's discriminator values, in today's text and in 1.36's (#171). */
2400
- parentDiscriminators, aggregateName, casing) => Effect.gen(function* () {
3842
+ parentDiscriminators, aggregateName, schema,
3843
+ /** The caller's own value here, on a write (see {@link Written}). */
3844
+ written) => Effect.gen(function* () {
2401
3845
  // Optional edges may have null/undefined values — skip decomposition
2402
3846
  if (value == null)
2403
3847
  return;
@@ -2411,10 +3855,10 @@ parentDiscriminators, aggregateName, casing) => Effect.gen(function* () {
2411
3855
  // Discriminator values for SK composition: the parent sub-aggregate's
2412
3856
  // (name#value pairs, empty at the top level) then this node's own, so a
2413
3857
  // nested sub-aggregate's rows are keyed apart per binding of its parent.
2414
- const own = ownDiscriminatorValues(node, casing);
3858
+ const own = ownDiscriminatorValues(node, schema);
2415
3859
  const discValues = {
2416
3860
  current: [...parentDiscriminators.current, ...own.current],
2417
- legacy: [...parentDiscriminators.legacy, ...own.legacy],
3861
+ other: () => [...parentDiscriminators.other(), ...own.other()],
2418
3862
  };
2419
3863
  // Sub-aggregate root item: fields not claimed by child edges
2420
3864
  const childEdgeNames = new Set(node.children.map((c) => c.fieldName).filter(Boolean));
@@ -2425,7 +3869,7 @@ parentDiscriminators, aggregateName, casing) => Effect.gen(function* () {
2425
3869
  subRootAttrs[key] = val;
2426
3870
  }
2427
3871
  // Serialize this node's own date fields to their wire primitive (#72).
2428
- applyNodeAttrEncoders(subRootAttrs, node.attrEncoders);
3872
+ const storedAsGiven = applyNodeAttrEncoders(subRootAttrs, node.attrEncoders);
2429
3873
  // Inject context and discriminator
2430
3874
  mergeContextValues(subRootAttrs, contextValues.stored);
2431
3875
  if (node.discriminator) {
@@ -2439,20 +3883,23 @@ parentDiscriminators, aggregateName, casing) => Effect.gen(function* () {
2439
3883
  attributes: subRootAttrs,
2440
3884
  transactionGroup: txGroup,
2441
3885
  skComposites: discValues.current,
2442
- skComposites136: discValues.legacy,
3886
+ skCompositesOther: discValues.other,
2443
3887
  member: node.fieldName ?? node.entityType,
3888
+ rowStamps: node.rowStamps,
3889
+ storedAsGiven,
3890
+ node,
2444
3891
  });
2445
3892
  // Decompose children within this sub-aggregate
2446
3893
  for (const child of node.children) {
2447
3894
  const childValue = subValue[child.fieldName];
2448
- yield* decomposeNode(items, child, childValue, contextValues, txGroup, discValues, aggregateName, casing);
3895
+ yield* decomposeNode(items, child, childValue, contextValues, txGroup, discValues, aggregateName, schema, writtenField(written, child.fieldName));
2449
3896
  }
2450
3897
  }
2451
3898
  else if (node.cardinality === "one") {
2452
3899
  // Simple one-to-one edge (no children)
2453
3900
  const attrs = { ...value };
2454
3901
  // Serialize this edge entity's own date fields to their wire primitive (#72).
2455
- applyNodeAttrEncoders(attrs, node.attrEncoders);
3902
+ const storedAsGiven = applyNodeAttrEncoders(attrs, node.attrEncoders);
2456
3903
  mergeContextValues(attrs, contextValues.stored);
2457
3904
  if (node.discriminator) {
2458
3905
  for (const [k, v] of Object.entries(node.discriminator)) {
@@ -2461,20 +3908,26 @@ parentDiscriminators, aggregateName, casing) => Effect.gen(function* () {
2461
3908
  }
2462
3909
  }
2463
3910
  // Own discriminator values as name#value pairs for SK composition
2464
- const own = ownDiscriminatorValues(node, casing);
3911
+ const own = ownDiscriminatorValues(node, schema);
2465
3912
  items.push({
2466
3913
  entityType: node.entityType,
2467
3914
  attributes: attrs,
2468
3915
  transactionGroup: parentGroup,
2469
3916
  skComposites: [...parentDiscriminators.current, ...own.current],
2470
- skComposites136: [...parentDiscriminators.legacy, ...own.legacy],
3917
+ skCompositesOther: () => [...parentDiscriminators.other(), ...own.other()],
2471
3918
  member: node.fieldName ?? node.entityType,
3919
+ rowStamps: node.rowStamps,
3920
+ storedAsGiven,
3921
+ node,
2472
3922
  });
2473
3923
  }
2474
3924
  else {
2475
3925
  // Many edge
3926
+ const handed = written === undefined || node.decomposeInput === undefined
3927
+ ? value
3928
+ : Option.getOrElse(node.decomposeInput(written), () => value);
2476
3929
  const arrayItems = node.decompose
2477
- ? node.decompose(value)
3930
+ ? node.decompose(handed)
2478
3931
  : Array.isArray(value)
2479
3932
  ? value
2480
3933
  : [];
@@ -2492,7 +3945,7 @@ parentDiscriminators, aggregateName, casing) => Effect.gen(function* () {
2492
3945
  // The element's attributes in their STORED form — every nested date,
2493
3946
  // transformed scalar and hydrated ref encoded (#72, #133).
2494
3947
  const attrs = { ...elem };
2495
- applyNodeAttrEncoders(attrs, node.attrEncoders);
3948
+ const storedAsGiven = applyNodeAttrEncoders(attrs, node.attrEncoders);
2496
3949
  withContext(attrs, contextValues.stored);
2497
3950
  // The sort key is read from the element as the pre-#133 encoders left
2498
3951
  // it, NOT from `attrs`: encoding a ref's nested `NumberFromString` turns
@@ -2508,13 +3961,54 @@ parentDiscriminators, aggregateName, casing) => Effect.gen(function* () {
2508
3961
  transactionGroup: parentGroup,
2509
3962
  skComposites: [
2510
3963
  ...parentDiscriminators.current,
2511
- ...values.map((value) => KeyComposer.serializeSortKeyValue(value, casing)),
3964
+ ...values.map((value) => KeyComposer.keyValueText(schema, value, schema.casing)),
2512
3965
  ],
2513
- skComposites136: [
2514
- ...parentDiscriminators.legacy,
2515
- ...values.map((value) => KeyText136.serializeValue(value)),
3966
+ skCompositesOther: () => [
3967
+ ...parentDiscriminators.other(),
3968
+ ...values.map((value) => otherKeyText(schema, value)),
2516
3969
  ],
3970
+ otherKindSortKey: (targets) => {
3971
+ const slots = values.map((_, i) => String(i));
3972
+ const settings = [
3973
+ [
3974
+ () => parentDiscriminators.current,
3975
+ (value) => KeyComposer.keyValueText(schema, value, schema.casing),
3976
+ ],
3977
+ [() => parentDiscriminators.other(), (value) => otherKeyText(schema, value)],
3978
+ ];
3979
+ for (const [parents, text] of settings) {
3980
+ const sortKey = (record) => composeKey(schema, node.entityType, [
3981
+ ...parents(),
3982
+ ...slots.map((slot) => text(record[slot])),
3983
+ ]);
3984
+ const reading = kindReadingOf({ ...values }, slots, () => undefined, ({ record }) => sortKey(record), targets);
3985
+ if (reading !== undefined && reading.asOther.size > 0)
3986
+ return sortKey(reading.record);
3987
+ }
3988
+ return undefined;
3989
+ },
3990
+ skTextFor: (taker, path) => {
3991
+ try {
3992
+ let from = keyAttrs;
3993
+ if (taker !== node) {
3994
+ from = { ...elem };
3995
+ applyNodeAttrEncoders(from, taker.keyAttrEncoders);
3996
+ mergeContextValues(from, contextValues.key);
3997
+ }
3998
+ const value = readCompositePath(from, path);
3999
+ return value == null || !isScalarComposite(value)
4000
+ ? undefined
4001
+ : KeyComposer.keyValueText(schema, value, schema.casing);
4002
+ }
4003
+ catch {
4004
+ // What `taker` can't compose a key from isn't a key it writes.
4005
+ return undefined;
4006
+ }
4007
+ },
2517
4008
  member: node.fieldName ?? node.entityType,
4009
+ rowStamps: node.rowStamps,
4010
+ storedAsGiven,
4011
+ node,
2518
4012
  });
2519
4013
  }
2520
4014
  }
@@ -2538,13 +4032,6 @@ const readCompositePath = (attrs, path) => {
2538
4032
  }
2539
4033
  return current;
2540
4034
  };
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
4035
  /**
2549
4036
  * Whether a resolved composite value can be a sort-key segment.
2550
4037
  *
@@ -2607,7 +4094,8 @@ const manyEdgeSkComposites = (node, attrs, aggregateName) => Effect.gen(function
2607
4094
  `attribute itself by dotted path (e.g. "umpire.id", not "umpire").`,
2608
4095
  });
2609
4096
  }
2610
- return values;
4097
+ // A number its field stores as a string holds its `NaN` in key form, as the root's key does.
4098
+ return values.map((value, i) => storedNaNKeyForm(fieldAtPath(node.ownFields, declared[i]), value));
2611
4099
  });
2612
4100
  /**
2613
4101
  * Extract ref identifier values from an item's attributes for use as SK composites.
@@ -2660,7 +4148,86 @@ const hashToShard = (value, cardinality) => {
2660
4148
  }
2661
4149
  return Math.abs(hash) % cardinality;
2662
4150
  };
4151
+ /**
4152
+ * A `many` value's rows, each through `fill`, put back in the shape the value has. A custom
4153
+ * `decompose` says what the rows are, and only its `assemble` can put them back: with no `assemble`,
4154
+ * a value that isn't an array has no way back, so its rows can't be filled. This runs before the
4155
+ * input is decoded, so a value they can't take apart or put back is left for the schema to report.
4156
+ */
4157
+ const fillRows = (child, value, fill) => {
4158
+ const filledOf = (rows) => {
4159
+ const filled = rows.map(fill);
4160
+ return filled.some((row, i) => row !== rows[i]) ? filled : undefined;
4161
+ };
4162
+ if (child.decompose !== undefined && child.assemble !== undefined) {
4163
+ try {
4164
+ const filled = value === undefined ? undefined : filledOf(child.decompose(value));
4165
+ return filled === undefined ? value : child.assemble(filled);
4166
+ }
4167
+ catch {
4168
+ return value;
4169
+ }
4170
+ }
4171
+ return Array.isArray(value) ? (filledOf(value) ?? value) : value;
4172
+ };
4173
+ /**
4174
+ * `value` with the dates its rows declare, walking the graph. `"declared"` (`create`) stamps every one
4175
+ * the input lacks, and one it holds unless the root declares that date `Schema.optional` (`replaces`):
4176
+ * up to 1.39.0 the input had to hold a date the root required, which the stamp then replaced, so a
4177
+ * value there is a placeholder; 1.39.0 stamped one the root declares `Schema.optionalKey` over a value
4178
+ * passed, and one it declares `Schema.optional` was the caller's to store. `"required"`
4179
+ * (`update`) fills only one the mutated state lacks and a schema requires; one it doesn't require a
4180
+ * rewrite stamps anyway: a mutation that changes nothing still has nothing to write. A value with
4181
+ * nothing to add comes back as it is.
4182
+ */
4183
+ const fillStamps = (node, value, now, which) => {
4184
+ if (value === null || typeof value !== "object" || Array.isArray(value))
4185
+ return value;
4186
+ const given = value;
4187
+ const added = {};
4188
+ const row = node.rowStamps;
4189
+ const fill = (name, declared, required, replaces, encoding) => {
4190
+ if (name === null || (given[name] !== undefined && (which === "required" || !replaces)))
4191
+ return;
4192
+ if (which === "declared" ? declared : required) {
4193
+ added[name] = generateTimestampPrimitive(now, encoding);
4194
+ }
4195
+ };
4196
+ if (row !== undefined) {
4197
+ fill(row.createdAt, row.createdDeclared, row.createdRequired, row.createdReplaces, row.createdEncoding);
4198
+ fill(row.updatedAt, row.updatedDeclared, row.updatedRequired, row.updatedReplaces, row.updatedEncoding);
4199
+ }
4200
+ for (const child of node.children) {
4201
+ const current = given[child.fieldName];
4202
+ const next = child.cardinality === "many"
4203
+ ? fillRows(child, current, (row) => fillStamps(child, row, now, which))
4204
+ : fillStamps(child, current, now, which);
4205
+ if (next !== current)
4206
+ added[child.fieldName] = next;
4207
+ }
4208
+ return Object.keys(added).length === 0 ? value : { ...given, ...added };
4209
+ };
4210
+ /**
4211
+ * A key's composites, in key text. One with no value has no key text, so this throws: `[EDD-9123]`,
4212
+ * a `KeyValueError` that `composeKeysOrFail` makes a `ValidationError` before anything is written.
4213
+ * Only for a key the aggregate can't do without: a list's keys are sparse (`buildDynamoItems`).
4214
+ */
4215
+ const keyCompositesOrThrow = (aggregateName, key, schema, composite, record) => {
4216
+ const absent = composite.filter((attr) => record[attr] === undefined || record[attr] === null);
4217
+ if (absent.length > 0) {
4218
+ const names = absent.map((attr) => `"${attr}"`).join(", ");
4219
+ throw new KeyValueError({
4220
+ value: undefined,
4221
+ reason: `no value for ${names}`,
4222
+ message: `[EDD-9123] Aggregate "${aggregateName}": ${key} is composed from ${names}, which has no ` +
4223
+ `value here. An aggregate can't be read without this key, so nothing was sent. Supply it, ` +
4224
+ `or compose the key from a field that always has one.`,
4225
+ });
4226
+ }
4227
+ return KeyComposer.extractKeyComposites(schema, {}, composite, record);
4228
+ };
2663
4229
  const EMPTY_CREATED = new Map();
4230
+ const hasKeyValue = (value) => value !== undefined && value !== null;
2664
4231
  /**
2665
4232
  * Convert decomposed items into DynamoDB attribute maps with composed keys.
2666
4233
  *
@@ -2670,7 +4237,12 @@ const EMPTY_CREATED = new Map();
2670
4237
  * on every comparison and silently collapse the diff into a full-partition
2671
4238
  * rewrite on every update (#98).
2672
4239
  */
2673
- const buildDynamoItems = (groups, config, pkValue, rootCollectionSkComposites,
4240
+ const buildDynamoItems = (groups, config, pkValue,
4241
+ /**
4242
+ * The root's value, the collection sort key's composites read from. Undefined: the caller wants
4243
+ * each row's identity (`pk`, `sk`) only, and neither that key nor the list keys are composed.
4244
+ */
4245
+ rootValue,
2674
4246
  /**
2675
4247
  * The aggregate's composite key-form normaliser. Required, not optional: the
2676
4248
  * list-GSI keys composed below have to be spelled exactly as `Aggregate.list`
@@ -2687,49 +4259,70 @@ keyRecord, stamp) => groups.map((group) => ({
2687
4259
  attrs[config.pk.field] = pkValue;
2688
4260
  // SK: entity-type specific
2689
4261
  attrs.sk = composeKey(config.schema, item.entityType, [...item.skComposites]);
4262
+ // System timestamps. Written last, so a generated value wins over the same-named field
4263
+ // propagated onto edge items via `context`; known first, so a key over one holds what the row
4264
+ // holds. A date the row declares holds what the row does: on `create` the stamp `fillStamps`
4265
+ // put there, on `update` a value the mutation changed, and `created` stays what's stored
4266
+ // whatever the mutation did to it.
4267
+ const stamped = {};
4268
+ const row = item.rowStamps;
4269
+ if (stamp && row !== undefined) {
4270
+ const { existingCreated, now } = stamp;
4271
+ const sk = attrs.sk;
4272
+ if (row.createdAt !== null) {
4273
+ const held = row.createdDeclared ? item.attributes[row.createdAt] : undefined;
4274
+ stamped[row.createdAt] =
4275
+ existingCreated.get(sk) ?? held ?? generateTimestampPrimitive(now, row.createdStored);
4276
+ }
4277
+ if (row.updatedAt !== null) {
4278
+ const held = row.updatedDeclared ? item.attributes[row.updatedAt] : undefined;
4279
+ const before = stamp.updatedBefore;
4280
+ const supplied = held !== undefined && !(before?.has(sk) && deepEqual(before.get(sk), held));
4281
+ stamped[row.updatedAt] =
4282
+ stamp.existingUpdated?.get(sk) ??
4283
+ (supplied ? held : generateTimestampPrimitive(now, row.updatedStored));
4284
+ }
4285
+ }
2690
4286
  // Collection SK mirror — only written when an index is actually provisioned.
2691
4287
  // Root items get the collection key; every other item's value is a verbatim copy
2692
4288
  // of its own `sk`. With no index there is nothing to sort, so the attribute is
2693
4289
  // omitted entirely rather than duplicating `sk` on every item.
2694
4290
  const isRootItem = item.entityType === config.root.entityType && item.skComposites.length === 0;
2695
4291
  const collectionSk = config.collection.sk;
2696
- if (config.collection.index !== undefined && collectionSk !== undefined) {
4292
+ if (rootValue !== undefined &&
4293
+ config.collection.index !== undefined &&
4294
+ collectionSk !== undefined) {
2697
4295
  attrs[collectionSk.field] = isRootItem
2698
- ? composeCollectionKey(config.schema, config.collection.name, rootCollectionSkComposites)
4296
+ ? composeCollectionKey(config.schema, config.collection.name, keyCompositesOrThrow(config.root.entityType, "its collection sort key", config.schema, collectionSk.composite, keyRecord({ ...rootValue, ...stamped })))
2699
4297
  : composeKey(config.schema, item.entityType, [...item.skComposites]);
2700
4298
  }
2701
- // List collection GSI keys (root items only)
2702
- if (isRootItem && config.list) {
2703
- const listPkComposites = KeyComposer.extractComposites(config.list.pk.composite, keyRecord(item.keyAttributes ?? item.attributes));
2704
- if (config.list.cardinality) {
2705
- const shard = hashToShard(pkValue, config.list.cardinality);
2706
- attrs[config.list.pk.field] = composeCollectionKey(config.schema, config.list.name, [
2707
- ...listPkComposites,
2708
- String(shard),
2709
- ]);
2710
- }
2711
- else {
2712
- attrs[config.list.pk.field] = composeCollectionKey(config.schema, config.list.name, listPkComposites);
2713
- }
2714
- const listSkComposites = sortKeyComposites(config.schema, KeyComposer.extractComposites(config.list.sk.composite, keyRecord(item.keyAttributes ?? item.attributes)));
2715
- attrs[config.list.sk.field] = composeCollectionKey(config.schema, config.list.name, listSkComposites);
2716
- }
2717
- // System timestamps — last, so a generated value wins over the same-named
2718
- // field propagated onto edge items via `context`.
2719
- if (stamp) {
2720
- const { existingCreated, fields, now } = stamp;
2721
- const sk = attrs.sk;
2722
- if (fields.createdAt !== null) {
2723
- const prior = existingCreated.get(sk);
2724
- attrs[fields.createdAt] = prior ?? generateTimestampPrimitive(now, fields.createdEncoding);
2725
- }
2726
- if (fields.updatedAt !== null) {
2727
- attrs[fields.updatedAt] =
2728
- stamp.existingUpdated?.get(sk) ??
2729
- generateTimestampPrimitive(now, fields.updatedEncoding);
4299
+ // List collection GSI keys (root items only). Sparse, as an entity index is: a row with no
4300
+ // value for a composite isn't in the list, whole index or nothing, and a later write that
4301
+ // gives it one puts it there. Every aggregate write is a whole-row Put, so leaving both
4302
+ // attributes off is also what takes it out.
4303
+ if (rootValue !== undefined && isRootItem && config.list) {
4304
+ const listKeyValues = keyRecord({
4305
+ ...(item.keyAttributes ?? item.attributes),
4306
+ ...stamped,
4307
+ });
4308
+ const listComposites = [...config.list.pk.composite, ...config.list.sk.composite];
4309
+ if (listComposites.every((attr) => hasKeyValue(listKeyValues[attr]))) {
4310
+ const listPkComposites = KeyComposer.extractKeyComposites(config.schema, {}, config.list.pk.composite, listKeyValues);
4311
+ if (config.list.cardinality) {
4312
+ const shard = hashToShard(pkValue, config.list.cardinality);
4313
+ attrs[config.list.pk.field] = composeCollectionKey(config.schema, config.list.name, [
4314
+ ...listPkComposites,
4315
+ String(shard),
4316
+ ]);
4317
+ }
4318
+ else {
4319
+ attrs[config.list.pk.field] = composeCollectionKey(config.schema, config.list.name, listPkComposites);
4320
+ }
4321
+ const listSkComposites = KeyComposer.extractKeyComposites(config.schema, {}, config.list.sk.composite, listKeyValues);
4322
+ attrs[config.list.sk.field] = composeCollectionKey(config.schema, config.list.name, listSkComposites);
2730
4323
  }
2731
4324
  }
2732
- return toAttributeMap(attrs);
4325
+ return toAttributeMap({ ...attrs, ...stamped });
2733
4326
  }),
2734
4327
  }));
2735
4328
  function writeTransactionGroups(client, tableName, groups, aggregateName, keys, rootGuard) {
@@ -2765,31 +4358,15 @@ function writeTransactionGroups(client, tableName, groups, aggregateName, keys,
2765
4358
  },
2766
4359
  })),
2767
4360
  ...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
4361
  ];
2781
- // The 1.36 root's check, last in the transaction.
2782
- const root136Index = rootGuard?.key136 !== undefined && rootIndex >= 0 ? itemCount : -1;
2783
4362
  // Named once, for both diagnoses below.
2784
4363
  const sent = () => ({
2785
4364
  _tag: "Transaction",
2786
4365
  items: transactItems,
2787
4366
  targets: () => transactItems.map((item) => {
2788
4367
  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}"`);
4368
+ return transactItemTarget(item, tableName, [keys.pkField, "sk"], entityType, `the ${item.Put !== undefined ? entityType : "removed"} item of ` +
4369
+ `sub-aggregate "${group.group}"`);
2793
4370
  }),
2794
4371
  });
2795
4372
  const already = [...committed];
@@ -2829,8 +4406,7 @@ function writeTransactionGroups(client, tableName, groups, aggregateName, keys,
2829
4406
  const reasons = cancelled.CancellationReasons;
2830
4407
  if (rootGuard !== undefined &&
2831
4408
  rootIndex >= 0 &&
2832
- (reasons?.[rootIndex]?.Code === "ConditionalCheckFailed" ||
2833
- (root136Index >= 0 && reasons?.[root136Index]?.Code === "ConditionalCheckFailed"))) {
4409
+ reasons?.[rootIndex]?.Code === "ConditionalCheckFailed") {
2834
4410
  return new ConditionalCheckFailed({
2835
4411
  entityType: rootGuard.entityType,
2836
4412
  key: rootGuard.key,
@@ -2854,18 +4430,57 @@ function writeTransactionGroups(client, tableName, groups, aggregateName, keys,
2854
4430
  }
2855
4431
  });
2856
4432
  }
2857
- // ---------------------------------------------------------------------------
2858
- // Internal: Rows under their 1.36 keys (#171)
2859
- // ---------------------------------------------------------------------------
2860
- /** DynamoDB's limit on the items of one `TransactWriteItems`. */
2861
- const TRANSACT_LIMIT = 100;
4433
+ /**
4434
+ * `update`'s cleanup Deletes with `ownsRows` (DESIGN.md §7 "Which rows in its partition are an
4435
+ * aggregate's"), sent after the update's groups have committed, up to {@link TRANSACT_WRITE_ITEMS_LIMIT} to a
4436
+ * request: Deletes of keys already stored reach no other limit of a transaction. Each holds while
4437
+ * its row is gone or still of the type read, so a row another write removed in between is fine,
4438
+ * and one replaced with a row of another type is left. A cancelled request is sent once more
4439
+ * without the Deletes whose condition failed; the mutation isn't run again and nothing is read
4440
+ * again. A failure is reported as a later group's is: the update's groups have committed, and the
4441
+ * rows it didn't delete stay until the next update of their node.
4442
+ */
4443
+ const deleteOwnedRows = (client, tableName, pkField, rows) => Effect.gen(function* () {
4444
+ const deleteOf = (row) => ({
4445
+ Delete: {
4446
+ TableName: tableName,
4447
+ Key: toAttributeMap({ [pkField]: row.pk, sk: row.sk }),
4448
+ ConditionExpression: "attribute_not_exists(#pk) OR #e = :e",
4449
+ ExpressionAttributeNames: { "#pk": pkField, "#e": "__edd_e__" },
4450
+ ExpressionAttributeValues: { ":e": { S: row.entityType } },
4451
+ },
4452
+ });
4453
+ for (let start = 0; start < rows.length; start += TRANSACT_WRITE_ITEMS_LIMIT) {
4454
+ const chunk = rows.slice(start, start + TRANSACT_WRITE_ITEMS_LIMIT);
4455
+ const reasons = yield* client
4456
+ .transactWriteItems({ TransactItems: chunk.map((row) => deleteOf(row)) })
4457
+ .pipe(Effect.as(undefined), Effect.catch((error) => isAwsTransactionCancelled(error.cause)
4458
+ ? Effect.succeed(error.cause.CancellationReasons ?? [])
4459
+ : Effect.fail(error)));
4460
+ if (reasons === undefined)
4461
+ continue;
4462
+ const rest = chunk.filter((_, i) => reasons[i]?.Code !== "ConditionalCheckFailed");
4463
+ if (rest.length === 0)
4464
+ continue;
4465
+ yield* client.transactWriteItems({ TransactItems: rest.map((row) => deleteOf(row)) }).pipe(Effect.mapError((error) => isAwsTransactionCancelled(error.cause)
4466
+ ? new TransactionCancelled({
4467
+ operation: "TransactWriteItems",
4468
+ reasons: (error.cause.CancellationReasons ?? []).map((r) => ({
4469
+ code: r?.Code,
4470
+ message: r?.Message,
4471
+ })),
4472
+ cause: error.cause,
4473
+ })
4474
+ : error));
4475
+ }
4476
+ });
2862
4477
  /**
2863
4478
  * 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:
4479
+ * a `current` and an `old` position. Off doesn't escape sort key text,
4480
+ * so in one partition a row's unescaped key can be another row's escaped key —
4481
+ * `a%20b`'s unescaped sort key is `a b`'s escaped one — and the rows' keys chain:
2867
4482
  * `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
4483
+ * one of them free, the rows before it are under their old keys and those
2869
4484
  * after it under their current keys. With every key held, a lone row is
2870
4485
  * stored under `both` keys, and a longer chain is `ambiguous`; with more than
2871
4486
  * one free, a row with neither key held is `missing` and the rest are
@@ -2882,7 +4497,7 @@ const placeRows = (slots, held) => {
2882
4497
  currents.add(slot.current);
2883
4498
  }
2884
4499
  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.
4500
+ // A chain starts at a row whose old key is no other row's current key.
2886
4501
  if (slot.current === slot.old || currents.has(slot.old))
2887
4502
  continue;
2888
4503
  const chain = [];
@@ -2924,7 +4539,8 @@ const deleteAllItems = (client, tableName, allItems, pkField) => Effect.gen(func
2924
4539
  // Chunk into batches of 25 (DynamoDB batchWriteItem limit). Items DynamoDB
2925
4540
  // leaves unprocessed (throttling) are retried with exponential backoff, as
2926
4541
  // `Batch.write` retries them; a bounded number of retries, then a clear
2927
- // failure — never a silent partial delete (#134).
4542
+ // failure — never a silent partial delete (#134). By count alone: 25 stored keys (at most
4543
+ // 2048 + 1024 bytes each, so at most about 0.5 MB as JSON) can't reach the 16 MB request limit.
2928
4544
  for (let i = 0; i < deleteRequests.length; i += 25) {
2929
4545
  let pending = deleteRequests.slice(i, i + 25);
2930
4546
  let retries = 0;