effect-dynamodb 1.42.2 → 1.44.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 (221) hide show
  1. package/dist/Aggregate.d.ts +157 -20
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +1219 -286
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/Batch.d.ts +17 -4
  6. package/dist/Batch.d.ts.map +1 -1
  7. package/dist/Batch.js +129 -62
  8. package/dist/Batch.js.map +1 -1
  9. package/dist/BlobGc.d.ts +243 -0
  10. package/dist/BlobGc.d.ts.map +1 -0
  11. package/dist/BlobGc.js +961 -0
  12. package/dist/BlobGc.js.map +1 -0
  13. package/dist/BlobStore.d.ts +83 -0
  14. package/dist/BlobStore.d.ts.map +1 -0
  15. package/dist/BlobStore.js +70 -0
  16. package/dist/BlobStore.js.map +1 -0
  17. package/dist/Collection.d.ts +88 -8
  18. package/dist/Collection.d.ts.map +1 -1
  19. package/dist/Collection.js +22 -26
  20. package/dist/Collection.js.map +1 -1
  21. package/dist/Collections.d.ts +0 -7
  22. package/dist/Collections.d.ts.map +1 -1
  23. package/dist/Collections.js +0 -16
  24. package/dist/Collections.js.map +1 -1
  25. package/dist/DynamoClient.d.ts +68 -35
  26. package/dist/DynamoClient.d.ts.map +1 -1
  27. package/dist/DynamoClient.js +58 -12
  28. package/dist/DynamoClient.js.map +1 -1
  29. package/dist/Entity.d.ts +403 -104
  30. package/dist/Entity.d.ts.map +1 -1
  31. package/dist/Entity.js +1771 -382
  32. package/dist/Entity.js.map +1 -1
  33. package/dist/EventStore.d.ts +323 -77
  34. package/dist/EventStore.d.ts.map +1 -1
  35. package/dist/EventStore.js +473 -96
  36. package/dist/EventStore.js.map +1 -1
  37. package/dist/Offload.d.ts +199 -0
  38. package/dist/Offload.d.ts.map +1 -0
  39. package/dist/Offload.js +120 -0
  40. package/dist/Offload.js.map +1 -0
  41. package/dist/Query.d.ts +132 -59
  42. package/dist/Query.d.ts.map +1 -1
  43. package/dist/Query.js +95 -31
  44. package/dist/Query.js.map +1 -1
  45. package/dist/StorageEncoding.d.ts +62 -15
  46. package/dist/StorageEncoding.d.ts.map +1 -1
  47. package/dist/StorageEncoding.js +108 -24
  48. package/dist/StorageEncoding.js.map +1 -1
  49. package/dist/Table.d.ts +1 -1
  50. package/dist/Table.d.ts.map +1 -1
  51. package/dist/Transaction.d.ts +16 -3
  52. package/dist/Transaction.d.ts.map +1 -1
  53. package/dist/Transaction.js +28 -9
  54. package/dist/Transaction.js.map +1 -1
  55. package/dist/blob/S3BlobStore.d.ts +178 -0
  56. package/dist/blob/S3BlobStore.d.ts.map +1 -0
  57. package/dist/blob/S3BlobStore.js +770 -0
  58. package/dist/blob/S3BlobStore.js.map +1 -0
  59. package/dist/blob/s3.d.ts +122 -0
  60. package/dist/blob/s3.d.ts.map +1 -0
  61. package/dist/blob/s3.js +143 -0
  62. package/dist/blob/s3.js.map +1 -0
  63. package/dist/index.d.ts +9 -3
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +4 -1
  66. package/dist/index.js.map +1 -1
  67. package/dist/internal/AggregateWrite.d.ts +130 -0
  68. package/dist/internal/AggregateWrite.d.ts.map +1 -0
  69. package/dist/internal/AggregateWrite.js +341 -0
  70. package/dist/internal/AggregateWrite.js.map +1 -0
  71. package/dist/internal/BlobCalls.d.ts +70 -0
  72. package/dist/internal/BlobCalls.d.ts.map +1 -0
  73. package/dist/internal/BlobCalls.js +105 -0
  74. package/dist/internal/BlobCalls.js.map +1 -0
  75. package/dist/internal/BlobKeys.d.ts +100 -0
  76. package/dist/internal/BlobKeys.d.ts.map +1 -0
  77. package/dist/internal/BlobKeys.js +135 -0
  78. package/dist/internal/BlobKeys.js.map +1 -0
  79. package/dist/internal/BlobLedger.d.ts +323 -0
  80. package/dist/internal/BlobLedger.d.ts.map +1 -0
  81. package/dist/internal/BlobLedger.js +1012 -0
  82. package/dist/internal/BlobLedger.js.map +1 -0
  83. package/dist/internal/BlobMetadata.d.ts +109 -0
  84. package/dist/internal/BlobMetadata.d.ts.map +1 -0
  85. package/dist/internal/BlobMetadata.js +249 -0
  86. package/dist/internal/BlobMetadata.js.map +1 -0
  87. package/dist/internal/BlobResolver.d.ts +146 -0
  88. package/dist/internal/BlobResolver.d.ts.map +1 -0
  89. package/dist/internal/BlobResolver.js +417 -0
  90. package/dist/internal/BlobResolver.js.map +1 -0
  91. package/dist/internal/BlobStoreContract.d.ts +214 -0
  92. package/dist/internal/BlobStoreContract.d.ts.map +1 -0
  93. package/dist/internal/BlobStoreContract.js +181 -0
  94. package/dist/internal/BlobStoreContract.js.map +1 -0
  95. package/dist/internal/BoundCrud.d.ts +153 -53
  96. package/dist/internal/BoundCrud.d.ts.map +1 -1
  97. package/dist/internal/BoundCrud.js +27 -5
  98. package/dist/internal/BoundCrud.js.map +1 -1
  99. package/dist/internal/BoundQuery.d.ts +49 -33
  100. package/dist/internal/BoundQuery.d.ts.map +1 -1
  101. package/dist/internal/BoundQuery.js +8 -2
  102. package/dist/internal/BoundQuery.js.map +1 -1
  103. package/dist/internal/BoundVectorQuery.d.ts +59 -25
  104. package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
  105. package/dist/internal/BoundVectorQuery.js +38 -17
  106. package/dist/internal/BoundVectorQuery.js.map +1 -1
  107. package/dist/internal/Capacity.d.ts +17 -2
  108. package/dist/internal/Capacity.d.ts.map +1 -1
  109. package/dist/internal/Capacity.js +47 -9
  110. package/dist/internal/Capacity.js.map +1 -1
  111. package/dist/internal/ConditionHolds.d.ts.map +1 -1
  112. package/dist/internal/ConditionHolds.js +2 -8
  113. package/dist/internal/ConditionHolds.js.map +1 -1
  114. package/dist/internal/CredentialRefusal.d.ts.map +1 -1
  115. package/dist/internal/CredentialRefusal.js +4 -0
  116. package/dist/internal/CredentialRefusal.js.map +1 -1
  117. package/dist/internal/Digest.d.ts +4 -3
  118. package/dist/internal/Digest.d.ts.map +1 -1
  119. package/dist/internal/Digest.js +25 -82
  120. package/dist/internal/Digest.js.map +1 -1
  121. package/dist/internal/EntityCombinators.d.ts +93 -45
  122. package/dist/internal/EntityCombinators.d.ts.map +1 -1
  123. package/dist/internal/EntityCombinators.js +42 -7
  124. package/dist/internal/EntityCombinators.js.map +1 -1
  125. package/dist/internal/EntityOps.d.ts +47 -6
  126. package/dist/internal/EntityOps.d.ts.map +1 -1
  127. package/dist/internal/EntityOps.js +30 -10
  128. package/dist/internal/EntityOps.js.map +1 -1
  129. package/dist/internal/EventProjection.d.ts +99 -25
  130. package/dist/internal/EventProjection.d.ts.map +1 -1
  131. package/dist/internal/EventProjection.js +124 -33
  132. package/dist/internal/EventProjection.js.map +1 -1
  133. package/dist/internal/ExpressionLimits.d.ts +22 -3
  134. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  135. package/dist/internal/ExpressionLimits.js +46 -7
  136. package/dist/internal/ExpressionLimits.js.map +1 -1
  137. package/dist/internal/GcSupport.d.ts +258 -0
  138. package/dist/internal/GcSupport.d.ts.map +1 -0
  139. package/dist/internal/GcSupport.js +284 -0
  140. package/dist/internal/GcSupport.js.map +1 -0
  141. package/dist/internal/ItemSize.d.ts +7 -1
  142. package/dist/internal/ItemSize.d.ts.map +1 -1
  143. package/dist/internal/ItemSize.js +13 -5
  144. package/dist/internal/ItemSize.js.map +1 -1
  145. package/dist/internal/MemoryBlobStore.d.ts +203 -0
  146. package/dist/internal/MemoryBlobStore.d.ts.map +1 -0
  147. package/dist/internal/MemoryBlobStore.js +623 -0
  148. package/dist/internal/MemoryBlobStore.js.map +1 -0
  149. package/dist/internal/MultiProjection.d.ts +56 -28
  150. package/dist/internal/MultiProjection.d.ts.map +1 -1
  151. package/dist/internal/MultiProjection.js +9 -3
  152. package/dist/internal/MultiProjection.js.map +1 -1
  153. package/dist/internal/Multipart.d.ts +96 -0
  154. package/dist/internal/Multipart.d.ts.map +1 -0
  155. package/dist/internal/Multipart.js +143 -0
  156. package/dist/internal/Multipart.js.map +1 -0
  157. package/dist/internal/OffloadChange.d.ts +187 -0
  158. package/dist/internal/OffloadChange.d.ts.map +1 -0
  159. package/dist/internal/OffloadChange.js +391 -0
  160. package/dist/internal/OffloadChange.js.map +1 -0
  161. package/dist/internal/OffloadInput.d.ts +141 -0
  162. package/dist/internal/OffloadInput.d.ts.map +1 -0
  163. package/dist/internal/OffloadInput.js +236 -0
  164. package/dist/internal/OffloadInput.js.map +1 -0
  165. package/dist/internal/OffloadRead.d.ts +140 -0
  166. package/dist/internal/OffloadRead.d.ts.map +1 -0
  167. package/dist/internal/OffloadRead.js +369 -0
  168. package/dist/internal/OffloadRead.js.map +1 -0
  169. package/dist/internal/OffloadTypes.d.ts +182 -0
  170. package/dist/internal/OffloadTypes.d.ts.map +1 -0
  171. package/dist/internal/OffloadTypes.js +15 -0
  172. package/dist/internal/OffloadTypes.js.map +1 -0
  173. package/dist/internal/OffloadValues.d.ts +87 -0
  174. package/dist/internal/OffloadValues.d.ts.map +1 -0
  175. package/dist/internal/OffloadValues.js +114 -0
  176. package/dist/internal/OffloadValues.js.map +1 -0
  177. package/dist/internal/OffloadWrite.d.ts +267 -0
  178. package/dist/internal/OffloadWrite.d.ts.map +1 -0
  179. package/dist/internal/OffloadWrite.js +766 -0
  180. package/dist/internal/OffloadWrite.js.map +1 -0
  181. package/dist/internal/Packed.d.ts +58 -23
  182. package/dist/internal/Packed.d.ts.map +1 -1
  183. package/dist/internal/Packed.js +108 -33
  184. package/dist/internal/Packed.js.map +1 -1
  185. package/dist/internal/ProjectionEngine.d.ts +28 -3
  186. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  187. package/dist/internal/ProjectionEngine.js +47 -9
  188. package/dist/internal/ProjectionEngine.js.map +1 -1
  189. package/dist/internal/RangePlanner.d.ts +3 -6
  190. package/dist/internal/RangePlanner.d.ts.map +1 -1
  191. package/dist/internal/RangePlanner.js +3 -29
  192. package/dist/internal/RangePlanner.js.map +1 -1
  193. package/dist/internal/Rekey.d.ts +16 -0
  194. package/dist/internal/Rekey.d.ts.map +1 -1
  195. package/dist/internal/Rekey.js +31 -2
  196. package/dist/internal/Rekey.js.map +1 -1
  197. package/dist/internal/StoredPointer.d.ts +19 -0
  198. package/dist/internal/StoredPointer.d.ts.map +1 -0
  199. package/dist/internal/StoredPointer.js +59 -0
  200. package/dist/internal/StoredPointer.js.map +1 -0
  201. package/dist/internal/TransactPlan.d.ts +18 -1
  202. package/dist/internal/TransactPlan.d.ts.map +1 -1
  203. package/dist/internal/TransactPlan.js +50 -10
  204. package/dist/internal/TransactPlan.js.map +1 -1
  205. package/dist/internal/TransactWriteOps.d.ts +33 -12
  206. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  207. package/dist/internal/TransactWriteOps.js +49 -19
  208. package/dist/internal/TransactWriteOps.js.map +1 -1
  209. package/dist/internal/TransactableOps.d.ts +58 -11
  210. package/dist/internal/TransactableOps.d.ts.map +1 -1
  211. package/dist/internal/TransactableOps.js +95 -19
  212. package/dist/internal/TransactableOps.js.map +1 -1
  213. package/dist/internal/Utf8Order.d.ts +21 -0
  214. package/dist/internal/Utf8Order.d.ts.map +1 -0
  215. package/dist/internal/Utf8Order.js +44 -0
  216. package/dist/internal/Utf8Order.js.map +1 -0
  217. package/dist/internal/WriteDiagnosis.d.ts +7 -1
  218. package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
  219. package/dist/internal/WriteDiagnosis.js +12 -16
  220. package/dist/internal/WriteDiagnosis.js.map +1 -1
  221. package/package.json +15 -4
package/dist/Aggregate.js CHANGED
@@ -9,10 +9,12 @@
9
9
  * Created via {@link make}. Sub-aggregates compose recursively via `.with()`.
10
10
  */
11
11
  import { TypeId as SchemaAggregateTypeId } from "@effect-dynamodb/schema/Aggregate.js";
12
+ import { Compression } from "@effect-dynamodb/schema/Compression.js";
12
13
  import * as DynamoModel from "@effect-dynamodb/schema/DynamoModel.js";
13
14
  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 { AggregateAssemblyError, AggregateDecompositionError, ConditionalCheckFailed, DynamoError, DynamoValidationError, isAwsTransactionCancelled, OptimisticLockError, RefNotFound, ValidationError, } from "@effect-dynamodb/schema/Errors.js";
15
16
  import { fieldAtPath, kindReadingOf, kindTargets, makeCompositeKeyForm, readBackAs, readBackUnsure, readsBackOtherwise, refuseInexact, storedNaNKeyForm, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
17
+ import { refOffloadRefusal } from "@effect-dynamodb/schema/internal/EntityOffload.js";
16
18
  import { buildDateTransform, containedKindOf, containedOperand, containsWireTransform, entityRefsOf, heldRefMember, keepsAsGiven, matchDateRepresentation, optionalField, refHeldTarget, resolveSystemFields, substituteSchemaDeep, unionHoldsRef, validateNoTransformOverride, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
17
19
  import { failingAsBefore, issueDecoding } from "@effect-dynamodb/schema/internal/FailingAsBefore.js";
18
20
  import { readingInstances } from "@effect-dynamodb/schema/internal/InstanceReads.js";
@@ -21,35 +23,44 @@ import * as KeyText136 from "@effect-dynamodb/schema/internal/KeyText136.js";
21
23
  import { lostIn } from "@effect-dynamodb/schema/internal/LostValues.js";
22
24
  import { KeyValueError } from "@effect-dynamodb/schema/internal/NumericKey.js";
23
25
  import { declaredCopy, givenEntry, given as givenValue, hasOwnName, ownValue, setOwn, } from "@effect-dynamodb/schema/internal/OwnNames.js";
24
- import { isDispatchEligible } from "@effect-dynamodb/schema/internal/PackedCodec.js";
26
+ import { binaryShapeRefusal, isDispatchEligible, } from "@effect-dynamodb/schema/internal/PackedCodec.js";
25
27
  import { extractArrayElement, extractKeyedValue, getSchemaFields, hasEncodingTransformation, holdsCustomDeclaration, holdsUntyped, refuseUnreadable, storedBelowFields, } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
26
28
  import { refuseAggregateKeyInTableKey } from "@effect-dynamodb/schema/internal/SharedKeyAttribute.js";
27
29
  import { isZoneInstance, zoneEntriesWritten } from "@effect-dynamodb/schema/internal/StoredForm.js";
28
30
  import { givenZoneReading } from "@effect-dynamodb/schema/internal/ZoneKeyText.js";
29
31
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
30
- import { BigDecimal, Cause, Chunk, DateTime, Effect, Equal, Exit, HashMap, HashSet, Option, Redacted, Result, Schema, SchemaAST, } from "effect";
32
+ import { BigDecimal, Cause, Chunk, Context, DateTime, Effect, Equal, Exit, HashMap, HashSet, Option, Redacted, Result, Schema, SchemaAST, Stream, } from "effect";
31
33
  import * as Batch from "./Batch.js";
34
+ import { BlobStore } from "./BlobStore.js";
32
35
  import { fromDefinition as entityFromDefinition } from "./Entity.js";
36
+ import * as AggregateWrite from "./internal/AggregateWrite.js";
37
+ import * as BlobLedger from "./internal/BlobLedger.js";
33
38
  import { entityNaming } from "./internal/BoundQuery.js";
34
39
  import * as Capacity from "./internal/Capacity.js";
35
40
  import { decodeKeyCursor, encodeKeyCursor } from "./internal/Cursor.js";
36
41
  import { digest } from "./internal/Digest.js";
42
+ import { offloaded as offloadedCombinator } from "./internal/EntityCombinators.js";
37
43
  import { and as andExpr, compileExpr, createConditionOps, emptyPartProblem, isEmptyExpr, parseSimpleShorthand, } from "./internal/Expr.js";
38
44
  import { asReadGuard, preferredGuard, wholeRowGuard, } from "./internal/ExpressionLimits.js";
45
+ import * as GcSupport from "./internal/GcSupport.js";
39
46
  import { packRequests, transactWriteShape, transactWriteUnit } from "./internal/ItemSize.js";
40
- import { hasStoredForm, packItemSync, unpackItemSync, withRegistry } from "./internal/Packed.js";
47
+ import { isBlobSource } from "./internal/OffloadInput.js";
48
+ import * as OffloadRead from "./internal/OffloadRead.js";
49
+ import { isBlobHandle, isOffloadedValue } from "./internal/OffloadValues.js";
50
+ import * as OffloadWrite from "./internal/OffloadWrite.js";
51
+ import { codecRequirements, hasStoredForm, packItemSync, unpackItemSync, unregisteredCodecError, withRegistry, } from "./internal/Packed.js";
41
52
  import { pathBuilderOf } from "./internal/PathBuilder.js";
42
53
  import * as Rekey from "./internal/Rekey.js";
43
54
  import { asRead, notReadBack, notStoredForm, readBackRefusal } from "./internal/RoundTrip.js";
44
- import { composePrimaryKeyOrFail, generateTimestampPrimitive, INCARNATION_TOKEN, KEY_TEXT, marshalOrFail, OUTBOX_CLAIM, OUTBOX_CLAIMED_UNTIL, OUTBOX_READ_MODEL, OUTBOX_ROW_PK, OUTBOX_ROW_SK, outboxMarkInUse, ROW_TOKEN, rowTokened, rowTokenInUse, } from "./internal/TransactableOps.js";
45
- import { diagnosedValidationError, diagnoseFailure, explainDiagnosis, mergeKeyAttributes, transactItemTarget, withCause, } from "./internal/WriteDiagnosis.js";
55
+ import { composePrimaryKeyOrFail, freshIncarnationToken, generateTimestampPrimitive, INCARNATION_TOKEN, KEY_TEXT, marshalOrFail, OUTBOX_CLAIM, OUTBOX_CLAIMED_UNTIL, OUTBOX_READ_MODEL, OUTBOX_ROW_PK, OUTBOX_ROW_SK, outboxMarkInUse, ROW_TOKEN, rowTokened, rowTokenInUse, } from "./internal/TransactableOps.js";
56
+ import { diagnoseFailure, explainDiagnosis, mergeKeyAttributes, withCause, } from "./internal/WriteDiagnosis.js";
46
57
  import { fromAttributeMap, isCachedNormal, toAttributeMap, toAttributeValue, unstorableIn, } from "./Marshaller.js";
47
58
  import { addTableKeyAttributes, resolvePrimaryKey } from "./Table.js";
48
59
  // Internal modules (decomposed from Aggregate.ts)
49
60
  export { isManyEdge, isOneEdge, isRefEdge, many, one, ref, } from "@effect-dynamodb/schema/internal/AggregateEdges.js";
50
61
  export { deriveAggregateSchemas, deriveElementInputSchema, deriveEntityFieldName, extractArrayElement, getSchemaFields, isFieldOptional, isSchemaMatchingEntity, unwrapModel, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
51
62
  import { makeCursor, } from "@effect-dynamodb/schema/internal/AggregateCursor.js";
52
- import { declaredValueNames, deriveAggregateSchemas, deriveEntityFieldName, elementHoldsRef, given, holdsRefId, isEntityElement, isFieldOptional, manyEdgePaths, manyElementFields, manyElementSchema, readRowOf, readTakesOff, refIdField, refIdValue, refKeyComposite, refKeyComposites, refuseAggregateKeyOverMovingValue, refuseAggregateKeysOverBothKinds, refuseAggregateProtoName, refuseManySortKeysOverMovingValue, resolveAggregateStamps, rowKeysOn, subAggregateRowKind, unwrapModel, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
63
+ import { aggregateVersionField, declaredValueNames, deriveAggregateSchemas, deriveEntityFieldName, elementHoldsRef, given, holdsRefId, isEntityElement, isFieldOptional, isSchemaMatchingEntity, manyEdgePaths, manyElementFields, manyElementSchema, readRowOf, readTakesOff, refIdField, refIdValue, refKeyComposite, refKeyComposites, refuseAggregateKeyOverMovingValue, refuseAggregateKeysOverBothKinds, refuseAggregateProtoName, refuseAggregateVersioning, refuseManySortKeysOverMovingValue, resolveAggregateStamps, rowKeysOn, subAggregateRowKind, unwrapModel, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
53
64
  // ---------------------------------------------------------------------------
54
65
  // TypeId
55
66
  // ---------------------------------------------------------------------------
@@ -940,10 +951,13 @@ const collectRefTargets = (rootFields, rootEdges) => {
940
951
  //
941
952
  // `heldOnly`: registered only where the read holds less than the target (`refHeldTarget` decides
942
953
  // another schema), so a declaration 1.40.0 left unregistered decodes as it did everywhere else.
943
- const register = (field, model, heldOnly) => {
954
+ //
955
+ // `edge`: the position is the aggregate's own edge, whose row keeps the fields its entity offloads
956
+ // and uploads them afresh (#179, design §6.9); a ref nested in an edge entity holds none of them.
957
+ const register = (field, model, heldOnly, edge = false) => {
944
958
  if (field !== undefined && model !== undefined && !targets.has(field)) {
945
959
  const target = unwrapEntityModel(model);
946
- const held = refHeldTarget(target);
960
+ const held = refHeldTarget(target, edge);
947
961
  if (!heldOnly || held !== target)
948
962
  targets.set(field, held);
949
963
  }
@@ -952,13 +966,13 @@ const collectRefTargets = (rootFields, rootEdges) => {
952
966
  // read can't do without: the walker would demand it of a hydrated value that has none (1.40.0
953
967
  // refused every such create), so the field is re-pointed at what a read of it holds. Anywhere
954
968
  // else `refHeldTarget` returns the class itself and nothing is registered.
955
- const registerHeld = (field) => {
969
+ const registerHeld = (field, edge = false) => {
956
970
  if (field === undefined || targets.has(field))
957
971
  return;
958
972
  const inner = unwrapOptionalField(field);
959
973
  if (getSchemaFields(inner) === undefined)
960
974
  return;
961
- const held = refHeldTarget(inner);
975
+ const held = refHeldTarget(inner, edge);
962
976
  if (held !== inner)
963
977
  targets.set(field, held);
964
978
  };
@@ -1022,10 +1036,11 @@ const collectRefTargets = (rootFields, rootEdges) => {
1022
1036
  const entity = edge.entity;
1023
1037
  const field = ownValue(fields, edgeName);
1024
1038
  if (field !== undefined && (isRoot || isOpaqueRefField(field))) {
1025
- register(field, entity?.model, heldOnly);
1039
+ // A `one` edge is its own row; a ref edge's copy holds no offloaded field (#179).
1040
+ register(field, entity?.model, heldOnly, edge._tag === "OneEdge");
1026
1041
  }
1027
1042
  else if (entity !== undefined)
1028
- registerHeld(field);
1043
+ registerHeld(field, edge._tag === "OneEdge");
1029
1044
  registerNested(entity);
1030
1045
  }
1031
1046
  else if (edge._tag === "ManyEdge") {
@@ -1039,7 +1054,7 @@ const collectRefTargets = (rootFields, rootEdges) => {
1039
1054
  const model = entity?.model;
1040
1055
  if (model !== undefined && !targets.has(arrayField)) {
1041
1056
  const target = unwrapEntityModel(model);
1042
- const held = refHeldTarget(target);
1057
+ const held = refHeldTarget(target, true);
1043
1058
  if (!heldOnly || held !== target) {
1044
1059
  targets.set(arrayField, Schema.Array(held));
1045
1060
  }
@@ -1050,7 +1065,7 @@ const collectRefTargets = (rootFields, rootEdges) => {
1050
1065
  isEntityElement(element, edge.entity)) {
1051
1066
  // The element IS the entity's class, which the walker sees into (`Array<Umpire>`): as
1052
1067
  // `registerHeld`, re-pointed only where its read holds less than the class.
1053
- const held = refHeldTarget(element);
1068
+ const held = refHeldTarget(element, true);
1054
1069
  if (held !== element && !targets.has(arrayField)) {
1055
1070
  targets.set(arrayField, Schema.Array(held));
1056
1071
  }
@@ -1103,9 +1118,6 @@ const applyNodeAttrEncoders = (attrs, encoders) => {
1103
1118
  }
1104
1119
  return asGiven;
1105
1120
  };
1106
- // ---------------------------------------------------------------------------
1107
- // Top-level aggregate construction
1108
- // ---------------------------------------------------------------------------
1109
1121
  const makeAggregate = (schema, config) => {
1110
1122
  const aggregateName = config.root.entityType;
1111
1123
  const groupKeys = {
@@ -1139,6 +1151,7 @@ const makeAggregate = (schema, config) => {
1139
1151
  validateNoTransformOverride(schemaFields, {});
1140
1152
  }
1141
1153
  validateNestedDiscriminators(aggregateName, config.edges);
1154
+ validateRefEdgeOffload(aggregateName, schemaFields, config.edges);
1142
1155
  // Ref fields whose target the schema walker must be told about (see
1143
1156
  // `collectRefTargets`). Keyed by the field SCHEMA, not its name: the resolver
1144
1157
  // is consulted at every depth, so a name-keyed table re-pointed any
@@ -1175,9 +1188,29 @@ const makeAggregate = (schema, config) => {
1175
1188
  updatedKey: storedIn(schemaFields, timestampFields.updatedAt, timestampFields.updatedAtCollision, timestampFields.updatedAtEncoding, true),
1176
1189
  }
1177
1190
  : undefined;
1191
+ // `versioned` and `fence` (#168, `docs/designs/aggregate-concurrency.md` §3.4, §3.5): judged at
1192
+ // load (`EDD-9177`, `EDD-9179`). The version is a number on the root row, beside the entity's hidden
1193
+ // incarnation token; `versioned` implies the fence.
1194
+ refuseAggregateVersioning(aggregateName, config, schemaFields, schema);
1195
+ const versionField = aggregateVersionField(config.versioned);
1196
+ const fenced = versionField !== undefined || config.fence === true;
1197
+ /**
1198
+ * The root model declares the version field: a read hands it over (0 for a root without one). A
1199
+ * root of members (a union, a suspended schema) declares it when a member does.
1200
+ */
1201
+ const versionDeclared = versionField !== undefined &&
1202
+ (schemaFields === undefined
1203
+ ? storedFieldNames(schema).includes(versionField)
1204
+ : ownValue(schemaFields, versionField) !== undefined);
1205
+ /** The root's sort key: composed from its entity type alone, under every key-text setting. */
1206
+ const rootSortKey = composeKey(config.schema, config.root.entityType, []);
1178
1207
  // What the read path may drop before decoding: each node drops those its rows
1179
- // don't declare ({@link stampsToStrip}). Declared, it belongs to the domain object.
1180
- const systemAttrs = new Set([timestampFields.createdAt, timestampFields.updatedAt].filter((name) => name !== null));
1208
+ // don't declare ({@link stampsToStrip}). Declared, it belongs to the domain object. A versioned
1209
+ // root's version is dropped the same way, and its incarnation token always (#168).
1210
+ const systemAttrs = new Set([
1211
+ ...[timestampFields.createdAt, timestampFields.updatedAt].filter((name) => name !== null),
1212
+ ...(versionField === undefined ? [] : [versionField, INCARNATION_TOKEN]),
1213
+ ]);
1181
1214
  const requiredIn = (fields, name) => name !== null && ownValue(fields, name) !== undefined && !isFieldOptional(fields[name]);
1182
1215
  // On `create`, a stamp replaces a value the input holds, as on 1.39.0, except under a date the root
1183
1216
  // declares `Schema.optional`: 1.39.0 left that field the caller's and stored a value passed for it.
@@ -1238,6 +1271,8 @@ const makeAggregate = (schema, config) => {
1238
1271
  cardinality: "root",
1239
1272
  edges: config.edges,
1240
1273
  parentFields: schemaFields,
1274
+ // A root that exposes no `.fields` (a union, a suspended schema): its stored names.
1275
+ valueSchema: schema,
1241
1276
  resolveRef,
1242
1277
  escapeKeys: config.schema.escapeKeys === true,
1243
1278
  rowKeys: config,
@@ -1251,7 +1286,11 @@ const makeAggregate = (schema, config) => {
1251
1286
  const returnsStamps = declaresStamp(rootNode);
1252
1287
  // Packed edge attributes, and those read by stored form, by item entity type (#147).
1253
1288
  const packedByType = collectPackedByType(rootNode);
1289
+ const offloadByType = collectOffloadByType(rootNode);
1254
1290
  const dispatchByType = collectDispatchByType(rootNode);
1291
+ // How each item type's offloaded attributes are uploaded and read (#179).
1292
+ const offloadInfoByType = collectOffloadInfoByType(rootNode);
1293
+ const readPlans = collectReadPlans(rootNode, aggregateName);
1255
1294
  // Attribute ENCODERS for the root item: decompose works from the
1256
1295
  // schema-decoded domain object, so every root attribute holding a wire
1257
1296
  // transform — a date, a transformed scalar, or a container of either — is
@@ -1387,6 +1426,14 @@ const makeAggregate = (schema, config) => {
1387
1426
  // assembly read diagnoses it, naming the aggregate and the index (#144).
1388
1427
  const consistentRead = config.consistentRead ?? false;
1389
1428
  const tablePrimary = resolvePrimaryKey(config.table.entities);
1429
+ /**
1430
+ * Whether `update`, an If-Match and `delete`'s second read read strongly consistent whatever
1431
+ * `consistentRead` says (#168, D11 reversed): on the base table only. A collection index is read
1432
+ * as `consistentRead` says, as on 1.43.0: an index keyed on the table's own partition key may be a
1433
+ * GSI (one added to a table after it was created, where an LSI can't be), which DynamoDB refuses a
1434
+ * consistent read of, so only the caller's `consistentRead: true` says it is an LSI.
1435
+ */
1436
+ const readConsistent = config.collection.index === undefined;
1390
1437
  if (tablePrimary !== undefined && config.collection.index === undefined) {
1391
1438
  if (config.pk.field !== tablePrimary.pk) {
1392
1439
  throw new Error(`[EDD-9041] Aggregate "${aggregateName}": collection PK field "${config.pk.field}" is ` +
@@ -1506,9 +1553,27 @@ const makeAggregate = (schema, config) => {
1506
1553
  "Drop `consistentRead` from the aggregate, or key it on the table's primary " +
1507
1554
  "partition key so assembly reads the base table.", original);
1508
1555
  /** Compose the PK and query all items; a rejected read fails as `rejected` names it. */
1509
- const readPartition = (key, rejected, rekeyRead) => Effect.flatMap(readPartitionRaw(key, rejected, rekeyRead), (read) =>
1510
- // Packed edge attributes, read by their stored form (#147).
1511
- Effect.as(unpackAggregateItems(read.allItems, dispatchByType, aggregateName), read));
1556
+ /**
1557
+ * A versioned root the model declares the version of reads 0 without one (#168, §3.5): a root
1558
+ * written before `versioned` was turned on. In place, on rows read.
1559
+ */
1560
+ const withReadVersion = (rows) => {
1561
+ if (!versionDeclared)
1562
+ return;
1563
+ for (const row of rows) {
1564
+ if (row.__edd_e__ === config.root.entityType &&
1565
+ row.sk === rootSortKey &&
1566
+ !hasOwnName(row, versionField)) {
1567
+ setOwn(row, versionField, 0);
1568
+ }
1569
+ }
1570
+ };
1571
+ const readPartition = (key, rejected, rekeyRead) => Effect.flatMap(readPartitionRaw(key, rejected, rekeyRead), (read) => {
1572
+ withReadVersion(read.allItems);
1573
+ // Packed edge attributes, read by their stored form (#147); offloaded ones resolved
1574
+ // eagerly, both kinds (#179, design §8.4).
1575
+ return Effect.as(loadAggregateItems(read.allItems, readPlans), read);
1576
+ });
1512
1577
  // A root row's partition key composites as a read takes them: decoded through their fields, as
1513
1578
  // assembly decodes the root row. `create` composes the key from the value it holds, so a key
1514
1579
  // composed again from a stored row (`list`, `rekey`) is composed from these, never from the
@@ -1591,12 +1656,12 @@ const makeAggregate = (schema, config) => {
1591
1656
  };
1592
1657
  /** The collection partition key `record`'s values compose under `under`. */
1593
1658
  const collectionPkUnder = (under, record) => composeCollectionKey(config.schema, config.collection.name, KeyComposer.extractKeyComposites(under, {}, config.pk.composite, keyRecord(record)));
1594
- /** {@link readPartition} without unpacking — `delete` needs only the keys. */
1659
+ /** {@link readPartition} without loading — `delete` needs only the keys. */
1595
1660
  const readPartitionRaw = (key, rejected, rekeyRead) => Effect.gen(function* () {
1596
1661
  const client = yield* Capacity.client;
1597
1662
  const tableConfig = yield* config.table.Tag;
1598
- const pkValue = yield* composeOrFail("key", () => collectionPkOf(key));
1599
- const read = (partition) => queryAllItems(client, tableConfig.name, config.collection.index, config.pk.field, partition, consistentRead, rejected, rekeyRead?.stored);
1663
+ const pkValue = rekeyRead?.partition ?? (yield* composeOrFail("key", () => collectionPkOf(key)));
1664
+ const read = (partition) => queryAllItems(client, tableConfig.name, config.collection.index, config.pk.field, partition, consistentRead || rekeyRead?.consistent === true, rejected, rekeyRead?.stored);
1600
1665
  const from = rekeyRead?.from;
1601
1666
  const allItems = from === undefined
1602
1667
  ? yield* read(pkValue)
@@ -2085,7 +2150,7 @@ const makeAggregate = (schema, config) => {
2085
2150
  operation: `${operation}.consistentRead`,
2086
2151
  cause: assemblyReadCause(operation, diagnosis, original),
2087
2152
  }), rekeyRead);
2088
- const derivedSchemas = deriveAggregateSchemas(schema, config.edges, config.pk.composite, config.timestamps);
2153
+ const derivedSchemas = deriveAggregateSchemas(schema, config.edges, config.pk.composite, config.timestamps, versionField === undefined ? [] : [versionField]);
2089
2154
  /** A stored row's position: its partition and sort key. */
2090
2155
  const positionOf = (pk, sk) => Rekey.identity(pk, sk);
2091
2156
  /**
@@ -2576,8 +2641,9 @@ const makeAggregate = (schema, config) => {
2576
2641
  return stale;
2577
2642
  };
2578
2643
  /**
2579
- * `[EDD-9160]` (#241): an update about to write a group one of whose values was read from a row
2580
- * stored under a sort key other than the one this configuration composes for that value, through
2644
+ * `[EDD-9160]` (#241): an update about to send or delete a row (#168: judged per row, not per
2645
+ * group) whose value was read from a row stored under a sort key other than the one this
2646
+ * configuration composes for that value, through
2581
2647
  * the function the write itself keys rows with ({@link sortKeyOf}). Each value's row is the one a
2582
2648
  * read took it from ({@link rowsReadAt}). Such a row was written under the other `escapeKeys`
2583
2649
  * setting (`$`, `#` or another escaped character, a number other than a non-negative integer
@@ -2589,8 +2655,6 @@ const makeAggregate = (schema, config) => {
2589
2655
  */
2590
2656
  const refuseOtherSettingRows = (oldGroups, written, readAt, moved) => {
2591
2657
  for (const group of oldGroups) {
2592
- if (!written(group.name))
2593
- continue;
2594
2658
  for (const item of group.items) {
2595
2659
  if (item.path === undefined)
2596
2660
  continue;
@@ -2599,6 +2663,8 @@ const makeAggregate = (schema, config) => {
2599
2663
  const sk = sortKeyOf(config.schema, item);
2600
2664
  if (typeof stored !== "string" || sk === undefined || stored === sk)
2601
2665
  continue;
2666
+ if (!written(group.name, sk))
2667
+ continue;
2602
2668
  if (moved.get(group.name)?.includes(stored) === true)
2603
2669
  continue;
2604
2670
  return Effect.fail(new ValidationError({
@@ -2616,8 +2682,28 @@ const makeAggregate = (schema, config) => {
2616
2682
  }
2617
2683
  return Effect.void;
2618
2684
  };
2619
- const updateCore = (key, mutationFn) => Effect.gen(function* () {
2620
- const { client, tableConfig, pkValue, allItems } = yield* fetchPartition(key, "update");
2685
+ const updateCore = (key, mutationFn, options) => Effect.gen(function* () {
2686
+ const expectedVersion = options?.expectedVersion;
2687
+ // `[EDD-9178]` (#168): an unversioned aggregate keeps no version to compare. Refused before
2688
+ // anything is read.
2689
+ if (expectedVersion !== undefined && versionField === undefined) {
2690
+ return yield* new ValidationError({
2691
+ entityType: aggregateName,
2692
+ operation: "aggregate.update",
2693
+ cause: new Error(`[EDD-9178] Aggregate "${aggregateName}": \`expectedVersion\` on an aggregate that ` +
2694
+ "isn't `versioned`, which keeps no version to compare it with. Turn on `versioned` " +
2695
+ "in `Aggregate.make`, or drop `expectedVersion`. Nothing was read or written."),
2696
+ });
2697
+ }
2698
+ // The rows as stored, kept beside the ones read: each row the write sends is guarded on its
2699
+ // stored form, never on a row unmarshalled and marshalled again (#168, §3.2). Read strongly
2700
+ // consistent where the collection allows (D11 reversed): a guard on an out-of-date read fails
2701
+ // on every attempt until the read catches up.
2702
+ const stored = [];
2703
+ const { client, tableConfig, pkValue, allItems } = yield* fetchPartition(key, "update", {
2704
+ stored,
2705
+ consistent: readConsistent,
2706
+ });
2621
2707
  if (allItems.length === 0) {
2622
2708
  return yield* new AggregateAssemblyError({
2623
2709
  aggregate: aggregateName,
@@ -2625,8 +2711,26 @@ const makeAggregate = (schema, config) => {
2625
2711
  key,
2626
2712
  });
2627
2713
  }
2714
+ const rawBySk = new Map();
2715
+ for (const row of stored) {
2716
+ const sk = row.sk?.S;
2717
+ if (sk !== undefined)
2718
+ rawBySk.set(sk, row);
2719
+ }
2720
+ const rawRoot = rawBySk.get(rootSortKey);
2628
2721
  // 1. Assemble current state
2629
2722
  const current = yield* assembleAggregate(assembly, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
2723
+ // A versioned root's version and incarnation token as read (#168, §3.5): 0 and none on a root
2724
+ // written before `versioned` was turned on.
2725
+ const versionRead = versionField === undefined ? undefined : storedRootVersion(rawRoot, versionField);
2726
+ if (expectedVersion !== undefined && versionRead.version !== expectedVersion) {
2727
+ return yield* new OptimisticLockError({
2728
+ entityType: aggregateName,
2729
+ key,
2730
+ expectedVersion,
2731
+ actualVersion: versionRead.version,
2732
+ });
2733
+ }
2630
2734
  const now = yield* DateTime.now;
2631
2735
  // 2. Apply mutation — provide optics context for composable updates
2632
2736
  const state = toPlainState(current);
@@ -2635,7 +2739,11 @@ const makeAggregate = (schema, config) => {
2635
2739
  cursor: makeCursor(state, opticRoot),
2636
2740
  optic: opticRoot,
2637
2741
  current: current,
2742
+ ...(versionRead !== undefined && { version: versionRead.version }),
2638
2743
  });
2744
+ // An offloaded edge field takes its value, never a stream, handle, source or lazy value
2745
+ // (`[EDD-9120]`, #179).
2746
+ yield* refuseEdgeInputs(updated, rootNode, aggregateName, "aggregate.update");
2639
2747
  // 3. Validate the mutated state — its tolerant transforms take the domain
2640
2748
  // values the mutation yields as what they are, for every field (root +
2641
2749
  // nested edges), so update no longer trips the "Expected string, got
@@ -2643,7 +2751,12 @@ const makeAggregate = (schema, config) => {
2643
2751
  // update path), and a transformation with one type on both sides isn't
2644
2752
  // applied again to a value it already made.
2645
2753
  // A row the mutation added doesn't need the dates the library stamps.
2646
- const written = fillStamps(rootNode, updated, now, "required");
2754
+ // A version the root declares is the library's: the one read, whatever the mutation set.
2755
+ const filled = fillStamps(rootNode, updated, now, "required");
2756
+ const written = versionDeclared &&
2757
+ ownValue(filled, versionField) !== versionRead.version
2758
+ ? { ...filled, [versionField]: versionRead.version }
2759
+ : filled;
2647
2760
  const decoded = yield* Schema.decodeUnknownEffect(mutatedStateSchema)(written).pipe(Effect.mapError((cause) => new ValidationError({
2648
2761
  entityType: aggregateName,
2649
2762
  operation: "aggregate.update",
@@ -2780,8 +2893,6 @@ const makeAggregate = (schema, config) => {
2780
2893
  yield* refuseNotReadBack(newDynamo, key, "aggregate.update", storedAsGivenIn(newGroups));
2781
2894
  // The row each value of the state was read from (#241).
2782
2895
  const readAt = rowsReadAt(rootNode, allItems, systemAttrs);
2783
- yield* refuseOtherSettingRows(oldGroups, groupChanged, readAt, previousRows);
2784
- const newItemsByGroup = new Map(newDynamo.map((g) => [g.group, g.items]));
2785
2896
  const oldItemsByGroup = new Map(oldDynamo.map((g) => [g.group, g.items]));
2786
2897
  // Every sk that survives anywhere in the new decomposition — an old item is
2787
2898
  // an orphan to DELETE only if its key appears in no new group at all.
@@ -2790,87 +2901,365 @@ const makeAggregate = (schema, config) => {
2790
2901
  for (const item of g.items)
2791
2902
  survivingSks.add(skOf(item));
2792
2903
  }
2793
- // 7. Per group (union of old + new names), collect PUTs + orphan DELETEs.
2794
- const groupWrites = [];
2795
- const groupNames = new Set([...newGroupMap.keys(), ...oldGroupMap.keys()]);
2904
+ // 7. The rows the write sends (#168, D2, design §3.3). A changed group sends the rows whose
2905
+ // decomposed value changed, the rows the new value adds and its `Delete`s; an unchanged row
2906
+ // isn't sent and keeps its `updated`. Every row of a group is sent when a context field
2907
+ // changed or the group's copies of one are stale (#241). Rows are matched old to new by the
2908
+ // sort key they compose, not by group: an item can change group without changing key.
2909
+ const oldBySk = new Map();
2910
+ oldGroups.forEach((group, g) => {
2911
+ group.items.forEach((item, i) => {
2912
+ const sk = skOf(oldDynamo[g].items[i]);
2913
+ oldBySk.set(sk, [...(oldBySk.get(sk) ?? []), item]);
2914
+ });
2915
+ });
2916
+ // Rows read under the sort key text 1.40.0 composed, which a changed group moves (#241).
2917
+ const movedFrom = new Set([...previousRows.values()].flat());
2918
+ /** The row a value was read from: by its place in the value, else at its key. */
2919
+ const readFrom = (item, sk) => (item.path === undefined ? undefined : readAt.get(JSON.stringify(item.path))) ??
2920
+ readRows.get(sk);
2921
+ /** Whether a new item is its row as read: one old item composes its key, alike, and was read. */
2922
+ const unchanged = (item, sk) => {
2923
+ const olds = oldBySk.get(sk);
2924
+ if (olds === undefined || olds.length !== 1)
2925
+ return false;
2926
+ const old = olds[0];
2927
+ if (old.entityType !== item.entityType || !deepEqual(old.attributes, item.attributes)) {
2928
+ return false;
2929
+ }
2930
+ const row = readFrom(old, sk);
2931
+ return row !== undefined && !(typeof row.sk === "string" && movedFrom.has(row.sk));
2932
+ };
2933
+ // Every group's name, in order: the root's first, then the new value's, then the old one's.
2934
+ const rootGroup = rootRead?.transactionGroup;
2935
+ const groupNames = [
2936
+ ...new Set([
2937
+ ...(rootGroup === undefined ? [] : [rootGroup]),
2938
+ ...newGroupMap.keys(),
2939
+ ...oldGroupMap.keys(),
2940
+ ]),
2941
+ ];
2942
+ const sentRows = [];
2943
+ const deletedRows = [];
2944
+ const changedGroups = new Set();
2945
+ // Each item's member path (D15): a `many` element by its sort key values.
2946
+ const elementKeys = new Map();
2947
+ for (const item of [...oldGroups, ...newGroups].flatMap((group) => group.items)) {
2948
+ const last = item.path?.at(-1);
2949
+ if (typeof last === "number" && item.elementKey !== undefined) {
2950
+ elementKeys.set(JSON.stringify(item.path), item.elementKey);
2951
+ }
2952
+ }
2953
+ const nameOf = (item, sk) => item === undefined ? sk : memberPath(item, elementKeys);
2796
2954
  for (const name of groupNames) {
2797
2955
  if (!groupChanged(name))
2798
2956
  continue;
2799
- const puts = newItemsByGroup.get(name) ?? [];
2957
+ changedGroups.add(name);
2958
+ const whole = contextChanged || stale.has(name);
2959
+ const g = newGroups.findIndex((group) => group.name === name);
2960
+ if (g >= 0) {
2961
+ newGroups[g].items.forEach((item, i) => {
2962
+ const sk = skOf(newDynamo[g].items[i]);
2963
+ if (!whole && unchanged(item, sk))
2964
+ return;
2965
+ sentRows.push({ group: name, g, i, item, sk });
2966
+ });
2967
+ }
2800
2968
  // Each row once: two old items can compose one key (rows stored under two keys, #241).
2801
2969
  const deleteSks = new Set((oldItemsByGroup.get(name) ?? [])
2802
2970
  .map((item) => skOf(item))
2803
2971
  .filter((sk) => !survivingSks.has(sk)));
2804
2972
  // A row read under the text 1.40.0 composed goes in the same transaction (#241).
2805
- const previous = (previousRows.get(name) ?? []).filter((sk) => !survivingSks.has(sk));
2806
- for (const sk of previous)
2807
- deleteSks.add(sk);
2808
- const deletes = [...deleteSks].map((sk) => ({
2809
- [config.pk.field]: { S: pkValue },
2810
- sk: { S: sk },
2811
- }));
2812
- if (puts.length === 0 && deletes.length === 0)
2973
+ for (const sk of previousRows.get(name) ?? []) {
2974
+ if (!survivingSks.has(sk))
2975
+ deleteSks.add(sk);
2976
+ }
2977
+ // Only a row read: a key nothing was read at holds nothing to delete.
2978
+ for (const sk of deleteSks) {
2979
+ if (rawBySk.has(sk)) {
2980
+ deletedRows.push({ group: name, sk, name: nameOf(oldBySk.get(sk)?.[0], sk) });
2981
+ }
2982
+ }
2983
+ }
2984
+ const sentSks = new Set(sentRows.map((row) => row.sk));
2985
+ // `EDD-9160`, judged on the rows the write sends (§3.3): an unchanged row under the other
2986
+ // setting's text in a changed group isn't sent, and stays for `rekey`.
2987
+ yield* refuseOtherSettingRows(oldGroups, (group, sk) => changedGroups.has(group) && (sentSks.has(sk) || !survivingSks.has(sk)), readAt, previousRows);
2988
+ // With `ownsRows`, every row of its types in the partition is the aggregate's (DESIGN.md §7
2989
+ // "Which rows in its partition are an aggregate's"): the rows read of each node whose
2990
+ // decomposition changed that the new value doesn't write are deleted too (`ownedRowsLeft`),
2991
+ // in the update's own transactions, each while it's gone or still as read (D10).
2992
+ const touched = new Set([
2993
+ ...sentRows.map(({ group }) => group),
2994
+ ...deletedRows.map(({ group }) => group),
2995
+ ]);
2996
+ const cleanup = ownsRows
2997
+ ? ownedRowsLeft(allItems, pkValue, oldGroups, newGroups, touched, survivingSks, deletedRows.map(({ sk }) => sk))
2998
+ : [];
2999
+ const anything = sentRows.length > 0 || deletedRows.length > 0 || cleanup.length > 0;
3000
+ // A versioned root moves by one on every write that sends anything (§3.5), under its token,
3001
+ // or a fresh one on a root written before `versioned` was turned on.
3002
+ const token = versionRead === undefined || !anything
3003
+ ? undefined
3004
+ : (versionRead.token ?? (yield* freshIncarnationToken));
3005
+ const nextVersion = versionRead === undefined ? undefined : versionRead.version + 1;
3006
+ const rootSent = sentRows.some((row) => row.sk === rootSortKey && row.item.node === rootNode);
3007
+ /** A row as built, a versioned root's carrying its next version and token. */
3008
+ const builtOf = (row) => {
3009
+ const built = newDynamo[row.g].items[row.i];
3010
+ if (versionField === undefined || row.sk !== rootSortKey || row.item.node !== rootNode) {
3011
+ return built;
3012
+ }
3013
+ return {
3014
+ ...built,
3015
+ [versionField]: { N: String(nextVersion) },
3016
+ [INCARNATION_TOKEN]: { S: token },
3017
+ };
3018
+ };
3019
+ // Route and upload the offloaded attributes of the rows the write sends, every one afresh
3020
+ // (#179, design §6.9), before the first transaction: decided on the decomposed values above,
3021
+ // so an unchanged row uploads nothing, and no pointer read from the partition is written
3022
+ // back (each sent row's values were read eagerly, and are uploaded again).
3023
+ const sentByGroup = new Map();
3024
+ for (const row of sentRows) {
3025
+ sentByGroup.set(row.group, [...(sentByGroup.get(row.group) ?? []), row]);
3026
+ }
3027
+ const routed = yield* routeBuiltGroups([...sentByGroup].map(([group, rows]) => ({
3028
+ group,
3029
+ items: rows.map(builtOf),
3030
+ written: rows.map((row) => newDynamo[row.g].written[row.i]),
3031
+ rows,
3032
+ })), offloadInfoByType, {
3033
+ table: tableConfig.name,
3034
+ pkAttribute: config.pk.field,
3035
+ operation: "Aggregate.update",
3036
+ escapeKeys: config.schema.escapeKeys === true,
3037
+ });
3038
+ // 8. The write's units (§3.1): the root's group first, then each changed group, then each
3039
+ // cleanup `Delete`, every item guarded (§3.2) and asking for the row as stored when its
3040
+ // condition fails.
3041
+ const tableName = tableConfig.name;
3042
+ const pkField = config.pk.field;
3043
+ const updatedPrefer = stampFields?.updatedAt ? [stampFields.updatedAt] : [];
3044
+ const preferFor = (entityType) => versionField !== undefined && entityType === config.root.entityType
3045
+ ? [versionField, INCARNATION_TOKEN, ...updatedPrefer]
3046
+ : updatedPrefer;
3047
+ const absentFor = (entityType) => writableAttributes.get(entityType) ?? [];
3048
+ const keyAt = (sk) => toAttributeMap({ [pkField]: pkValue, sk });
3049
+ const typeOf = (read) => read.__edd_e__?.S ?? aggregateName;
3050
+ const putOf = (row, item) => {
3051
+ const read = rawBySk.get(row.sk);
3052
+ const isRoot = row.sk === rootSortKey && row.item.node === rootNode;
3053
+ const name = nameOf(row.item, row.sk);
3054
+ const expects = isRoot ? versionRead : undefined;
3055
+ if (read === undefined) {
3056
+ return {
3057
+ action: {
3058
+ Put: AggregateWrite.withAllOld({
3059
+ TableName: tableName,
3060
+ Item: item,
3061
+ ...AggregateWrite.absentGuard(pkField),
3062
+ }),
3063
+ },
3064
+ role: isRoot ? "root" : "new",
3065
+ name,
3066
+ expects,
3067
+ };
3068
+ }
3069
+ const entityType = typeOf(read);
3070
+ const put = (bySize) => ({
3071
+ Put: AggregateWrite.withAllOld({
3072
+ TableName: tableName,
3073
+ Item: item,
3074
+ ...AggregateWrite.rowGuard(read, pkField, preferFor(entityType), absentFor(entityType), bySize),
3075
+ }),
3076
+ });
3077
+ return { action: put(), role: isRoot ? "root" : "row", name, read, sized: put, expects };
3078
+ };
3079
+ const deleteOf = (row) => {
3080
+ const read = rawBySk.get(row.sk);
3081
+ const entityType = typeOf(read);
3082
+ const remove = (bySize) => ({
3083
+ Delete: AggregateWrite.withAllOld({
3084
+ TableName: tableName,
3085
+ Key: keyAt(row.sk),
3086
+ ...AggregateWrite.rowGuard(read, pkField, preferFor(entityType), absentFor(entityType), bySize),
3087
+ }),
3088
+ });
3089
+ return { action: remove(), role: "row", name: row.name, read, sized: remove };
3090
+ };
3091
+ const units = [];
3092
+ const routedByGroup = new Map(routed.map((group) => [group.group, group]));
3093
+ for (const name of groupNames) {
3094
+ const sent = routedByGroup.get(name);
3095
+ const items = [
3096
+ ...(sent === undefined ? [] : sent.rows.map((row, k) => putOf(row, sent.items[k]))),
3097
+ ...deletedRows.filter((row) => row.group === name).map(deleteOf),
3098
+ ];
3099
+ if (items.length === 0)
2813
3100
  continue;
2814
- groupWrites.push({
3101
+ // The root first in its unit: what a request holding it is fenced by.
3102
+ items.sort((a, b) => Number(b.role === "root") - Number(a.role === "root"));
3103
+ const previous = (previousRows.get(name) ?? []).filter((sk) => !survivingSks.has(sk));
3104
+ units.push({
2815
3105
  group: name,
2816
- puts,
2817
- deletes,
3106
+ items,
2818
3107
  ...(previous.length > 0 && { previous: previous.length }),
2819
3108
  });
2820
3109
  }
2821
- // With `ownsRows`, every row of its types in the partition is the aggregate's (DESIGN.md §7
2822
- // "Which rows in its partition are an aggregate's"). After the update's groups, the rows read
2823
- // of each node whose decomposition changed that the new value doesn't write are deleted too
2824
- // (`ownedRowsLeft`): a node's rows are what its decomposition writes.
2825
- const cleanup = ownsRows
2826
- ? ownedRowsLeft(allItems, pkValue, oldGroups, newGroups, new Set(groupWrites.map(({ group }) => group)), survivingSks, groupWrites.flatMap(({ deletes }) => deletes.map((item) => skOf(item))))
2827
- : [];
2828
- if (groupWrites.length > 0) {
2829
- yield* writeTransactionGroups(client, tableConfig.name, groupWrites, aggregateName, groupKeys);
3110
+ // A versioned root not rewritten moves its version with an `Update` of the root, first (§3.4).
3111
+ if (versionField !== undefined && anything && !rootSent) {
3112
+ const condition = [
3113
+ "attribute_exists(#pk)",
3114
+ versionRead.version === 0 ? "(attribute_not_exists(#ver) OR #ver = :v)" : "#ver = :v",
3115
+ versionRead.token === undefined ? "attribute_not_exists(#inc)" : "#inc = :inc",
3116
+ ].join(" AND ");
3117
+ const versionUpdate = {
3118
+ action: {
3119
+ Update: AggregateWrite.withAllOld({
3120
+ TableName: tableName,
3121
+ Key: keyAt(rootSortKey),
3122
+ UpdateExpression: "SET #ver = :v1, #inc = :inc",
3123
+ ConditionExpression: condition,
3124
+ ExpressionAttributeNames: {
3125
+ "#pk": pkField,
3126
+ "#ver": versionField,
3127
+ "#inc": INCARNATION_TOKEN,
3128
+ },
3129
+ ExpressionAttributeValues: {
3130
+ ":v": { N: String(versionRead.version) },
3131
+ ":v1": { N: String(nextVersion) },
3132
+ ":inc": { S: token },
3133
+ },
3134
+ }),
3135
+ },
3136
+ role: "root",
3137
+ name: "",
3138
+ read: rawRoot,
3139
+ expects: versionRead,
3140
+ };
3141
+ const first = units.findIndex((unit) => unit.group === rootGroup);
3142
+ if (first >= 0) {
3143
+ const unit = units[first];
3144
+ units.splice(first, 1);
3145
+ units.unshift({ ...unit, items: [versionUpdate, ...unit.items] });
3146
+ }
3147
+ else {
3148
+ units.unshift({ group: rootGroup ?? aggregateName, items: [versionUpdate] });
3149
+ }
2830
3150
  }
2831
- if (cleanup.length > 0) {
2832
- yield* deleteOwnedRows(client, tableConfig.name, config.pk.field, cleanup);
3151
+ for (const row of cleanup) {
3152
+ const read = rawBySk.get(row.sk);
3153
+ if (read === undefined)
3154
+ continue;
3155
+ const remove = (bySize) => ({
3156
+ Delete: AggregateWrite.withAllOld({
3157
+ TableName: tableName,
3158
+ Key: keyAt(row.sk),
3159
+ ...AggregateWrite.goneOrAsReadGuard(read, pkField, preferFor(row.entityType), absentFor(row.entityType), row.entityType, bySize),
3160
+ }),
3161
+ });
3162
+ units.push({
3163
+ group: row.sk,
3164
+ items: [{ action: remove(), role: "cleanup", name: row.sk, read, sized: remove }],
3165
+ });
2833
3166
  }
2834
- if (!returnsStamps) {
3167
+ // The fence (§3.4) on each request without the root: the root's next version and token on a
3168
+ // versioned aggregate, its existence with `fence: true`, nothing otherwise.
3169
+ const fence = versionField !== undefined && anything
3170
+ ? {
3171
+ action: {
3172
+ ConditionCheck: AggregateWrite.withAllOld({
3173
+ TableName: tableName,
3174
+ Key: keyAt(rootSortKey),
3175
+ ConditionExpression: "#ver = :v1 AND #inc = :inc",
3176
+ ExpressionAttributeNames: { "#ver": versionField, "#inc": INCARNATION_TOKEN },
3177
+ ExpressionAttributeValues: {
3178
+ ":v1": { N: String(nextVersion) },
3179
+ ":inc": { S: token },
3180
+ },
3181
+ }),
3182
+ },
3183
+ role: "fence",
3184
+ name: "",
3185
+ expects: { version: nextVersion, token, reported: versionRead.version },
3186
+ }
3187
+ : fenced
3188
+ ? {
3189
+ action: {
3190
+ ConditionCheck: AggregateWrite.withAllOld({
3191
+ TableName: tableName,
3192
+ Key: keyAt(rootSortKey),
3193
+ ConditionExpression: "attribute_exists(#pk)",
3194
+ ExpressionAttributeNames: { "#pk": pkField },
3195
+ }),
3196
+ },
3197
+ role: "fence",
3198
+ name: "",
3199
+ }
3200
+ : undefined;
3201
+ if (anything) {
3202
+ yield* AggregateWrite.sendUnits(client, units, {
3203
+ tableName,
3204
+ aggregateName,
3205
+ keys: groupKeys,
3206
+ operation: "update",
3207
+ fence,
3208
+ verdict: AggregateWrite.updateVerdict({
3209
+ aggregateName,
3210
+ key,
3211
+ pkField,
3212
+ versioned: versionField === undefined
3213
+ ? undefined
3214
+ : { field: versionField, read: versionRead.version },
3215
+ }),
3216
+ });
3217
+ }
3218
+ if (!returnsStamps && !(versionDeclared && anything)) {
2835
3219
  // 1.40.0's result, the mutated state as decoded, with one change (#241): a member value's
2836
3220
  // copy of a context attribute is what its row now holds: the root's, on a row the write
2837
- // sent; what it held when read, on one it didn't.
3221
+ // sent; what it held when read, on one it didn't (judged per row, #168).
3222
+ const sentPaths = new Set(sentRows.flatMap(({ item }) => item.path === undefined ? [] : [JSON.stringify(item.path)]));
2838
3223
  const rowsNow = new Map();
2839
3224
  for (const group of newGroups) {
2840
- const sent = groupChanged(group.name);
2841
3225
  for (const item of group.items) {
2842
3226
  if (item.path === undefined)
2843
3227
  continue;
3228
+ const path = JSON.stringify(item.path);
2844
3229
  let now;
2845
- if (sent)
3230
+ if (sentPaths.has(path))
2846
3231
  now = { written: true };
2847
3232
  else {
2848
- // A group the write didn't send holds the values it was read as, each on its row.
2849
- const row = readAt.get(JSON.stringify(item.path));
3233
+ // A row the write didn't send holds the value it was read as.
3234
+ const row = readAt.get(path);
2850
3235
  if (row !== undefined)
2851
3236
  now = { row };
2852
3237
  }
2853
3238
  if (now !== undefined)
2854
- rowsNow.set(JSON.stringify(item.path), now);
3239
+ rowsNow.set(path, now);
2855
3240
  }
2856
3241
  }
2857
3242
  return withStoredContextCopies(decoded, (path) => rowsNow.get(JSON.stringify(path)));
2858
3243
  }
2859
- // A stamp the domain object holds: what's returned is what's stored, as `get` would read it,
2860
- // and no read is needed to know that. The partition as read, with these writes applied, as
2861
- // 1.40.0 assembled it.
2862
- const stored = new Map(allItems.map((item) => [String(item.sk), item]));
3244
+ // A stamp or a version the domain object holds: what's returned is what's stored, as `get`
3245
+ // would read it, and no read is needed to know that. The partition as read, with these writes
3246
+ // applied, as 1.40.0 assembled it.
3247
+ const storedNow = new Map(allItems.map((item) => [String(item.sk), item]));
2863
3248
  for (const { sk } of cleanup)
2864
- stored.delete(sk);
2865
- for (const { deletes, puts } of groupWrites) {
2866
- for (const item of deletes)
2867
- stored.delete(String(item.sk.S));
2868
- const written = puts.map((item) => fromAttributeMap(item));
2869
- yield* unpackAggregateItems(written, dispatchByType, aggregateName);
2870
- for (const item of written)
2871
- stored.set(String(item.sk), item);
2872
- }
2873
- return (yield* assembleAggregate(assembly, rootNode, [...stored.values()], contextFields, key, aggregateName, systemAttrs));
3249
+ storedNow.delete(sk);
3250
+ for (const { sk } of deletedRows)
3251
+ storedNow.delete(sk);
3252
+ // The rows as built, not as sent: an offloaded value is inline there (#179).
3253
+ const writtenRows = sentRows.map((row) => fromAttributeMap(builtOf(row)));
3254
+ yield* unpackAggregateItems(writtenRows, dispatchByType, aggregateName);
3255
+ for (const row of writtenRows)
3256
+ storedNow.set(String(row.sk), row);
3257
+ if (versionDeclared && anything && !rootSent) {
3258
+ const root = storedNow.get(rootSortKey);
3259
+ if (root !== undefined)
3260
+ storedNow.set(rootSortKey, { ...root, [versionField]: nextVersion });
3261
+ }
3262
+ return (yield* assembleAggregate(assembly, rootNode, [...storedNow.values()], contextFields, key, aggregateName, systemAttrs));
2874
3263
  });
2875
3264
  /** How many times `rekey` reads an aggregate again after a write changed it in between. */
2876
3265
  const REKEY_ATTEMPTS = 3;
@@ -2907,6 +3296,12 @@ const makeAggregate = (schema, config) => {
2907
3296
  walk(child);
2908
3297
  };
2909
3298
  walk(rootNode);
3299
+ // A versioned root's version and incarnation token (#168): a guard checks each is as read.
3300
+ if (versionField !== undefined) {
3301
+ const root = byType.get(rootNode.entityType);
3302
+ root.add(versionField);
3303
+ root.add(INCARNATION_TOKEN);
3304
+ }
2910
3305
  return new Map([...byType].map(([entityType, names]) => [entityType, [...names].sort()]));
2911
3306
  })();
2912
3307
  /**
@@ -3183,6 +3578,21 @@ const makeAggregate = (schema, config) => {
3183
3578
  positionOf(item[config.pk.field]?.S ?? "", item.sk?.S ?? ""),
3184
3579
  item,
3185
3580
  ]));
3581
+ // Rekey's backstop (#179, design §11.10): a row holding a blob pointer never moves, nor is
3582
+ // it deleted as a copy of a row at its current key. Its objects are named from its key
3583
+ // text, so moved it would name objects no write of its new key made. Offloading requires
3584
+ // `escapeKeys: true`, under which such a row is only ever written at its final key text:
3585
+ // judged on the row as read, dry run or not, before anything is written. Any well-formed
3586
+ // pointer, at any depth, whatever the edge entities now declare.
3587
+ for (const [r, row] of rows.entries()) {
3588
+ if (row.placement !== "old" && !copies.has(r))
3589
+ continue;
3590
+ const read = storedAt.get(positionOf(row.old.pk, row.old.sk));
3591
+ const attribute = BlobLedger.pointerAttributeOf(read);
3592
+ if (attribute !== undefined) {
3593
+ return yield* Rekey.refusePointerRow(`Aggregate "${aggregateName}"`, { [config.pk.field]: row.old.pk, sk: row.old.sk }, attribute);
3594
+ }
3595
+ }
3186
3596
  // An aggregate is left as it is, reported, only while nothing of it has moved. One already
3187
3597
  // part-moved, in this run or a run cut short, is finished under the strongest guard that
3188
3598
  // fits, as 1.39.0 finished it: left across two keys, a read under either misses rows.
@@ -3226,9 +3636,27 @@ const makeAggregate = (schema, config) => {
3226
3636
  : undefined;
3227
3637
  const itemOf = (r) => {
3228
3638
  const row = rows[r];
3229
- if (!row.custom)
3230
- return built[r];
3231
3639
  const at = row.placement === "old" ? row.old : row.current;
3640
+ if (!row.custom) {
3641
+ const item = built[r];
3642
+ if (versionField === undefined ||
3643
+ item.sk?.S !== rootSortKey ||
3644
+ item.__edd_e__?.S !== config.root.entityType) {
3645
+ return item;
3646
+ }
3647
+ // A versioned root moves with its version and incarnation token as read (#168): built
3648
+ // from the model, it holds the version only where the model declares it, and the
3649
+ // token never, so a moved root would read as version 0 and a new incarnation.
3650
+ const read = storedAt.get(positionOf(at.pk, at.sk)) ?? {};
3651
+ const held = [versionField, INCARNATION_TOKEN];
3652
+ const moved = Object.fromEntries(Object.entries(item).filter(([name]) => !held.includes(name)));
3653
+ for (const name of held) {
3654
+ const value = read[name];
3655
+ if (value !== undefined)
3656
+ moved[name] = value;
3657
+ }
3658
+ return moved;
3659
+ }
3232
3660
  return {
3233
3661
  ...storedAt.get(positionOf(at.pk, at.sk)),
3234
3662
  [config.pk.field]: { S: row.current.pk },
@@ -3666,7 +4094,8 @@ const makeAggregate = (schema, config) => {
3666
4094
  const items = rows
3667
4095
  .filter((item) => item[config.pk.field]?.S === pk)
3668
4096
  .map((item) => fromAttributeMap(item));
3669
- yield* unpackAggregateItems(items, dispatchByType, aggregateName);
4097
+ withReadVersion(items);
4098
+ yield* loadAggregateItems(items, readPlans);
3670
4099
  const assembled = yield* assembleAggregate(assembly, rootNode, items, contextFields, key, aggregateName, systemAttrs);
3671
4100
  const groups = yield* decomposeAggregate({ ...assembled }, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
3672
4101
  const composed = yield* composeOrFail("rekey", () => buildDynamoItems(groups, config, current, undefined, keyRecord));
@@ -3688,7 +4117,32 @@ const makeAggregate = (schema, config) => {
3688
4117
  holder: rekeyHolder,
3689
4118
  finish: rekeyFinish,
3690
4119
  };
3691
- return Rekey.carry(rekeyHandler, withOperations(aggregateName, {
4120
+ /**
4121
+ * What `BlobGc` reads of the aggregate (#179, design §11): its edge items
4122
+ * live in one base-table partition, keyed `pk.field` / `sk` (the collection
4123
+ * index, when there is one, is a local index of that partition). The
4124
+ * partition is the current key's: a row under a 1.36 key never holds a
4125
+ * pointer (design §11.10).
4126
+ */
4127
+ const gcSupport = {
4128
+ kind: "aggregate",
4129
+ name: aggregateName,
4130
+ tableTag: () => config.table.Tag,
4131
+ pkField: config.pk.field,
4132
+ skField: "sk",
4133
+ edges: offloadInfoByType,
4134
+ ownsPartition: (pk) => config.pk.composite.length === 0 ? pk === partitionHead : pk.startsWith(`${partitionHead}#`),
4135
+ partitionOfKey: (key, operation) => Effect.try({
4136
+ try: () => {
4137
+ if (typeof key !== "object" || key === null) {
4138
+ throw new Error(`An aggregate key must be an object, got ${typeof key}`);
4139
+ }
4140
+ return composeCollectionKey(config.schema, config.collection.name, KeyComposer.extractComposites(config.pk.composite, keyRecord(key)));
4141
+ },
4142
+ catch: (cause) => new ValidationError({ entityType: aggregateName, operation, cause }),
4143
+ }),
4144
+ };
4145
+ const aggregate = Rekey.carry(rekeyHandler, withOperations(aggregateName, {
3692
4146
  [TypeId]: TypeId,
3693
4147
  _tag: "Aggregate",
3694
4148
  _tableTag: config.table.Tag,
@@ -3696,6 +4150,9 @@ const makeAggregate = (schema, config) => {
3696
4150
  _ownsRows: ownsRows,
3697
4151
  _attributeWriters: attributeWriters,
3698
4152
  _ownership: ownership,
4153
+ _offloadByType: offloadByType,
4154
+ _name: aggregateName,
4155
+ _keySchema: config.schema,
3699
4156
  schema,
3700
4157
  pkField: config.pk.field,
3701
4158
  collection: {
@@ -3731,14 +4188,20 @@ const makeAggregate = (schema, config) => {
3731
4188
  // 1. Hydrate refs from edges
3732
4189
  const hydrated = yield* hydrateAggregateRefs(
3733
4190
  // What `create`'s type takes (`CreateArgument`) is judged here, at run time.
3734
- input, config.edges, schemaFields, aggregateName);
4191
+ input, config.edges, schemaFields, rootNode, aggregateName);
4192
+ // An offloaded edge field takes its value, never a stream, handle, source or lazy value
4193
+ // (`[EDD-9120]`, #179).
4194
+ yield* refuseEdgeInputs(hydrated, rootNode, aggregateName, "aggregate.create");
3735
4195
  // 2. Validate via schema decode (decodeSchema substitutes nested edge
3736
4196
  // self-date/Redacted leaves — Option A — and is identical to `schema`
3737
4197
  // when no edge needs it). A date the library stamps is stamped now,
3738
4198
  // over what the input holds for it unless the root declares it
3739
4199
  // optional, so what's composed and returned is what's stored.
3740
4200
  const now = yield* DateTime.now;
3741
- const written = fillStamps(rootNode, hydrated, now, "declared");
4201
+ const stamped = fillStamps(rootNode, hydrated, now, "declared");
4202
+ // A versioned root starts at 1 (#168, §3.5): a version the root declares is the
4203
+ // library's, whatever the input holds.
4204
+ const written = versionDeclared ? { ...stamped, [versionField]: 1 } : stamped;
3742
4205
  const decoded = yield* Schema.decodeUnknownEffect(writeSchema)(written).pipe(Effect.mapError((cause) => new ValidationError({
3743
4206
  entityType: aggregateName,
3744
4207
  operation: "aggregate.create",
@@ -3761,38 +4224,73 @@ const makeAggregate = (schema, config) => {
3761
4224
  yield* refuseOtherKindKeys(groups, "aggregate.create");
3762
4225
  yield* refuseGivenOverRows(packedGroups, dynamoGroups);
3763
4226
  yield* refuseNotReadBack(dynamoGroups, assembled, "aggregate.create", storedAsGivenIn(groups));
3764
- // 6. Write via sub-aggregate transactions. The root item goes first in
3765
- // the first transaction, guarded by `attribute_not_exists` (#134):
3766
- // an existing aggregate cancels it before any edge or sub-aggregate
3767
- // row is written. Rows below the root need no guard of their own —
3768
- // they are only ever written after the root's transaction commits.
3769
- const rootSk = composeKey(config.schema, config.root.entityType, []);
3770
- const isRoot = (item) => item.sk?.S === rootSk;
3771
- const ordered = [...dynamoGroups]
4227
+ // 5b. Route and upload the edge entities' offloaded attributes on the built items — their
4228
+ // keys composed, their values judged — before the first transaction (#179, §6.9).
4229
+ const sentGroups = yield* routeBuiltGroups(dynamoGroups, offloadInfoByType, {
4230
+ table: tableConfig.name,
4231
+ pkAttribute: config.pk.field,
4232
+ operation: "Aggregate.create",
4233
+ escapeKeys: config.schema.escapeKeys === true,
4234
+ });
4235
+ // 6. Write: every group in one transaction when they fit (#168, §3.7), else whole groups
4236
+ // in as few as fit, the root's first. The root item is guarded by
4237
+ // `attribute_not_exists` (#134): an existing aggregate cancels it before any edge or
4238
+ // sub-aggregate row is written. Rows below the root need no guard of their own: past one
4239
+ // transaction they are only ever written after the root's has committed. A versioned
4240
+ // root holds version 1 and a fresh incarnation token.
4241
+ const token = versionField === undefined ? undefined : yield* freshIncarnationToken;
4242
+ const isRoot = (item) => item.sk?.S === rootSortKey;
4243
+ const rootKey = { [config.pk.field]: pkValue, sk: rootSortKey };
4244
+ const units = [...sentGroups]
3772
4245
  .sort((a, b) => Number(b.items.some(isRoot)) - Number(a.items.some(isRoot)))
3773
- .map((g) => ({
3774
- group: g.group,
3775
- puts: [...g.items].sort((a, b) => Number(isRoot(b)) - Number(isRoot(a))),
3776
- deletes: [],
4246
+ .map((group) => ({
4247
+ group: group.group,
4248
+ items: [...group.items]
4249
+ .sort((a, b) => Number(isRoot(b)) - Number(isRoot(a)))
4250
+ .map((item) => isRoot(item)
4251
+ ? {
4252
+ action: {
4253
+ Put: {
4254
+ TableName: tableConfig.name,
4255
+ Item: versionField === undefined
4256
+ ? item
4257
+ : {
4258
+ ...item,
4259
+ [versionField]: { N: "1" },
4260
+ [INCARNATION_TOKEN]: { S: token },
4261
+ },
4262
+ ...AggregateWrite.absentGuard(config.pk.field),
4263
+ },
4264
+ },
4265
+ role: "root",
4266
+ name: "",
4267
+ }
4268
+ : {
4269
+ action: { Put: { TableName: tableConfig.name, Item: item } },
4270
+ role: "new",
4271
+ name: item.sk?.S ?? "",
4272
+ }),
3777
4273
  }));
3778
- yield* writeTransactionGroups(client, tableConfig.name, ordered, aggregateName, groupKeys, {
3779
- pkField: config.pk.field,
3780
- entityType: config.root.entityType,
3781
- key: { [config.pk.field]: pkValue, sk: rootSk },
4274
+ yield* AggregateWrite.sendUnits(client, units, {
4275
+ tableName: tableConfig.name,
4276
+ aggregateName,
4277
+ keys: groupKeys,
4278
+ operation: "create",
4279
+ verdict: (reasons, items) => reasons.some((reason, i) => reason?.Code === "ConditionalCheckFailed" && items[i]?.role === "root")
4280
+ ? new ConditionalCheckFailed({ entityType: config.root.entityType, key: rootKey })
4281
+ : undefined,
3782
4282
  });
3783
4283
  return decoded;
3784
4284
  }),
3785
- update: (key, mutationFn) => updateCore(key, mutationFn),
4285
+ update: (key, mutationFn, options) => updateCore(key, mutationFn, options),
3786
4286
  delete: (key) => Effect.gen(function* () {
3787
- const { client, tableConfig, allItems } = yield* readPartitionRaw(key,
3788
- // `delete` declares no `ValidationError`: a rejected read keeps
3789
- // DynamoDB's own tag, its message explained.
3790
- (diagnosis, original) => new DynamoValidationError({
4287
+ // `delete` declares no `ValidationError`: a rejected read keeps DynamoDB's own tag, its
4288
+ // message explained; nor a key with no value, reported as a key that finds nothing.
4289
+ // The caller's key is read once (#239): a second read of the partition is given its key.
4290
+ const read = (consistent, partition) => readPartitionRaw(key, (diagnosis, original) => new DynamoValidationError({
3791
4291
  operation: "Query",
3792
4292
  cause: assemblyReadCause("delete", diagnosis, original),
3793
- })).pipe(
3794
- // Nor a key with no value: nothing to read, reported as a key that finds nothing.
3795
- Effect.catchTag("ValidationError", (error) => Effect.fail(new AggregateAssemblyError({
4293
+ }), consistent || partition !== undefined ? { consistent, partition } : undefined).pipe(Effect.catchTag("ValidationError", (error) => Effect.fail(new AggregateAssemblyError({
3796
4294
  aggregate: aggregateName,
3797
4295
  reason: String(error.cause?.message ?? error.cause),
3798
4296
  key,
@@ -3800,15 +4298,52 @@ const makeAggregate = (schema, config) => {
3800
4298
  // Only the aggregate's own rows (DESIGN.md §7 "delete"): a row of another entity type in
3801
4299
  // its partition is an entity's or another aggregate's, and stays. Nothing is keyed by
3802
4300
  // value, so every row of the aggregate's types is deleted, whoever wrote it.
3803
- const ownItems = allItems.filter((item) => typeof item.__edd_e__ === "string" && ownedTypes.has(item.__edd_e__));
3804
- if (ownItems.length === 0) {
3805
- return yield* new AggregateAssemblyError({
4301
+ const ownOf = (items) => items.filter((item) => typeof item.__edd_e__ === "string" && ownedTypes.has(item.__edd_e__));
4302
+ const isRootRow = (item) => item.__edd_e__ === config.root.entityType && item.sk === rootSortKey;
4303
+ const notFound = new AggregateAssemblyError({
4304
+ aggregate: aggregateName,
4305
+ reason: "No items found for aggregate key",
4306
+ key,
4307
+ });
4308
+ if (fenced) {
4309
+ // With the fence (#168, §3.8): the root first, so no update commits after it (each
4310
+ // checks the root), then one read, consistent where the collection allows, and the rest.
4311
+ const client = yield* Capacity.client;
4312
+ const tableConfig = yield* config.table.Tag;
4313
+ const pkValue = yield* composeOrFail("key", () => collectionPkOf(key)).pipe(Effect.catchTag("ValidationError", (error) => Effect.fail(new AggregateAssemblyError({
3806
4314
  aggregate: aggregateName,
3807
- reason: "No items found for aggregate key",
4315
+ reason: String(error.cause?.message ?? error.cause),
3808
4316
  key,
4317
+ }))));
4318
+ const removed = yield* client.deleteItem({
4319
+ TableName: tableConfig.name,
4320
+ Key: toAttributeMap({ [config.pk.field]: pkValue, sk: rootSortKey }),
4321
+ ReturnValues: "ALL_OLD",
3809
4322
  });
4323
+ const { allItems } = yield* read(readConsistent, pkValue);
4324
+ const ownItems = ownOf(allItems);
4325
+ if (removed.Attributes === undefined && ownItems.length === 0) {
4326
+ return yield* notFound;
4327
+ }
4328
+ // A root found after the root was deleted is a `create` that reused the key in between:
4329
+ // its aggregate is left as it is, as the sweep without the fence leaves it (§3.8).
4330
+ if (ownItems.length > 0 && !ownItems.some(isRootRow)) {
4331
+ yield* deleteAllItems(client, tableConfig.name, ownItems, config.pk.field);
4332
+ }
4333
+ return;
3810
4334
  }
4335
+ const { client, tableConfig, allItems, pkValue } = yield* read(false);
4336
+ const ownItems = ownOf(allItems);
4337
+ if (ownItems.length === 0)
4338
+ return yield* notFound;
3811
4339
  yield* deleteAllItems(client, tableConfig.name, ownItems, config.pk.field);
4340
+ // Without the fence (§2.6, §3.8): one more read, consistent where the collection allows,
4341
+ // finds the rows a write added after the first, and deletes them, unless it finds a root:
4342
+ // a `create` reused the key, and its aggregate is left as it is.
4343
+ const swept = ownOf((yield* read(readConsistent, pkValue)).allItems);
4344
+ if (swept.length > 0 && !swept.some(isRootRow)) {
4345
+ yield* deleteAllItems(client, tableConfig.name, swept, config.pk.field);
4346
+ }
3812
4347
  }),
3813
4348
  list: (filter, options) => Effect.gen(function* () {
3814
4349
  const client = yield* Capacity.client;
@@ -4006,6 +4541,9 @@ const makeAggregate = (schema, config) => {
4006
4541
  return { data: aggregates, cursor };
4007
4542
  }),
4008
4543
  }));
4544
+ // Hidden, not part of the aggregate's type.
4545
+ Object.defineProperty(aggregate, GcSupport.GcSupportId, { value: gcSupport, enumerable: false });
4546
+ return aggregate;
4009
4547
  };
4010
4548
  /**
4011
4549
  * Each aggregate operation as a named operation for consumed-capacity
@@ -4016,9 +4554,11 @@ const withOperations = (aggregateName, ops) => {
4016
4554
  return {
4017
4555
  ...ops,
4018
4556
  get: (key) => Capacity.operation("Aggregate.get", target, ops.get(key)),
4019
- create: (input) => Capacity.operation("Aggregate.create", target, ops.create(input)),
4020
- update: (key, mutationFn) => Capacity.operation("Aggregate.update", target, ops.update(key, mutationFn)),
4021
- delete: (key) => Capacity.operation("Aggregate.delete", target, ops.delete(key)),
4557
+ // The writes are ledger roots (#179): the edge entities' uploads settle
4558
+ // by the one transaction that carries them.
4559
+ create: (input) => Capacity.operation("Aggregate.create", target, BlobLedger.root(ops.create(input))),
4560
+ update: (key, mutationFn, options) => Capacity.operation("Aggregate.update", target, BlobLedger.root(ops.update(key, mutationFn, options))),
4561
+ delete: (key) => Capacity.operation("Aggregate.delete", target, BlobLedger.root(ops.delete(key))),
4022
4562
  list: (filter, options) => Capacity.operation("Aggregate.list", target, ops.list(filter, options)),
4023
4563
  };
4024
4564
  };
@@ -4034,12 +4574,28 @@ const withOperations = (aggregateName, ops) => {
4034
4574
  export const bind = (aggregate) => Effect.gen(function* () {
4035
4575
  // Detached: no current operation or parent span is pinned for later calls (#174).
4036
4576
  const ctx = Capacity.detachContext(yield* Effect.context());
4577
+ // Configuration checks where the aggregate is first resolvable (#147,
4578
+ // #179): its edges' packed codecs must be registered (`[EDD-9078]`) and
4579
+ // their offloaded fields need a blob store (`[EDD-9115]`) in the context
4580
+ // it is bound with — `DynamoClient.make` binds under the one it bundled.
4581
+ const owner = `aggregate "${aggregate._name ?? "?"}"`;
4582
+ const requirements = OffloadWrite.aggregateStoreRequirements(owner, aggregate);
4583
+ // Offloading requires escaped key text (`[EDD-9146]`), before the store.
4584
+ const keysError = OffloadWrite.unescapedKeysError("Aggregate.bind", requirements);
4585
+ if (keysError !== undefined)
4586
+ throw keysError;
4587
+ const codecError = unregisteredCodecError("Aggregate.bind", [...(aggregate._packedByType ?? new Map())].flatMap(([edgeType, packed]) => codecRequirements(`${owner} (edge "${edgeType}")`, Object.entries(packed))), Context.getOrUndefined(ctx, Compression));
4588
+ if (codecError !== undefined)
4589
+ throw codecError;
4590
+ const storeError = OffloadWrite.missingStoreError("Aggregate.bind", requirements, Context.getOrUndefined(ctx, BlobStore));
4591
+ if (storeError !== undefined)
4592
+ throw storeError;
4037
4593
  const provide = (effect) => Effect.provide(effect, ctx);
4038
4594
  return {
4039
4595
  schema: aggregate.schema,
4040
4596
  get: (key) => provide(aggregate.get(key)),
4041
4597
  create: (input) => provide(aggregate.create(input)),
4042
- update: (key, mutationFn) => provide(aggregate.update(key, mutationFn)),
4598
+ update: (key, mutationFn, options) => provide(aggregate.update(key, mutationFn, options)),
4043
4599
  delete: (key) => provide(aggregate.delete(key)),
4044
4600
  list: (filter, options) => provide(aggregate.list(filter, options)),
4045
4601
  inputSchema: aggregate.inputSchema,
@@ -4060,6 +4616,18 @@ const deepEqual = (a, b) => {
4060
4616
  return false;
4061
4617
  if (typeof a !== "object")
4062
4618
  return false;
4619
+ // Bytes compare by content (#179): a binary edge field of megabytes was
4620
+ // compared through `Object.keys`, one string key per byte.
4621
+ if (a instanceof Uint8Array || b instanceof Uint8Array) {
4622
+ if (!(a instanceof Uint8Array && b instanceof Uint8Array))
4623
+ return false;
4624
+ if (a.length !== b.length)
4625
+ return false;
4626
+ for (let i = 0; i < a.length; i++)
4627
+ if (a[i] !== b[i])
4628
+ return false;
4629
+ return true;
4630
+ }
4063
4631
  if (Array.isArray(a) && Array.isArray(b)) {
4064
4632
  if (a.length !== b.length)
4065
4633
  return false;
@@ -4147,6 +4715,88 @@ const edgePackedFields = (edgeName, entity, itemFields, discriminator, skComposi
4147
4715
  }
4148
4716
  return Object.keys(packed).length > 0 ? packed : undefined;
4149
4717
  };
4718
+ /**
4719
+ * Validate the edge entity's `External` (binary) fields that are top-level
4720
+ * attributes of the node's items (`itemFields`), as {@link edgePackedFields}
4721
+ * does for packed ones (#179): such a field's item schema must be binary
4722
+ * (`[EDD-9111]` — a `many` element may redeclare it), and it cannot be a
4723
+ * discriminator or a declared sort-key composite (`[EDD-9142]`).
4724
+ */
4725
+ const validateEdgeExternalFields = (edgeName, entity, itemFields, discriminator, skComposite) => {
4726
+ if (entity === undefined)
4727
+ return;
4728
+ for (const field of Object.keys(DynamoModel.getExternalFields(entity.model))) {
4729
+ if (itemFields !== undefined && !Object.hasOwn(itemFields, field))
4730
+ continue;
4731
+ const itemSchema = itemFields?.[field];
4732
+ const notBinary = itemSchema === undefined ? undefined : binaryShapeRefusal(itemSchema);
4733
+ if (notBinary !== undefined) {
4734
+ throw new Error(`[EDD-9111] Aggregate edge "${edgeName}": "${field}" is an External field of entity ` +
4735
+ `"${entity.entityType}", but the edge's item schema declares it as non-binary: ` +
4736
+ `${notBinary}. Declare it as the entity does (Schema.Uint8Array).`);
4737
+ }
4738
+ if (discriminator !== undefined && Object.hasOwn(discriminator, field)) {
4739
+ throw new Error(`[EDD-9142] Aggregate edge "${edgeName}": discriminator "${field}" is an External field ` +
4740
+ `of entity "${entity.entityType}". A discriminator is matched as a scalar stored value.`);
4741
+ }
4742
+ if ((skComposite ?? []).some((path) => path.split(".")[0] === field)) {
4743
+ throw new Error(`[EDD-9142] Aggregate edge "${edgeName}": sort-key composite "${field}" is an External ` +
4744
+ `field of entity "${entity.entityType}". Key composites must be scalar model values.`);
4745
+ }
4746
+ }
4747
+ };
4748
+ /**
4749
+ * Refuse a denormalised copy of an entity, at any depth, whose schema includes
4750
+ * a field that entity offloads (`[EDD-9143]`, #179). Two edges copy an entity
4751
+ * into a map inside another item, where no offload routing reaches:
4752
+ *
4753
+ * - a ref edge (`Aggregate.ref`) — its field, kept inline in its parent's item;
4754
+ * - a `many` edge whose element WRAPS the ref (`PlayerSheet { player }`) — the
4755
+ * element field named after the entity (`deriveEntityFieldName`), which
4756
+ * hydration fills from `${name}Id` (as `deriveElementInputSchema` derives
4757
+ * it, by name, whether or not the field is `DynamoModel.ref`-annotated) and
4758
+ * the edge item stores as a nested map. An element that IS the entity is
4759
+ * stored as the edge item's own attributes, which `validateEdgeExternalFields`
4760
+ * checks and the edge entity's offload settings route.
4761
+ */
4762
+ const validateRefEdgeOffload = (aggregateName, fields, edges) => {
4763
+ const owner = `Aggregate "${aggregateName}"`;
4764
+ for (const [edgeName, edge] of Object.entries(edges)) {
4765
+ if (!("_tag" in edge))
4766
+ continue;
4767
+ if (edge._tag === "RefEdge") {
4768
+ const fieldSchema = fields?.[edgeName];
4769
+ if (fieldSchema === undefined)
4770
+ continue;
4771
+ const refused = refOffloadRefusal(owner, edgeName, fieldSchema, edge.entity);
4772
+ if (refused !== undefined)
4773
+ throw new Error(refused);
4774
+ }
4775
+ else if (edge._tag === "ManyEdge") {
4776
+ const entity = edge.entity;
4777
+ const arrayField = fields?.[edgeName];
4778
+ const element = arrayField === undefined ? undefined : extractArrayElement(arrayField);
4779
+ if (entity === undefined || element === undefined)
4780
+ continue;
4781
+ if (isSchemaMatchingEntity(element, entity))
4782
+ continue;
4783
+ const entityFieldName = deriveEntityFieldName(entity);
4784
+ const elementFields = getSchemaFields(element);
4785
+ const refField = elementFields !== undefined && Object.hasOwn(elementFields, entityFieldName)
4786
+ ? elementFields[entityFieldName]
4787
+ : undefined;
4788
+ if (refField === undefined)
4789
+ continue;
4790
+ const refused = refOffloadRefusal(owner, `${edgeName}.${entityFieldName}`, refField, entity);
4791
+ if (refused !== undefined)
4792
+ throw new Error(refused);
4793
+ }
4794
+ else if (edge._tag === "BoundSubAggregate") {
4795
+ const bound = edge;
4796
+ validateRefEdgeOffload(aggregateName, fieldsOf(bound.aggregate.schema), bound.aggregate.edges);
4797
+ }
4798
+ }
4799
+ };
4150
4800
  /**
4151
4801
  * The attributes of an edge entity's items a reader dispatches on by stored
4152
4802
  * form: its packed ones, plus every non-sparse field of the item whose encoded
@@ -4166,10 +4816,67 @@ const edgeDispatchFields = (entity, itemFields, packed) => {
4166
4816
  }
4167
4817
  return dispatch.size > 0 ? [...dispatch] : undefined;
4168
4818
  };
4169
- /** A node's packed and stored-form-dispatch attributes, as `resolveNode` args. */
4819
+ /** The edge entity's offloaded fields among the node's item attributes (#179). */
4820
+ const edgeOffloadedFields = (packed, entity, itemFields) => {
4821
+ if (entity === undefined)
4822
+ return undefined;
4823
+ const offloaded = [
4824
+ ...Object.entries(packed ?? {})
4825
+ .filter(([, storedAs]) => storedAs.external !== undefined)
4826
+ .map(([field]) => field),
4827
+ ...Object.keys(DynamoModel.getExternalFields(entity.model)).filter((field) => itemFields === undefined || Object.hasOwn(itemFields, field)),
4828
+ ];
4829
+ return offloaded.length > 0 ? offloaded : undefined;
4830
+ };
4831
+ /**
4832
+ * How the node's items offload (#179): the edge entity's overflow fields among its packed ones, its
4833
+ * binary fields among the item attributes, and its `offload` settings — `undefined` when it
4834
+ * offloads none of them.
4835
+ */
4836
+ const edgeOffload = (packed, entity, itemFields) => {
4837
+ if (entity === undefined)
4838
+ return undefined;
4839
+ const overflow = {};
4840
+ for (const [field, storedAs] of Object.entries(packed ?? {})) {
4841
+ if (storedAs.external !== undefined) {
4842
+ setOwn(overflow, field, storedAs);
4843
+ }
4844
+ }
4845
+ const binary = {};
4846
+ for (const [field, storedAs] of Object.entries(DynamoModel.getExternalFields(entity.model))) {
4847
+ if (itemFields === undefined || Object.hasOwn(itemFields, field)) {
4848
+ setOwn(binary, field, storedAs);
4849
+ }
4850
+ }
4851
+ if (Object.keys(overflow).length === 0 && Object.keys(binary).length === 0)
4852
+ return undefined;
4853
+ return {
4854
+ overflow,
4855
+ binary,
4856
+ itemBudget: entity.offload?.itemBudget,
4857
+ prefix: entity.offload?.prefix,
4858
+ };
4859
+ };
4860
+ /**
4861
+ * The node's item attributes whose encoded side is bytes (design §4.7): every non-sparse field of
4862
+ * the item a bytes pointer may be stored on.
4863
+ */
4864
+ const edgeBytesFields = (entity, itemFields) => {
4865
+ if (entity === undefined)
4866
+ return undefined;
4867
+ const sparse = DynamoModel.getSparseFields(entity.model);
4868
+ const bytes = Object.entries(itemFields ?? {})
4869
+ .filter(([field, schema]) => !Object.hasOwn(sparse, field) && binaryShapeRefusal(schema) === undefined)
4870
+ .map(([field]) => field);
4871
+ return bytes.length > 0 ? bytes : undefined;
4872
+ };
4873
+ /** A node's packed, stored-form-dispatch and offloaded attributes, as `resolveNode` args. */
4170
4874
  const edgeStorage = (packed, entity, itemFields) => ({
4171
4875
  packed,
4172
4876
  dispatch: edgeDispatchFields(entity, itemFields, packed),
4877
+ offloaded: edgeOffloadedFields(packed, entity, itemFields),
4878
+ offload: edgeOffload(packed, entity, itemFields),
4879
+ bytes: edgeBytesFields(entity, itemFields),
4173
4880
  });
4174
4881
  const resolveNode = (args) => {
4175
4882
  const { assemble, cardinality, attrEncoders, decompose, discriminator, edges, entityType, fieldName, keyAttrEncoders, ownDiscriminator, parentFields, refIdentifierField, resolveRef, skComposite, } = args;
@@ -4189,6 +4896,7 @@ const resolveNode = (args) => {
4189
4896
  (parentField === undefined
4190
4897
  ? undefined
4191
4898
  : getSchemaFields(unwrapOptionalField(parentField)));
4899
+ validateEdgeExternalFields(field, edge.entity, valueFields, edge.discriminator, undefined);
4192
4900
  children.push(resolveNode({
4193
4901
  fieldName: field,
4194
4902
  entityType: edge.entityType,
@@ -4232,6 +4940,7 @@ const resolveNode = (args) => {
4232
4940
  const entityKeyEncoders = buildKeyAttrEncoders(entityFields);
4233
4941
  const recomposed = entityEdgeEncodedComposites(edge.entity?.model, edge.sk?.composite).length > 0;
4234
4942
  const escaped = args.escapeKeys === true;
4943
+ validateEdgeExternalFields(field, edge.entity, elementFields, discriminator, edge.sk?.composite);
4235
4944
  children.push(resolveNode({
4236
4945
  fieldName: field,
4237
4946
  entityType: edge.entityType,
@@ -4286,6 +4995,7 @@ const resolveNode = (args) => {
4286
4995
  cardinality: "one",
4287
4996
  edges: bound.aggregate.edges,
4288
4997
  parentFields: subFields,
4998
+ valueSchema: bound.aggregate.schema,
4289
4999
  resolveRef,
4290
5000
  discriminator: inherited,
4291
5001
  ownDiscriminator: bound.discriminator,
@@ -4334,6 +5044,9 @@ const resolveNode = (args) => {
4334
5044
  ...(refIdentifierField !== undefined && { refIdentifierField }),
4335
5045
  ...(args.packed !== undefined && { packed: args.packed }),
4336
5046
  ...(args.dispatch !== undefined && { dispatch: args.dispatch }),
5047
+ ...(args.offloaded !== undefined && { offloaded: args.offloaded }),
5048
+ ...(args.offload !== undefined && { offload: args.offload }),
5049
+ ...(args.bytes !== undefined && { bytes: args.bytes }),
4337
5050
  attrEncoders,
4338
5051
  ...(args.elementEncoder !== undefined && { elementEncoder: args.elementEncoder }),
4339
5052
  ...(keyAttrEncoders !== undefined && { keyAttrEncoders }),
@@ -4359,6 +5072,22 @@ const collectPackedByType = (root) => {
4359
5072
  walk(root);
4360
5073
  return out;
4361
5074
  };
5075
+ /** Every node's offloaded fields (#179), by the entity type of its items. */
5076
+ const collectOffloadByType = (root) => {
5077
+ const out = new Map();
5078
+ const walk = (node) => {
5079
+ if (node.offloaded !== undefined) {
5080
+ const fields = out.get(node.entityType) ?? new Set();
5081
+ for (const field of node.offloaded)
5082
+ fields.add(field);
5083
+ out.set(node.entityType, fields);
5084
+ }
5085
+ for (const child of node.children)
5086
+ walk(child);
5087
+ };
5088
+ walk(root);
5089
+ return new Map([...out].map(([type, fields]) => [type, [...fields]]));
5090
+ };
4362
5091
  /** Every node's stored-form-dispatch attributes, by the entity type of its items. */
4363
5092
  const collectDispatchByType = (root) => {
4364
5093
  const out = new Map();
@@ -4424,6 +5153,253 @@ const unpackAggregateItems = (items, dispatchByType, aggregateName) => dispatchB
4424
5153
  return undefined;
4425
5154
  });
4426
5155
  // ---------------------------------------------------------------------------
5156
+ // Internal: offloaded edge attributes (#179)
5157
+ // ---------------------------------------------------------------------------
5158
+ /**
5159
+ * How each edge entity type's items offload, keyed by the entity type the items carry
5160
+ * (`__edd_e__`): routed and uploaded on the built items (`OffloadWrite.route`, design §6.9). Edge
5161
+ * rows never copy pointers — aggregate writes create no snapshots, tombstones or events.
5162
+ */
5163
+ const collectOffloadInfoByType = (root) => {
5164
+ const out = new Map();
5165
+ const walk = (node) => {
5166
+ const offload = node.offload;
5167
+ if (offload !== undefined) {
5168
+ const known = out.get(node.entityType);
5169
+ const overflow = { ...(known?.overflow ?? {}), ...offload.overflow };
5170
+ const binary = { ...(known?.binary ?? {}), ...offload.binary };
5171
+ const budgets = [known?.itemBudget, offload.itemBudget].filter((budget) => budget !== undefined);
5172
+ out.set(node.entityType, {
5173
+ entityType: node.entityType,
5174
+ overflow,
5175
+ binary,
5176
+ // Aggregates store domain names: every attribute is its field.
5177
+ fieldOf: Object.fromEntries([...Object.keys(overflow), ...Object.keys(binary)].map((field) => [field, field])),
5178
+ // Two nodes of one item type (rare): the tighter budget holds for both.
5179
+ itemBudget: budgets.length === 0 ? undefined : Math.min(...budgets),
5180
+ prefix: known?.prefix ?? offload.prefix,
5181
+ copiesPointers: false,
5182
+ });
5183
+ }
5184
+ for (const child of node.children)
5185
+ walk(child);
5186
+ };
5187
+ walk(root);
5188
+ return out;
5189
+ };
5190
+ /** A read plan's lazy-value decoder; aggregates read eagerly, so it is never called. */
5191
+ const decodeWire = (_field, wire) => Effect.succeed(wire);
5192
+ /**
5193
+ * How each edge entity type's stored rows are read (design §8.4): its stored-form-dispatch
5194
+ * attributes, its bytes attributes (a `~edbp:` text is a bytes pointer, §4.7) and its offloaded
5195
+ * ones. Types with nothing to read by stored form have no plan: their rows are final as stored.
5196
+ */
5197
+ const collectReadPlans = (root, aggregateName) => {
5198
+ const dispatch = new Map();
5199
+ const bytes = new Map();
5200
+ const offloaded = new Map();
5201
+ const contentTypes = new Map();
5202
+ const add = (into, type, attrs) => {
5203
+ const set = into.get(type) ?? new Set();
5204
+ for (const attr of attrs)
5205
+ set.add(attr);
5206
+ into.set(type, set);
5207
+ };
5208
+ const walk = (node) => {
5209
+ if (node.dispatch !== undefined)
5210
+ add(dispatch, node.entityType, node.dispatch);
5211
+ if (node.bytes !== undefined)
5212
+ add(bytes, node.entityType, node.bytes);
5213
+ if (node.offload !== undefined) {
5214
+ const kinds = offloaded.get(node.entityType) ?? {};
5215
+ const types = contentTypes.get(node.entityType) ?? {};
5216
+ for (const field of Object.keys(node.offload.overflow))
5217
+ setOwn(kinds, field, "overflow");
5218
+ for (const [field, storedAs] of Object.entries(node.offload.binary)) {
5219
+ setOwn(kinds, field, "binary");
5220
+ setOwn(types, field, storedAs.contentType);
5221
+ }
5222
+ offloaded.set(node.entityType, kinds);
5223
+ contentTypes.set(node.entityType, types);
5224
+ }
5225
+ for (const child of node.children)
5226
+ walk(child);
5227
+ };
5228
+ walk(root);
5229
+ const plans = new Map();
5230
+ for (const type of new Set([...dispatch.keys(), ...bytes.keys()])) {
5231
+ plans.set(type, {
5232
+ entityType: `${aggregateName}.${type}`,
5233
+ dispatch: [...(dispatch.get(type) ?? [])],
5234
+ binary: [...(bytes.get(type) ?? [])],
5235
+ offloaded: offloaded.get(type) ?? {},
5236
+ // Aggregates store domain names: every attribute is its field.
5237
+ fieldOf: {},
5238
+ contentTypeOf: contentTypes.get(type) ?? {},
5239
+ decodeField: decodeWire,
5240
+ });
5241
+ }
5242
+ return plans;
5243
+ };
5244
+ /**
5245
+ * Read, in place, each item of a partition by its type's plan (design §8.4): packed and
5246
+ * dispatch-eligible attributes by their stored form — whatever the edge entity configures now —
5247
+ * and every offloaded value resolved eagerly, both kinds, so assembly decodes values, never
5248
+ * handles. A pointer on an attribute the edge entity no longer offloads resolves through the
5249
+ * ambient store (§4.7). A row with no string or binary value on any attribute of its plan costs
5250
+ * one `typeof` per attribute.
5251
+ */
5252
+ const loadAggregateItems = (items, plans) => {
5253
+ if (plans.size === 0 || items.length === 0)
5254
+ return Effect.void;
5255
+ const rowsByType = new Map();
5256
+ for (const item of items) {
5257
+ const type = ownValue(item, "__edd_e__");
5258
+ if (typeof type !== "string" || !plans.has(type))
5259
+ continue;
5260
+ const rows = rowsByType.get(type) ?? [];
5261
+ rows.push(item);
5262
+ rowsByType.set(type, rows);
5263
+ }
5264
+ return Effect.forEach(rowsByType, ([type, rows]) => OffloadRead.loadRows(plans.get(type), rows, {
5265
+ operation: "aggregate.decode",
5266
+ modes: OffloadRead.EAGER_MODES,
5267
+ }), { discard: true });
5268
+ };
5269
+ /**
5270
+ * Route and upload the offloaded attributes of built edge items (design §6.9): after
5271
+ * `buildDynamoItems` composed each item's keys, which the object key (§4.5) and the whole-item
5272
+ * budget need, and after the write's read-back checks, which judge the values as given. Every item
5273
+ * of the groups the write sends is uploaded afresh — no pointer read from the partition is written
5274
+ * back (group `Put`s carry no condition, §6.4) — and all of them before the first transaction, so
5275
+ * an upload failure writes nothing. Each group's uploads settle by the transaction that carries
5276
+ * them (the ledger, §6.2). Returns the groups with each uploaded attribute holding its pointer; an
5277
+ * item with nothing uploaded is the item built.
5278
+ */
5279
+ const routeBuiltGroups = (groups, infos, keys) => {
5280
+ if (infos.size === 0)
5281
+ return Effect.succeed(groups);
5282
+ const targets = [];
5283
+ groups.forEach((group, g) => {
5284
+ group.items.forEach((built, i) => {
5285
+ const info = infos.get(built.__edd_e__?.S ?? "");
5286
+ if (info === undefined)
5287
+ return;
5288
+ // The values as they will be stored: the router measures and uploads them in place.
5289
+ const item = fromAttributeMap(built);
5290
+ targets.push({ g, i, info, item, uploaded: new Set() });
5291
+ });
5292
+ });
5293
+ if (targets.length === 0)
5294
+ return Effect.succeed(groups);
5295
+ return Effect.map(OffloadWrite.forEachSettled(targets, (target) => Effect.map(OffloadWrite.route(target.info, target.item, OffloadWrite.rowOf(target.item, {
5296
+ table: keys.table,
5297
+ pkAttribute: keys.pkAttribute,
5298
+ skAttribute: "sk",
5299
+ operation: keys.operation,
5300
+ escapeKeys: keys.escapeKeys,
5301
+ })), (routed) => {
5302
+ target.uploaded = routed.uploaded;
5303
+ })), () => {
5304
+ const routed = groups.map((group) => ({ ...group, items: [...group.items] }));
5305
+ for (const { g, i, item, uploaded } of targets) {
5306
+ if (uploaded.size === 0)
5307
+ continue;
5308
+ const built = { ...routed[g].items[i] };
5309
+ for (const attribute of uploaded) {
5310
+ setOwn(built, attribute, toAttributeValue(ownValue(item, attribute)));
5311
+ }
5312
+ routed[g].items[i] = built;
5313
+ }
5314
+ return routed;
5315
+ });
5316
+ };
5317
+ /** Why `value` cannot be an offloaded edge field's aggregate input, or `undefined`. */
5318
+ const edgeInputRefusal = (kind, value) => {
5319
+ const what = Stream.isStream(value)
5320
+ ? "a Stream"
5321
+ : isBlobHandle(value)
5322
+ ? "a BlobHandle"
5323
+ : isBlobSource(value)
5324
+ ? "an Offload.source(...)"
5325
+ : isOffloadedValue(value)
5326
+ ? "an OffloadedValue (a lazy read)"
5327
+ : undefined;
5328
+ if (what === undefined)
5329
+ return undefined;
5330
+ return kind === "binary"
5331
+ ? `takes a Uint8Array, got ${what}: an aggregate's binary edge fields take their bytes ` +
5332
+ "(design §6.9)"
5333
+ : `takes its domain value, got ${what}`;
5334
+ };
5335
+ /**
5336
+ * Refuse an offloaded edge field holding a stream, handle, source or lazy value in an aggregate's
5337
+ * write input (`[EDD-9120]`, design §6.9): the aggregate's input is its own schema, which takes a
5338
+ * binary edge field's bytes only. Walks the input along the resolved graph — `one` edges, `many`
5339
+ * edge elements and sub-aggregates — before the schema decode, whose refusal would not say why.
5340
+ */
5341
+ const refuseEdgeInputs = (input, root, aggregateName, operation) => {
5342
+ // Only the subtrees holding an offloading node are read: an aggregate whose edges offload
5343
+ // nothing reads none of the caller's object here, which reads it as 1.40.0 did (#239).
5344
+ const offloads = new Map();
5345
+ const holdsOffload = (node) => {
5346
+ const known = offloads.get(node);
5347
+ if (known !== undefined)
5348
+ return known;
5349
+ const holds = node.offload !== undefined || node.children.some(holdsOffload);
5350
+ offloads.set(node, holds);
5351
+ return holds;
5352
+ };
5353
+ if (!holdsOffload(root))
5354
+ return Effect.void;
5355
+ const visit = (value, node, path) => {
5356
+ if (value === null || typeof value !== "object")
5357
+ return undefined;
5358
+ const offload = node.offload;
5359
+ if (offload !== undefined) {
5360
+ for (const [kind, fields] of [
5361
+ ["overflow", offload.overflow],
5362
+ ["binary", offload.binary],
5363
+ ]) {
5364
+ for (const field of Object.keys(fields)) {
5365
+ const why = edgeInputRefusal(kind, givenValue(value, field));
5366
+ if (why !== undefined) {
5367
+ return (`${kind} field "${field}" of edge "${path}" (entity type ` +
5368
+ `"${node.entityType}") ${why}`);
5369
+ }
5370
+ }
5371
+ }
5372
+ }
5373
+ for (const child of node.children) {
5374
+ if (child.fieldName === null || !holdsOffload(child))
5375
+ continue;
5376
+ const childPath = path === "" ? child.fieldName : `${path}.${child.fieldName}`;
5377
+ const childValue = givenValue(value, child.fieldName);
5378
+ if (child.cardinality === "many" && Array.isArray(childValue)) {
5379
+ for (const [index, element] of childValue.entries()) {
5380
+ const refused = visit(element, child, `${childPath}[${index}]`);
5381
+ if (refused !== undefined)
5382
+ return refused;
5383
+ }
5384
+ }
5385
+ else {
5386
+ const refused = visit(childValue, child, childPath);
5387
+ if (refused !== undefined)
5388
+ return refused;
5389
+ }
5390
+ }
5391
+ return undefined;
5392
+ };
5393
+ const refused = visit(input, root, "");
5394
+ return refused === undefined
5395
+ ? Effect.void
5396
+ : Effect.fail(new ValidationError({
5397
+ entityType: aggregateName,
5398
+ operation,
5399
+ cause: new Error(`[EDD-9120] Aggregate "${aggregateName}": ${refused}`),
5400
+ }));
5401
+ };
5402
+ // ---------------------------------------------------------------------------
4427
5403
  // Internal: Query all items in the aggregate partition
4428
5404
  // ---------------------------------------------------------------------------
4429
5405
  const queryAllItems = (client, tableName, indexName, pkField, pkValue, consistentRead,
@@ -4638,9 +5614,11 @@ const EMPTY_ATTRS = new Set();
4638
5614
  /** The timestamps a node's rows hold beside its value: those its value doesn't declare. */
4639
5615
  const stampsToStrip = (node, systemAttrs) => {
4640
5616
  const own = node.ownFields;
4641
- if (own === undefined)
5617
+ const stored = node.storedNames;
5618
+ if (own === undefined && stored === undefined)
4642
5619
  return systemAttrs;
4643
- const kept = [...systemAttrs].filter((name) => !Object.hasOwn(own, name));
5620
+ // A value of members (a union, a suspended schema) declares a name when a member does.
5621
+ const kept = [...systemAttrs].filter((name) => own === undefined ? !stored.includes(name) : !Object.hasOwn(own, name));
4644
5622
  return kept.length === systemAttrs.size ? systemAttrs : new Set(kept);
4645
5623
  };
4646
5624
  /**
@@ -4712,6 +5690,12 @@ const doubledKeys = (items, schema, rowAt) => {
4712
5690
  }
4713
5691
  return doubled;
4714
5692
  };
5693
+ /** `node`'s child for edge `edgeName`. */
5694
+ const childNode = (node, edgeName) => node?.children.find((child) => child.fieldName === edgeName);
5695
+ /** What an item copy for edge `edgeName` of `node` keeps (see {@link RefRequest.keeps}). */
5696
+ const keptByChild = (node, edgeName) => childNode(node, edgeName)?.offloaded ?? [];
5697
+ /** A lazily read value's own value (an eager one is returned as it is). */
5698
+ const readLazyValue = (value) => isOffloadedValue(value) || isBlobHandle(value) ? value.read() : Effect.succeed(value);
4715
5699
  /** An object as given, to name it in an error, whatever its `toString` (a JSON body's may be text). */
4716
5700
  const describeObject = (value) => {
4717
5701
  try {
@@ -4747,10 +5731,12 @@ const refIdText = (id) => typeof id === "string" ? id : id instanceof Date ? id.
4747
5731
  * 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,
4748
5732
  * composed as `Batch.get` composes an entity's own `get` (`composePrimaryKeyOrFail`), once per key.
4749
5733
  */
4750
- const hydrateAggregateRefs = (input, edges, fields, aggregateName) => Effect.gen(function* () {
5734
+ const hydrateAggregateRefs = (input, edges, fields,
5735
+ /** The resolved graph of `edges`, which says what each copy keeps ({@link RefRequest.keeps}). */
5736
+ root, aggregateName) => Effect.gen(function* () {
4751
5737
  // Collect all ref IDs from the entire input hierarchy
4752
5738
  const refRequests = [];
4753
- collectRefIdsFromEdges(refRequests, input, edges, fields, [], "");
5739
+ collectRefIdsFromEdges(refRequests, input, edges, fields, root, [], "");
4754
5740
  // A `many` edge's value given under its `inputField` is decoded under its field's name, ids
4755
5741
  // or not (#241): up to 1.40.0 it was renamed only where an id was fetched.
4756
5742
  if (refRequests.length === 0)
@@ -4882,12 +5868,50 @@ const hydrateAggregateRefs = (input, edges, fields, aggregateName) => Effect.gen
4882
5868
  }
4883
5869
  // Batch-fetch all refs — one Batch.get call per entity type
4884
5870
  const hydratedLookup = new Map();
5871
+ // What each copy drops: the target's offloaded fields it doesn't keep (#179).
5872
+ const droppedOf = new Map();
5873
+ const readConcurrency = Option.match(yield* Effect.serviceOption(BlobStore), {
5874
+ onNone: () => 1,
5875
+ onSome: (store) => store.readConcurrency,
5876
+ });
4885
5877
  for (const { entityType, runtimeEntity, ops } of fetches) {
4886
5878
  const composite = refKeyComposite(runtimeEntity);
5879
+ // A target that offloads fields (#179, design §8.4) is read for what its copies keep: an
5880
+ // edge item keeps the offloaded fields its node's items hold (and uploads them again under
5881
+ // its own key), a ref copy keeps none, and nothing else is fetched. A kind kept whole is
5882
+ // read eagerly; one kept in part, or not at all, lazily, and the fields kept are then read
5883
+ // from their lazy values. Never a pointer: a copy holds values, which the edge entity routes.
5884
+ const offloaded = runtimeEntity
5885
+ ._offloadedFields ?? [];
5886
+ const binary = new Set(Object.keys(DynamoModel.getExternalFields(runtimeEntity.model)));
5887
+ const reqsOfType = refRequests.filter((req) => req.entity.entityType === entityType && lookupKeys.has(req));
5888
+ const kept = offloaded.filter((field) => reqsOfType.some((req) => req.keeps.includes(field)));
5889
+ for (const req of reqsOfType) {
5890
+ const dropped = offloaded.filter((field) => !req.keeps.includes(field));
5891
+ if (dropped.length > 0)
5892
+ droppedOf.set(req, dropped);
5893
+ }
5894
+ const keepsWhole = (isBinary) => offloaded.every((field) => binary.has(field) !== isBinary || kept.includes(field));
5895
+ const modes = {
5896
+ overflow: keepsWhole(false) ? "eager" : "lazy",
5897
+ binary: keepsWhole(true) ? "eager" : "lazy",
5898
+ };
5899
+ const readAfter = kept.filter((field) => modes[binary.has(field) ? "binary" : "overflow"] === "lazy");
4887
5900
  // Build EntityGet intermediates for batch fetching: `Batch.get` composes each key as the
4888
5901
  // entity's own `get` does, the key `Entity.put` wrote.
4889
- const getOps = ops.map(({ req }) => runtimeEntity.get({ [composite]: Option.getOrThrow(req.id) }));
5902
+ const getOps = ops.map(({ req }) => {
5903
+ const get = runtimeEntity.get({ [composite]: Option.getOrThrow(req.id) });
5904
+ return offloaded.length === 0 ? get : offloadedCombinator(get, modes);
5905
+ });
4890
5906
  const results = yield* Batch.get(getOps);
5907
+ // The kept fields of a kind read lazily, at the store's read concurrency.
5908
+ if (readAfter.length > 0) {
5909
+ yield* Effect.forEach(results.flatMap((result) => result == null
5910
+ ? []
5911
+ : readAfter.map((field) => [result, field])), ([record, field]) => Effect.map(readLazyValue(ownValue(record, field)), (value) => {
5912
+ setOwn(record, field, value);
5913
+ }), { concurrency: readConcurrency, discard: true });
5914
+ }
4891
5915
  // Map results back to lookup, failing on missing refs.
4892
5916
  for (let i = 0; i < ops.length; i++) {
4893
5917
  const { lookupKey, req } = ops[i];
@@ -4906,10 +5930,20 @@ const hydrateAggregateRefs = (input, edges, fields, aggregateName) => Effect.gen
4906
5930
  hydratedLookup.set(lookupKey, result);
4907
5931
  }
4908
5932
  }
4909
- // Walk the input again and replace IDs with hydrated data
5933
+ // Walk the input again and replace IDs with hydrated data: each copy without the target's
5934
+ // offloaded fields it doesn't keep (#179).
4910
5935
  const result = replaceRefIds(input, refRequests, (req) => {
4911
5936
  const lookupKey = lookupKeys.get(req);
4912
- return lookupKey === undefined ? undefined : hydratedLookup.get(lookupKey);
5937
+ const data = lookupKey === undefined ? undefined : hydratedLookup.get(lookupKey);
5938
+ const dropped = droppedOf.get(req);
5939
+ if (data === undefined || dropped === undefined)
5940
+ return data;
5941
+ const copy = {};
5942
+ for (const [field, value] of Object.entries(data)) {
5943
+ if (!dropped.includes(field))
5944
+ setOwn(copy, field, value);
5945
+ }
5946
+ return copy;
4913
5947
  });
4914
5948
  return renameInputFields(result, edges);
4915
5949
  });
@@ -4986,7 +6020,12 @@ const idEquivalence = (entity) => {
4986
6020
  */
4987
6021
  const collectRefIdsFromEdges = (result, input, edges,
4988
6022
  /** The fields of the schema `input` is a value of: a `many` element's schema is read off it. */
4989
- fields, path,
6023
+ fields,
6024
+ /**
6025
+ * The resolved node of `edges` (the root, or a sub-aggregate's), whose children say what each
6026
+ * item copy keeps ({@link RefRequest.keeps}).
6027
+ */
6028
+ node, path,
4990
6029
  /** Where `input` is, to name an id in an error: `""` at the root, `"sub."` under `sub`. */
4991
6030
  at) => {
4992
6031
  for (const [edgeName, edge] of Object.entries(edges)) {
@@ -5007,6 +6046,8 @@ at) => {
5007
6046
  fieldName: edgeName,
5008
6047
  idFieldName,
5009
6048
  at: `${at}${idFieldName}`,
6049
+ // A `one` edge's entity is an edge item of its own; a ref edge's a copy inside the row.
6050
+ keeps: edge._tag === "OneEdge" ? keptByChild(node, edgeName) : [],
5010
6051
  });
5011
6052
  }
5012
6053
  }
@@ -5014,7 +6055,7 @@ at) => {
5014
6055
  const bound = edge;
5015
6056
  const subInput = given(input, edgeName);
5016
6057
  if (subInput != null && typeof subInput === "object") {
5017
- collectRefIdsFromEdges(result, subInput, bound.aggregate.edges, fieldsOf(bound.aggregate.schema), [...path, edgeName], `${at}${edgeName}.`);
6058
+ collectRefIdsFromEdges(result, subInput, bound.aggregate.edges, fieldsOf(bound.aggregate.schema), childNode(node, edgeName), [...path, edgeName], `${at}${edgeName}.`);
5018
6059
  }
5019
6060
  }
5020
6061
  else if (edge._tag === "ManyEdge" && edge.entity) {
@@ -5044,6 +6085,7 @@ at) => {
5044
6085
  fieldName: edgeName,
5045
6086
  idFieldName: String(i),
5046
6087
  at: `${at}${inputKey}[${i}]`,
6088
+ keeps: keptByChild(node, edgeName),
5047
6089
  });
5048
6090
  }
5049
6091
  else if (typeof elem === "object" &&
@@ -5063,6 +6105,8 @@ at) => {
5063
6105
  fieldName: entityFieldName,
5064
6106
  idFieldName,
5065
6107
  at: `${at}${inputKey}[${i}].${idFieldName}`,
6108
+ // The entity is a copy inside the element's row.
6109
+ keeps: [],
5066
6110
  });
5067
6111
  }
5068
6112
  }
@@ -5082,7 +6126,12 @@ at) => {
5082
6126
  * such a value in its create input (#133).
5083
6127
  *
5084
6128
  * - Values implementing `Equal` — `DateTime`, `Redacted`, `Option`, `Duration`,
5085
- * `Chunk`, `HashMap`, … — are immutable, so they are kept by reference.
6129
+ * `Chunk`, `HashMap`, a `BlobHandle`, … — are immutable, so they are kept by
6130
+ * reference.
6131
+ * - A `Stream`, an `Offload.source(...)` and an `OffloadedValue` are kept by
6132
+ * reference too (#179): a copy is a bare object without their type ids, so
6133
+ * the `[EDD-9120]` refusal of them on an edge field would not see them, and
6134
+ * the schema decode or the packer would refuse the husk without saying why.
5086
6135
  * - Built-ins `structuredClone` knows (`Date`, `Map`, `Set`, `RegExp`, binary
5087
6136
  * data) still go through it.
5088
6137
  * - Plain objects, arrays and other class instances (a `Schema.Class` value
@@ -5095,6 +6144,8 @@ const cloneInput = (value, seen = new WeakMap()) => {
5095
6144
  return value;
5096
6145
  if (Equal.isEqual(value))
5097
6146
  return value;
6147
+ if (Stream.isStream(value) || isBlobSource(value) || isOffloadedValue(value))
6148
+ return value;
5098
6149
  const prior = seen.get(value);
5099
6150
  if (prior !== undefined)
5100
6151
  return prior;
@@ -5984,6 +7035,7 @@ path) => Effect.gen(function* () {
5984
7035
  own,
5985
7036
  ...(elementInput !== undefined && { input: elementInput }),
5986
7037
  ...(node.decompose === undefined && { value: elem, path: [...path, index] }),
7038
+ elementKey: values.map((value) => String(value)).join("#"),
5987
7039
  transactionGroup: parentGroup,
5988
7040
  skComposites: [
5989
7041
  ...parentDiscriminators.current,
@@ -6470,160 +7522,6 @@ own) => groups.map((group) => {
6470
7522
  });
6471
7523
  return { group: group.name, items, written };
6472
7524
  });
6473
- function writeTransactionGroups(client, tableName, groups, aggregateName, keys, rootGuard) {
6474
- return Effect.gen(function* () {
6475
- // Each group is its own transaction (DynamoDB: 100 items per
6476
- // TransactWriteItems, Puts AND Deletes together). DynamoDB's limits are
6477
- // not pre-checked (#144): a group over one is sent, rejected whole, and
6478
- // diagnosed — naming the sub-aggregates earlier groups already committed,
6479
- // since a multi-group write was never atomic.
6480
- const committed = [];
6481
- for (const [groupIndex, group] of groups.entries()) {
6482
- // Each group is one transaction — Puts AND Deletes applied atomically, so an
6483
- // edge add and a sibling edge removal in the same sub-aggregate commit together.
6484
- const itemCount = group.puts.length + group.deletes.length;
6485
- if (itemCount === 0)
6486
- continue;
6487
- // The root item, in the first transaction only.
6488
- const rootIndex = rootGuard !== undefined && groupIndex === 0
6489
- ? group.puts.findIndex((item) => item.sk?.S === rootGuard.key.sk)
6490
- : -1;
6491
- // Build TransactWriteItems request — Puts first, then Deletes for orphans.
6492
- const transactItems = [
6493
- ...group.puts.map((item, i) => ({
6494
- Put: {
6495
- TableName: tableName,
6496
- Item: item,
6497
- ...(rootGuard !== undefined && i === rootIndex
6498
- ? {
6499
- ConditionExpression: "attribute_not_exists(#pk)",
6500
- ExpressionAttributeNames: { "#pk": rootGuard.pkField },
6501
- }
6502
- : {}),
6503
- },
6504
- })),
6505
- ...group.deletes.map((key) => ({ Delete: { TableName: tableName, Key: key } })),
6506
- ];
6507
- // Named once, for both diagnoses below.
6508
- const sent = () => ({
6509
- _tag: "Transaction",
6510
- items: transactItems,
6511
- targets: () => transactItems.map((item) => {
6512
- const entityType = item.Put?.Item?.__edd_e__?.S ?? aggregateName;
6513
- return transactItemTarget(item, tableName, [keys.pkField, "sk"], entityType, `the ${item.Put !== undefined ? entityType : "removed"} item of ` +
6514
- `sub-aggregate "${group.group}"`);
6515
- }),
6516
- });
6517
- const already = [...committed];
6518
- const diagnosed = (diagnosis, original) => diagnosis._tag === "TooManyItems"
6519
- ? new AggregateTransactionOverflow({
6520
- aggregate: aggregateName,
6521
- subgraph: group.group,
6522
- itemCount: diagnosis.count,
6523
- limit: diagnosis.limit,
6524
- committed: already,
6525
- operation: rootGuard !== undefined ? "create" : "update",
6526
- // Over only because of the rows it moves off 1.40.0's text: `rekey` moves them.
6527
- ...(group.previous !== undefined &&
6528
- diagnosis.count - group.previous <= diagnosis.limit && {
6529
- previousKeyText: group.previous,
6530
- }),
6531
- cause: original,
6532
- })
6533
- : diagnosedValidationError(diagnosis, original, {
6534
- operation: `Aggregate.write(${aggregateName})`,
6535
- entityType: aggregateName,
6536
- // Each group commits on its own: say exactly what already did.
6537
- ...(already.length > 0 && {
6538
- committed: `earlier transactions of this write already committed sub-aggregates ` +
6539
- already.map((name) => `"${name}"`).join(", ") +
6540
- (rootGuard !== undefined
6541
- ? ", so a retried create fails on the existing root: update or delete " +
6542
- "the partial aggregate instead"
6543
- : ""),
6544
- }),
6545
- });
6546
- yield* client.transactWriteItems({ TransactItems: transactItems }).pipe(
6547
- // One operation per item (#144): diagnosed BEFORE the root guard's
6548
- // mapping, which would read a repeat's conditional failure as an
6549
- // existing root.
6550
- diagnoseFailure({ sent, only: ["RepeatedItem"], rewrite: diagnosed }), Effect.mapError((error) => {
6551
- if (error.cause != null &&
6552
- typeof error.cause === "object" &&
6553
- "name" in error.cause &&
6554
- error.cause.name === "TransactionCanceledException") {
6555
- const cancelled = error.cause;
6556
- const reasons = cancelled.CancellationReasons;
6557
- if (rootGuard !== undefined &&
6558
- rootIndex >= 0 &&
6559
- reasons?.[rootIndex]?.Code === "ConditionalCheckFailed") {
6560
- return new ConditionalCheckFailed({
6561
- entityType: rootGuard.entityType,
6562
- key: rootGuard.key,
6563
- });
6564
- }
6565
- return new TransactionCancelled({
6566
- operation: "TransactWriteItems",
6567
- reasons: (cancelled.CancellationReasons ?? []).map((r) => ({
6568
- code: r?.Code,
6569
- message: r?.Message,
6570
- })),
6571
- cause: error.cause,
6572
- });
6573
- }
6574
- return error;
6575
- }),
6576
- // A limit DynamoDB enforced (#144), named — after the root guard's
6577
- // mapping, which a conditional failure always takes.
6578
- diagnoseFailure({ sent, keys: () => keys.keys, rewrite: diagnosed }));
6579
- committed.push(group.group);
6580
- }
6581
- });
6582
- }
6583
- /**
6584
- * `update`'s cleanup Deletes with `ownsRows` (DESIGN.md §7 "Which rows in its partition are an
6585
- * aggregate's"), sent after the update's groups have committed, up to {@link TRANSACT_WRITE_ITEMS_LIMIT} to a
6586
- * request: Deletes of keys already stored reach no other limit of a transaction. Each holds while
6587
- * its row is gone or still of the type read, so a row another write removed in between is fine,
6588
- * and one replaced with a row of another type is left. A cancelled request is sent once more
6589
- * without the Deletes whose condition failed; the mutation isn't run again and nothing is read
6590
- * again. A failure is reported as a later group's is: the update's groups have committed, and the
6591
- * rows it didn't delete stay until the next update of their node.
6592
- */
6593
- const deleteOwnedRows = (client, tableName, pkField, rows) => Effect.gen(function* () {
6594
- const deleteOf = (row) => ({
6595
- Delete: {
6596
- TableName: tableName,
6597
- Key: toAttributeMap({ [pkField]: row.pk, sk: row.sk }),
6598
- ConditionExpression: "attribute_not_exists(#pk) OR #e = :e",
6599
- ExpressionAttributeNames: { "#pk": pkField, "#e": "__edd_e__" },
6600
- ExpressionAttributeValues: { ":e": { S: row.entityType } },
6601
- },
6602
- });
6603
- for (let start = 0; start < rows.length; start += TRANSACT_WRITE_ITEMS_LIMIT) {
6604
- const chunk = rows.slice(start, start + TRANSACT_WRITE_ITEMS_LIMIT);
6605
- const reasons = yield* client
6606
- .transactWriteItems({ TransactItems: chunk.map((row) => deleteOf(row)) })
6607
- .pipe(Effect.as(undefined), Effect.catch((error) => isAwsTransactionCancelled(error.cause)
6608
- ? Effect.succeed(error.cause.CancellationReasons ?? [])
6609
- : Effect.fail(error)));
6610
- if (reasons === undefined)
6611
- continue;
6612
- const rest = chunk.filter((_, i) => reasons[i]?.Code !== "ConditionalCheckFailed");
6613
- if (rest.length === 0)
6614
- continue;
6615
- yield* client.transactWriteItems({ TransactItems: rest.map((row) => deleteOf(row)) }).pipe(Effect.mapError((error) => isAwsTransactionCancelled(error.cause)
6616
- ? new TransactionCancelled({
6617
- operation: "TransactWriteItems",
6618
- reasons: (error.cause.CancellationReasons ?? []).map((r) => ({
6619
- code: r?.Code,
6620
- message: r?.Message,
6621
- })),
6622
- cause: error.cause,
6623
- })
6624
- : error));
6625
- }
6626
- });
6627
7525
  /**
6628
7526
  * Place an aggregate's rows from the keys that hold a row (#171). Each row has
6629
7527
  * a `current` and an `old` position. Off doesn't escape sort key text,
@@ -6905,4 +7803,39 @@ const queryListPartition = (client, tableConfig, listConfig, schema, options, ag
6905
7803
  }
6906
7804
  return { items, lastKey };
6907
7805
  });
7806
+ // ---------------------------------------------------------------------------
7807
+ // Internal: versioned roots and member paths (#168)
7808
+ // ---------------------------------------------------------------------------
7809
+ /**
7810
+ * A versioned root's version and incarnation token as stored (`docs/designs/aggregate-concurrency.md`
7811
+ * §3.5): 0 and none on a root written before `versioned` was turned on.
7812
+ */
7813
+ const storedRootVersion = (root, field) => {
7814
+ const version = root?.[field]?.N;
7815
+ return {
7816
+ version: version === undefined ? 0 : Number(version),
7817
+ token: root?.[INCARNATION_TOKEN]?.S,
7818
+ };
7819
+ };
7820
+ /**
7821
+ * A row's member path in the aggregate (D15): its fields from the root, a `many` element by its
7822
+ * sort key values (`team1.lines[b]`); `""` for the root. An element of a custom `decompose` has no
7823
+ * place in the value: its edge and key.
7824
+ */
7825
+ const memberPath = (item, elementKeys) => {
7826
+ const path = item.path;
7827
+ if (path === undefined)
7828
+ return `${item.member}[${item.elementKey ?? ""}]`;
7829
+ let name = "";
7830
+ path.forEach((segment, j) => {
7831
+ if (typeof segment === "number") {
7832
+ const key = elementKeys.get(JSON.stringify(path.slice(0, j + 1)));
7833
+ name += `[${key ?? segment}]`;
7834
+ }
7835
+ else {
7836
+ name += name === "" ? segment : `.${segment}`;
7837
+ }
7838
+ });
7839
+ return name;
7840
+ };
6908
7841
  //# sourceMappingURL=Aggregate.js.map