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/Entity.js CHANGED
@@ -6,20 +6,22 @@
6
6
  * carries derived schemas for 7 type extractors (Model, Record, Input, Update,
7
7
  * Key, Item, Marshalled).
8
8
  */
9
- import { isConfiguredModel, isRefField, } from "@effect-dynamodb/schema/DynamoModel.js";
9
+ import { Compression } from "@effect-dynamodb/schema/Compression.js";
10
+ import { isConfiguredModel, isPackedConfig, isRefField, } from "@effect-dynamodb/schema/DynamoModel.js";
10
11
  import * as DynamoSchema from "@effect-dynamodb/schema/DynamoSchema.js";
11
12
  import { Embedder } from "@effect-dynamodb/schema/Embedder.js";
12
13
  import { CascadePartialFailure, ConcurrentModification, ConditionalCheckFailed, DeleteAppliedButUnreadable, DynamoError, DynamoValidationError, EmbeddingError, ItemAlreadyExists, ItemNotDeleted, ItemNotFound, isAwsConditionalCheckFailed, isAwsDuplicateItem, isAwsTransactionCancelled, isDuplicateItemReason, OptimisticLockError, RefNotFound, StaleAppend, TransactionOverflow, UniqueConstraintViolation, UpdateAppliedButUnreadable, ValidationError, } from "@effect-dynamodb/schema/Errors.js";
13
14
  import { keyValueOf, refIdAttribute } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
14
15
  import { compositeKeyFormKind, keyFormValueKind, kindReadingOf, makeCompositeKeyForm, makeCompositeStoredForm, otherNumericKind, readsBackOtherwise, refuseInexact, storedFormOfRead, storedNumericForm, storedZoneText, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
15
16
  import { makeDefaultCrypto } from "@effect-dynamodb/schema/internal/DefaultCrypto.js";
17
+ import { externalIndexRefusal } from "@effect-dynamodb/schema/internal/EntityOffload.js";
16
18
  import { packedIndexRefusal } from "@effect-dynamodb/schema/internal/EntityPacked.js";
17
19
  import { failingAsBefore, issueDecoding } from "@effect-dynamodb/schema/internal/FailingAsBefore.js";
18
20
  import { keyReadings } from "@effect-dynamodb/schema/internal/KeyReadings.js";
19
21
  import * as KeyText136 from "@effect-dynamodb/schema/internal/KeyText136.js";
20
22
  import { lostIn } from "@effect-dynamodb/schema/internal/LostValues.js";
21
23
  import { given, hasOwnName, isUnreadableName, lackedByName, lacksAny, ownValue, setOwn, } from "@effect-dynamodb/schema/internal/OwnNames.js";
22
- import { unpackStoredSync } from "@effect-dynamodb/schema/internal/PackedCodec.js";
24
+ import { binaryShapeRefusal, stringifyStrict, unpackStoredSync, } from "@effect-dynamodb/schema/internal/PackedCodec.js";
23
25
  import { restoredObjectReading } from "@effect-dynamodb/schema/internal/RestoredKeyText.js";
24
26
  import { absentReading, absentStored, holdsCustomDeclaration, holdsUntyped, pathIsRequired, readersAt, rowOmits, storedBelowFields, } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
25
27
  import { CANT_SAY } from "@effect-dynamodb/schema/internal/SchemaIssue.js";
@@ -29,9 +31,12 @@ import { givenZoneReading, staleZonesOf, } from "@effect-dynamodb/schema/interna
29
31
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
30
32
  import { normalizeGsiConfig } from "@effect-dynamodb/schema/KeyComposer.js";
31
33
  import { deriveSourceText } from "@effect-dynamodb/schema/VectorIndex.js";
32
- import { Cause, Context, Data, DateTime, Effect, Equal, Exit, Option, Schema, SchemaAST, SchemaIssue, Stream, } from "effect";
34
+ import { Cause, Clock, Context, Data, DateTime, Effect, Equal, Exit, Option, Result, Schema, SchemaAST, SchemaIssue, Stream, } from "effect";
33
35
  import { SecureRandom } from "effect/crypto";
36
+ import { BlobStore } from "./BlobStore.js";
34
37
  import { attributeValueEquals } from "./internal/AttributeValueEquals.js";
38
+ import { blobError } from "./internal/BlobCalls.js";
39
+ import * as BlobLedger from "./internal/BlobLedger.js";
35
40
  import { isBoundOp, makeBoundAppend, makeBoundDelete, makeBoundGet, makeBoundInsert, makeBoundPut, makeBoundUpdate, } from "./internal/BoundCrud.js";
36
41
  import { BoundQueryImpl, entityNaming, wholeRowsOf, } from "./internal/BoundQuery.js";
37
42
  import * as Capacity from "./internal/Capacity.js";
@@ -39,28 +44,34 @@ import { isNumeric, memberKind, numberSum, setDifference, setUnion, } from "./in
39
44
  import { compileExpr, createConditionOps, ExprTag, emptyPartProblem, isExpr, nonEmptyCondition, operandsAsStored, parseShorthand, parseSimpleShorthand, splitByForms, toExpr, } from "./internal/Expr.js";
40
45
  import { asReadGuard, countOperators, expressionFits, substitutionsFit, wholeRowGuard, } from "./internal/ExpressionLimits.js";
41
46
  import { formGuard, formGuardName, rejectedBy } from "./internal/FormGuard.js";
47
+ import * as GcSupport from "./internal/GcSupport.js";
42
48
  import { BASE_DELAY_MS, MAX_RETRIES } from "./internal/Hydrate.js";
43
49
  import { encodeInput } from "./internal/InputForm.js";
44
50
  import { insertStatement } from "./internal/InsertStatement.js";
51
+ import * as OffloadChange from "./internal/OffloadChange.js";
52
+ import * as OffloadInput from "./internal/OffloadInput.js";
53
+ import * as OffloadRead from "./internal/OffloadRead.js";
54
+ import { isOffloadedValue } from "./internal/OffloadValues.js";
55
+ import * as OffloadWrite from "./internal/OffloadWrite.js";
45
56
  import { judgeOperand } from "./internal/OperandReaders.js";
46
- import { decodeImage, imageEntityType, ownRowsRawRow, packAttributeValueSync, packedExprRefusal, packedProjectionRefusal, packItemSync, unpackRow, withRegistry, } from "./internal/Packed.js";
57
+ import { codecRequirements, imageEntityType, imageForm, normalizeImage, ownRowsRawRow, packAttributeValueSync, packedExprRefusal, packedProjectionRefusal, packItemSync, unpackRow, unregisteredCodecError, withRegistry, } from "./internal/Packed.js";
47
58
  import { compilePath, entryOfPath, pathBuilderOf, storedPath, withEntry, } from "./internal/PathBuilder.js";
48
59
  import { KEY_MAX, KEY_TOP, keyJustBelow } from "./internal/RangePlanner.js";
49
60
  import * as Rekey from "./internal/Rekey.js";
50
61
  import { asRead, notReadBack, readBackOf, readBackRefusal, } from "./internal/RoundTrip.js";
51
- import { andRaw, composeKeysOrFail, freshIncarnationToken, generateTimestampPrimitive, hasProjectionTombstones, INCARNATION_TOKEN, isProjectionTombstone, KEY_TEXT, marshalOrFail, OUTBOX_CLAIM, OUTBOX_CLAIMED_UNTIL, OUTBOX_ROW_PK, OUTBOX_ROW_SK, overTombstone, UNSENTINELED_DEFAULTS, } from "./internal/TransactableOps.js";
52
- import { planWrite } from "./internal/TransactPlan.js";
53
- import { batchEntries, diagnosedValidationError, diagnoseFailure, keyAttributesOf, storedTypeName, targetsFor, transactItemTarget, withCause, } from "./internal/WriteDiagnosis.js";
62
+ import { andRaw, capturedServices, composeKeysOrFail, freshIncarnationToken, generateTimestampPrimitive, hasProjectionTombstones, INCARNATION_TOKEN, isProjectionTombstone, KEY_TEXT, marshalOrFail, OUTBOX_CLAIM, OUTBOX_CLAIMED_UNTIL, OUTBOX_ROW_PK, OUTBOX_ROW_SK, overTombstone, UNSENTINELED_DEFAULTS, } from "./internal/TransactableOps.js";
63
+ import { conditionCheckItem, planWrite } from "./internal/TransactPlan.js";
64
+ import { batchEntries, diagnosedValidationError, diagnoseFailure, isItemSizeRejection, keyAttributesOf, storedTypeName, targetsFor, transactItemTarget, withCause, } from "./internal/WriteDiagnosis.js";
54
65
  import { decodeSparseFields, encodeSparseFields, fromAttributeMap, fromAttributeValue, hasNoStoredForm, isEmptySet, protoEntryAt, toAttributeMap, toAttributeValue, UnstorableValue, unstorableIn, } from "./Marshaller.js";
55
66
  import * as Query from "./Query.js";
56
67
  import { filterExprStored, selectPaths } from "./Query.js";
57
68
  import { resolveTtlAttributeName, } from "./Table.js";
58
69
  export { EntityDeleteImpl, EntityDeleteTypeId, EntityGetImpl, EntityOpTypeId, EntityPutImpl, EntityUpdateImpl, EntityUpdateTypeId, emptyUpdateState, returnValuesMap, } from "./internal/EntityOps.js";
59
70
  import * as Projection from "@effect-dynamodb/schema/Projection.js";
60
- import { EntityDeleteImpl, EntityDeleteTypeId, EntityGetImpl, EntityOpTypeId, EntityPutImpl, EntityUpdateImpl, emptyUpdateState, withGuard, } from "./internal/EntityOps.js";
61
- export { add, append, asItem, asModel, asNative, asRecord, cascade, clearMap, consistentRead, deleteFromSet, expectedVersion, keepRefs, pathAdd, pathAppend, pathDelete, pathIfNotExists, pathPrepend, pathRemove, pathSet, pathSubtract, project, remove, removeEntries, returnValues, set, subtract, } from "./internal/EntityCombinators.js";
62
- import { allCompositeAttributes, allKeyFieldNames, entityRefsOf, getSchemaFields, heldStorageOf, inferDefaultEncoding, makePathValueEncoder, primaryKeyComposites, refHeldTarget, resolveUniqueFields, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
63
- import { asModel, condition as conditionCombinator, expectedVersion, set, } from "./internal/EntityCombinators.js";
71
+ import { EntityDeleteImpl, EntityDeleteTypeId, EntityGetImpl, EntityOpTypeId, EntityPutImpl, EntityUpdateImpl, emptyUpdateState, withGuard, withReadModes, } from "./internal/EntityOps.js";
72
+ export { add, append, asItem, asModel, asNative, asRecord, cascade, clearMap, consistentRead, deleteFromSet, expectedVersion, keepRefs, offloaded, pathAdd, pathAppend, pathDelete, pathIfNotExists, pathPrepend, pathRemove, pathSet, pathSubtract, project, remove, removeEntries, returnValues, set, subtract, } from "./internal/EntityCombinators.js";
73
+ import { allCompositeAttributes, allKeyFieldNames, entityRefsOf, getSchemaFields, heldStorageOf, inferDefaultEncoding, makePathValueEncoder, optionalField, primaryKeyComposites, refHeldTarget, resolveUniqueFields, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
74
+ import { asModel, condition as conditionCombinator, expectedVersion, offloaded as offloadedCombinator, set, } from "./internal/EntityCombinators.js";
64
75
  // ---------------------------------------------------------------------------
65
76
  // Sparse-aware unique sentinel composition
66
77
  // ---------------------------------------------------------------------------
@@ -177,6 +188,14 @@ const keyFormFor = (target, record) => {
177
188
  });
178
189
  return toCompositeKeyRecord(form, record);
179
190
  };
191
+ /**
192
+ * Internal: the standard `UpdateItem` of an entity with an item budget was
193
+ * rejected for item size; the caller re-runs the update on the read-merge
194
+ * branch, which routes the whole item to the blob store (#179, design §6.3).
195
+ * Never escapes the entity.
196
+ */
197
+ class OffloadSizeRetry extends Data.TaggedError("OffloadSizeRetry") {
198
+ }
180
199
  /**
181
200
  * @internal A plain update of a complete item found no item: the caller
182
201
  * creates it instead (`updateOrCreate`). Never escapes the update operation.
@@ -338,7 +357,9 @@ const expressionTargets = (expression, names) => {
338
357
  * input is in). A refusal surfaces the domain form's issue: its message is keyed on the caller's
339
358
  * input shape, which is what the user expects to see.
340
359
  */
341
- const encodeOrDecodeEncode = (schema, input, entityType, operation) => encodeInput(schema, input).pipe(Effect.mapError(({ domain }) => new ValidationError({ entityType, operation: `${operation}.decode`, cause: domain })));
360
+ const encodeOrDecodeEncode = (schema, input, entityType, operation,
361
+ /** The failure's `operation`; default `${operation}.decode`. */
362
+ errorOperation = `${operation}.decode`) => encodeInput(schema, input).pipe(Effect.mapError(({ domain }) => new ValidationError({ entityType, operation: errorOperation, cause: domain })));
342
363
  /**
343
364
  * Compile a condition that may be either an Expr ADT node or a ConditionInput object.
344
365
  * Routes both paths through the Expr ADT compiler for a single compilation backend.
@@ -499,7 +520,26 @@ const storedRefKeyOf = (ref, id) => {
499
520
  * 1.40.0 a cascade marshalled the domain item as it was, so a `Schema.Redacted` was stored as an
500
521
  * empty map (the row then failed every read) and a date as its `DateTime`'s internals.
501
522
  */
502
- const refDataOf = (refEntity, model, entityType, operation) => Schema.encodeUnknownEffect(refEntity.schemas.modelSchema)(model).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation, cause })));
523
+ const refDataOf = (refEntity, model, entityType, operation) => {
524
+ // The fields the referenced entity offloads (#179) are never stored in a ref: their values
525
+ // live in the referenced entity's own blobs, named from its own row's key, and a pointer
526
+ // copied into this row would outlive them (a ref schema may not include one, `EDD-9143`).
527
+ const dropped = offloadedFieldsOf(refEntity);
528
+ let schema = refEntity.schemas.modelSchema;
529
+ let value = model;
530
+ if (dropped.length > 0 && typeof model === "object" && model !== null) {
531
+ const copy = { ...model };
532
+ for (const field of dropped)
533
+ delete copy[field];
534
+ value = copy;
535
+ const fields = getSchemaFields(schema) ?? {};
536
+ schema = Schema.Struct(Object.fromEntries(Object.entries(fields).filter(([field]) => !dropped.includes(field))));
537
+ }
538
+ return Schema.encodeUnknownEffect(schema)(value).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation, cause })));
539
+ };
540
+ /** @internal The fields an entity offloads (#179); none for a definition that offloads nothing. */
541
+ const offloadedFieldsOf = (entity) => entity._offloadedFields ??
542
+ [];
503
543
  /** @internal Copy the schema + table tag a definition received via `_configure`
504
544
  * (Table.make injects them at table-definition time) onto a promoted entity. */
505
545
  const carryConfigure = (from, to) => {
@@ -1694,15 +1734,23 @@ const makeImpl = (config, precomputedData) => {
1694
1734
  * A write's payload, encoded (see `encodeOrDecodeEncode`) and refused if it wouldn't read back.
1695
1735
  * Every write of the entity's own encodes through this.
1696
1736
  */
1697
- const encodeForWrite = (schema, input, operation) => {
1698
- const encoded = encodeOrDecodeEncode(schema, input, entityType, operation);
1737
+ const encodeForWrite = (schema, input, operation, errorOperation) => {
1738
+ // A binary field holding a stream's or a handle's placeholder (a prepared
1739
+ // input, `prepareInput`) is not checked by its schema: its content is not
1740
+ // in hand before the upload (#179, design §3.8); `Offload.source(bytes)`
1741
+ // bytes are. The placeholder is carried into the encoded value.
1742
+ const opaque = inputFields === undefined ? [] : OffloadInput.opaqueFields(input, inputFields.binary);
1743
+ const encoded = encodeOrDecodeEncode(opaque.length === 0 ? schema : withOpaque(schema, opaque), input, entityType, operation, errorOperation);
1699
1744
  const readBack = readBacks.size === 0
1700
1745
  ? encoded
1701
1746
  : encoded.pipe(Effect.tap((value) => refuseNotReadBack(value, operation)));
1702
1747
  const reads = operation === "append" ? kindReads().append : kindReads().model;
1703
- return reads.size === 0
1748
+ const checked = reads.size === 0
1704
1749
  ? readBack
1705
1750
  : readBack.pipe(Effect.tap((value) => refuseOtherKindRead(value, operation, reads)));
1751
+ return inputFields === undefined
1752
+ ? checked
1753
+ : Effect.map(checked, (out) => OffloadInput.carry(input, out, inputFields.binary));
1706
1754
  };
1707
1755
  /**
1708
1756
  * An update's operand that wouldn't read back. An operand of `.add`, `.subtract` or `.deleteFromSet`
@@ -2475,7 +2523,19 @@ const makeImpl = (config, precomputedData) => {
2475
2523
  // Read twice, as 1.40.0 read it.
2476
2524
  if (given(record, field) === undefined)
2477
2525
  continue;
2478
- const encoded = encodePathValue([field], given(record, field), "value");
2526
+ const restated = given(record, field);
2527
+ // A binary input's placeholder (#179, design §3.8): a stream's content
2528
+ // is not in hand without consuming it; a handle's is its checksum.
2529
+ const prepared = OffloadInput.preparedOf(restated);
2530
+ if (prepared?._tag === "Stream") {
2531
+ return (`[EDD-9120] Entity "${entityType}": .set() of immutable binary field "${field}" ` +
2532
+ "restates it with a Stream, whose content cannot be compared with the stored value " +
2533
+ "without consuming it. Restate it with its bytes or a BlobHandle, or leave it out.");
2534
+ }
2535
+ const handle = prepared?._tag === "Handle" ? prepared.handle : undefined;
2536
+ const encoded = handle === undefined
2537
+ ? encodePathValue([field], restated, "value")
2538
+ : { encoded: restated, issue: undefined };
2479
2539
  if (encoded.issue !== undefined) {
2480
2540
  return `.set() of immutable "${field}": ${String(encoded.issue)}`;
2481
2541
  }
@@ -2488,26 +2548,73 @@ const makeImpl = (config, precomputedData) => {
2488
2548
  value: toAttributeValue(encoded.encoded),
2489
2549
  wire: encoded.encoded,
2490
2550
  packed: Object.hasOwn(packedFields, field),
2551
+ offloaded: Object.hasOwn(data.overflowFields, field)
2552
+ ? "overflow"
2553
+ : Object.hasOwn(data.externalFields, field)
2554
+ ? "binary"
2555
+ : undefined,
2556
+ handle,
2491
2557
  });
2492
2558
  }
2493
2559
  return out;
2494
2560
  };
2495
2561
  const immutableChangedMessage = (field) => `.set() of "${field}": "${field}" is immutable and the update's value ` +
2496
2562
  "differs from the stored one.";
2497
- /** A restated immutable value that differs from the stored item's (packed fields excepted). */
2563
+ /** A restated immutable value that differs from the stored item's (packed and offloaded fields excepted). */
2498
2564
  const immutableMismatch = (asserted, stored) => {
2499
- const changed = asserted.find(({ attr, value, packed }) => !packed &&
2565
+ const changed = asserted.find(({ attr, value, packed, offloaded }) => !packed &&
2566
+ offloaded === undefined &&
2500
2567
  !attributeValueEquals(ownValue(stored, attr), value));
2501
2568
  return changed === undefined ? undefined : immutableChangedMessage(changed.field);
2502
2569
  };
2503
2570
  /**
2504
- * A restated immutable PACKED value that differs from the stored item's,
2505
- * compared by the stored value's unpacked JSON (#147) — whatever codec or
2506
- * threshold it was written under.
2571
+ * Whether a restated immutable OFFLOADED value matches the pointer stored
2572
+ * for it (#179, design §6.5): by content checksum and size first — a match
2573
+ * passes — then, for an overflow value whose checksum differs, by fetching
2574
+ * the stored JSON and comparing structurally (key order aside), as a packed
2575
+ * value is compared. A binary value whose checksum or size differs is
2576
+ * different bytes: no fetch can make it equal. `undefined` when the stored
2577
+ * value is not a pointer (it is compared inline).
2578
+ */
2579
+ const offloadedImmutableMatches = (asserted, storedValue) => Effect.gen(function* () {
2580
+ if (offloadInfo === undefined || asserted.offloaded === undefined)
2581
+ return undefined;
2582
+ const raw = fromAttributeMap({ [asserted.attr]: storedValue });
2583
+ const pointer = OffloadWrite.pointerOf(offloadInfo, asserted.attr, raw[asserted.attr]);
2584
+ if (pointer === undefined)
2585
+ return undefined;
2586
+ if (asserted.offloaded === "binary") {
2587
+ if (asserted.handle !== undefined) {
2588
+ return OffloadWrite.matchesChecksum(pointer, asserted.handle.checksum, asserted.handle.size);
2589
+ }
2590
+ return (asserted.wire instanceof Uint8Array && OffloadWrite.matchesPointer(pointer, asserted.wire));
2591
+ }
2592
+ let text;
2593
+ try {
2594
+ text = stringifyStrict(asserted.wire, asserted.field);
2595
+ }
2596
+ catch {
2597
+ return false;
2598
+ }
2599
+ if (OffloadWrite.matchesPointer(pointer, text))
2600
+ return true;
2601
+ yield* loadRow(raw, {
2602
+ operation: "update.immutable",
2603
+ modes: OffloadRead.EAGER_MODES,
2604
+ raw: true,
2605
+ });
2606
+ return attributeValueEquals(toAttributeValue(raw[asserted.attr]), toAttributeValue(asserted.wire));
2607
+ });
2608
+ /**
2609
+ * A restated immutable PACKED or OFFLOADED value that differs from the
2610
+ * stored item's, compared by the stored value's unpacked JSON (#147) —
2611
+ * whatever codec or threshold it was written under — or, for a pointer, by
2612
+ * {@link offloadedImmutableMatches}.
2507
2613
  */
2508
2614
  const packedImmutableMismatch = (asserted, stored) => Effect.gen(function* () {
2509
- for (const { field, attr, wire, packed } of asserted) {
2510
- if (!packed)
2615
+ for (const immutable of asserted) {
2616
+ const { field, attr, wire, value, packed, offloaded } = immutable;
2617
+ if (!packed && offloaded === undefined)
2511
2618
  continue;
2512
2619
  const storedValue = ownValue(stored, attr);
2513
2620
  if (storedValue === undefined) {
@@ -2515,8 +2622,30 @@ const makeImpl = (config, precomputedData) => {
2515
2622
  continue;
2516
2623
  return immutableChangedMessage(field);
2517
2624
  }
2625
+ const viaPointer = yield* offloadedImmutableMatches(immutable, storedValue);
2626
+ if (viaPointer !== undefined) {
2627
+ if (!viaPointer)
2628
+ return immutableChangedMessage(field);
2629
+ continue;
2630
+ }
2631
+ if (!packed) {
2632
+ // A binary value stored natively (before the field was `External`);
2633
+ // a handle restating it compares by checksum and size.
2634
+ const { handle } = immutable;
2635
+ const same = handle === undefined
2636
+ ? attributeValueEquals(storedValue, value)
2637
+ : storedValue.B !== undefined &&
2638
+ OffloadWrite.bytesMatch(storedValue.B, handle.checksum, handle.size);
2639
+ if (!same)
2640
+ return immutableChangedMessage(field);
2641
+ continue;
2642
+ }
2518
2643
  const raw = fromAttributeMap({ [attr]: storedValue });
2519
- yield* unpackFields(raw, "update.decode");
2644
+ yield* loadRow(raw, {
2645
+ operation: "update.decode",
2646
+ modes: OffloadRead.EAGER_MODES,
2647
+ raw: true,
2648
+ });
2520
2649
  if (!attributeValueEquals(toAttributeValue(raw[attr]), toAttributeValue(wire))) {
2521
2650
  return immutableChangedMessage(field);
2522
2651
  }
@@ -2626,25 +2755,224 @@ const makeImpl = (config, precomputedData) => {
2626
2755
  const unpackFields = (raw, operation = "decode") => dispatchAttributes.length === 0
2627
2756
  ? Effect.void
2628
2757
  : unpackRow(raw, dispatchAttributes, { entityType, operation });
2758
+ // ---------------------------------------------------------------------------
2759
+ // Offloaded fields (#179) — `Packed({ external })` (overflow) and `External`
2760
+ // (binary): see `docs/designs/blob-offload.md` §6. Routing and uploads run
2761
+ // on the packed, stored-name item, just before marshalling; write results
2762
+ // resolve the pointers the write stored (its own uploads from the ledger's
2763
+ // read cache).
2764
+ // ---------------------------------------------------------------------------
2765
+ const offloadInfo = data.offload === undefined
2766
+ ? undefined
2767
+ : {
2768
+ entityType,
2769
+ overflow: Object.fromEntries(Object.entries(data.overflowFields).map(([field, storedAs]) => [
2770
+ resolveDbName(field),
2771
+ storedAs,
2772
+ ])),
2773
+ binary: Object.fromEntries(Object.entries(data.externalFields).map(([field, storedAs]) => [
2774
+ resolveDbName(field),
2775
+ storedAs,
2776
+ ])),
2777
+ fieldOf: Object.fromEntries([...Object.keys(data.overflowFields), ...Object.keys(data.externalFields)].map((field) => [resolveDbName(field), field])),
2778
+ itemBudget: data.offload.itemBudget,
2779
+ prefix: data.offload.prefix,
2780
+ copiesPointers: (typeof config.versioned === "object" &&
2781
+ config.versioned !== null &&
2782
+ config.versioned.retain === true) ||
2783
+ config.softDelete === true ||
2784
+ (typeof config.softDelete === "object" && config.softDelete !== null) ||
2785
+ config.timeSeries !== undefined,
2786
+ };
2787
+ /** The stored names of the offloaded attributes (empty when the entity offloads nothing). */
2788
+ const offloadedAttributeNames = offloadInfo === undefined ? [] : OffloadWrite.offloadedAttributes(offloadInfo);
2789
+ /** Domain name → `External` config of every binary field. */
2790
+ const binaryFields = data.externalFields;
2791
+ /**
2792
+ * The offloaded fields a write input may hold a stream, handle or source on
2793
+ * (#179, design §3.8): `undefined` when the entity offloads nothing.
2794
+ */
2795
+ const inputFields = offloadInfo === undefined
2796
+ ? undefined
2797
+ : {
2798
+ entityType,
2799
+ binary: Object.keys(data.externalFields),
2800
+ overflow: Object.keys(data.overflowFields),
2801
+ };
2802
+ /**
2803
+ * A write input with every binary input that is not a `Uint8Array` (a
2804
+ * stream, a handle, `Offload.source(...)`) replaced by its placeholder, and
2805
+ * an unusable one refused (`[EDD-9120]`). Idempotent; the input itself when
2806
+ * the entity has no offloaded field.
2807
+ */
2808
+ const prepareInput = (input, operation) => inputFields === undefined
2809
+ ? Effect.succeed(input)
2810
+ : OffloadInput.prepare(input, inputFields, operation);
2811
+ /** `schema` with each of `opaque` (fields holding a stream's or handle's placeholder) left unchecked. */
2812
+ const opaqueVariants = new Map();
2813
+ const withOpaque = (schema, opaque) => {
2814
+ const fields = schema.fields;
2815
+ if (fields === undefined)
2816
+ return schema;
2817
+ let variants = opaqueVariants.get(schema);
2818
+ if (variants === undefined) {
2819
+ variants = new Map();
2820
+ opaqueVariants.set(schema, variants);
2821
+ }
2822
+ const id = opaque.join("\u0000");
2823
+ let variant = variants.get(id);
2824
+ if (variant === undefined) {
2825
+ variant = Schema.Struct({
2826
+ ...fields,
2827
+ ...Object.fromEntries(opaque.map((field) => [field, Schema.Unknown])),
2828
+ });
2829
+ variants.set(id, variant);
2830
+ }
2831
+ return variant;
2832
+ };
2833
+ /** The row of a stored-name item an operation's uploads are for (its live key). */
2834
+ const offloadRow = (item, table, operation) => OffloadWrite.rowOf(item, {
2835
+ table,
2836
+ pkAttribute: config.indexes.primary.pk.field,
2837
+ skAttribute: config.indexes.primary.sk.field,
2838
+ operation: `Entity.${operation}`,
2839
+ escapeKeys: schema.escapeKeys === true,
2840
+ });
2841
+ /**
2842
+ * Route and upload, in place, the offloaded attributes of a packed,
2843
+ * stored-name item (design §6.3): `only` restricts it to the attributes the
2844
+ * write names (a read-merge update), the rest keep what they hold.
2845
+ */
2846
+ const offloadItem = (item, table, operation, only) => offloadInfo === undefined
2847
+ ? Effect.succeed(new Set())
2848
+ : Effect.map(OffloadWrite.route(offloadInfo, item, offloadRow(item, table, operation), only), (routed) => routed.uploaded);
2849
+ /** `_offloadItem`: {@link offloadItem} of an item another entry point built, under its own name. */
2850
+ const offloadBuiltItem = (item, table, operation, reuse) => {
2851
+ if (offloadInfo === undefined)
2852
+ return Effect.succeed(OffloadWrite.NO_PINS);
2853
+ const info = offloadInfo;
2854
+ const row = OffloadWrite.rowOf(item, {
2855
+ table,
2856
+ pkAttribute: config.indexes.primary.pk.field,
2857
+ skAttribute: config.indexes.primary.sk.field,
2858
+ operation,
2859
+ escapeKeys: schema.escapeKeys === true,
2860
+ });
2861
+ return Effect.flatMap(reuse === undefined
2862
+ ? Effect.succeed(OffloadWrite.NO_PINS)
2863
+ : OffloadWrite.reuse(info, item, reuse, operation), (pins) => Effect.as(OffloadWrite.route(info, item, row), pins));
2864
+ };
2865
+ /**
2866
+ * The pins of a put that reuses its read row's pointers (`opts.reuse`,
2867
+ * §6.11), the reused values now holding them — none for any other put.
2868
+ */
2869
+ const reusePointers = (item, reuse, operation) => offloadInfo === undefined || reuse === undefined
2870
+ ? Effect.succeed(OffloadWrite.NO_PINS)
2871
+ : OffloadWrite.reuse(offloadInfo, item, reuse, `Entity.${operation}`);
2872
+ // ---------------------------------------------------------------------------
2873
+ // Reads (#179, design §8): the two-phase decode. `loadRows` unpacks every
2874
+ // stored-form attribute (a pointer becoming a placeholder) and resolves the
2875
+ // batch's placeholders per the read's modes; the read schemas then accept a
2876
+ // lazily read field's handle (`OffloadRead.lazyReadSchema`).
2877
+ // ---------------------------------------------------------------------------
2878
+ /** The domain fields this entity offloads, by kind. */
2879
+ const offloadedByKind = {
2880
+ overflow: Object.keys(data.overflowFields),
2881
+ binary: Object.keys(data.externalFields),
2882
+ };
2883
+ const fieldDecoders = new Map();
2884
+ const decodeOffloadedField = (field, wire, operation) => {
2885
+ let decode = fieldDecoders.get(field);
2886
+ if (decode === undefined) {
2887
+ const schema = readFieldSchemas[field];
2888
+ const inner = schema === undefined ? undefined : (optionalField(schema)?.inner ?? schema);
2889
+ decode =
2890
+ inner === undefined
2891
+ ? (value) => Effect.succeed(value)
2892
+ : Schema.decodeUnknownEffect(inner);
2893
+ fieldDecoders.set(field, decode);
2894
+ }
2895
+ return decode(wire).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation, cause })));
2896
+ };
2897
+ const readPlan = {
2898
+ entityType,
2899
+ dispatch: dispatchAttributes,
2900
+ // Every attribute whose encoded side is bytes, `External` or not (§4.7).
2901
+ binary: Object.entries(data.modelFields)
2902
+ .filter(([field, schema]) => !Object.hasOwn(sparseFields, field) && binaryShapeRefusal(schema) === undefined)
2903
+ .map(([field]) => resolveDbName(field)),
2904
+ offloaded: Object.fromEntries([
2905
+ ...offloadedByKind.overflow.map((field) => [resolveDbName(field), "overflow"]),
2906
+ ...offloadedByKind.binary.map((field) => [resolveDbName(field), "binary"]),
2907
+ ]),
2908
+ fieldOf: Object.fromEntries(Object.keys(data.modelFields).map((field) => [resolveDbName(field), field])),
2909
+ contentTypeOf: Object.fromEntries(Object.entries(binaryFields).map(([field, storedAs]) => [
2910
+ resolveDbName(field),
2911
+ storedAs.contentType,
2912
+ ])),
2913
+ decodeField: decodeOffloadedField,
2914
+ };
2915
+ /** The attributes a raw read rewrites: a projection naming none runs no hook. */
2916
+ const readAttributeNames = OffloadRead.readAttributes(readPlan);
2917
+ /** Unpack and resolve, in place, a batch of stored-name rows (see `OffloadRead.loadRows`). */
2918
+ const loadRows = (rows, options) => OffloadRead.loadRows(readPlan, rows, options);
2919
+ /** {@link loadRows} of one row. */
2920
+ const loadRow = (raw, options) => loadRows([raw], options);
2921
+ /**
2922
+ * The read schema `base` under `modes`: each lazily read offloaded field
2923
+ * accepts its handle. `base` itself when no field is lazy.
2924
+ */
2925
+ const readSchema = (base, modes) => offloadInfo === undefined
2926
+ ? base
2927
+ : OffloadRead.lazyReadSchema(base, OffloadRead.lazyFields(offloadedByKind, modes));
2928
+ /** True iff a read under `modes` holds a handle on some field. */
2929
+ const readsLazily = (modes) => offloadInfo !== undefined &&
2930
+ ((modes.overflow === "lazy" && offloadedByKind.overflow.length > 0) ||
2931
+ (modes.binary === "lazy" && offloadedByKind.binary.length > 0));
2932
+ /**
2933
+ * Drop, from a stored-name copy of a row, every offloaded attribute whose
2934
+ * field is not in `keep` (#179): the vector paths read source fields only,
2935
+ * so loading the copy fetches no other offloaded value — a large binary
2936
+ * beside the text is never downloaded to re-embed it.
2937
+ */
2938
+ const keepOffloaded = (stored, keep) => {
2939
+ if (offloadInfo === undefined)
2940
+ return;
2941
+ for (const attribute of offloadedAttributeNames) {
2942
+ if (!keep.has(offloadInfo.fieldOf[attribute] ?? attribute))
2943
+ delete stored[attribute];
2944
+ }
2945
+ };
2629
2946
  /**
2630
2947
  * A domain-named copy of `record` with its packed (or once-packed) attributes
2631
2948
  * read by their stored form. The update paths derive vector source text from
2632
2949
  * it: an untouched packed field still holds its stored value there (a JSON
2633
- * string or compressed bytes), not the value the source `compose` expects.
2634
- * `record` itself is left as is, so the write still carries the stored bytes.
2635
- */
2636
- const unpackedDomainCopy = (record, operation) => {
2637
- if (dispatchAttributes.length === 0)
2950
+ * string or compressed bytes), not the value the source `compose` expects —
2951
+ * and an untouched offloaded one its pointer, resolved here eagerly (one GET
2952
+ * per pointer, design §6.5) when it is one of `sources`; any other offloaded
2953
+ * field is left out of the copy. `record` itself is left as is, so the
2954
+ * write still carries the stored bytes.
2955
+ */
2956
+ const unpackedDomainCopy = (record, operation, sources) => {
2957
+ if (OffloadRead.isEmptyPlan(readPlan))
2638
2958
  return Effect.succeed(record);
2639
2959
  const stored = { ...record };
2640
2960
  renameToDynamo(stored);
2641
- return Effect.map(unpackFields(stored, operation), () => {
2961
+ keepOffloaded(stored, sources);
2962
+ return Effect.map(loadRow(stored, { operation, modes: OffloadRead.EAGER_MODES, raw: true }), () => {
2642
2963
  renameFromDynamo(stored);
2643
2964
  return stored;
2644
2965
  });
2645
2966
  };
2646
- /** The packed attributes an expression or projection may not look inside (EDD-9076). */
2647
- const packedGuards = Object.entries(packedFields).flatMap(([field, storedAs]) => {
2967
+ /**
2968
+ * The packed and External attributes an expression or projection may not
2969
+ * look inside (EDD-9076): a binary field's stored value is a pointer (#179),
2970
+ * as opaque to DynamoDB as packed JSON.
2971
+ */
2972
+ const packedGuards = [
2973
+ ...Object.entries(packedFields),
2974
+ ...Object.entries(binaryFields),
2975
+ ].flatMap(([field, storedAs]) => {
2648
2976
  const guard = (attribute) => ({
2649
2977
  attribute,
2650
2978
  owner: `Entity "${entityType}"`,
@@ -2663,14 +2991,23 @@ const makeImpl = (config, precomputedData) => {
2663
2991
  throw new Error(refused);
2664
2992
  };
2665
2993
  /**
2666
- * The `Query.make` options of this entity's queries: the packed guards, and
2667
- * the raw-row hook that reads packed attributes of a projected row of THIS
2668
- * entity type by their stored form (parsed JSON, not schema-decoded) — rows
2669
- * of other types (`ignoreOwnership()`) are left untouched.
2994
+ * The `Query.make` options of this entity's queries: the packed guards, the
2995
+ * raw-row hook that reads packed attributes of a projected row of THIS
2996
+ * entity type by their stored form (parsed JSON, not schema-decoded) and
2997
+ * resolves its blob pointers per the query's modes — rows of other types
2998
+ * (`ignoreOwnership()`) are left untouched — and the page prefetch that
2999
+ * loads a window of rows together (#179, design §8.2).
2670
3000
  */
2671
3001
  const packedQueryOptions = {
2672
3002
  packed: packedGuards,
2673
- rawRow: ownRowsRawRow(entityType, dispatchAttributes, (raw) => unpackFields(raw)),
3003
+ rawRow: ownRowsRawRow(entityType, readAttributeNames, (raw, modes) => loadRow(raw, { operation: "query.select", modes, raw: true })),
3004
+ prefetch: OffloadRead.isEmptyPlan(readPlan)
3005
+ ? undefined
3006
+ : (rows, { modes, raw, operation }) => loadRows(raw ? rows.filter((row) => row.__edd_e__ === entityType) : rows, {
3007
+ operation,
3008
+ modes,
3009
+ raw,
3010
+ }),
2674
3011
  };
2675
3012
  /**
2676
3013
  * `[EDD-9077]`: an update applies anything but a whole-value `.set()` /
@@ -2678,12 +3015,16 @@ const makeImpl = (config, precomputedData) => {
2678
3015
  * value. `undefined` when the update is fine.
2679
3016
  */
2680
3017
  const refusedPackedUpdate = (uState) => {
2681
- if (!hasPackedFields)
3018
+ if (!hasPackedFields && Object.keys(binaryFields).length === 0)
2682
3019
  return undefined;
2683
- const refuse = (op, field) => `[EDD-9077] Entity "${entityType}": ${op} on "${field}", but "${field}" is stored packed ` +
2684
- `(format "${packedFields[field].format}"): DynamoDB holds it as one opaque string or ` +
2685
- `binary value and cannot apply ${op} inside it. Write the whole value with ` +
2686
- `.set({ ${field} }) (or .remove(["${field}"])).`;
3020
+ const guarded = (field) => field in packedFields || Object.hasOwn(binaryFields, field);
3021
+ const refuse = (op, field) => `[EDD-9077] Entity "${entityType}": ${op} on "${field}", but "${field}" is stored ` +
3022
+ (field in packedFields
3023
+ ? `packed (format "${packedFields[field].format}")`
3024
+ : `External (content type "${binaryFields[field].contentType}", in the blob store)`) +
3025
+ ": DynamoDB holds it as one opaque string or binary value " +
3026
+ `and cannot apply ${op} inside it. Write the whole value with .set({ ${field} }) ` +
3027
+ `(or .remove(["${field}"])).`;
2687
3028
  const records = [
2688
3029
  [".add()", uState.add],
2689
3030
  [".subtract()", uState.subtract],
@@ -2692,7 +3033,7 @@ const makeImpl = (config, precomputedData) => {
2692
3033
  ];
2693
3034
  for (const [op, values] of records) {
2694
3035
  for (const field of Object.keys(values ?? {})) {
2695
- if (Object.hasOwn(packedFields, field))
3036
+ if (guarded(field))
2696
3037
  return refuse(op, field);
2697
3038
  }
2698
3039
  }
@@ -2711,16 +3052,40 @@ const makeImpl = (config, precomputedData) => {
2711
3052
  const head = segments[0];
2712
3053
  if (typeof head !== "string" || entryOfPath(segments) !== undefined)
2713
3054
  continue;
2714
- if (Object.hasOwn(packedFields, head))
3055
+ if (guarded(head))
2715
3056
  return refuse(op, head);
2716
3057
  }
2717
3058
  }
3059
+ // A copy FROM a packed or External field would put its opaque stored value (a packed string,
3060
+ // or a blob pointer the collector never looks for there) into another attribute.
3061
+ const copies = [
3062
+ ["pathSet", uState.pathSets ?? []],
3063
+ ["pathSubtract", uState.pathSubtracts ?? []],
3064
+ ];
3065
+ for (const [op, ops] of copies) {
3066
+ for (const copy of ops) {
3067
+ if (!isCopy(copy))
3068
+ continue;
3069
+ const source = copy.valueSegments;
3070
+ const head = source[0];
3071
+ if (typeof head !== "string" || entryOfPath(source) !== undefined)
3072
+ continue;
3073
+ if (guarded(head)) {
3074
+ return (`[EDD-9077] Entity "${entityType}": ${op} copies from "${head}", but "${head}" is stored ` +
3075
+ (head in packedFields
3076
+ ? `packed (format "${packedFields[head].format}")`
3077
+ : `External (content type "${binaryFields[head].contentType}", in the blob store)`) +
3078
+ ": DynamoDB holds it as one opaque string or binary value, so a copy would put that " +
3079
+ `stored form in another attribute. Read the value and write it with .set().`);
3080
+ }
3081
+ }
3082
+ }
2718
3083
  for (const { field } of uState.sparseRemoveEntries ?? []) {
2719
- if (Object.hasOwn(packedFields, field))
3084
+ if (guarded(field))
2720
3085
  return refuse(".removeEntries()", field);
2721
3086
  }
2722
3087
  for (const field of uState.sparseClearFields ?? []) {
2723
- if (Object.hasOwn(packedFields, field))
3088
+ if (guarded(field))
2724
3089
  return refuse(".clearMap()", field);
2725
3090
  }
2726
3091
  return undefined;
@@ -3433,29 +3798,69 @@ const makeImpl = (config, precomputedData) => {
3433
3798
  ? undefined
3434
3799
  : issueDecoding(Schema.Struct({ [field]: Schema.Never }), {});
3435
3800
  }, (cause) => new ValidationError({ entityType, operation, cause }));
3436
- const decodeRecord = (raw) => {
3801
+ /**
3802
+ * Decode a stored-name row as a record (`Entity.Record`, under `modes`):
3803
+ * the full read pipeline — load (unpack + resolve, unless a query's page
3804
+ * prefetch already did), sparse rebuild, renames, schema decode. Queries,
3805
+ * collections, `Batch.get` and `transactGet` pass their modes; a caller
3806
+ * that passes none reads eagerly (internal callers whose results are typed
3807
+ * as the domain model).
3808
+ */
3809
+ const decodeRecord = (raw, modes = OffloadRead.EAGER_MODES, operation = "decode") => {
3437
3810
  const corruption = versionCorruption(raw, "decode");
3438
3811
  if (corruption !== undefined)
3439
3812
  return Effect.fail(corruption);
3440
- return Effect.flatMap(unpackFields(raw), () => {
3813
+ return Effect.flatMap(loadRow(raw, { operation, modes }), () => {
3441
3814
  deserializeSparseFields(raw);
3442
3815
  renameFromDynamo(raw);
3443
- return Schema.decodeUnknownEffect(schemas.recordSchema)(raw).pipe(Effect.map(attachPrototype), Effect.mapError((cause) => new ValidationError({
3816
+ return Schema.decodeUnknownEffect(readSchema(schemas.recordSchema, modes))(raw).pipe(Effect.map(attachPrototype), Effect.mapError((cause) => new ValidationError({
3444
3817
  entityType,
3445
3818
  operation: "decode",
3446
3819
  cause,
3447
3820
  })), missingKeyOnDefect(raw, "decode"));
3448
3821
  });
3449
3822
  };
3450
- /** Decode a raw item using the schema selected by mode */
3451
- const decodeAs = (raw, marshalled, mode) => {
3823
+ /**
3824
+ * Decode a raw item using the schema selected by mode, under the running
3825
+ * operation's read modes — or `load`'s: an error payload decodes with
3826
+ * `noFetch` (lazy handles, no store I/O, §6.13).
3827
+ */
3828
+ const decodeAs = (raw, marshalled, mode, load) => {
3452
3829
  const corruption = versionCorruption(raw, "decode");
3453
3830
  if (corruption !== undefined)
3454
3831
  return Effect.fail(corruption);
3455
- // Native: the item as stored — packed values stay their `S` / `B`.
3832
+ // Native: the item as stored — packed values stay their `S` / `B`, and an
3833
+ // offloaded one its pointer.
3456
3834
  if (mode === "native")
3457
3835
  return Effect.succeed(marshalled);
3458
- return Effect.flatMap(unpackFields(raw), () => {
3836
+ if (load?.noFetch === true) {
3837
+ return decodeStored(raw, mode, {
3838
+ operation: "decode",
3839
+ modes: OffloadRead.LAZY_MODES,
3840
+ noFetch: true,
3841
+ });
3842
+ }
3843
+ return Effect.flatMap(OffloadRead.currentModes, (modes) => decodeStored(raw, mode, { operation: "decode", modes }));
3844
+ };
3845
+ /**
3846
+ * {@link decodeAs} of a write's result (#179, design §6.13): its pointers
3847
+ * resolve per the operation's modes — what `operation` uploaded from the
3848
+ * ledger's read cache (no GET), anything else fetched — and a store failure
3849
+ * is `BlobStoreError { committed: true }`. Exactly `decodeAs` for an entity
3850
+ * that offloads nothing.
3851
+ */
3852
+ const decodeWritten = (raw, marshalled, mode, operation) => {
3853
+ if (offloadInfo === undefined || mode === "native")
3854
+ return decodeAs(raw, marshalled, mode);
3855
+ const corruption = versionCorruption(raw, "decode");
3856
+ if (corruption !== undefined)
3857
+ return Effect.fail(corruption);
3858
+ return Effect.flatMap(OffloadRead.currentModes, (modes) => decodeStored(raw, mode, { operation: `${operation}.decode`, modes, committed: true }));
3859
+ };
3860
+ /** {@link decodeAs} of a stored-name row: load it per `load`, then decode it. */
3861
+ const decodeStored = (raw, mode, load) => {
3862
+ const modes = load.noFetch === true ? OffloadRead.LAZY_MODES : load.modes;
3863
+ return Effect.flatMap(loadRow(raw, load), () => {
3459
3864
  // Collect flattened sparse-map attributes back into the domain Record.
3460
3865
  // Must happen before rename so the rebuilt Record sits at the domain field
3461
3866
  // name (sparse field renaming is not supported).
@@ -3468,7 +3873,14 @@ const makeImpl = (config, precomputedData) => {
3468
3873
  : mode === "record"
3469
3874
  ? schemas.recordSchema
3470
3875
  : schemas.itemSchema;
3471
- return Schema.decodeUnknownEffect(targetSchema)(raw).pipe(Effect.map((decoded) => mode === "model" && isSchemaClass && !hasHiddenFields && !refsHoldLess
3876
+ // A model holding handles is not the class's value: its constructor
3877
+ // would validate the handle against the domain field.
3878
+ const construct = mode === "model" &&
3879
+ isSchemaClass &&
3880
+ !hasHiddenFields &&
3881
+ !refsHoldLess &&
3882
+ !readsLazily(modes);
3883
+ return Schema.decodeUnknownEffect(readSchema(targetSchema, modes))(raw).pipe(Effect.map((decoded) => construct
3472
3884
  ? new rawModel(decoded)
3473
3885
  : mode !== "item"
3474
3886
  ? attachPrototype(decoded)
@@ -3482,23 +3894,124 @@ const makeImpl = (config, precomputedData) => {
3482
3894
  /**
3483
3895
  * Decode a DynamoDB Streams image into an item record (`Entity.Item`): the
3484
3896
  * image normalised (DynamoDB JSON or unmarshalled; `B` as bytes or base64),
3485
- * its dispatch-eligible attributes read by stored form, then sparse rebuild,
3897
+ * loaded — its stored-form attributes unpacked and its pointers resolved
3898
+ * per `modes` (lazy by default, design §10.1) — then sparse rebuild,
3486
3899
  * renames and the item-schema decode — exactly what a table read applies.
3900
+ * `operation` names the decode in errors (a lazy value's reads name
3901
+ * `<operation>.read`, design §8.7).
3487
3902
  */
3488
- const decodeImageItem = (image) => Effect.gen(function* () {
3903
+ const decodeImageItem = (image, modes = OffloadRead.LAZY_MODES, operation = "decodeMarshalledItem") => Effect.gen(function* () {
3904
+ const ctx = { entityType, operation };
3905
+ const options = { probe: config.indexes.primary.pk.field };
3489
3906
  // An image of another entity type is decoded as 1.25.0 decoded it: its
3490
3907
  // attributes are never read as packed values (a plain string of that
3491
3908
  // type is not this entity's JSON). The type is read off the raw image.
3492
3909
  const owner = imageEntityType(image);
3493
- const raw = yield* decodeImage(image, owner === undefined || owner === entityType ? dispatchAttributes : [], { entityType, operation: "decodeMarshalledItem" }, { probe: config.indexes.primary.pk.field });
3494
- const corruption = versionCorruption(raw, "decodeMarshalledItem");
3910
+ const form = imageForm(image, options);
3911
+ const raw = yield* normalizeImage(image, ctx, { ...options, form });
3912
+ if (owner === undefined || owner === entityType) {
3913
+ // Unmarshalled, a `B` value may still be base64 text.
3914
+ yield* loadRow(raw, { operation, modes, image: form === "unmarshalled" });
3915
+ }
3916
+ const corruption = versionCorruption(raw, operation);
3495
3917
  if (corruption !== undefined)
3496
3918
  return yield* corruption;
3497
3919
  deserializeSparseFields(raw);
3498
3920
  renameFromDynamo(raw);
3499
- const decoded = yield* Schema.decodeUnknownEffect(schemas.itemSchema)(raw).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation: "decodeMarshalledItem", cause })), missingKeyOnDefect(raw, "decodeMarshalledItem"));
3921
+ const decoded = yield* Schema.decodeUnknownEffect(readSchema(schemas.itemSchema, modes))(raw).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation, cause })), missingKeyOnDefect(raw, operation));
3500
3922
  return attachPrototype(decoded);
3501
3923
  });
3924
+ /**
3925
+ * Decode a DynamoDB Streams record of this entity type (#179, design §10.3,
3926
+ * §10.4) — the implementation of {@link decodeStreamRecord}: `[EDD-9119]`
3927
+ * unless it carries the images of a `NEW_AND_OLD_IMAGES` stream (checked
3928
+ * for every record, before its type), `Option.none()` when no image is of
3929
+ * this type, else each image of this type decoded per `modes` (as
3930
+ * {@link decodeImageItem}) and every offloaded field present in either
3931
+ * classified from the two stored forms (`OffloadChange.compareForms`),
3932
+ * with no store I/O. An image of another type counts as absent.
3933
+ */
3934
+ const decodeChange = (record, modes) => Effect.gen(function* () {
3935
+ const operation = "decodeStreamRecord";
3936
+ const ctx = { entityType, operation };
3937
+ const images = OffloadChange.recordImages(record, "Entity.decodeStreamRecord");
3938
+ if (typeof images === "string") {
3939
+ return yield* new ValidationError({ ...ctx, cause: new Error(images) });
3940
+ }
3941
+ const own = (image) => image !== undefined && imageEntityType(image) === entityType
3942
+ ? image
3943
+ : undefined;
3944
+ const oldImage = own(images.oldImage);
3945
+ const newImage = own(images.newImage);
3946
+ if (oldImage === undefined && newImage === undefined) {
3947
+ return Option.none();
3948
+ }
3949
+ const decode = (image) => image === undefined
3950
+ ? Effect.succeed(Option.none())
3951
+ : Effect.map(decodeImageItem(image, modes, operation), Option.some);
3952
+ const oldItem = yield* decode(oldImage);
3953
+ const newItem = yield* decode(newImage);
3954
+ const offloaded = yield* classifyOffloaded(oldImage, newImage, ctx);
3955
+ return Option.some({ eventName: images.eventName, oldItem, newItem, offloaded });
3956
+ });
3957
+ /**
3958
+ * Every offloaded field present in `oldImage` or `newImage`, by domain name,
3959
+ * classified from its stored forms — read off the raw images, before any
3960
+ * decode, with no store I/O (an inline compressed value is decompressed with
3961
+ * the registry in scope to checksum its content). Empty when the entity
3962
+ * offloads nothing.
3963
+ */
3964
+ const classifyOffloaded = (oldImage, newImage, ctx) => offloadInfo === undefined
3965
+ ? Effect.succeed({})
3966
+ : withRegistry((registry) => {
3967
+ const probe = { probe: config.indexes.primary.pk.field };
3968
+ const formsOf = (image) => {
3969
+ if (image === undefined)
3970
+ return undefined;
3971
+ const form = imageForm(image, probe);
3972
+ const values = image;
3973
+ return (attribute, kind) => form === "attributeValues"
3974
+ ? OffloadChange.formOfAttributeValue(values[attribute], kind, registry, ctx, attribute)
3975
+ : OffloadChange.formOfUnmarshalled(values[attribute], kind, true, toAttributeValue, registry, ctx, attribute);
3976
+ };
3977
+ const before = formsOf(oldImage);
3978
+ const after = formsOf(newImage);
3979
+ const out = {};
3980
+ for (const attribute of offloadedAttributeNames) {
3981
+ const kind = readPlan.offloaded[attribute];
3982
+ const a = before === undefined ? OffloadChange.ABSENT : before(attribute, kind);
3983
+ if (a instanceof ValidationError)
3984
+ return a;
3985
+ const b = after === undefined ? OffloadChange.ABSENT : after(attribute, kind);
3986
+ if (b instanceof ValidationError)
3987
+ return b;
3988
+ if (a._tag === "absent" && b._tag === "absent")
3989
+ continue;
3990
+ out[offloadInfo.fieldOf[attribute] ?? attribute] = OffloadChange.compareForms(a, b);
3991
+ }
3992
+ return out;
3993
+ });
3994
+ /**
3995
+ * `_loadForReuse`: an eager load that snapshots the pointers the row held
3996
+ * (§6.11), then the item decode — the item schema keeps Hidden fields, which
3997
+ * the record schema strips and the whole-row rewrite must carry.
3998
+ */
3999
+ const loadForReuse = (raw, operation) => {
4000
+ const corruption = versionCorruption(raw, operation);
4001
+ if (corruption !== undefined)
4002
+ return Effect.fail(corruption);
4003
+ // Read before the load, which replaces each pointer with its value.
4004
+ const held = offloadInfo === undefined ? [] : OffloadWrite.pointersIn(offloadInfo, raw);
4005
+ const load = { operation, modes: OffloadRead.EAGER_MODES };
4006
+ return Effect.flatMap(loadRow(raw, load), () => {
4007
+ // Snapshotted by stored name, before the decode renames the attributes;
4008
+ // the decode's own load is then a no-op.
4009
+ const pointers = offloadInfo === undefined
4010
+ ? new Map()
4011
+ : OffloadWrite.snapshotPointers(offloadInfo, held, raw);
4012
+ return Effect.map(decodeStored(raw, "item", load), (item) => ({ item, pointers }));
4013
+ });
4014
+ };
3502
4015
  const nowIso = (now) => DateTime.formatIso(now);
3503
4016
  /**
3504
4017
  * Generate a timestamp value as a wire primitive ready for marshalling.
@@ -3859,6 +4372,11 @@ const makeImpl = (config, precomputedData) => {
3859
4372
  }
3860
4373
  return { sets, removes };
3861
4374
  });
4375
+ /**
4376
+ * The source fields of `indexes` an embedding is derived from: those of the
4377
+ * indexes without an explicit vector (`withVector`), which need no text.
4378
+ */
4379
+ const embeddedSources = (indexes, withVectors) => new Set(indexes.flatMap(([logicalName, definition]) => withVectors?.[logicalName] === undefined ? definition.sourceFields : []));
3862
4380
  /**
3863
4381
  * Which vector indexes does this update require work for?
3864
4382
  *
@@ -3944,8 +4462,17 @@ const makeImpl = (config, precomputedData) => {
3944
4462
  if (current.Item) {
3945
4463
  const currentDomain = fromAttributeMap(current.Item);
3946
4464
  // Packed fields are read by their stored form: the source text is
3947
- // derived from the value, not its JSON string or compressed bytes.
3948
- yield* unpackFields(currentDomain, "update.vector");
4465
+ // derived from the value, not its JSON string or compressed bytes —
4466
+ // and an offloaded one is fetched (one GET per pointer, #179) when
4467
+ // it is a source the payload does not supply. No other offloaded
4468
+ // value is.
4469
+ const supplied = merged;
4470
+ keepOffloaded(currentDomain, new Set([...embeddedSources(needing, withVectors)].filter((f) => !(f in supplied))));
4471
+ yield* loadRow(currentDomain, {
4472
+ operation: "update.vector",
4473
+ modes: OffloadRead.EAGER_MODES,
4474
+ raw: true,
4475
+ });
3949
4476
  deserializeSparseFields(currentDomain);
3950
4477
  renameFromDynamo(currentDomain);
3951
4478
  merged = { ...currentDomain, ...merged };
@@ -4257,8 +4784,12 @@ const makeImpl = (config, precomputedData) => {
4257
4784
  delete values[key];
4258
4785
  const uniqueAttrs = Object.values(config.unique ?? {}).flatMap((def) => resolveUniqueFields(def).map(compositeAttribute));
4259
4786
  const modelAttrs = Object.keys(data.modelFields).map(resolveDbName);
4787
+ // Offloaded attributes come first (#179, design §6.4): a write carrying a
4788
+ // pointer it did not upload must be pinned to the row still holding it,
4789
+ // so a narrowed guard never drops one.
4260
4790
  const ordered = [
4261
4791
  ...new Set([
4792
+ ...offloadedAttributeNames,
4262
4793
  ...(updatedAttr !== null ? [updatedAttr] : []),
4263
4794
  ...uniqueAttrs,
4264
4795
  ...modelAttrs,
@@ -4325,12 +4856,33 @@ const makeImpl = (config, precomputedData) => {
4325
4856
  };
4326
4857
  /** The item at a key, strongly consistent: the read a read-then-write op starts with. */
4327
4858
  const readCurrent = (tableName, marshalledKey) => Effect.flatMap(Capacity.client, (client) => client.getItem({ TableName: tableName, Key: marshalledKey, ConsistentRead: true }));
4859
+ /**
4860
+ * The row an update finds at its key: `undefined` for none, and for a projection tombstone
4861
+ * (#154), a removed row that every read by key reports as absent. An update of it is an update
4862
+ * of a missing row, by every path (#132).
4863
+ */
4864
+ const liveRow = (row) => row !== undefined && isProjectionTombstone(row, entityType) ? undefined : row;
4865
+ /**
4866
+ * The condition that the row an update writes exists, under `pkName`: `attribute_exists` of its
4867
+ * partition key, and, on a read model whose rows may be projection tombstones, that it isn't one
4868
+ * (#132). The term is free when it holds, and every other entity sends what it did.
4869
+ */
4870
+ const rowExists = (names, values, pkName) => {
4871
+ names[pkName] = config.indexes.primary.pk.field;
4872
+ if (!hasProjectionTombstones(self))
4873
+ return `attribute_exists(${pkName})`;
4874
+ names["#eddLive"] = "__edd_e__";
4875
+ values[":eddTomb"] = { S: `${entityType}#tombstone` };
4876
+ return `attribute_exists(${pkName}) AND #eddLive <> :eddTomb`;
4877
+ };
4328
4878
  /** Fill a `ConcurrentModification`'s `current` with the stored item, decoded. */
4329
4879
  const withCurrentItem = (effect, stored) => effect.pipe(Effect.catchIf((e) => e instanceof ConcurrentModification, (e) => Effect.gen(function* () {
4330
4880
  const item = stored();
4331
4881
  const current = item === undefined
4332
4882
  ? Option.none()
4333
- : yield* Effect.option(decodeAs(fromAttributeMap(item), item, "model"));
4883
+ : yield* Effect.option(decodeAs(fromAttributeMap(item), item, "model",
4884
+ // An error payload: offloaded fields as lazy handles (§6.13).
4885
+ { noFetch: true }));
4334
4886
  return yield* keepReleaseRace(e, new ConcurrentModification({ ...e, current }));
4335
4887
  })));
4336
4888
  /**
@@ -4400,7 +4952,9 @@ const makeImpl = (config, precomputedData) => {
4400
4952
  * Decode only `attributes` of a stored image (`updatedOld` / `updatedNew`):
4401
4953
  * a partial — the fields present, each through its own schema.
4402
4954
  */
4403
- const decodePartial = (image, attributes, mode) => {
4955
+ const decodePartial = (image, attributes, mode,
4956
+ /** The write whose result this is: its pointers resolve (see `decodeWritten`). */
4957
+ written) => {
4404
4958
  const corruption = versionCorruption(image, "decode");
4405
4959
  if (corruption !== undefined)
4406
4960
  return Effect.fail(corruption);
@@ -4412,7 +4966,11 @@ const makeImpl = (config, precomputedData) => {
4412
4966
  if (mode === "native")
4413
4967
  return Effect.succeed(projected);
4414
4968
  const raw = fromAttributeMap(projected);
4415
- return Effect.flatMap(unpackFields(raw), () => {
4969
+ return Effect.flatMap(OffloadRead.currentModes, (modes) => Effect.flatMap(loadRow(raw, {
4970
+ operation: written === undefined ? "decode" : `${written}.decode`,
4971
+ modes,
4972
+ committed: written !== undefined,
4973
+ }), () => {
4416
4974
  deserializeSparseFields(raw);
4417
4975
  renameFromDynamo(raw);
4418
4976
  const target = mode === "model"
@@ -4420,11 +4978,11 @@ const makeImpl = (config, precomputedData) => {
4420
4978
  : mode === "record"
4421
4979
  ? schemas.recordSchema
4422
4980
  : schemas.itemSchema;
4423
- const fields = target.fields;
4981
+ const fields = readSchema(target, modes).fields;
4424
4982
  const present = Object.fromEntries(Object.entries(fields).filter(([name]) => hasOwnName(raw, name)));
4425
4983
  const presentSchema = Schema.Struct(present);
4426
4984
  return Schema.decodeUnknownEffect(presentSchema)(raw).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation: "decode", cause })));
4427
- });
4985
+ }));
4428
4986
  };
4429
4987
  /**
4430
4988
  * The value an update returns for its `returnValues` mode, from the item
@@ -4432,20 +4990,22 @@ const makeImpl = (config, precomputedData) => {
4432
4990
  * `none` → `undefined`; `allOld` / `allNew` → the whole item; `updatedOld` /
4433
4991
  * `updatedNew` → just the written attributes, decoded as a partial.
4434
4992
  */
4435
- const updateResult = (rv, old, next, written, mode, encodedKey) => {
4993
+ const updateResult = (rv, old, next, written, mode, encodedKey,
4994
+ /** The operation whose committed result this is (its pointers resolve, §6.13). */
4995
+ operation = "update") => {
4436
4996
  const landed = rv === "allOld" || rv === "updatedOld" ? "replaced" : "stored";
4437
4997
  switch (rv) {
4438
4998
  case "none":
4439
4999
  return Effect.succeed(undefined);
4440
5000
  case "updatedOld":
4441
- return appliedUpdate(decodePartial(old, written, mode), landed);
5001
+ return appliedUpdate(decodePartial(old, written, mode, operation), landed);
4442
5002
  case "updatedNew":
4443
- return appliedUpdate(decodePartial(next, written, mode), landed);
5003
+ return appliedUpdate(decodePartial(next, written, mode, operation), landed);
4444
5004
  default: {
4445
5005
  const image = rv === "allOld" ? old : next;
4446
5006
  if (image === undefined)
4447
5007
  return Effect.fail(new ItemNotFound({ entityType, key: encodedKey }));
4448
- return appliedUpdate(decodeAs(fromAttributeMap(image), image, mode), landed);
5008
+ return appliedUpdate(decodeWritten(fromAttributeMap(image), image, mode, operation), landed);
4449
5009
  }
4450
5010
  }
4451
5011
  };
@@ -4457,6 +5017,10 @@ const makeImpl = (config, precomputedData) => {
4457
5017
  * failed" as "nothing changed".
4458
5018
  */
4459
5019
  const appliedUpdate = (decoding, row) => Effect.mapError(decoding, (error) => {
5020
+ // A store failure resolving the written row's pointers (#179) is its own
5021
+ // `BlobStoreError { committed: true }`, passed through as it is.
5022
+ if (error._tag === "BlobStoreError")
5023
+ return error;
4460
5024
  const problem = decodeProblem(error.cause);
4461
5025
  return new ValidationError({
4462
5026
  entityType,
@@ -4657,6 +5221,175 @@ const makeImpl = (config, precomputedData) => {
4657
5221
  });
4658
5222
  /** The live sort key of the item at `encodedKey` (the caller's key, encoded). */
4659
5223
  const liveSkOf = (encodedKey) => KeyComposer.composeSk(schema, entityType, entityVersion, config.indexes.primary, keyForm(encodedKey));
5224
+ // ---------------------------------------------------------------------------
5225
+ // Garbage collection (#179, design §11): how `BlobGc` and `purge` read this
5226
+ // entity's item families — see `internal/GcSupport.ts`.
5227
+ // ---------------------------------------------------------------------------
5228
+ /** `EntityGcSupport.liveSkOfRow`: the live SK the row's sort-key composites compose. */
5229
+ const gcLiveSkOfRow = (row) => {
5230
+ try {
5231
+ // The whole row: a ref's id in the sort key is read from the ref it stores (`toDomainView`),
5232
+ // never from a top-level attribute the row doesn't hold.
5233
+ return liveSkOf(toDomainView(row));
5234
+ }
5235
+ catch {
5236
+ return undefined;
5237
+ }
5238
+ };
5239
+ /** `EntityGcSupport.liveSkCandidates`: the row SK, and its prefix before each event marker. */
5240
+ const gcLiveSkCandidates = (rowSk) => {
5241
+ const marker = KeyComposer.composeEventSkPrefix("", schema.casing);
5242
+ const candidates = [rowSk];
5243
+ for (let at = rowSk.indexOf(marker); at >= 0; at = rowSk.indexOf(marker, at + 1)) {
5244
+ candidates.push(rowSk.slice(0, at));
5245
+ }
5246
+ return candidates;
5247
+ };
5248
+ /** `EntityGcSupport.familyOfKey`: the partition and live SK of a caller's key. */
5249
+ const gcFamilyOfKey = (key, operation) => Effect.map(encodeKey(key, operation), (encoded) => ({
5250
+ pk: KeyComposer.composePk(schema, entityType, config.indexes.primary, keyForm(encoded)),
5251
+ liveSk: liveSkOf(encoded),
5252
+ }));
5253
+ /**
5254
+ * `EntityGcSupport.readFamily`: the item family's rows in `ranges` (design
5255
+ * §11.2), each range one strongly consistent query, classified as `purge`
5256
+ * classifies them — this entity's type, the live row and the events under
5257
+ * it, the item's own history, and unsegmented history whose composites
5258
+ * compose the item's live key. Without sort-key composites the partition
5259
+ * holds one item: its rows of this type, whatever the ranges.
5260
+ */
5261
+ const gcReadFamily = (client, tableName, family, ranges) => Effect.gen(function* () {
5262
+ const primary = config.indexes.primary;
5263
+ const rows = [];
5264
+ const read = (condition, keep) => Effect.gen(function* () {
5265
+ let start;
5266
+ do {
5267
+ const result = yield* client.query({
5268
+ TableName: tableName,
5269
+ KeyConditionExpression: condition === undefined ? "#pk = :pk" : `#pk = :pk AND ${condition.expression}`,
5270
+ ExpressionAttributeNames: condition === undefined
5271
+ ? { "#pk": primary.pk.field }
5272
+ : { "#pk": primary.pk.field, "#sk": primary.sk.field },
5273
+ ExpressionAttributeValues: { ":pk": { S: family.pk }, ...condition?.values },
5274
+ ConsistentRead: true,
5275
+ ExclusiveStartKey: start,
5276
+ });
5277
+ for (const row of (result.Items ?? [])) {
5278
+ const sk = row[primary.sk.field]?.S;
5279
+ if (row.__edd_e__?.S !== entityType || sk === undefined || !keep(row, sk))
5280
+ continue;
5281
+ rows.push(row);
5282
+ }
5283
+ start = result.LastEvaluatedKey;
5284
+ } while (start !== undefined);
5285
+ });
5286
+ if (!hasItemHistory) {
5287
+ yield* read(undefined, () => true);
5288
+ return rows;
5289
+ }
5290
+ const { liveSk } = family;
5291
+ const history = historyKeyOptions(liveSk);
5292
+ const beginsWith = (prefix) => ({
5293
+ expression: "begins_with(#sk, :prefix)",
5294
+ values: { ":prefix": { S: prefix } },
5295
+ });
5296
+ if (ranges.has("live")) {
5297
+ yield* read(beginsWith(liveSk), (_, sk) => sk === liveSk || sk.startsWith(`${liveSk}#`));
5298
+ }
5299
+ if (ranges.has("snapshots")) {
5300
+ yield* read(beginsWith(DynamoSchema.composeVersionKeyPrefix(schema, entityType, history)), () => true);
5301
+ }
5302
+ if (ranges.has("tombstones")) {
5303
+ yield* read(beginsWith(DynamoSchema.composeDeletedKeyPrefix(schema, entityType, history)), () => true);
5304
+ }
5305
+ for (const [range, prefix] of [
5306
+ ["legacySnapshots", DynamoSchema.composeVersionKeyPrefix(schema, entityType)],
5307
+ ["legacyTombstones", DynamoSchema.composeDeletedKeyPrefix(schema, entityType)],
5308
+ ]) {
5309
+ if (!ranges.has(range))
5310
+ continue;
5311
+ // Unsegmented history ends in a version or timestamp, which starts
5312
+ // with a digit: the range bounds it (as `legacyHistory` reads it).
5313
+ yield* read({
5314
+ expression: "#sk BETWEEN :lo AND :hi",
5315
+ values: { ":lo": { S: `${prefix}0` }, ":hi": { S: `${prefix}:` } },
5316
+ }, (row, sk) => !sk.slice(prefix.length).includes("#") && isItemsRow(row, liveSk));
5317
+ }
5318
+ return rows;
5319
+ });
5320
+ const gcSupport = {
5321
+ kind: "entity",
5322
+ entityType,
5323
+ tableTag: () => tableTag,
5324
+ pkField: config.indexes.primary.pk.field,
5325
+ skField: config.indexes.primary.sk.field,
5326
+ offload: offloadInfo,
5327
+ lifecycle: {
5328
+ retain: isRetainEnabled(),
5329
+ softDelete: isSoftDeleteEnabled(),
5330
+ timeSeries: config.timeSeries !== undefined,
5331
+ },
5332
+ familyOfKey: gcFamilyOfKey,
5333
+ liveSkOfRow: gcLiveSkOfRow,
5334
+ liveSkCandidates: gcLiveSkCandidates,
5335
+ readFamily: gcReadFamily,
5336
+ };
5337
+ /**
5338
+ * Purge's store step (#179, design §11.6), once every DynamoDB delete of
5339
+ * the item's rows succeeded: re-read the family (bracketed, every range),
5340
+ * then delete each own version no row references that the purged rows
5341
+ * named or that is too old to be in flight — a younger unnamed one may be
5342
+ * the upload of a write racing the purge, left for the sweep. A family
5343
+ * whose live row kept changing meanwhile is left to the sweep whole.
5344
+ * Foreign pointers (another table's versions, §11.2) are never touched.
5345
+ */
5346
+ const purgeOffloaded = (args) => Effect.gen(function* () {
5347
+ const { client, store, info, tableName, family } = args;
5348
+ const primary = config.indexes.primary;
5349
+ const segment = GcSupport.familySegment(tableName, { S: family.pk }, { S: family.liveSk });
5350
+ const prefixes = new Set([`${info.prefix ?? store.prefix}${segment}`]);
5351
+ const named = [];
5352
+ for (const row of args.purged) {
5353
+ for (const attribute of offloadedAttributeNames) {
5354
+ const pointer = GcSupport.pointerOf(row[attribute]);
5355
+ if (pointer === undefined)
5356
+ continue;
5357
+ const leading = GcSupport.leadingPrefix(pointer.ref.key, segment, GcSupport.FAMILY_REST);
5358
+ if (leading === undefined)
5359
+ continue;
5360
+ named.push(pointer.ref);
5361
+ prefixes.add(`${leading}${segment}`);
5362
+ }
5363
+ }
5364
+ const referenced = yield* GcSupport.confirmRead({
5365
+ client,
5366
+ table: tableName,
5367
+ liveKey: {
5368
+ [primary.pk.field]: { S: family.pk },
5369
+ [primary.sk.field]: { S: family.liveSk },
5370
+ },
5371
+ readRows: gcReadFamily(client, tableName, family, GcSupport.ALL_RANGES),
5372
+ });
5373
+ if (Option.isNone(referenced)) {
5374
+ return yield* Effect.logWarning(`effect-dynamodb: purge of a ${entityType} item left its offloaded versions to the ` +
5375
+ "sweep: the item's live row changed while the purge re-read its family " +
5376
+ `(${GcSupport.CONFIRM_ATTEMPTS} attempts) — a writer is racing the purge.`).pipe(Effect.annotateLogs({ table: tableName, pk: family.pk, sk: family.liveSk }));
5377
+ }
5378
+ const now = yield* Clock.currentTimeMillis;
5379
+ yield* GcSupport.purgeVersions({
5380
+ store,
5381
+ ctx: {
5382
+ entityType,
5383
+ attribute: offloadedAttributeNames.length === 1 ? offloadedAttributeNames[0] : "(several)",
5384
+ operation: "Entity.purge",
5385
+ committed: true,
5386
+ },
5387
+ named,
5388
+ prefixes,
5389
+ referenced: referenced.value,
5390
+ now,
5391
+ });
5392
+ });
4660
5393
  /**
4661
5394
  * Build a version snapshot item: same PK, version SK, stripped GSI keys,
4662
5395
  * keeps __edd_e__ for entity type filtering.
@@ -5312,9 +6045,14 @@ const makeImpl = (config, precomputedData) => {
5312
6045
  const keyInput = {
5313
6046
  [ref.keyField]: Option.getOrElse(keyValueOf(ref.keySchema, id), () => id),
5314
6047
  };
6048
+ // A target that offloads fields is read lazily (#179, design §8.4):
6049
+ // the ref schema never includes an offloaded field (`EDD-9143`), and
6050
+ // `refDataOf` leaves them out, so nothing is fetched.
6051
+ const dropped = offloadedFieldsOf(ref.refEntity);
6052
+ const get = ref.refEntity.get(keyInput);
5315
6053
  // Use asModel to convert EntityGet to Effect<ModelType>
5316
- const getEffect = asModel(ref.refEntity.get(keyInput));
5317
- const model = yield* getEffect.pipe(Effect.catchTag("ItemNotFound", () => Effect.fail(new RefNotFound({
6054
+ const getEffect = asModel(dropped.length === 0 ? get : offloadedCombinator(get, "lazy"));
6055
+ const fetched = yield* getEffect.pipe(Effect.catchTag("ItemNotFound", () => Effect.fail(new RefNotFound({
5318
6056
  entity: entityType,
5319
6057
  field: ref.fieldName,
5320
6058
  refEntity: ref.refEntityType,
@@ -5322,8 +6060,9 @@ const makeImpl = (config, precomputedData) => {
5322
6060
  }))));
5323
6061
  // `asModel` returns the DECODED domain value (transform fields lifted to
5324
6062
  // their domain form, e.g. `Schema.DateTimeUtcFromString` → `DateTime`): stored
5325
- // as `refDataOf` encodes it, as a cascade stores it (issue #72, #241).
5326
- const wire = yield* refDataOf(ref.refEntity, model, entityType, "hydrateRefs.encode");
6063
+ // as `refDataOf` encodes it, as a cascade stores it (issue #72, #241). Fields the
6064
+ // target offloads are left out (#179): no blob pointer is ever copied into this row.
6065
+ const wire = yield* refDataOf(ref.refEntity, fetched, entityType, "hydrateRefs.encode");
5327
6066
  return { fieldName: ref.fieldName, idFieldName: ref.idFieldName, data: wire };
5328
6067
  });
5329
6068
  });
@@ -5499,6 +6238,8 @@ const makeImpl = (config, precomputedData) => {
5499
6238
  keyFields,
5500
6239
  refAttribute: refSet.attribute,
5501
6240
  refData: refSet.value,
6241
+ heldAttribute: gsiPkField,
6242
+ heldValue: { S: gsiPkValue },
5502
6243
  });
5503
6244
  }
5504
6245
  exclusiveStartKey = queryResult.LastEvaluatedKey;
@@ -5507,58 +6248,88 @@ const makeImpl = (config, precomputedData) => {
5507
6248
  }
5508
6249
  if (allUpdateOps.length === 0)
5509
6250
  return;
6251
+ /**
6252
+ * A target's update: its ref SET, conditioned on the target still naming the source (#132).
6253
+ * The index the targets were found through is eventually consistent, so a target deleted or
6254
+ * pointed at another source since may still be listed: unconditioned, the update would
6255
+ * create a key-only item at a deleted target's key (one no read decodes, blocking a later
6256
+ * `create` there), or write this source's data into a target that no longer names it.
6257
+ * Refused, the target is no longer this source's, and is skipped.
6258
+ */
6259
+ const cascadeUpdate = (op) => ({
6260
+ TableName: op.tableName,
6261
+ Key: op.key,
6262
+ UpdateExpression: "SET #ref = :refData",
6263
+ ConditionExpression: "#held = :held",
6264
+ ExpressionAttributeNames: { "#ref": op.refAttribute, "#held": op.heldAttribute },
6265
+ ExpressionAttributeValues: { ":refData": op.refData, ":held": op.heldValue },
6266
+ });
5510
6267
  if (mode === "transactional") {
5511
6268
  // Transactional mode — one atomic transaction. DynamoDB's limits (100
5512
6269
  // items, 4 MB, item size, sort keys) are not pre-checked (#144): a
5513
6270
  // rejection is diagnosed and reported as a cascade that wrote nothing.
5514
- const cascadeItems = allUpdateOps.map((op) => ({
5515
- Update: {
5516
- TableName: op.tableName,
5517
- Key: op.key,
5518
- UpdateExpression: "SET #ref = :refData",
5519
- ExpressionAttributeNames: { "#ref": op.refAttribute },
5520
- ExpressionAttributeValues: { ":refData": op.refData },
5521
- },
5522
- }));
5523
- yield* client.transactWriteItems({ TransactItems: [...cascadeItems] }).pipe(diagnoseFailure({
5524
- sent: () => ({
5525
- _tag: "Transaction",
5526
- items: cascadeItems,
5527
- targets: () => cascadeItems.map((item, index) => {
5528
- const op = allUpdateOps[index];
5529
- return transactItemTarget(item, op.tableName, op.keyFields, op.entityType, `the cascade update of ${op.entityType} (item ${index})`);
5530
- }),
5531
- }),
5532
- keys: () => ({
5533
- partition: [...new Set(allUpdateOps.map((op) => op.keyFields[0]))],
5534
- sort: [...new Set(allUpdateOps.map((op) => op.keyFields[1]))],
5535
- }),
5536
- rewrite: (diagnosis, original) => new CascadePartialFailure({
5537
- sourceEntity: sourceEntityType,
5538
- sourceId: sourceIdValue,
5539
- succeeded: 0,
5540
- failed: allUpdateOps.length,
5541
- errors: [
5542
- diagnosedValidationError(diagnosis, original, {
5543
- operation: "cascade",
5544
- entityType: sourceEntityType,
6271
+ // A target refused by its condition (#132) left the source since the query: it is
6272
+ // dropped, and the rest sent again, up to `GUARDED_PUT_ATTEMPTS` sends in all.
6273
+ let pending = allUpdateOps;
6274
+ for (let send = 1; pending.length > 0; send++) {
6275
+ const sentOps = pending;
6276
+ const cascadeItems = sentOps.map((op) => ({
6277
+ Update: cascadeUpdate(op),
6278
+ }));
6279
+ const sent = yield* Effect.result(client.transactWriteItems({ TransactItems: [...cascadeItems] }).pipe(diagnoseFailure({
6280
+ sent: () => ({
6281
+ _tag: "Transaction",
6282
+ items: cascadeItems,
6283
+ targets: () => cascadeItems.map((item, index) => {
6284
+ const op = sentOps[index];
6285
+ return transactItemTarget(item, op.tableName, op.keyFields, op.entityType, `the cascade update of ${op.entityType} (item ${index})`);
5545
6286
  }),
5546
- ],
5547
- }),
5548
- }));
6287
+ }),
6288
+ keys: () => ({
6289
+ partition: [...new Set(sentOps.map((op) => op.keyFields[0]))],
6290
+ sort: [...new Set(sentOps.map((op) => op.keyFields[1]))],
6291
+ }),
6292
+ rewrite: (diagnosis, original) => new CascadePartialFailure({
6293
+ sourceEntity: sourceEntityType,
6294
+ sourceId: sourceIdValue,
6295
+ succeeded: 0,
6296
+ failed: sentOps.length,
6297
+ errors: [
6298
+ diagnosedValidationError(diagnosis, original, {
6299
+ operation: "cascade",
6300
+ entityType: sourceEntityType,
6301
+ }),
6302
+ ],
6303
+ }),
6304
+ })));
6305
+ if (Result.isSuccess(sent))
6306
+ return;
6307
+ const error = sent.failure;
6308
+ const reasons = error._tag === "CascadePartialFailure" || !isAwsTransactionCancelled(error.cause)
6309
+ ? undefined
6310
+ : error.cause.CancellationReasons;
6311
+ const refused = new Set((reasons ?? []).flatMap((reason, index) => reason?.Code === "ConditionalCheckFailed" ? [index] : []));
6312
+ // Cancelled for another reason, or once the sends run out: a cascade that wrote nothing.
6313
+ if (refused.size === 0)
6314
+ return yield* error;
6315
+ pending = sentOps.filter((_, index) => !refused.has(index));
6316
+ if (send >= GUARDED_PUT_ATTEMPTS && pending.length > 0) {
6317
+ return yield* new CascadePartialFailure({
6318
+ sourceEntity: sourceEntityType,
6319
+ sourceId: sourceIdValue,
6320
+ succeeded: 0,
6321
+ failed: pending.length,
6322
+ errors: [error],
6323
+ });
6324
+ }
6325
+ }
5549
6326
  }
5550
6327
  else {
5551
6328
  // Eventual mode — concurrent updates with partial failure tracking
5552
6329
  let succeeded = 0;
5553
6330
  const errors = [];
5554
6331
  const updateEffects = allUpdateOps.map((op) => {
5555
- const update = {
5556
- TableName: op.tableName,
5557
- Key: op.key,
5558
- UpdateExpression: "SET #ref = :refData",
5559
- ExpressionAttributeNames: { "#ref": op.refAttribute },
5560
- ExpressionAttributeValues: { ":refData": op.refData },
5561
- };
6332
+ const update = cascadeUpdate(op);
5562
6333
  return client.updateItem(update).pipe(
5563
6334
  // An item the cascade grows past 400 KB is named in `errors`.
5564
6335
  diagnoseFailure({
@@ -5574,7 +6345,10 @@ const makeImpl = (config, precomputedData) => {
5574
6345
  }),
5575
6346
  }), Effect.tap(() => Effect.sync(() => {
5576
6347
  succeeded++;
5577
- })), Effect.catch((err) => Effect.sync(() => {
6348
+ })),
6349
+ // Refused (#132): the target was deleted, or no longer names this source, since the
6350
+ // query found it. It isn't this source's: skipped, neither succeeded nor failed.
6351
+ Effect.catchIf((err) => err._tag !== "ValidationError" && isAwsConditionalCheckFailed(err.cause), () => Effect.void), Effect.catch((err) => Effect.sync(() => {
5578
6352
  errors.push(err);
5579
6353
  })));
5580
6354
  });
@@ -5686,7 +6460,10 @@ const makeImpl = (config, precomputedData) => {
5686
6460
  // so this keeps the bound `put` at `R = never`. The filled id then
5687
6461
  // flows through input validation → key composition → stored item →
5688
6462
  // returned record in this same pass.
5689
- const withGeneratedId = yield* fillGeneratedId(input);
6463
+ // Binary inputs (#179, design §3.8): streams, handles and sources
6464
+ // become their placeholders before anything reads the input.
6465
+ const prepared = yield* prepareInput(input, operation);
6466
+ const withGeneratedId = yield* fillGeneratedId(prepared);
5690
6467
  const unsentineled = unsentineledDefaults(withGeneratedId);
5691
6468
  const inputWithGeneratedId = yield* fillDecodingDefaults(withGeneratedId);
5692
6469
  // Encode user input → wire form. Users typically construct domain
@@ -5801,6 +6578,10 @@ const makeImpl = (config, precomputedData) => {
5801
6578
  if (projected !== undefined)
5802
6579
  Object.assign(item, projected.attributes);
5803
6580
  if (opts.putKind === "insert") {
6581
+ // Offloaded fields (#179, design §6.2): routed and uploaded as
6582
+ // `put` does, before the `INSERT`; the ledger settles the
6583
+ // statement (or the `INSERT`-only transaction) that carries them.
6584
+ yield* offloadItem(item, tableName, operation);
5804
6585
  const marshalled = yield* runInsert({
5805
6586
  tableName,
5806
6587
  ttlAttrName,
@@ -5808,7 +6589,7 @@ const makeImpl = (config, precomputedData) => {
5808
6589
  item,
5809
6590
  given: encodedInput,
5810
6591
  });
5811
- return yield* decodeAs(item, marshalled, mode);
6592
+ return yield* decodeWritten(item, marshalled, mode, operation);
5812
6593
  }
5813
6594
  // The caller's condition, ANDed onto `create`'s not-exists guard —
5814
6595
  // a guard no `.condition()` can replace (#133). `upsert`'s create
@@ -5828,6 +6609,18 @@ const makeImpl = (config, precomputedData) => {
5828
6609
  userCondition = andRaw(compileOwnCondition(withGuard(over.value.guard, opts.condition)), over.value.term);
5829
6610
  }
5830
6611
  }
6612
+ // A projection's row rewrite (#179, design §6.11): a value whose
6613
+ // content the read row's pointer named keeps that pointer, and the
6614
+ // write holds only while the row still does (`#f = :P`).
6615
+ const pins = yield* reusePointers(item, opts.reuse, operation);
6616
+ if (pins.length > 0)
6617
+ userCondition = OffloadWrite.withPins(userCondition, pins);
6618
+ // Offloaded fields (#179, design §6.5): every one the item holds is
6619
+ // routed (thresholds, then the item budget) and uploaded — after the
6620
+ // local guards and the tombstone read, so a refused write uploads
6621
+ // nothing — and its pointer replaces the value. A guarded put's
6622
+ // snapshot of the replaced item copies that item's pointers.
6623
+ yield* offloadItem(item, tableName, operation);
5831
6624
  if (guarded) {
5832
6625
  const plan = yield* runGuardedPut({
5833
6626
  tableName,
@@ -5841,7 +6634,7 @@ const makeImpl = (config, precomputedData) => {
5841
6634
  composeKeys: (carried) => composeAllKeys({ ...keyValues, ...carried }, operation, ownSchema()),
5842
6635
  given: encodedInput,
5843
6636
  });
5844
- return yield* decodeAs(plan.item, plan.marshalled, mode);
6637
+ return yield* decodeWritten(plan.item, plan.marshalled, mode, operation);
5845
6638
  }
5846
6639
  const marshalledItem = yield* marshalOrFail(entityType, operation, () => toAttributeMap(item), { fieldOf: fieldOfAttribute });
5847
6640
  {
@@ -5874,7 +6667,7 @@ const makeImpl = (config, precomputedData) => {
5874
6667
  }), diagnoseItemWrite("put", { Put: putInput }));
5875
6668
  }
5876
6669
  // Decode and return using selected mode
5877
- return yield* decodeAs(item, marshalledItem, mode);
6670
+ return yield* decodeWritten(item, marshalledItem, mode, operation);
5878
6671
  }), self, input);
5879
6672
  // ---------------------------------------------------------------------------
5880
6673
  // create operation — put + attribute_not_exists condition
@@ -5943,10 +6736,15 @@ const makeImpl = (config, precomputedData) => {
5943
6736
  return yield* new ItemNotFound({ entityType, key: encodedKey });
5944
6737
  }
5945
6738
  // Raw mode: return unmarshalled record without schema decode — a
5946
- // packed attribute as its parsed JSON (#147).
6739
+ // packed attribute as its parsed JSON (#147), an offloaded one per
6740
+ // the read's modes (#179).
5947
6741
  if (mode === "raw") {
5948
6742
  const row = fromAttributeMap(result.Item);
5949
- yield* unpackFields(row);
6743
+ yield* loadRow(row, {
6744
+ operation: "get",
6745
+ modes: yield* OffloadRead.currentModes,
6746
+ raw: true,
6747
+ });
5950
6748
  return row;
5951
6749
  }
5952
6750
  // Unmarshall and decode using selected mode
@@ -5971,7 +6769,7 @@ const makeImpl = (config, precomputedData) => {
5971
6769
  if (unreadable !== undefined) {
5972
6770
  return yield* new ValidationError({ entityType, operation: "update", cause: unreadable });
5973
6771
  }
5974
- // A packed field takes only a whole-value .set() / .remove() (#147).
6772
+ // A packed or External field takes only a whole-value .set() / .remove() (#147, #179).
5975
6773
  const packedRefusal = refusedPackedUpdate(requested);
5976
6774
  if (packedRefusal !== undefined) {
5977
6775
  return yield* new ValidationError({
@@ -6032,7 +6830,12 @@ const makeImpl = (config, precomputedData) => {
6032
6830
  }
6033
6831
  // Removing a defaulted index composite re-materialises its default —
6034
6832
  // stored, keys recomposed from it — as a put that omits it does (#133).
6035
- const { state: uState, defaulted: removedToDefault } = yield* rematerializeRemovedDefaults(normalized);
6833
+ const { state: rematerialized, defaulted: removedToDefault } = yield* rematerializeRemovedDefaults(normalized);
6834
+ // Binary inputs (#179, design §3.8) become their placeholders.
6835
+ const preparedUpdates = yield* prepareInput(rematerialized.updates, "update");
6836
+ const uState = preparedUpdates === rematerialized.updates
6837
+ ? rematerialized
6838
+ : { ...rematerialized, updates: preparedUpdates };
6036
6839
  const refusedSet = refusedRecordSet(uState.updates, key);
6037
6840
  if (refusedSet !== undefined) {
6038
6841
  return yield* new ValidationError({
@@ -6321,14 +7124,20 @@ const makeImpl = (config, precomputedData) => {
6321
7124
  return checked;
6322
7125
  });
6323
7126
  /** An update from what {@link prepareUpdate} decided: its reads and its write. */
6324
- const runPreparedUpdate = (key, prepared, mode,
7127
+ const runPreparedUpdate = (prepared, mode,
6325
7128
  /**
6326
7129
  * The item as already read — consistently — by the caller (`upsert`, a transaction's plan).
6327
7130
  * Used instead of reading it again: the write is guarded on it either way. An update that
6328
7131
  * reads no row is handed it only to write a renamed sparse map's entries where it holds the
6329
7132
  * map (#238).
6330
7133
  */
6331
- preRead) => Effect.gen(function* () {
7134
+ preRead,
7135
+ /**
7136
+ * Take the read-then-write branch (#179, design §6.3): the standard
7137
+ * `UpdateItem` of an entity with an `itemBudget` was rejected for item
7138
+ * size, and the read-merge branch routes the whole merged item.
7139
+ */
7140
+ forceReadMerge = false) => Effect.gen(function* () {
6332
7141
  const { uState, removedToDefault, immutables, upsertable, createInput, lacks, requestedRv, needsBothImages, evExpected, userCond, tc, ttlAttrName, encodedKey, missingItem, encodedUpdates, operands, } = prepared;
6333
7142
  const client = yield* Capacity.client;
6334
7143
  const tableName = tc.name;
@@ -6344,11 +7153,12 @@ const makeImpl = (config, precomputedData) => {
6344
7153
  touchesUniqueFields,
6345
7154
  computedComposites,
6346
7155
  pathOpsPresent,
6347
- })) {
7156
+ }) ||
7157
+ (forceReadMerge && !pathOpsPresent)) {
6348
7158
  // --- Retain path: read-then-transact ---
6349
7159
  // Read current item (needed to create snapshot of pre-update state)
6350
7160
  const currentResult = preRead !== undefined ? { Item: preRead } : yield* readCurrent(tableName, marshalledKey);
6351
- if (!currentResult.Item) {
7161
+ if (!currentResult.Item || isProjectionTombstone(currentResult.Item, entityType)) {
6352
7162
  return yield* missingItem();
6353
7163
  }
6354
7164
  const currentRaw = fromAttributeMap(currentResult.Item);
@@ -6384,6 +7194,9 @@ const makeImpl = (config, precomputedData) => {
6384
7194
  ...uState.upsertOver?.fill,
6385
7195
  ...currentDomainItem,
6386
7196
  };
7197
+ // An upsert's fill values the row lacked land in `newItem` as given: they are packed and
7198
+ // routed like the fields the update names (#179), never stored as their plain encoding.
7199
+ const filled = Object.keys(uState.upsertOver?.fill ?? {}).filter((field) => !Object.hasOwn(currentDomainItem, field));
6387
7200
  // Sparse-map clear: blow away the entire bucket Record, before anything
6388
7201
  // the update writes into it, as the expression an update sends clears
6389
7202
  // first (#238). The retain path always reads-then-writes the full item,
@@ -6654,7 +7467,7 @@ const makeImpl = (config, precomputedData) => {
6654
7467
  // Untouched packed fields still hold their stored form on `newItem`
6655
7468
  // (kept byte-identical for the write diff), so the source text is
6656
7469
  // derived from an unpacked copy.
6657
- const vectorWrite = yield* computeVectorAttributes(yield* unpackedDomainCopy(newItem, "update.vector"), uState.withVectors, embedFor, ownUpdate);
7470
+ const vectorWrite = yield* computeVectorAttributes(yield* unpackedDomainCopy(newItem, "update.vector", embeddedSources(vectorIndexEntries.filter(([logicalName]) => embedFor.has(logicalName)), uState.withVectors)), uState.withVectors, embedFor, ownUpdate);
6658
7471
  Object.assign(newItem, vectorWrite.sets);
6659
7472
  for (const field of vectorWrite.removes)
6660
7473
  delete newItem[field];
@@ -6676,7 +7489,10 @@ const makeImpl = (config, precomputedData) => {
6676
7489
  // hold the stored value read above (a string or bytes), carried
6677
7490
  // byte-identical so the "write only what differs" diff below leaves
6678
7491
  // them alone (#147).
6679
- yield* packFields(newItem, "update", new Set(Object.entries(hydratedUpdates)
7492
+ yield* packFields(newItem, "update", new Set([
7493
+ ...Object.entries(hydratedUpdates),
7494
+ ...filled.map((field) => [field, uState.upsertOver?.fill[field]]),
7495
+ ]
6680
7496
  .filter(([field, value]) => Object.hasOwn(packedFields, field) && value != null)
6681
7497
  .map(([field]) => resolveDbName(field))));
6682
7498
  const currentItem = currentResult.Item;
@@ -6690,6 +7506,28 @@ const makeImpl = (config, precomputedData) => {
6690
7506
  cause: immutableChange,
6691
7507
  });
6692
7508
  }
7509
+ // A restated offloaded immutable that passed stays as stored (#179,
7510
+ // design §6.5): its stored value is carried byte-identical — so the
7511
+ // diff below leaves it out — and it uploads nothing.
7512
+ const keptImmutables = new Set();
7513
+ for (const { attr, offloaded } of immutables) {
7514
+ if (offloaded === undefined || currentItem[attr] === undefined)
7515
+ continue;
7516
+ newItem[attr] = fromAttributeValue(currentItem[attr]);
7517
+ keptImmutables.add(attr);
7518
+ }
7519
+ // Offloaded fields this update names (and does not clear) route on
7520
+ // the merged item and upload — after the local guards above, so a
7521
+ // refused update uploads nothing. Untouched pointers stay as read.
7522
+ if (offloadInfo !== undefined) {
7523
+ yield* offloadItem(newItem, tableName, "update", new Set([
7524
+ ...Object.entries(hydratedUpdates),
7525
+ ...filled.map((field) => [field, uState.upsertOver?.fill[field]]),
7526
+ ]
7527
+ .filter(([, value]) => value != null)
7528
+ .map(([field]) => resolveDbName(field))
7529
+ .filter((attr) => OffloadWrite.isOffloaded(offloadInfo, attr) && !keptImmutables.has(attr))));
7530
+ }
6693
7531
  const pkField = config.indexes.primary.pk.field;
6694
7532
  const skField = config.indexes.primary.sk.field;
6695
7533
  // A legacy item of an entity whose incarnation is proven by a
@@ -6709,7 +7547,9 @@ const makeImpl = (config, precomputedData) => {
6709
7547
  ...Object.keys(uState.subtract ?? {}),
6710
7548
  ...Object.keys(uState.append ?? {}),
6711
7549
  ...Object.keys(uState.deleteFromSet ?? {}),
6712
- ].map(resolveDbName));
7550
+ ]
7551
+ .map(resolveDbName)
7552
+ .filter((attr) => !keptImmutables.has(attr)));
6713
7553
  if (systemFields.version)
6714
7554
  named.add(systemFields.version);
6715
7555
  if (systemFields.updatedAt)
@@ -6935,7 +7775,9 @@ const makeImpl = (config, precomputedData) => {
6935
7775
  const withCurrent = (effect) => effect.pipe(Effect.catchIf((e) => e instanceof ConcurrentModification, (e) => Effect.gen(function* () {
6936
7776
  const current = rejectedItem === undefined
6937
7777
  ? Option.none()
6938
- : yield* Effect.option(decodeAs(fromAttributeMap(rejectedItem), rejectedItem, "model"));
7778
+ : yield* Effect.option(decodeAs(fromAttributeMap(rejectedItem), rejectedItem, "model",
7779
+ // An error payload: offloaded fields as lazy handles (§6.13).
7780
+ { noFetch: true }));
6939
7781
  return yield* keepReleaseRace(e, new ConcurrentModification({ ...e, current }));
6940
7782
  })));
6941
7783
  // Build snapshot of the pre-update state (only when retain is enabled)
@@ -7038,8 +7880,9 @@ const makeImpl = (config, precomputedData) => {
7038
7880
  }
7039
7881
  // Execute cascade if configured (retain path) — from the new item.
7040
7882
  if (uState.cascade) {
7883
+ // Lazily: a ref stores none of the offloaded fields (`refDataOf`), so nothing is fetched.
7041
7884
  const domainData = {
7042
- ...(yield* appliedUpdate(decodeAs(fromAttributeMap(newImage), newImage, "model"), "stored")),
7885
+ ...(yield* appliedUpdate(OffloadRead.withModes(decodeWritten(fromAttributeMap(newImage), newImage, "model", "update"), OffloadRead.LAZY_MODES), "stored")),
7043
7886
  };
7044
7887
  const sourceId = sourceIdentifierField != null
7045
7888
  ? ownValue(encodedKey, sourceIdentifierField)
@@ -7062,7 +7905,7 @@ const makeImpl = (config, precomputedData) => {
7062
7905
  let casRead;
7063
7906
  if (isRetainEnabled() || needsBothImages) {
7064
7907
  const current = yield* readCurrent(tableName, marshalledKey);
7065
- if (!current.Item) {
7908
+ if (!current.Item || isProjectionTombstone(current.Item, entityType)) {
7066
7909
  return yield* missingItem();
7067
7910
  }
7068
7911
  yield* checkVersion(current.Item, "update");
@@ -7136,9 +7979,10 @@ const makeImpl = (config, precomputedData) => {
7136
7979
  // read its row missing writes nothing that requires it, which is what
7137
7980
  // `transactWrite`'s planner relies on.
7138
7981
  let packedRead;
7139
- if (plainWrite && immutables.some((asserted) => asserted.packed)) {
7982
+ if (plainWrite &&
7983
+ immutables.some((asserted) => asserted.packed || asserted.offloaded !== undefined)) {
7140
7984
  const stored = yield* readCurrent(tableName, marshalledKey);
7141
- if (stored.Item === undefined) {
7985
+ if (!stored.Item || isProjectionTombstone(stored.Item, entityType)) {
7142
7986
  return yield* createsOnMissing
7143
7987
  ? new MissingForCreate({ input: createInput() })
7144
7988
  : missingItem();
@@ -7306,9 +8150,19 @@ const makeImpl = (config, precomputedData) => {
7306
8150
  const nullClears = [];
7307
8151
  // A sparse map's entries with no stored form, by their placeholders.
7308
8152
  const entryClears = [];
8153
+ // Offloaded values (#179): set inline here, uploaded once the request is
8154
+ // otherwise built (design §6.5) — so a refusal below uploads nothing.
8155
+ const offloadSets = [];
8156
+ // A restated offloaded immutable was read and matched above: it stays
8157
+ // as stored and uploads nothing (design §6.5).
8158
+ const keptImmutables = new Set(immutables
8159
+ .filter((asserted) => asserted.offloaded !== undefined && asserted.wire != null)
8160
+ .map((asserted) => asserted.field));
7309
8161
  for (const [attr, val] of Object.entries(encodedUpdatesMap)) {
7310
8162
  if (updateSystemColliders.has(attr))
7311
8163
  continue;
8164
+ if (keptImmutables.has(attr))
8165
+ continue;
7312
8166
  if (val === undefined || (val === null && lacks.omits(attr))) {
7313
8167
  // Sparse fields: clearing a sparse field with null is a no-op
7314
8168
  // here — the `.removeEntries` API is the explicit per-key
@@ -7366,6 +8220,9 @@ const makeImpl = (config, precomputedData) => {
7366
8220
  const set = yield* setOf(attr, val, "update");
7367
8221
  names[nameKey] = set.attribute;
7368
8222
  values[valKey] = set.value;
8223
+ if (offloadInfo !== undefined && OffloadWrite.isOffloaded(offloadInfo, set.attribute)) {
8224
+ offloadSets.push({ valKey, attr: set.attribute });
8225
+ }
7369
8226
  setClauses.push(`${nameKey} = ${valKey}`);
7370
8227
  counter++;
7371
8228
  }
@@ -7728,16 +8585,32 @@ const makeImpl = (config, precomputedData) => {
7728
8585
  addClauses.length > 0 ||
7729
8586
  deleteClauses.length > 0;
7730
8587
  const rv = uState.returnValues ?? "allNew";
7731
- if (!hasAnyUpdate) {
7732
- // Nothing to update: nothing written, so nothing "updated"; the
7733
- // whole-item modes are the current item.
8588
+ // Nothing to update (#132): nothing is written, but the op still establishes what its write
8589
+ // would have: the row exists (`ItemNotFound`, `patch`'s `ConditionalCheckFailed`), and its
8590
+ // condition holds. Existence alone is read, consistently, in every return mode; a condition
8591
+ // is sent in the update's own request with no `UpdateExpression`, which changes nothing. In a
8592
+ // transaction's plan the read is held to the commit by a `ConditionCheck` (`planned`), and
8593
+ // the request is recorded as one (`planWrite`).
8594
+ const noOp = !hasAnyUpdate;
8595
+ /**
8596
+ * A no-op's result: nothing "updated"; the whole-item modes, the row. `row`: the row it read,
8597
+ * or its request returned; `"held"`, its request's condition proved the row there and it
8598
+ * asked for nothing back.
8599
+ */
8600
+ const noOpResult = (row) => Effect.gen(function* () {
8601
+ if (row === undefined || (row !== "held" && liveRow(row) === undefined)) {
8602
+ return yield* missingItem();
8603
+ }
7734
8604
  if (rv === "none")
7735
8605
  return undefined;
7736
8606
  if (rv === "updatedOld" || rv === "updatedNew") {
7737
8607
  return yield* decodePartial(undefined, new Set(), mode);
7738
8608
  }
7739
- return yield* get(key)._run(mode);
7740
- }
8609
+ // A whole-item mode always asks its request for the row.
8610
+ if (row === "held")
8611
+ return yield* Effect.die(new Error("a no-op returned no row"));
8612
+ return yield* decodeAs(fromAttributeMap(row), row, mode);
8613
+ });
7741
8614
  // Compose UpdateExpression from all clause types
7742
8615
  const expressionParts = [];
7743
8616
  if (setClauses.length > 0)
@@ -7751,6 +8624,8 @@ const makeImpl = (config, precomputedData) => {
7751
8624
  const updateExpression = expressionParts.join(" ");
7752
8625
  // Build condition expression — combine optimistic lock + user condition
7753
8626
  const condParts = [];
8627
+ /** How many of `condParts` restate an immutable value (`#immN = :immN`). */
8628
+ let immutableTerms = 0;
7754
8629
  if (evExpected !== undefined && systemFields.version) {
7755
8630
  condParts.push(versionIs(evExpected, names, values, "#condVer", ":expectedVer"));
7756
8631
  }
@@ -7772,15 +8647,15 @@ const makeImpl = (config, precomputedData) => {
7772
8647
  }
7773
8648
  if (plainWrite) {
7774
8649
  // Restated immutable values must match the item's.
7775
- for (const [i, { attr, value, packed }] of immutables.entries()) {
7776
- if (packed)
7777
- continue; // read and compared above (#147)
8650
+ for (const [i, { attr, value, packed, offloaded }] of immutables.entries()) {
8651
+ if (packed || offloaded !== undefined)
8652
+ continue; // read and compared above (#147, #179)
7778
8653
  names[`#imm${i}`] = attr;
7779
8654
  values[`:imm${i}`] = value;
7780
8655
  condParts.push(`#imm${i} = :imm${i}`);
8656
+ immutableTerms++;
7781
8657
  }
7782
- names["#exists"] = config.indexes.primary.pk.field;
7783
- condParts.push("attribute_exists(#exists)");
8658
+ condParts.push(rowExists(names, values, "#exists"));
7784
8659
  // A `pathIfNotExists` operand a check refuses is written only where its path is absent:
7785
8660
  // the write requires the path, and a refusal returning an item without it is that
7786
8661
  // operand's (`fallbackRefusal`, #236). None: the request is as it was.
@@ -7796,6 +8671,27 @@ const makeImpl = (config, precomputedData) => {
7796
8671
  if (incarnation !== undefined)
7797
8672
  condParts.push(incarnation);
7798
8673
  }
8674
+ if (noOp) {
8675
+ // Required in a no-op's request whatever else it asserts: an `UpdateItem` with no
8676
+ // `UpdateExpression` creates a key-only item at a missing key.
8677
+ if (!plainWrite)
8678
+ condParts.push(rowExists(names, values, "#exists"));
8679
+ // Asserting nothing but existence, and restated immutable values: the row is read (or
8680
+ // was), consistently, and the values are compared with it, as the refusal of the same
8681
+ // update with a payload compares them (`immutableMismatch`).
8682
+ if (condParts.length === 1 + immutableTerms) {
8683
+ const row = liveRow(held ?? (yield* readCurrent(tableName, marshalledKey)).Item);
8684
+ const immutableChange = row !== undefined ? immutableMismatch(immutables, row) : undefined;
8685
+ if (immutableChange !== undefined) {
8686
+ return yield* new ValidationError({
8687
+ entityType,
8688
+ operation: "update",
8689
+ cause: immutableChange,
8690
+ });
8691
+ }
8692
+ return yield* noOpResult(row);
8693
+ }
8694
+ }
7799
8695
  // Sent as built: a condition over DynamoDB's expression limits is
7800
8696
  // DynamoDB's to reject, and is diagnosed naming the caller's part (#144).
7801
8697
  const conditionExpression = condParts.length > 0 ? condParts.join(" AND ") : undefined;
@@ -7825,6 +8721,12 @@ const makeImpl = (config, precomputedData) => {
7825
8721
  stored: stored,
7826
8722
  });
7827
8723
  };
8724
+ // Upload the offloaded values this update sets (thresholds only: the
8725
+ // whole item is not in hand, design §6.3) — every one named, even when
8726
+ // equal to what the item holds (§6.4).
8727
+ if (offloadInfo !== undefined && offloadSets.length > 0) {
8728
+ yield* OffloadWrite.setValues(offloadInfo, offloadSets, values, offloadRow(primaryKey, tableName, "update"));
8729
+ }
7828
8730
  // The top-level attributes this update writes — what `updatedOld` /
7829
8731
  // `updatedNew` return.
7830
8732
  const written = expressionTargets(updateExpression, names);
@@ -7836,7 +8738,8 @@ const makeImpl = (config, precomputedData) => {
7836
8738
  : undefined;
7837
8739
  if (sourceId == null)
7838
8740
  return;
7839
- const domainData = yield* appliedUpdate(decodeAs(fromAttributeMap(image), image, "model"), "stored");
8741
+ // Lazily: a ref stores none of the offloaded fields (`refDataOf`), so nothing is fetched.
8742
+ const domainData = yield* appliedUpdate(OffloadRead.withModes(decodeWritten(fromAttributeMap(image), image, "model", "update"), OffloadRead.LAZY_MODES), "stored");
7840
8743
  yield* executeCascade(uState.cascade, { ...domainData }, sourceId);
7841
8744
  });
7842
8745
  if (retainSnapshot !== undefined) {
@@ -7901,18 +8804,23 @@ const makeImpl = (config, precomputedData) => {
7901
8804
  // The image the mode returns; `none` asks for nothing unless a
7902
8805
  // cascade needs the new item.
7903
8806
  const wantsOld = casRead === undefined && (rv === "allOld" || rv === "updatedOld");
7904
- const returned = wantsOld
7905
- ? "ALL_OLD"
7906
- : rv === "none" && !uState.cascade && casRead === undefined
7907
- ? "NONE"
7908
- : "ALL_NEW";
8807
+ const returned = noOp
8808
+ ? // A no-op's item, unchanged: returned only to the whole-item modes, and never cascaded.
8809
+ rv === "allNew" || rv === "allOld"
8810
+ ? "ALL_NEW"
8811
+ : "NONE"
8812
+ : wantsOld
8813
+ ? "ALL_OLD"
8814
+ : rv === "none" && !uState.cascade && casRead === undefined
8815
+ ? "NONE"
8816
+ : "ALL_NEW";
7909
8817
  // DynamoDB rejects an empty `ExpressionAttributeValues` map. When
7910
8818
  // the UpdateExpression is REMOVE-only (e.g. clearMap with no other
7911
8819
  // combinators), `values` may be empty — omit the property entirely.
7912
8820
  const updateInput = {
7913
8821
  TableName: tableName,
7914
8822
  Key: marshalledKey,
7915
- UpdateExpression: updateExpression,
8823
+ ...(!noOp && { UpdateExpression: updateExpression }),
7916
8824
  ExpressionAttributeNames: names,
7917
8825
  ExpressionAttributeValues: Object.keys(values).length > 0 ? values : undefined,
7918
8826
  ConditionExpression: conditionExpression,
@@ -7926,9 +8834,10 @@ const makeImpl = (config, precomputedData) => {
7926
8834
  // item (it must exist), a restated immutable value, the
7927
8835
  // version CAS, or the user's condition.
7928
8836
  if (isAwsConditionalCheckFailed(err.cause)) {
7929
- const stored = err.cause.Item;
8837
+ const stored = liveRow(err.cause.Item);
7930
8838
  if (stored === undefined && !uState.patch) {
7931
- return createsOnMissing
8839
+ // A no-op never creates: its payload names nothing to create from.
8840
+ return createsOnMissing && !noOp
7932
8841
  ? new MissingForCreate({ input: createInput() })
7933
8842
  : new ItemNotFound({ entityType, key: encodedKey });
7934
8843
  }
@@ -7962,7 +8871,18 @@ const makeImpl = (config, precomputedData) => {
7962
8871
  : undefined, userCond !== undefined);
7963
8872
  }
7964
8873
  return err;
7965
- }), diagnoseItemWrite("update", { Update: updateInput }, () => uc?.expression));
8874
+ }),
8875
+ // An entity with an item budget: an update rejected for item size runs
8876
+ // once more on the read-merge branch, which routes the whole item
8877
+ // (design §6.3). Not with path operations (no read-merge form).
8878
+ Effect.catchIf((err) => offloadInfo?.itemBudget !== undefined &&
8879
+ !pathOpsPresent &&
8880
+ !forceReadMerge &&
8881
+ isItemSizeRejection(err), () => Effect.fail(new OffloadSizeRetry())), diagnoseItemWrite("update", { Update: updateInput }, () => uc?.expression));
8882
+ // The no-op's condition held: nothing changed, so nothing cascades.
8883
+ if (noOp) {
8884
+ return yield* noOpResult(returned === "NONE" ? "held" : result.Attributes);
8885
+ }
7966
8886
  // A cascade never meets an old-image mode here: that combination is
7967
8887
  // routed to the read-then-write branch, or read first (`casRead`).
7968
8888
  const newImage = wantsOld ? undefined : result.Attributes;
@@ -7972,7 +8892,20 @@ const makeImpl = (config, precomputedData) => {
7972
8892
  });
7973
8893
  const runUpdate = (key, mode, requested,
7974
8894
  /** See {@link runPreparedUpdate}. */
7975
- preRead) => Effect.flatMap(prepareUpdate(key, requested), (prepared) => runPreparedUpdate(key, prepared, mode, preRead));
8895
+ preRead,
8896
+ /** See {@link runPreparedUpdate}. */
8897
+ forceReadMerge = false) => Effect.flatMap(prepareUpdate(key, requested), (prepared) => runPreparedUpdate(prepared, mode, preRead, forceReadMerge));
8898
+ /**
8899
+ * {@link runUpdate}, re-run once on the read-merge branch when its standard
8900
+ * `UpdateItem` was rejected for item size under an item budget (#179,
8901
+ * design §6.3). The retry reuses the first attempt's uploads of the same
8902
+ * content (the ledger's memo); any it does not send again was rejected
8903
+ * with that request and is rolled back at the root's exit.
8904
+ */
8905
+ const sizedUpdate = (run) => run(false).pipe(Effect.catchIf((e) => e instanceof OffloadSizeRetry, () => run(true)),
8906
+ // A forced read-merge never retries: what escapes is a defect.
8907
+ Effect.catchIf((e) => e instanceof OffloadSizeRetry, () => Effect.die(new Error("OffloadSizeRetry escaped the read-merge update"))));
8908
+ const runUpdateSized = (key, mode, requested, preRead) => sizedUpdate((force) => runUpdate(key, mode, requested, preRead, force));
7976
8909
  /**
7977
8910
  * An update; on a missing item, a plain `.set()` of a complete item creates
7978
8911
  * it through `create` — exactly the item `put` writes (#133). If another
@@ -7984,8 +8917,8 @@ const makeImpl = (config, precomputedData) => {
7984
8917
  /** The row as the caller read it, consistently (a transaction's plan): see {@link runPreparedUpdate}. */
7985
8918
  held) => {
7986
8919
  const once = () => prepared === undefined
7987
- ? runUpdate(key, mode, requested, held)
7988
- : runPreparedUpdate(key, prepared, mode, held);
8920
+ ? runUpdateSized(key, mode, requested, held)
8921
+ : sizedUpdate((force) => runPreparedUpdate(prepared, mode, held, force));
7989
8922
  // A form race (#238): the row's renamed sparse map changed form between the update's read and
7990
8923
  // its write. Read again and written again, as a guarded put is; once every attempt raced, the
7991
8924
  // race is reported naming the map. A row handed in (a transaction's plan) is never re-read here:
@@ -8055,7 +8988,8 @@ const makeImpl = (config, precomputedData) => {
8055
8988
  Key: ownKey,
8056
8989
  ConsistentRead: true,
8057
8990
  });
8058
- if (read.Item === undefined) {
8991
+ // A projection tombstone is a removed row: missing, as every read by key reports it.
8992
+ if (read.Item === undefined || isProjectionTombstone(read.Item, entityType)) {
8059
8993
  ;
8060
8994
  ({ items, ownRow } = yield* plan({ rowMissing: true }));
8061
8995
  }
@@ -8089,6 +9023,26 @@ const makeImpl = (config, precomputedData) => {
8089
9023
  }
8090
9024
  const pkField = config.indexes.primary.pk.field;
8091
9025
  const skField = config.indexes.primary.sk.field;
9026
+ // An update with nothing to set writes nothing, and found its row with a consistent read
9027
+ // (#132). Standalone, that read IS the op's answer; in a transaction, the row could be
9028
+ // deleted before the commit, so the read is held to it: a `ConditionCheck` that the row
9029
+ // still exists, judged below as the op's main item (a refusal is a lost race, planned again,
9030
+ // which then finds the row missing). A no-op that asserts a condition recorded its own check.
9031
+ if (items.length === 0 && ownRow !== undefined) {
9032
+ const { name: tableName } = yield* tableTag;
9033
+ const names = {};
9034
+ const values = {};
9035
+ items = [
9036
+ conditionCheckItem({
9037
+ TableName: tableName,
9038
+ Key: ownKey,
9039
+ ConditionExpression: rowExists(names, values, "#pk"),
9040
+ ExpressionAttributeNames: names,
9041
+ ...(Object.keys(values).length > 0 && { ExpressionAttributeValues: values }),
9042
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
9043
+ }),
9044
+ ];
9045
+ }
8092
9046
  const isOwn = (row) => {
8093
9047
  if (row === undefined)
8094
9048
  return false;
@@ -8114,7 +9068,10 @@ const makeImpl = (config, precomputedData) => {
8114
9068
  const sentinelPrefix = `${entityType}._unique.`;
8115
9069
  const versionPrefix = DynamoSchema.composeVersionKeyPrefix(schema, entityType);
8116
9070
  const roles = items.map((item) => {
8117
- if (isOwn(item.Put?.Item) || isOwn(item.Update?.Key) || isOwn(item.Delete?.Key)) {
9071
+ if (isOwn(item.Put?.Item) ||
9072
+ isOwn(item.Update?.Key) ||
9073
+ isOwn(item.Delete?.Key) ||
9074
+ isOwn(item.ConditionCheck?.Key)) {
8118
9075
  return { _tag: "main" };
8119
9076
  }
8120
9077
  // A retain snapshot: in the row's partition, at a version key.
@@ -8160,7 +9117,7 @@ const makeImpl = (config, precomputedData) => {
8160
9117
  // every write carrying it asks (`internal/FormGuard.ts`, #238); its
8161
9118
  // attribute is no input of the rest.
8162
9119
  const mainItem = items[roles.findIndex((role) => role._tag === "main")];
8163
- const guarded = mainItem?.Update ?? mainItem?.Put ?? mainItem?.Delete;
9120
+ const guarded = mainItem?.Update ?? mainItem?.Put ?? mainItem?.Delete ?? mainItem?.ConditionCheck;
8164
9121
  const conditionAttrs = [
8165
9122
  ...new Set((guarded?.ConditionExpression?.match(/#[A-Za-z0-9_]+/g) ?? []).flatMap((token) => {
8166
9123
  const attr = guarded?.ExpressionAttributeNames?.[token];
@@ -8222,12 +9179,12 @@ const makeImpl = (config, precomputedData) => {
8222
9179
  return ownRow === undefined
8223
9180
  ? lostRace(undefined)
8224
9181
  : { _tag: "Fail", error: historyConflict(role.version, operation) };
8225
- case "main":
8226
- main =
8227
- reason.Item === undefined
8228
- ? "absent"
8229
- : reason.Item;
9182
+ case "main": {
9183
+ // A projection tombstone there is the row removed: absent, as a read reports it.
9184
+ const stored = liveRow(reason.Item);
9185
+ main = stored === undefined ? "absent" : stored;
8230
9186
  break;
9187
+ }
8231
9188
  case "side":
8232
9189
  sideFailed = true;
8233
9190
  }
@@ -8271,11 +9228,100 @@ const makeImpl = (config, precomputedData) => {
8271
9228
  // `.keepRefs()`'s guard is the caller's: a row holding another ref fails it, unchanged.
8272
9229
  callerCondition: uState.condition !== undefined || prepared.kept !== undefined,
8273
9230
  expectedVersion: uState.expectedVersion,
8274
- refuse: (row) => fallbackRefusal(prepared.operands.fallbacks, row),
9231
+ // A restated immutable value the row doesn't hold is refused as standalone refuses it
9232
+ // (`ValidationError`), never sent and retried as a lost race.
9233
+ refuse: (row) => {
9234
+ const immutableChange = immutableMismatch(prepared.immutables, row);
9235
+ return immutableChange !== undefined
9236
+ ? new ValidationError({ entityType, operation: "update", cause: immutableChange })
9237
+ : fallbackRefusal(prepared.operands.fallbacks, row);
9238
+ },
8275
9239
  });
8276
9240
  // ---------------------------------------------------------------------------
8277
9241
  // delete operation
8278
9242
  // ---------------------------------------------------------------------------
9243
+ /**
9244
+ * The parts of the transaction a read-first delete sends (#133), for the item at `primaryKey`:
9245
+ * the main `Delete`'s condition (its guard on the row as read, ANDed with the caller's), the
9246
+ * owned sentinels' releases, and how a cancellation of it reads. `delete` sends them for an
9247
+ * entity with `unique`, retain or soft delete, and `purge` for a unique entity's live row
9248
+ * (#132), so the two can't drift.
9249
+ */
9250
+ const hardDeleteParts = ({ encodedKey, primaryKey, userCondition, }) => {
9251
+ const primary = config.indexes.primary;
9252
+ /** The guard ANDed with the user's condition, for the main Delete. */
9253
+ const guardedDeleteCondition = (guard) => {
9254
+ const values = { ...guard.values, ...userCondition?.values };
9255
+ return {
9256
+ ConditionExpression: userCondition
9257
+ ? `${guard.expression} AND (${userCondition.expression})`
9258
+ : guard.expression,
9259
+ ExpressionAttributeNames: { ...guard.names, ...userCondition?.names },
9260
+ ...(Object.keys(values).length > 0 && { ExpressionAttributeValues: values }),
9261
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
9262
+ };
9263
+ };
9264
+ /**
9265
+ * Run a guarded delete transaction: index 0 is the main Delete, the
9266
+ * only conditioned item, so its rejection is read from the stored
9267
+ * item (ALL_OLD) — gone, raced, or the user's condition.
9268
+ */
9269
+ const guardedDelete = (write, read, inputs, snapshotAt, releases) => {
9270
+ let rejected;
9271
+ const reject = (stored) => {
9272
+ rejected = stored;
9273
+ // Deleted since the read: with nothing asserted, read it again —
9274
+ // a delete of a missing item reports what such a delete does.
9275
+ if (stored === undefined && userCondition === undefined) {
9276
+ return new DeletedConcurrently();
9277
+ }
9278
+ return deleteRejection(encodedKey, read, inputs, stored, userCondition !== undefined);
9279
+ };
9280
+ return withCurrentItem(write.pipe(Effect.mapError((err) => {
9281
+ if (isAwsTransactionCancelled(err.cause)) {
9282
+ const main = err.cause.CancellationReasons?.[0];
9283
+ if (main?.Code === "ConditionalCheckFailed")
9284
+ return reject(main.Item);
9285
+ if (snapshotAt !== undefined &&
9286
+ err.cause.CancellationReasons?.[snapshotAt.index]?.Code === "ConditionalCheckFailed") {
9287
+ return historyConflict(snapshotAt.version, "delete");
9288
+ }
9289
+ for (const { index, constraintName } of releases) {
9290
+ if (err.cause.CancellationReasons?.[index]?.Code === "ConditionalCheckFailed") {
9291
+ return releaseRaced(encodedKey, constraintName);
9292
+ }
9293
+ }
9294
+ }
9295
+ if (isAwsConditionalCheckFailed(err.cause))
9296
+ return reject(err.cause.Item);
9297
+ return err;
9298
+ })), () => rejected);
9299
+ };
9300
+ /**
9301
+ * Append a release for each sentinel the stored item `raw` holds AND
9302
+ * owns (#133) — composed from its domain view, since the stored row is
9303
+ * attribute-keyed and the constraint is not (#127) — returning where
9304
+ * each landed, so a release that lost a race can be reported.
9305
+ */
9306
+ const ownedReleases = (table, raw, into) => Effect.gen(function* () {
9307
+ const rawDomain = toDomainView(raw);
9308
+ const held = [];
9309
+ for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
9310
+ const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, rawDomain, readSentinelValue);
9311
+ if (!sentinel)
9312
+ continue;
9313
+ held.push({ ...sentinel.key, constraintName });
9314
+ }
9315
+ const owner = { pk: primaryKey[primary.pk.field], sk: primaryKey[primary.sk.field] };
9316
+ const releases = [];
9317
+ for (const sentinel of yield* ownedSentinels(table, held, owner)) {
9318
+ releases.push({ index: into.length, constraintName: sentinel.constraintName });
9319
+ into.push(sentinelRelease(table, sentinel, owner));
9320
+ }
9321
+ return releases;
9322
+ });
9323
+ return { guardedDeleteCondition, guardedDelete, ownedReleases };
9324
+ };
8279
9325
  const del = (key) => new EntityDeleteImpl((opts) => Effect.gen(function* () {
8280
9326
  const client = yield* Capacity.client;
8281
9327
  const tc = yield* tableTag;
@@ -8320,13 +9366,17 @@ const makeImpl = (config, precomputedData) => {
8320
9366
  if (opts.returnValues !== "allOld" || old === undefined)
8321
9367
  return Effect.succeed(undefined);
8322
9368
  const raw = fromAttributeMap(old);
8323
- // The delete is applied: a decode failure must not read as a refusal.
8324
- return decodeAs({ ...raw }, old, "model").pipe(Effect.mapError((cause) => new DeleteAppliedButUnreadable({
8325
- entityType,
8326
- key: encodedKey,
8327
- item: raw,
8328
- cause,
8329
- })));
9369
+ // The delete is applied: a decode failure must not read as a
9370
+ // refusal. A store failure resolving the removed item's pointers
9371
+ // (#179) is its own `BlobStoreError { committed: true }`.
9372
+ return decodeWritten({ ...raw }, old, "model", "delete").pipe(Effect.mapError((cause) => cause._tag === "BlobStoreError"
9373
+ ? cause
9374
+ : new DeleteAppliedButUnreadable({
9375
+ entityType,
9376
+ key: encodedKey,
9377
+ item: raw,
9378
+ cause,
9379
+ })));
8330
9380
  };
8331
9381
  /** The item is missing: what a delete that read it reports. */
8332
9382
  const missing = (otherwise) => mustExist
@@ -8354,77 +9404,10 @@ const makeImpl = (config, precomputedData) => {
8354
9404
  }
8355
9405
  return err;
8356
9406
  };
8357
- /** The guard ANDed with the user's condition, for the main Delete. */
8358
- const guardedDeleteCondition = (guard) => {
8359
- const values = { ...guard.values, ...userCondition?.values };
8360
- return {
8361
- ConditionExpression: userCondition
8362
- ? `${guard.expression} AND (${userCondition.expression})`
8363
- : guard.expression,
8364
- ExpressionAttributeNames: { ...guard.names, ...userCondition?.names },
8365
- ...(Object.keys(values).length > 0 && { ExpressionAttributeValues: values }),
8366
- ReturnValuesOnConditionCheckFailure: "ALL_OLD",
8367
- };
8368
- };
8369
- /**
8370
- * Run a guarded delete transaction: index 0 is the main Delete, the
8371
- * only conditioned item, so its rejection is read from the stored
8372
- * item (ALL_OLD) — gone, raced, or the user's condition.
8373
- */
8374
- const guardedDelete = (write, read, inputs, snapshotAt, releases) => {
8375
- let rejected;
8376
- const reject = (stored) => {
8377
- rejected = stored;
8378
- // Deleted since the read: with nothing asserted, read it again —
8379
- // a delete of a missing item reports what such a delete does.
8380
- if (stored === undefined && userCondition === undefined) {
8381
- return new DeletedConcurrently();
8382
- }
8383
- return deleteRejection(encodedKey, read, inputs, stored, userCondition !== undefined);
8384
- };
8385
- return withCurrentItem(write.pipe(Effect.mapError((err) => {
8386
- if (isAwsTransactionCancelled(err.cause)) {
8387
- const main = err.cause.CancellationReasons?.[0];
8388
- if (main?.Code === "ConditionalCheckFailed")
8389
- return reject(main.Item);
8390
- if (snapshotAt !== undefined &&
8391
- err.cause.CancellationReasons?.[snapshotAt.index]?.Code ===
8392
- "ConditionalCheckFailed") {
8393
- return historyConflict(snapshotAt.version, "delete");
8394
- }
8395
- for (const { index, constraintName } of releases) {
8396
- if (err.cause.CancellationReasons?.[index]?.Code === "ConditionalCheckFailed") {
8397
- return releaseRaced(encodedKey, constraintName);
8398
- }
8399
- }
8400
- }
8401
- if (isAwsConditionalCheckFailed(err.cause))
8402
- return reject(err.cause.Item);
8403
- return err;
8404
- })), () => rejected);
8405
- };
8406
- /**
8407
- * Append a release for each sentinel the stored item `raw` holds AND
8408
- * owns (#133) — composed from its domain view, since the stored row is
8409
- * attribute-keyed and the constraint is not (#127) — returning where
8410
- * each landed, so a release that lost a race can be reported.
8411
- */
8412
- const ownedReleases = (table, raw, into) => Effect.gen(function* () {
8413
- const rawDomain = toDomainView(raw);
8414
- const held = [];
8415
- for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
8416
- const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, rawDomain, readSentinelValue);
8417
- if (!sentinel)
8418
- continue;
8419
- held.push({ ...sentinel.key, constraintName });
8420
- }
8421
- const owner = { pk: primaryKey[primary.pk.field], sk: primaryKey[primary.sk.field] };
8422
- const releases = [];
8423
- for (const sentinel of yield* ownedSentinels(table, held, owner)) {
8424
- releases.push({ index: into.length, constraintName: sentinel.constraintName });
8425
- into.push(sentinelRelease(table, sentinel, owner));
8426
- }
8427
- return releases;
9407
+ const { guardedDeleteCondition, guardedDelete, ownedReleases } = hardDeleteParts({
9408
+ encodedKey: encodedKey,
9409
+ primaryKey,
9410
+ userCondition,
8428
9411
  });
8429
9412
  if (isSoftDeleteEnabled() || hasUniqueConstraints || isRetainEnabled()) {
8430
9413
  const readFirst = Effect.gen(function* () {
@@ -8663,7 +9646,13 @@ const makeImpl = (config, precomputedData) => {
8663
9646
  */
8664
9647
  const guardedUpsert = (input, mode, opts,
8665
9648
  /** The stored item, when the caller has it: a rejected write returned it. */
8666
- stored) => Effect.gen(function* () {
9649
+ stored,
9650
+ /**
9651
+ * A plain upsert's `UpdateItem` was rejected for item size under an item
9652
+ * budget (#179, design §6.3): an existing item is updated on the
9653
+ * read-merge branch, which routes the whole merged item.
9654
+ */
9655
+ forceReadMerge = false) => Effect.gen(function* () {
8667
9656
  const client = yield* Capacity.client;
8668
9657
  const { name: tableName } = yield* tableTag;
8669
9658
  const now = yield* DateTime.now;
@@ -8758,13 +9747,16 @@ const makeImpl = (config, precomputedData) => {
8758
9747
  return yield* created;
8759
9748
  continue;
8760
9749
  }
8761
- const updated = yield* Effect.exit(runUpdate(key, mode, {
9750
+ const upsertState = {
8762
9751
  ...emptyUpdateState,
8763
9752
  updates,
8764
9753
  condition: opts.condition,
8765
9754
  withVectors: opts.withVectors,
8766
9755
  upsertOver: { fill },
8767
- }, current).pipe(
9756
+ };
9757
+ const updated = yield* Effect.exit((forceReadMerge
9758
+ ? runUpdate(key, mode, upsertState, current, true)
9759
+ : runUpdateSized(key, mode, upsertState, current)).pipe(
8768
9760
  // Its errors name the upsert, not the update it runs.
8769
9761
  Effect.mapError((e) => e instanceof ValidationError && e.operation.startsWith("update")
8770
9762
  ? new ValidationError({
@@ -8807,7 +9799,9 @@ const makeImpl = (config, precomputedData) => {
8807
9799
  current: Option.none(),
8808
9800
  });
8809
9801
  });
8810
- const upsert = (input) => new EntityPutImpl((mode, opts) => Effect.gen(function* () {
9802
+ const upsert = (rawInput) => new EntityPutImpl((mode, opts) => Effect.gen(function* () {
9803
+ // Binary inputs (#179, design §3.8) become their placeholders.
9804
+ const input = yield* prepareInput(rawInput, "upsert");
8811
9805
  const lacks = writeLacks();
8812
9806
  // A primary key over `createdAt` the input doesn't supply names no item that exists yet.
8813
9807
  if (systemFields.createdAt !== null &&
@@ -8884,6 +9878,10 @@ const makeImpl = (config, precomputedData) => {
8884
9878
  // The sparse maps a `field:` rename stores whole whose entries this upsert writes as
8885
9879
  // attributes of their own: guarded on the row not holding the map whole (#238).
8886
9880
  const entriesWritten = new Set();
9881
+ // Offloaded values (#179): set inline, uploaded once the request is
9882
+ // otherwise built — each before it becomes its `:v`; an immutable one
9883
+ // keeps `if_not_exists`, and the ledger settles it by `ALL_NEW`.
9884
+ const offloadSets = [];
8887
9885
  // The physical key attributes (`pk` / `sk`) live in `Key` and cannot
8888
9886
  // appear in an UpdateExpression. The COMPOSITE SOURCE fields are
8889
9887
  // ordinary attributes and must be written like any other model field —
@@ -8962,6 +9960,9 @@ const makeImpl = (config, precomputedData) => {
8962
9960
  const set = yield* setOf(attr, val, "upsert");
8963
9961
  names[nameKey] = set.attribute;
8964
9962
  values[valKey] = set.value;
9963
+ if (offloadInfo !== undefined && OffloadWrite.isOffloaded(offloadInfo, set.attribute)) {
9964
+ offloadSets.push({ valKey, attr: set.attribute });
9965
+ }
8965
9966
  placeholders.set(attr, [nameKey, valKey]);
8966
9967
  // Immutable fields use if_not_exists — only set on first create
8967
9968
  if (immutableFields.has(attr)) {
@@ -9126,6 +10127,9 @@ const makeImpl = (config, precomputedData) => {
9126
10127
  };
9127
10128
  // The row a key guard's rejection returned: DynamoDB charges no read for it.
9128
10129
  const rejected = {};
10130
+ if (offloadInfo !== undefined && offloadSets.length > 0) {
10131
+ yield* OffloadWrite.setValues(offloadInfo, offloadSets, values, offloadRow(primaryKey, tableName, "upsert"));
10132
+ }
9129
10133
  const mapUpsertFailure = (err) => {
9130
10134
  if (isAwsConditionalCheckFailed(err.cause)) {
9131
10135
  const corrupt = versionCorruption(err.cause.Item, "upsert");
@@ -9154,14 +10158,21 @@ const makeImpl = (config, precomputedData) => {
9154
10158
  }
9155
10159
  return err;
9156
10160
  };
9157
- const written = yield* client.updateItem(upsertInput).pipe(Effect.mapError(mapUpsertFailure), diagnoseItemWrite("upsert", {
10161
+ // An entity with an item budget: rejected for item size, the upsert
10162
+ // runs once more through the read-then-write path, which routes the
10163
+ // whole item (#179, design §6.3).
10164
+ const sizeRetry = (err) => offloadInfo?.itemBudget !== undefined && isItemSizeRejection(err);
10165
+ const written = yield* client.updateItem(upsertInput).pipe(Effect.mapError(mapUpsertFailure), Effect.map((output) => Option.some(output)), Effect.catchIf(sizeRetry, () => Effect.succeed(Option.none())), diagnoseItemWrite("upsert", {
9158
10166
  Update: upsertInput,
9159
10167
  }), Effect.exit);
9160
10168
  // One write couldn't get a key right: compose from the row. If it was the caller's
9161
10169
  // condition that rejected the write, this write is rejected too.
9162
10170
  if (rejected.row !== undefined)
9163
10171
  return yield* guardedUpsert(input, mode, opts, rejected.row);
9164
- const result = yield* written;
10172
+ const sent = yield* written;
10173
+ if (Option.isNone(sent))
10174
+ return yield* guardedUpsert(input, mode, opts, undefined, true);
10175
+ const result = sent.value;
9165
10176
  if (!result.Attributes) {
9166
10177
  return yield* new ItemNotFound({
9167
10178
  entityType,
@@ -9169,8 +10180,8 @@ const makeImpl = (config, precomputedData) => {
9169
10180
  });
9170
10181
  }
9171
10182
  const raw = fromAttributeMap(result.Attributes);
9172
- return yield* decodeAs(raw, result.Attributes, mode);
9173
- }), self, input, undefined, undefined,
10183
+ return yield* decodeWritten(raw, result.Attributes, mode, "upsert");
10184
+ }), self, rawInput, undefined, undefined,
9174
10185
  // Tagged so the transact/batch compilers can refuse it: this op is an
9175
10186
  // UpdateItem with `if_not_exists`, not a Put (#100).
9176
10187
  "upsert");
@@ -9369,7 +10380,9 @@ const makeImpl = (config, precomputedData) => {
9369
10380
  const removes = [...(requestedRemoves ?? [])].filter((attr) => !removedToDefault.some(([name]) => name === attr));
9370
10381
  const namedRemoves = removes.length > 0 ? new Set(removes) : undefined;
9371
10382
  // Encode user input via appendInputSchema (see `put` for strategy).
9372
- const encodedInput = yield* encodeForWrite(appendInputSchema, removedToDefault.length === 0 ? input : { ...input, ...defaulted }, "append");
10383
+ const encodedInput = yield* encodeForWrite(appendInputSchema, yield* prepareInput(removedToDefault.length === 0
10384
+ ? input
10385
+ : { ...input, ...defaulted }, "append"), "append");
9373
10386
  const encoded = encodedInput;
9374
10387
  // After encoding, detect SET/REMOVE conflict — DynamoDB rejects an
9375
10388
  // UpdateExpression that touches the same attribute in SET and REMOVE.
@@ -9479,6 +10492,9 @@ const makeImpl = (config, precomputedData) => {
9479
10492
  // attributes on the item (mirrors `.put()`), and though their values
9480
10493
  // never change, writing them on every append makes the first append
9481
10494
  // (where the row doesn't yet exist) materialise the row correctly.
10495
+ // Offloaded `appendInput` fields (#179): uploaded once the request is
10496
+ // built, keyed by the event item (design §6.8).
10497
+ const appendOffloads = [];
9482
10498
  for (const [attr, val] of Object.entries(serialisedInput)) {
9483
10499
  if (val === undefined || isEmptySet(val))
9484
10500
  continue;
@@ -9487,6 +10503,9 @@ const makeImpl = (config, precomputedData) => {
9487
10503
  const storedName = resolveDbName(attr);
9488
10504
  names[nameKey] = storedName;
9489
10505
  values[valKey] = toAttributeValue(Object.hasOwn(packedFields, attr) ? packedStored[storedName] : val);
10506
+ if (offloadInfo !== undefined && OffloadWrite.isOffloaded(offloadInfo, storedName)) {
10507
+ appendOffloads.push({ valKey, attr: storedName });
10508
+ }
9490
10509
  setClauses.push(`${nameKey} = ${valKey}`);
9491
10510
  counter++;
9492
10511
  }
@@ -9649,6 +10668,26 @@ const makeImpl = (config, precomputedData) => {
9649
10668
  delete eventItem[k];
9650
10669
  }
9651
10670
  }
10671
+ // Offloaded `appendInput` values (#179, design §6.8): uploaded once —
10672
+ // thresholds only (the append's CAS transaction has no read-merge
10673
+ // form) — under the EVENT item's key, and the one pointer is SET on the
10674
+ // current item and written on the event item.
10675
+ if (offloadInfo !== undefined && appendOffloads.length > 0) {
10676
+ const staged = {};
10677
+ for (const { attr } of appendOffloads)
10678
+ staged[attr] = eventItem[attr];
10679
+ const row = {
10680
+ ...offloadRow({ [primary.pk.field]: pkValue, [primary.sk.field]: currentSk }, tableName, "append"),
10681
+ rowSk: { S: eventSk },
10682
+ };
10683
+ const { uploaded } = yield* OffloadWrite.route({ ...offloadInfo, itemBudget: undefined }, staged, row);
10684
+ for (const { valKey, attr } of appendOffloads) {
10685
+ if (!uploaded.has(attr))
10686
+ continue;
10687
+ values[valKey] = toAttributeValue(staged[attr]);
10688
+ eventItem[attr] = staged[attr];
10689
+ }
10690
+ }
9652
10691
  const marshalledEventItem = toAttributeMap(eventItem);
9653
10692
  /**
9654
10693
  * DynamoDB's refusal of the guard on the stored `orderBy` (`#_tsob < :_tsNewOb`), as
@@ -9758,6 +10797,14 @@ const makeImpl = (config, precomputedData) => {
9758
10797
  };
9759
10798
  /** The current item, decoded — for a result or an error's `current`. */
9760
10799
  const decodeCurrent = (item) => decodeAs(fromAttributeMap(item), item, "model");
10800
+ /**
10801
+ * The current item for an error's `current`: an error payload never does
10802
+ * store I/O (#179, §6.13) — an offloading entity's offloaded fields are
10803
+ * lazy handles.
10804
+ */
10805
+ const errorCurrent = (item) => Effect.map(decodeAs(fromAttributeMap(item), item, "model", {
10806
+ noFetch: true,
10807
+ }), (decoded) => Option.some(decoded));
9761
10808
  const staleAppend = (current) => new StaleAppend({ entityType, orderByField, attemptedOrderBy: newObValue, current });
9762
10809
  /**
9763
10810
  * The post-append current item: one GetItem (skipped under
@@ -9782,6 +10829,13 @@ const makeImpl = (config, precomputedData) => {
9782
10829
  cause: "Current item not found after append — possible TTL race or concurrent delete.",
9783
10830
  });
9784
10831
  }
10832
+ // An offloading entity's result resolves its pointers — this append's
10833
+ // from the ledger's read cache (#179, §6.13).
10834
+ if (offloadInfo !== undefined) {
10835
+ const raw = fromAttributeMap(followUp.Item);
10836
+ const current = yield* decodeWritten(raw, followUp.Item, "model", "append");
10837
+ return { current: current };
10838
+ }
9785
10839
  return { current: yield* decodeCurrent(followUp.Item) };
9786
10840
  });
9787
10841
  const readCurrentRow = () => client
@@ -9814,7 +10868,7 @@ const makeImpl = (config, precomputedData) => {
9814
10868
  (storedOb === undefined || !((yield* storedKeyForm(storedOb)) < attempted))) {
9815
10869
  return yield* skipFollowUp
9816
10870
  ? staleAppend(Option.none())
9817
- : staleAppend(Option.some(yield* decodeCurrent(current)));
10871
+ : staleAppend(yield* errorCurrent(current));
9818
10872
  }
9819
10873
  if (createdAtKeyed) {
9820
10874
  const stored = ownValue(current, resolveDbName(systemFields.createdAt));
@@ -9845,7 +10899,7 @@ const makeImpl = (config, precomputedData) => {
9845
10899
  // reported as stale too).
9846
10900
  if (skipFollowUp)
9847
10901
  return yield* staleAppend(Option.none());
9848
- const decoded = again === undefined ? Option.none() : Option.some(yield* decodeCurrent(again));
10902
+ const decoded = again === undefined ? Option.none() : yield* errorCurrent(again);
9849
10903
  return yield* userCondition !== undefined
9850
10904
  ? new ConditionalCheckFailed({
9851
10905
  entityType,
@@ -9951,7 +11005,27 @@ const makeImpl = (config, precomputedData) => {
9951
11005
  });
9952
11006
  }
9953
11007
  const rawCurrent = fromAttributeMap(followUp.Item);
9954
- const currentModel = yield* decodeAs(rawCurrent, followUp.Item, "model");
11008
+ if (offloadInfo !== undefined) {
11009
+ // An offloading entity (#179): a stale append's error payload never
11010
+ // does I/O — its offloaded fields are lazy handles.
11011
+ const storedOrderBy = fromAttributeMap(followUp.Item)[resolveDbName(orderByField)];
11012
+ const current = Option.some(yield* decodeAs(rawCurrent, followUp.Item, "model", { noFetch: true }));
11013
+ if (!isCasFailure(storedOrderBy, newObValue) && userCondition !== undefined) {
11014
+ return yield* new ConditionalCheckFailed({
11015
+ entityType,
11016
+ key: encoded,
11017
+ current,
11018
+ });
11019
+ }
11020
+ return yield* new StaleAppend({
11021
+ entityType,
11022
+ orderByField,
11023
+ attemptedOrderBy: newObValue,
11024
+ current,
11025
+ });
11026
+ }
11027
+ // A stale append's `current` is an error payload: no store I/O (§6.13).
11028
+ const currentModel = yield* decodeAs(rawCurrent, followUp.Item, "model", { noFetch: true });
9955
11029
  // Compare in the WIRE form (what DynamoDB evaluated): `newObValue` is
9956
11030
  // the encoded value passed to the CAS, and `rawCurrent` carries the
9957
11031
  // encoded values read back. `decodeAs` mutated `rawCurrent` to rename
@@ -9975,7 +11049,9 @@ const makeImpl = (config, precomputedData) => {
9975
11049
  // history operation — BoundQuery for event items only
9976
11050
  // ---------------------------------------------------------------------------
9977
11051
  // The public `append`: the core as the named operation (consumed capacity, #174).
9978
- const append = (input, givenCondition, skipFollowUp = false, removeAttrs) => Capacity.operation("Entity.append", { target: entityType }, appendCore(input, givenCondition, skipFollowUp, removeAttrs));
11052
+ const append = (input, givenCondition, skipFollowUp = false, removeAttrs,
11053
+ // Internal: the bound builder's `.offloaded()` modes for `current` (#179).
11054
+ offloadModes) => Capacity.operation("Entity.append", { target: entityType }, withReadModes(self, offloadModes, BlobLedger.rootIf(data.offload !== undefined, appendCore(input, givenCondition, skipFollowUp, removeAttrs))));
9979
11055
  const historyQuery = (key) => {
9980
11056
  if (!timeSeriesConfig) {
9981
11057
  throw new Error(`[EDD-9010] Entity "${entityType}": .history() requires timeSeries config on the entity.`);
@@ -9985,15 +11061,15 @@ const makeImpl = (config, precomputedData) => {
9985
11061
  const pkValue = KeyComposer.composePk(schema, entityType, primary, keyForm(encodedKey));
9986
11062
  const currentSk = KeyComposer.composeSk(schema, entityType, entityVersion, primary, keyForm(encodedKey));
9987
11063
  const prefix = KeyComposer.composeEventSkPrefix(currentSk, schema.casing);
9988
- const decodeHistory = (raw) => {
11064
+ const decodeHistory = (raw, modes) => {
9989
11065
  // Sparse fields are aggregate state, not event state — event items DO
9990
11066
  // NOT carry `<prefix>#*` attributes. `deserializeSparseFields` populates
9991
11067
  // empty `{}` Records under the domain field names so the historyRecord
9992
11068
  // schema (which still includes the sparse Record fields) decodes.
9993
- return Effect.flatMap(unpackFields(raw, "history.decode"), () => {
11069
+ return Effect.flatMap(loadRow(raw, { operation: "history.decode", modes }), () => {
9994
11070
  deserializeSparseFields(raw);
9995
11071
  renameFromDynamo(raw);
9996
- return Schema.decodeUnknownEffect(schemas.historyRecordSchema)(raw).pipe(Effect.map(attachPrototype), Effect.mapError((cause) => new ValidationError({
11072
+ return Schema.decodeUnknownEffect(readSchema(schemas.historyRecordSchema, modes))(raw).pipe(Effect.map(attachPrototype), Effect.mapError((cause) => new ValidationError({
9997
11073
  entityType,
9998
11074
  operation: "history.decode",
9999
11075
  cause,
@@ -10009,7 +11085,7 @@ const makeImpl = (config, precomputedData) => {
10009
11085
  pkValue,
10010
11086
  skField: primary.sk.field,
10011
11087
  entityTypes: [entityType],
10012
- decoder: (raw) => decodeHistory(raw),
11088
+ decoder: (raw, modes) => decodeHistory(raw, modes),
10013
11089
  ...packedQueryOptions,
10014
11090
  resolveTableName: tableTag.useSync((tc) => tc.name),
10015
11091
  keyFields: [primary.pk.field, primary.sk.field],
@@ -10062,7 +11138,7 @@ const makeImpl = (config, precomputedData) => {
10062
11138
  pkValue,
10063
11139
  skField: indexDef.sk.field,
10064
11140
  entityTypes: [entityType],
10065
- decoder: (raw) => decodeRecord(raw),
11141
+ decoder: (raw, modes) => decodeRecord(raw, modes, "query.decode"),
10066
11142
  ...packedQueryOptions,
10067
11143
  resolveTableName: tableTag.useSync((tc) => tc.name),
10068
11144
  keyFields: [
@@ -10095,7 +11171,7 @@ const makeImpl = (config, precomputedData) => {
10095
11171
  storedAt: storedFormAt,
10096
11172
  indexName: undefined,
10097
11173
  entityTypes: [entityType],
10098
- decoder: (raw) => decodeRecord(raw),
11174
+ decoder: (raw, modes) => decodeRecord(raw, modes, "scan.decode"),
10099
11175
  ...packedQueryOptions,
10100
11176
  resolveTableName: tableTag.useSync((tc) => tc.name),
10101
11177
  keyFields: [config.indexes.primary.pk.field, config.indexes.primary.sk.field],
@@ -10207,7 +11283,7 @@ const makeImpl = (config, precomputedData) => {
10207
11283
  pkValue,
10208
11284
  skField: primary.sk.field,
10209
11285
  entityTypes: [entityType],
10210
- decoder: (raw) => decodeRecord(raw),
11286
+ decoder: (raw, modes) => decodeRecord(raw, modes, "versions.decode"),
10211
11287
  ...packedQueryOptions,
10212
11288
  resolveTableName: tableTag.useSync((tc) => tc.name),
10213
11289
  keyFields: [primary.pk.field, primary.sk.field],
@@ -10236,8 +11312,9 @@ const makeImpl = (config, precomputedData) => {
10236
11312
  if (mode === "native")
10237
11313
  return tombstone;
10238
11314
  // Packed fields: read by their stored form (copied as-is onto the
10239
- // tombstone, #147).
10240
- yield* unpackFields(raw, "deleted.get.decode");
11315
+ // tombstone, #147); offloaded ones per the read's modes (#179).
11316
+ const modes = yield* OffloadRead.currentModes;
11317
+ yield* loadRow(raw, { operation: "deleted.get.decode", modes });
10241
11318
  // Sparse Map fields: rebuild domain Records from flattened attrs so
10242
11319
  // soft-deleted items decode correctly. Sparse data is preserved
10243
11320
  // verbatim across soft-delete (GSI keys are stripped, sparse data is
@@ -10248,7 +11325,7 @@ const makeImpl = (config, precomputedData) => {
10248
11325
  // (#127). Without it a `field:`-renamed attribute decodes as a missing
10249
11326
  // key and every soft-deleted row of such an entity is unreadable.
10250
11327
  renameFromDynamo(raw);
10251
- const targetSchema = schemas.deletedRecordSchema;
11328
+ const targetSchema = readSchema(schemas.deletedRecordSchema, modes);
10252
11329
  return yield* Schema.decodeUnknownEffect(targetSchema)(raw).pipe(Effect.map(attachPrototype), Effect.mapError((cause) => new ValidationError({
10253
11330
  entityType,
10254
11331
  operation: "deleted.get.decode",
@@ -10262,17 +11339,17 @@ const makeImpl = (config, precomputedData) => {
10262
11339
  // The whole partition's tombstones — every item's, with sort key
10263
11340
  // composites (#133): no item segment.
10264
11341
  const deletedPrefix = DynamoSchema.composeDeletedKeyPrefix(schema, entityType);
10265
- const decodeDeleted = (raw) => {
11342
+ const decodeDeleted = (raw, modes) => {
10266
11343
  const corruption = versionCorruption(raw, "deleted.list.decode");
10267
11344
  if (corruption !== undefined)
10268
11345
  return Effect.fail(corruption);
10269
- return Effect.flatMap(unpackFields(raw, "deleted.list.decode"), () => {
11346
+ return Effect.flatMap(loadRow(raw, { operation: "deleted.list.decode", modes }), () => {
10270
11347
  // Sparse fields are domain data and are preserved across soft-delete.
10271
11348
  // Rebuild Records from flattened attrs before schema decode.
10272
11349
  deserializeSparseFields(raw);
10273
11350
  // Then attribute → domain names, same order as `decodeRecord` (#127).
10274
11351
  renameFromDynamo(raw);
10275
- return Schema.decodeUnknownEffect(schemas.deletedRecordSchema)(raw).pipe(Effect.map(attachPrototype), Effect.mapError((cause) => new ValidationError({
11352
+ return Schema.decodeUnknownEffect(readSchema(schemas.deletedRecordSchema, modes))(raw).pipe(Effect.map(attachPrototype), Effect.mapError((cause) => new ValidationError({
10276
11353
  entityType,
10277
11354
  operation: "deleted.list.decode",
10278
11355
  cause,
@@ -10288,7 +11365,7 @@ const makeImpl = (config, precomputedData) => {
10288
11365
  pkValue,
10289
11366
  skField: primary.sk.field,
10290
11367
  entityTypes: [],
10291
- decoder: (raw) => decodeDeleted(raw),
11368
+ decoder: (raw, modes) => decodeDeleted(raw, modes),
10292
11369
  ...packedQueryOptions,
10293
11370
  resolveTableName: tableTag.useSync((tc) => tc.name),
10294
11371
  keyFields: [primary.pk.field, primary.sk.field],
@@ -10477,7 +11554,7 @@ const makeImpl = (config, precomputedData) => {
10477
11554
  }
10478
11555
  return err;
10479
11556
  }), diagnoseTransactionWrite("restore", transactItems));
10480
- return yield* decodeAs(restoredItem, marshalledRestoredItem, mode);
11557
+ return yield* decodeWritten(restoredItem, marshalledRestoredItem, mode, "restore");
10481
11558
  }), self, key);
10482
11559
  // ---------------------------------------------------------------------------
10483
11560
  // purge operation
@@ -10504,10 +11581,25 @@ const makeImpl = (config, precomputedData) => {
10504
11581
  const { name: tableName } = yield* tableTag;
10505
11582
  // Caller key: Type side in, ENCODED out (see `encodeKey`).
10506
11583
  const encodedKey = yield* encodeKey(key, "purge.decode");
11584
+ // An entity that offloads deletes the purged item's versions once
11585
+ // its rows are gone (#179, design §11.6): without a store that step
11586
+ // could not run, so the purge fails before deleting anything rather
11587
+ // than leave the versions behind with no row to name them.
11588
+ const store = offloadInfo === undefined
11589
+ ? undefined
11590
+ : Option.getOrUndefined(yield* Effect.serviceOption(BlobStore));
11591
+ if (offloadInfo !== undefined && store === undefined) {
11592
+ return yield* blobError({
11593
+ entityType,
11594
+ attribute: offloadedAttributeNames.length === 1 ? offloadedAttributeNames[0] : "(several)",
11595
+ operation: "Entity.purge",
11596
+ }, "delete", "NotProvided", undefined, "no BlobStore is in context: purge deletes the item's offloaded versions after its " +
11597
+ "rows, so provide one (DynamoClient.make({ blobStore }), BlobStore.layer, or the " +
11598
+ "S3 store's layer) where the operation runs or the client is bound");
11599
+ }
10507
11600
  const primary = config.indexes.primary;
10508
11601
  const pkValue = KeyComposer.composePk(schema, entityType, primary, keyForm(encodedKey));
10509
11602
  const liveSk = liveSkOf(encodedKey);
10510
- const allItems = [];
10511
11603
  const history = historyKeyOptions(liveSk);
10512
11604
  /**
10513
11605
  * Whether a row of the partition is this item's (#133). Only this
@@ -10556,97 +11648,195 @@ const makeImpl = (config, precomputedData) => {
10556
11648
  };
10557
11649
  // Query ALL items in this partition (current + versions + deleted).
10558
11650
  // Keys and entity type only — plus, with sort key composites, the
10559
- // composites that attribute an unsegmented history row to its item.
11651
+ // composites that attribute an unsegmented history row to its item,
11652
+ // and the offloaded attributes, whose pointers name the versions the
11653
+ // store step deletes (#179).
10560
11654
  const projected = { "#ent": "__edd_e__" };
10561
11655
  if (history !== undefined) {
10562
11656
  primary.sk.composite.forEach((attr, i) => {
10563
11657
  projected[`#c${i}`] = resolveDbName(attr);
10564
11658
  });
10565
11659
  }
10566
- let exclusiveStartKey;
10567
- do {
10568
- const result = yield* client.query({
10569
- TableName: tableName,
10570
- KeyConditionExpression: "#pk = :pk",
10571
- ExpressionAttributeNames: {
10572
- "#pk": primary.pk.field,
10573
- "#sk": primary.sk.field,
10574
- ...projected,
10575
- },
10576
- ExpressionAttributeValues: { ":pk": toAttributeValue(pkValue) },
10577
- ProjectionExpression: ["#pk", "#sk", ...Object.keys(projected)].join(", "),
10578
- ExclusiveStartKey: exclusiveStartKey,
10579
- });
10580
- allItems.push(...(result.Items ?? []).filter(belongsToItem));
10581
- exclusiveStartKey = result.LastEvaluatedKey;
10582
- } while (exclusiveStartKey);
10583
- // The unique sentinels the item holds — live, or soft-deleted with
10584
- // `preserveUnique` — and owns (#133): a sentinel of a value the item
10585
- // holds without owning its reservation belongs to another item.
10586
- if (config.unique && Object.keys(config.unique).length > 0) {
10587
- const owner = { pk: pkValue, sk: liveSk };
10588
- const holders = [];
10589
- const mainResult = yield* client.getItem({
10590
- TableName: tableName,
10591
- Key: toAttributeMap({ [primary.pk.field]: owner.pk, [primary.sk.field]: owner.sk }),
10592
- ConsistentRead: true,
10593
- });
10594
- if (mainResult.Item)
10595
- holders.push(mainResult.Item);
10596
- // Every soft-deleted incarnation (each kept its reservations).
10597
- const deletedPrefix = DynamoSchema.composeDeletedKeyPrefix(schema, entityType);
10598
- let deletedStart;
11660
+ offloadedAttributeNames.forEach((attr, i) => {
11661
+ projected[`#o${i}`] = attr;
11662
+ });
11663
+ const hasUniqueConstraints = config.unique !== undefined && Object.keys(config.unique).length > 0;
11664
+ const owner = { pk: pkValue, sk: liveSk };
11665
+ const liveKey = toAttributeMap({
11666
+ [primary.pk.field]: owner.pk,
11667
+ [primary.sk.field]: owner.sk,
11668
+ });
11669
+ const isLiveRow = (row) => row[primary.pk.field]?.S === pkValue && row[primary.sk.field]?.S === liveSk;
11670
+ /**
11671
+ * One attempt: read the item's rows, and with `unique`, delete the live row and the
11672
+ * sentinels it owns in one transaction guarded on the row as read — the one `delete`
11673
+ * sends (#132). A batch delete carries no condition, so a concurrent update moving a
11674
+ * unique value after the read would otherwise leave the new value's sentinel reserving
11675
+ * for a row the batch then deletes. A lost race fails the attempt, and the purge starts
11676
+ * again from the query. Returns every row read, and whether the transaction deleted the
11677
+ * live row.
11678
+ *
11679
+ * The live row is read before the partition query: on a versioned entity its guard then
11680
+ * covers every row the query can see, since a write landing after the read moves the
11681
+ * version and refuses the transaction. Read after the query, a write in between was
11682
+ * guarded against while the rows it added (its snapshot) were missed.
11683
+ */
11684
+ const attempt = Effect.gen(function* () {
11685
+ const mainResult = hasUniqueConstraints
11686
+ ? yield* client.getItem({ TableName: tableName, Key: liveKey, ConsistentRead: true })
11687
+ : undefined;
11688
+ let liveDeleted = false;
11689
+ const allItems = [];
11690
+ let exclusiveStartKey;
10599
11691
  do {
10600
- const deletedResult = yield* client.query({
11692
+ // Consistent (#132): a purge straight after the item's last write sees every row
11693
+ // that write left — a new live row, a fresh snapshot — and deletes it.
11694
+ const result = yield* client.query({
10601
11695
  TableName: tableName,
10602
- KeyConditionExpression: "#pk = :pk AND begins_with(#sk, :skPrefix)",
11696
+ KeyConditionExpression: "#pk = :pk",
10603
11697
  ExpressionAttributeNames: {
10604
11698
  "#pk": primary.pk.field,
10605
11699
  "#sk": primary.sk.field,
11700
+ ...projected,
10606
11701
  },
10607
- ExpressionAttributeValues: {
10608
- ":pk": toAttributeValue(pkValue),
10609
- ":skPrefix": toAttributeValue(deletedPrefix),
10610
- },
11702
+ ExpressionAttributeValues: { ":pk": toAttributeValue(pkValue) },
11703
+ ProjectionExpression: ["#pk", "#sk", ...Object.keys(projected)].join(", "),
10611
11704
  ConsistentRead: true,
10612
- ExclusiveStartKey: deletedStart,
11705
+ ExclusiveStartKey: exclusiveStartKey,
10613
11706
  });
10614
- holders.push(...(deletedResult.Items ?? []).filter(belongsToItem));
10615
- deletedStart = deletedResult.LastEvaluatedKey;
10616
- } while (deletedStart !== undefined);
10617
- // Sparse — fields that were unset never had a sentinel. The stored
10618
- // row is attribute-keyed, the constraint is not (#127).
10619
- const held = new Map();
10620
- for (const holder of holders) {
10621
- const holderDomain = toDomainView(fromAttributeMap(holder));
10622
- for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
10623
- const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, holderDomain, readSentinelValue);
10624
- if (!sentinel)
10625
- continue;
10626
- held.set(`${sentinel.key.pk}\u0000${sentinel.key.sk}`, sentinel.key);
11707
+ allItems.push(...(result.Items ?? []).filter(belongsToItem));
11708
+ exclusiveStartKey = result.LastEvaluatedKey;
11709
+ } while (exclusiveStartKey);
11710
+ // The unique sentinels the item holds — live, or soft-deleted with
11711
+ // `preserveUnique` — and owns (#133): a sentinel of a value the item
11712
+ // holds without owning its reservation belongs to another item.
11713
+ if (hasUniqueConstraints) {
11714
+ // The live row, with the sentinels it owns, in `delete`'s guarded transaction.
11715
+ if (mainResult?.Item) {
11716
+ const live = mainResult.Item;
11717
+ const parts = hardDeleteParts({
11718
+ encodedKey: encodedKey,
11719
+ primaryKey: { [primary.pk.field]: owner.pk, [primary.sk.field]: owner.sk },
11720
+ userCondition: undefined,
11721
+ });
11722
+ const hardGuard = deleteGuard(live, [
11723
+ ...new Set(Object.values(config.unique).flatMap((def) => resolveUniqueFields(def).map(compositeAttribute))),
11724
+ ], undefined);
11725
+ const transactItems = [
11726
+ {
11727
+ Delete: {
11728
+ TableName: tableName,
11729
+ Key: liveKey,
11730
+ ...parts.guardedDeleteCondition(hardGuard),
11731
+ },
11732
+ },
11733
+ ];
11734
+ const releases = yield* parts.ownedReleases(tableName, fromAttributeMap(live), transactItems);
11735
+ yield* parts
11736
+ .guardedDelete(client.transactWriteItems({ TransactItems: transactItems }), live, hardGuard.inputs, undefined, releases)
11737
+ .pipe(
11738
+ // A delete of stored keys meets no size limit; wrapped for uniformity (#144).
11739
+ diagnoseFailure({
11740
+ sent: () => ({
11741
+ _tag: "Transaction",
11742
+ items: transactItems,
11743
+ targets: () => targetsFor(transactItems, entityKeyFields(), entityType, (index) => index === 0 ? "the item" : `item ${index} of the purge transaction`),
11744
+ }),
11745
+ keys: entityKeys,
11746
+ rewrite: (diagnosis, original) => diagnosedValidationError(diagnosis, original, {
11747
+ operation: "purge",
11748
+ entityType,
11749
+ }),
11750
+ }));
11751
+ liveDeleted = true;
11752
+ }
11753
+ // Every soft-deleted incarnation (each kept its reservations).
11754
+ const holders = [];
11755
+ const deletedPrefix = DynamoSchema.composeDeletedKeyPrefix(schema, entityType);
11756
+ let deletedStart;
11757
+ do {
11758
+ const deletedResult = yield* client.query({
11759
+ TableName: tableName,
11760
+ KeyConditionExpression: "#pk = :pk AND begins_with(#sk, :skPrefix)",
11761
+ ExpressionAttributeNames: {
11762
+ "#pk": primary.pk.field,
11763
+ "#sk": primary.sk.field,
11764
+ },
11765
+ ExpressionAttributeValues: {
11766
+ ":pk": toAttributeValue(pkValue),
11767
+ ":skPrefix": toAttributeValue(deletedPrefix),
11768
+ },
11769
+ ConsistentRead: true,
11770
+ ExclusiveStartKey: deletedStart,
11771
+ });
11772
+ holders.push(...(deletedResult.Items ?? []).filter(belongsToItem));
11773
+ deletedStart = deletedResult.LastEvaluatedKey;
11774
+ } while (deletedStart !== undefined);
11775
+ // Sparse — fields that were unset never had a sentinel. The stored
11776
+ // row is attribute-keyed, the constraint is not (#127).
11777
+ const held = new Map();
11778
+ for (const holder of holders) {
11779
+ const holderDomain = toDomainView(fromAttributeMap(holder));
11780
+ for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
11781
+ const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, holderDomain, readSentinelValue);
11782
+ if (!sentinel)
11783
+ continue;
11784
+ held.set(`${sentinel.key.pk}\u0000${sentinel.key.sk}`, sentinel.key);
11785
+ }
11786
+ }
11787
+ // Released one by one, each only while still this item's: a batch
11788
+ // delete cannot carry the ownership condition. A tombstone's
11789
+ // reservation that the live row shared went with it above.
11790
+ for (const sentinel of yield* ownedSentinels(tableName, [...held.values()], owner)) {
11791
+ const release = sentinelRelease(tableName, sentinel, owner);
11792
+ yield* client.deleteItem(release.Delete).pipe(Effect.catchIf((err) => isAwsConditionalCheckFailed(err.cause), () => Effect.void),
11793
+ // A delete of a stored key cannot meet a size limit; wrapped
11794
+ // for uniformity (#144), so it passes through in practice.
11795
+ diagnoseItemWrite("purge", release));
10627
11796
  }
10628
11797
  }
10629
- // Released one by one, each only while still this item's: a batch
10630
- // delete cannot carry the ownership condition.
10631
- for (const sentinel of yield* ownedSentinels(tableName, [...held.values()], owner)) {
10632
- const release = sentinelRelease(tableName, sentinel, owner);
10633
- yield* client.deleteItem(release.Delete).pipe(Effect.catchIf((err) => isAwsConditionalCheckFailed(err.cause), () => Effect.void),
10634
- // A delete of a stored key cannot meet a size limit; wrapped
10635
- // for uniformity (#144), so it passes through in practice.
10636
- diagnoseItemWrite("purge", release));
10637
- }
10638
- }
11798
+ return { allItems, liveDeleted };
11799
+ });
11800
+ // A lost race on the live row is retried from the query, as a read-first delete is;
11801
+ // purge refuses a `.condition()`, so it always is. Once every attempt has lost, it is
11802
+ // what such a delete reports — a row deleted concurrently each time, a change.
11803
+ const { allItems, liveDeleted } = yield* attempt.pipe(Effect.retry({
11804
+ times: GUARDED_PUT_ATTEMPTS - 1,
11805
+ while: (e) => e instanceof OptimisticLockError ||
11806
+ e instanceof ConcurrentModification ||
11807
+ e instanceof DeletedConcurrently,
11808
+ }), Effect.catchIf((e) => e instanceof DeletedConcurrently ||
11809
+ e instanceof ItemNotFound ||
11810
+ e instanceof ConditionalCheckFailed, () => Effect.fail(new ConcurrentModification({
11811
+ entityType,
11812
+ key: encodedKey,
11813
+ attributes: [],
11814
+ current: Option.none(),
11815
+ }))));
11816
+ // With `unique`, the live row went in the transaction: the batch never deletes it, so a
11817
+ // row created after the attempt's read keeps its sentinels with it.
11818
+ const batchItems = hasUniqueConstraints
11819
+ ? allItems.filter((row) => !isLiveRow(row))
11820
+ : allItems;
10639
11821
  // Batch delete in chunks of 25. `UnprocessedItems` are retried with
10640
11822
  // `Batch.write`'s backoff; what the purge had deleted is always
10641
11823
  // stated exactly, whether a request is rejected or retries run out. By count alone: 25
10642
11824
  // stored keys (at most 2048 + 1024 bytes each, so at most about 0.5 MB as JSON) can't
10643
11825
  // reach the 16 MB request limit.
11826
+ // The live row the transaction deleted is one of the partition's items, and counted;
11827
+ // the reservations it released are in other partitions, and named.
11828
+ const inTransaction = liveDeleted ? 1 : 0;
11829
+ const partitionItems = batchItems.length + inTransaction;
10644
11830
  let deleted = 0;
10645
- const deletedSoFar = () => deleted === 0
11831
+ const deletedSoFar = () => deleted + inTransaction === 0
10646
11832
  ? "the purge had deleted none of the partition's items"
10647
- : `the purge had already deleted ${deleted} of the partition's ${allItems.length} items`;
10648
- for (let i = 0; i < allItems.length; i += 25) {
10649
- const chunk = allItems.slice(i, i + 25);
11833
+ : `the purge had already deleted ${deleted + inTransaction} of the partition's ` +
11834
+ `${partitionItems} items` +
11835
+ (liveDeleted
11836
+ ? ", the live item among them, with the reservations of its unique values"
11837
+ : "");
11838
+ for (let i = 0; i < batchItems.length; i += 25) {
11839
+ const chunk = batchItems.slice(i, i + 25);
10650
11840
  let requestItems = {
10651
11841
  [tableName]: chunk.map((item) => ({
10652
11842
  DeleteRequest: {
@@ -10694,7 +11884,7 @@ const makeImpl = (config, precomputedData) => {
10694
11884
  if (retries > MAX_RETRIES) {
10695
11885
  return yield* new DynamoError({
10696
11886
  operation: "BatchWriteItem",
10697
- cause: new Error(`purge: ${remaining} of the partition's ${allItems.length} items were still ` +
11887
+ cause: new Error(`purge: ${remaining} of the partition's ${partitionItems} items were still ` +
10698
11888
  `unprocessed after ${MAX_RETRIES} retries; ${deletedSoFar()}. The rest ` +
10699
11889
  "were not deleted: purge again to finish."),
10700
11890
  });
@@ -10703,6 +11893,21 @@ const makeImpl = (config, precomputedData) => {
10703
11893
  requestItems = unprocessed;
10704
11894
  }
10705
11895
  }
11896
+ // Every DynamoDB delete succeeded: now the store (#179, §11.6). A
11897
+ // failure above leaves it untouched — a partial purge is finished by
11898
+ // purging again. The family is the item's key text: offloading
11899
+ // requires `escapeKeys`, so every row holding a pointer was written
11900
+ // there (design §11.10).
11901
+ if (offloadInfo !== undefined && store !== undefined) {
11902
+ yield* purgeOffloaded({
11903
+ client,
11904
+ store,
11905
+ info: offloadInfo,
11906
+ tableName,
11907
+ family: { pk: pkValue, liveSk },
11908
+ purged: allItems,
11909
+ });
11910
+ }
10706
11911
  }), self, key);
10707
11912
  const rekeyPk = config.indexes.primary.pk.field;
10708
11913
  const rekeySk = config.indexes.primary.sk.field;
@@ -11115,6 +12320,7 @@ const makeImpl = (config, precomputedData) => {
11115
12320
  if (targets === undefined || !sameStoredKey(targets.current, to)) {
11116
12321
  return Rekey.mergeTallies(tally, yield* movedAway(ctx, to));
11117
12322
  }
12323
+ yield* refuseMovingPointerRow(read, from);
11118
12324
  // Its Delete is guarded on the row as read: one nothing proves unchanged is the context's.
11119
12325
  const guard = deleteGuard(read, "item", undefined);
11120
12326
  if (!guard.proves) {
@@ -11461,6 +12667,20 @@ const makeImpl = (config, precomputedData) => {
11461
12667
  * misses a write that only adds an entry to a sparse map, which no declaration names.
11462
12668
  */
11463
12669
  const moveGap = (guard) => guard.by === "stamp" ? "stamp" : guard.by === "row" && hasSparseFields ? "sparse" : undefined;
12670
+ /**
12671
+ * Rekey's backstop (#179, design §11.10): a row holding a blob pointer never moves. Its objects
12672
+ * are named from its key text, so moved it would name objects no write of its new key made.
12673
+ * Offloading requires `escapeKeys: true`, under which such a row is only ever written at its
12674
+ * final key text: judged on the consistent read a move acts on, dry run or not, before anything
12675
+ * is written. Any well-formed pointer, at any depth, whatever the entity now declares: a table
12676
+ * can only be rekeyed off escaped text once its members' offloaded declarations are removed.
12677
+ */
12678
+ const refuseMovingPointerRow = (read, from) => {
12679
+ const attribute = BlobLedger.pointerAttributeOf(read);
12680
+ return attribute === undefined
12681
+ ? Effect.void
12682
+ : Rekey.refusePointerRow(`Entity "${entityType}"`, from, attribute);
12683
+ };
11464
12684
  const moveItem = (ctx, from, to) => Effect.gen(function* () {
11465
12685
  const client = yield* Capacity.client;
11466
12686
  let tally = {};
@@ -11477,6 +12697,7 @@ const makeImpl = (config, precomputedData) => {
11477
12697
  if (targets?.kind !== "item" || !sameStoredKey(targets.current, to)) {
11478
12698
  return Rekey.mergeTallies(tally, yield* movedAway(ctx, to));
11479
12699
  }
12700
+ yield* refuseMovingPointerRow(read, from);
11480
12701
  // Its Delete is guarded on the item as read: one nothing proves unchanged is the context's.
11481
12702
  // On a versioned entity with vector indexes, its vector attributes as read too
11482
12703
  // (`vectorsAsRead`): a move copying old ones lost a `reembed`'s write (#240).
@@ -13790,9 +15011,6 @@ const makeImpl = (config, precomputedData) => {
13790
15011
  ? cbOrShorthand(entityPathBuilder, entityConditionOps)
13791
15012
  : parseSimpleShorthand(cbOrShorthand);
13792
15013
  refusePackedExpr(expr, "filter");
13793
- // Each operand that is one of Effect's instances or a `Date` in the form this entity's
13794
- // attribute holds it (#242), whichever query it's added to, and its paths named as the entity
13795
- // stores them (#238).
13796
15014
  return (q) => {
13797
15015
  const { renameExpr } = ownNaming();
13798
15016
  return filterExprStored(q, renameExpr === undefined ? expr : renameExpr(expr));
@@ -13848,10 +15066,12 @@ const makeImpl = (config, precomputedData) => {
13848
15066
  timeSeries: config.timeSeries,
13849
15067
  generatedId: config.generatedId,
13850
15068
  vectorIndexes: config.vectorIndexes,
15069
+ offload: data.offload,
13851
15070
  _vectorIndexes: vectorIndexes,
13852
15071
  _reembedGuard: reembedGuard,
13853
15072
  _refuseTableAttributes: refuseTableAttributes,
13854
- _packedFields: Object.keys(packedFields),
15073
+ // Packed and External (binary) fields: both are opaque to expressions (#179, §9.1).
15074
+ _packedFields: [...Object.keys(packedFields), ...Object.keys(binaryFields)],
13855
15075
  _packFields: packFields,
13856
15076
  _unpackFields: unpackFields,
13857
15077
  _dispatchAttributes: dispatchAttributes,
@@ -13861,9 +15081,17 @@ const makeImpl = (config, precomputedData) => {
13861
15081
  const copy = { ...record };
13862
15082
  return lacksAny(copy, names) ? lackedByName(record, copy, names, undefined, "getter") : copy;
13863
15083
  },
13864
- _decodeImage: decodeImageItem,
15084
+ _decodeImage: (image, modes) => decodeImageItem(image, modes),
15085
+ _decodeStreamRecord: decodeChange,
15086
+ _loadRows: (rows, options) => loadRows(rows, options),
15087
+ _readAttributes: readAttributeNames,
15088
+ _offloads: offloadInfo !== undefined,
15089
+ _bindContext: (where, context) => bindingContext(where, entity, context),
15090
+ _offloadedFields: [...offloadedByKind.overflow, ...offloadedByKind.binary],
15091
+ _offloadItem: offloadBuiltItem,
15092
+ _loadForReuse: loadForReuse,
13865
15093
  _resolvedRefs: resolvedRefs,
13866
- /** @internal Full decode pipeline: unpack + sparse + rename + schema decode. Used by Batch/Aggregate. */
15094
+ /** @internal Full decode pipeline: load + sparse + rename + schema decode. Used by Batch/Aggregate. */
13867
15095
  _decodeRecord: decodeRecord,
13868
15096
  /** @internal Domain field name → stored attribute name (`storedAs` renames). */
13869
15097
  _resolveDbName: resolveDbName,
@@ -13887,9 +15115,7 @@ const makeImpl = (config, precomputedData) => {
13887
15115
  _incarnationToken: stampsIncarnation,
13888
15116
  _versionCorruption: versionCorruption,
13889
15117
  _fillDecodingDefaults: fillDecodingDefaults,
13890
- _refuseNotReadBack: (encoded, operation) => kindReads().model.size === 0
13891
- ? refuseNotReadBack(encoded, operation)
13892
- : Effect.andThen(refuseNotReadBack(encoded, operation), refuseOtherKindRead(encoded, operation)),
15118
+ _encodeInput: (input, operation) => Effect.flatMap(prepareInput(input, operation), (prepared) => encodeForWrite(schemas.inputSchema, prepared, operation, operation)),
13893
15119
  _ownSchema: () => ownSchema(),
13894
15120
  _composeUniqueSentinels: (under, record) => composeUniqueSentinels(under, record),
13895
15121
  _unsentineledDefaults: unsentineledDefaults,
@@ -13933,6 +15159,9 @@ const makeImpl = (config, precomputedData) => {
13933
15159
  const refused = packedIndexRefusal(entityType, packedFields, name, def);
13934
15160
  if (refused !== undefined)
13935
15161
  throw new Error(refused);
15162
+ const external = externalIndexRefusal(entityType, data.externalFields, name, def);
15163
+ if (external !== undefined)
15164
+ throw new Error(external);
13936
15165
  allIndexes = { ...allIndexes, [name]: def };
13937
15166
  },
13938
15167
  get _schema() {
@@ -13986,11 +15215,48 @@ const makeImpl = (config, precomputedData) => {
13986
15215
  // which makes it incompatible with the default Entity (Schema.Top).
13987
15216
  // This is safe — self is only used internally for extractTransactable.
13988
15217
  self = entity;
15218
+ // What `BlobGc` reads of the entity (#179): hidden, not part of its type.
15219
+ Object.defineProperty(entity, GcSupport.GcSupportId, { value: gcSupport, enumerable: false });
13989
15220
  return entity;
13990
15221
  };
13991
15222
  // ---------------------------------------------------------------------------
13992
15223
  // Entity binding — resolve services, return BoundEntity with R = never
13993
15224
  // ---------------------------------------------------------------------------
15225
+ /**
15226
+ * The context `entity`'s operations run in when it is bound in `context`
15227
+ * (`Entity.bind`, `GeoIndex.bind`). First the configuration checks where its
15228
+ * registries are first resolvable (#147, #179): an offloaded field needs a
15229
+ * schema setting `escapeKeys: true` (`[EDD-9146]`, checked first: a store
15230
+ * doesn't make the key text right), a codec its `Packed` fields name must be
15231
+ * registered (`[EDD-9078]`) and an offloaded field needs a blob store
15232
+ * (`[EDD-9115]`), each thrown as the defect naming `where` (`DynamoClient.make`
15233
+ * runs its own, over every member). Then a default `SecureRandom` service is
15234
+ * bundled when `context` has none: a `generatedId` put yields `SecureRandom`,
15235
+ * and the bound operations stay at `R = never`. A platform override
15236
+ * (`DynamoClient.make({ crypto })`) is kept.
15237
+ */
15238
+ const bindingContext = (where, entity, context) => {
15239
+ const owner = `entity "${entity.entityType}"`;
15240
+ const requirements = OffloadWrite.entityStoreRequirements(owner, entity);
15241
+ // Offloading requires escaped key text (`[EDD-9146]`), before the store.
15242
+ const keysError = OffloadWrite.unescapedKeysError(where, requirements);
15243
+ if (keysError !== undefined)
15244
+ throw keysError;
15245
+ const codecError = unregisteredCodecError(where, codecRequirements(owner, entity._packedFields.flatMap((field) => {
15246
+ const storedAs = entity._packedGuards.find((g) => g.attribute === field)?.storedAs;
15247
+ return storedAs !== undefined && isPackedConfig(storedAs)
15248
+ ? [[field, storedAs]]
15249
+ : [];
15250
+ })), Context.getOrUndefined(context, Compression));
15251
+ if (codecError !== undefined)
15252
+ throw codecError;
15253
+ const storeError = OffloadWrite.missingStoreError(where, requirements, Context.getOrUndefined(context, BlobStore));
15254
+ if (storeError !== undefined)
15255
+ throw storeError;
15256
+ return Option.isSome(Context.getOption(context, SecureRandom.SecureRandom))
15257
+ ? context
15258
+ : Context.add(context, SecureRandom.SecureRandom, makeDefaultCrypto());
15259
+ };
13994
15260
  /**
13995
15261
  * Bind an Entity to resolved `DynamoClient` and `TableConfig` services.
13996
15262
  * Returns a {@link BoundEntity} where all operations have `R = never`.
@@ -13998,19 +15264,15 @@ const makeImpl = (config, precomputedData) => {
13998
15264
  * @internal Used by `DynamoClient.make()` to bind entities.
13999
15265
  */
14000
15266
  export const bind = (entity) => Effect.gen(function* () {
14001
- // Bundle a default `SecureRandom` service into the captured context. This is how
14002
- // `generatedId` put auto-fills a UUID while keeping bound `put` at
14003
- // `R = never`: the entity op yields `SecureRandom`, and `provide` supplies
14004
- // it from this bundled context rather than surfacing it as a requirement.
14005
- // The `provide` helper is widened to admit `SecureRandom` so the
14006
- // SecureRandom-requiring entity ops typecheck. A platform override supplied via
14007
- // `DynamoClient.make({ crypto })` is already in `baseCtx` and is respected
14008
- // (we only fill the default when absent). See `DESIGN.md`.
15267
+ // The configuration checks where the entity is first resolvable, and a
15268
+ // default `SecureRandom` bundled into the captured context (`bindingContext`;
15269
+ // `DynamoClient.make` binds under the registries and crypto it bundled).
15270
+ // A `generatedId` put yields `SecureRandom`, which `provide` supplies
15271
+ // from this context rather than surfacing it as a requirement — widened
15272
+ // to admit it so the SecureRandom-requiring entity ops typecheck, and bound
15273
+ // `put` stays at `R = never`. See `DESIGN.md`.
14009
15274
  // Detached: no current operation or parent span is pinned for later calls (#174).
14010
- const baseCtx = Capacity.detachContext(yield* Effect.context());
14011
- const ctx = Option.isSome(Context.getOption(baseCtx, SecureRandom.SecureRandom))
14012
- ? baseCtx
14013
- : Context.add(baseCtx, SecureRandom.SecureRandom, makeDefaultCrypto());
15275
+ const ctx = bindingContext("Entity.bind", entity, Capacity.detachContext(yield* Effect.context()));
14014
15276
  const provide = (effect) => Effect.provide(effect, ctx);
14015
15277
  // The path builder every callback of the binding gets (`pathBuilderOf`), so `.entry(key)`
14016
15278
  // resolves on the entity's sparse maps in a condition as in a query.
@@ -14021,6 +15283,7 @@ export const bind = (entity) => Effect.gen(function* () {
14021
15283
  pathBuilder: boundPathBuilder(),
14022
15284
  conditionOps: createConditionOps(),
14023
15285
  provide,
15286
+ captured: capturedServices(ctx),
14024
15287
  };
14025
15288
  // Helper: apply query combinators then execute
14026
15289
  const applyQuery = (q, combinators) => {
@@ -14061,6 +15324,11 @@ export const bind = (entity) => Effect.gen(function* () {
14061
15324
  */
14062
15325
  const reembed = (options) => {
14063
15326
  const vectorDefs = Object.entries(entity._vectorIndexes);
15327
+ // The fields any index derives its text from: the only offloaded
15328
+ // values a re-embed reads (#179).
15329
+ const sourceFields = [
15330
+ ...new Set(vectorDefs.flatMap(([, definition]) => definition.sourceFields)),
15331
+ ];
14064
15332
  const boundSchema = entity._schema;
14065
15333
  const primary = entity.indexes.primary;
14066
15334
  const boundEntityVersion = entity._entityVersion;
@@ -14073,15 +15341,27 @@ export const bind = (entity) => Effect.gen(function* () {
14073
15341
  const reembedItem = (marshalled) => Effect.gen(function* () {
14074
15342
  const raw = fromAttributeMap(marshalled);
14075
15343
  const storedSk = raw[primary.sk.field];
14076
- const decoded = (yield* entity._decodeRecord(raw));
15344
+ // Lazy (#179, design §6.5): no offloaded value is fetched by
15345
+ // the decode.
15346
+ const decoded = (yield* entity._decodeRecord(raw, OffloadRead.LAZY_MODES, "reembed.decode"));
14077
15347
  // Snapshots / tombstones live in the same partition under a
14078
15348
  // rewritten SK — their SK cannot be recomposed from the record.
14079
15349
  // `decoded` holds domain values: the keys `put` wrote for them
14080
- // are the key form of the values it stores.
15350
+ // are the key form of the values it stores. Key and vector
15351
+ // partition composites are never packed or External (EDD-9072,
15352
+ // EDD-9142), so the key form needs no read.
14081
15353
  const decodedKeyForm = entity._domainKeyForm(decoded);
14082
15354
  const liveSk = KeyComposer.composeSk(boundSchema, entity.entityType, boundEntityVersion, primary, decodedKeyForm);
14083
15355
  if (storedSk !== liveSk)
14084
15356
  return false;
15357
+ // A live row: only its source fields' values are read — an
15358
+ // offloaded one stored externally costs one GET, an inline one
15359
+ // none — and no other offloaded field is fetched.
15360
+ for (const field of sourceFields) {
15361
+ const value = decoded[field];
15362
+ if (isOffloadedValue(value))
15363
+ decoded[field] = yield* value.read();
15364
+ }
14085
15365
  const attributes = {};
14086
15366
  const embedded = [];
14087
15367
  for (const [logicalName, definition] of vectorDefs) {
@@ -14217,7 +15497,7 @@ export const bind = (entity) => Effect.gen(function* () {
14217
15497
  append: (input) => {
14218
15498
  const appendCfg = {
14219
15499
  ...boundCrudConfig,
14220
- run: (opts) => provide(entity.append(opts.input, opts.condition, opts.skipFollowUp, opts.removeAttrs)),
15500
+ run: (opts) => provide(entity.append(opts.input, opts.condition, opts.skipFollowUp, opts.removeAttrs, opts.offloadModes)),
14221
15501
  };
14222
15502
  return makeBoundAppend(input, appendCfg);
14223
15503
  },
@@ -14377,6 +15657,7 @@ const planDeleteErrorTags = [
14377
15657
  "ConditionalCheckFailed",
14378
15658
  "ItemNotFound",
14379
15659
  "TransactionOverflow",
15660
+ "BlobStoreError",
14380
15661
  ];
14381
15662
  const isPlanDeleteError = tagged(new Set(planDeleteErrorTags));
14382
15663
  const isPlanUpdateError = tagged(new Set([
@@ -14387,6 +15668,14 @@ const isPlanUpdateError = tagged(new Set([
14387
15668
  ]));
14388
15669
  const isEntityOp = (op) => EntityOpTypeId in op;
14389
15670
  const isEntityDelete = (op) => EntityDeleteTypeId in op;
15671
+ /**
15672
+ * @internal `create`'s guard: the item must not exist. (Over a projection
15673
+ * tombstone, `create` reads it and guards on it instead — `overTombstone`.)
15674
+ */
15675
+ export const createGuard = (entity) => {
15676
+ const primary = entity.indexes.primary;
15677
+ return { attributeNotExists: [primary.pk.field, primary.sk.field] };
15678
+ };
14390
15679
  /**
14391
15680
  * Extract transactable metadata from an Entity operation intermediate.
14392
15681
  * Returns undefined if the value is not a recognized entity operation.
@@ -14400,28 +15689,31 @@ const isEntityDelete = (op) => EntityDeleteTypeId in op;
14400
15689
  * `Transaction.transactGet` and `Transaction.check` (#108). A pure definition
14401
15690
  * carries no operations, so the bound op is the only descriptor its author can
14402
15691
  * ever hold.
15692
+ *
15693
+ * A bound op also carries its binding's captured blob store and compressor
15694
+ * registry (`captured`, #179): the entry points build its item under them.
14403
15695
  */
14404
- /**
14405
- * @internal `create`'s guard: the item must not exist. (Over a projection
14406
- * tombstone, `create` reads it and guards on it instead — `overTombstone`.)
14407
- */
14408
- export const createGuard = (entity) => {
14409
- const primary = entity.indexes.primary;
14410
- return { attributeNotExists: [primary.pk.field, primary.sk.field] };
14411
- };
14412
15696
  export const extractTransactable = (op) => {
14413
15697
  if (op == null || typeof op !== "object")
14414
15698
  return undefined;
14415
15699
  // Unwrap a bound-CRUD builder to the intermediate it wraps. Combinators on the
14416
15700
  // builder (`.condition()`, `.set()`, …) are applied to that inner op, so the
14417
15701
  // unwrapped value carries the full request.
14418
- const target = isBoundOp(op) ? op._op : op;
15702
+ const bound = isBoundOp(op);
15703
+ const target = bound ? op._op : op;
14419
15704
  if (target == null || typeof target !== "object")
14420
15705
  return undefined;
15706
+ const captured = bound ? op._config?.captured : undefined;
14421
15707
  // Check for EntityOp intermediates (get, put, update)
14422
15708
  if (isEntityOp(target)) {
14423
15709
  if (target._opType === "get") {
14424
- return { opType: "get", entity: target._entity, key: target._key };
15710
+ return {
15711
+ opType: "get",
15712
+ entity: target._entity,
15713
+ key: target._key,
15714
+ offloadModes: target._offloadModes ?? OffloadRead.DEFAULT_MODES,
15715
+ captured,
15716
+ };
14425
15717
  }
14426
15718
  // `create`'s own not-exists guard is ANDed with the caller's condition:
14427
15719
  // no `.condition()` replaces it (#133).
@@ -14434,6 +15726,7 @@ export const extractTransactable = (op) => {
14434
15726
  condition: withGuard(putKind === "create" ? createGuard(target._entity) : undefined, target._condition),
14435
15727
  putKind,
14436
15728
  callerCondition: target._condition,
15729
+ captured,
14437
15730
  };
14438
15731
  }
14439
15732
  if (target._opType === "update") {
@@ -14446,6 +15739,7 @@ export const extractTransactable = (op) => {
14446
15739
  key: target._key,
14447
15740
  condition: target._updateState?.condition,
14448
15741
  updateState: target._updateState,
15742
+ captured,
14449
15743
  };
14450
15744
  }
14451
15745
  }
@@ -14464,6 +15758,7 @@ export const extractTransactable = (op) => {
14464
15758
  mustExist: target._mustExist === true,
14465
15759
  returnValues: target._returnValues,
14466
15760
  },
15761
+ captured,
14467
15762
  };
14468
15763
  }
14469
15764
  return undefined;
@@ -14500,6 +15795,19 @@ export const itemSchema = (entity) => entity.schemas.itemSchema;
14500
15795
  * binary (`B`). Lambda and EventBridge Pipes deliver `B` / `BS` members as
14501
15796
  * base64 text; they are decoded at any depth.
14502
15797
  * - Sparse-map fields are rebuilt and `field:` renames reversed.
15798
+ * - **Offloaded fields** (#179) are lazy by default: an overflow field is an
15799
+ * `OffloadedValue` and a binary field a `BlobHandle`, each fetching from the
15800
+ * ambient `BlobStore` only when read, so the decode itself does no store
15801
+ * I/O. `{ offloaded: "eager" }` (or per kind, `{ overflow, binary }`)
15802
+ * resolves them as the decode runs; a store failure is then a
15803
+ * `BlobStoreError`. A value stored inline is wrapped too when lazy (its
15804
+ * `location` is `"inline"`; reading it does no I/O), and is the value
15805
+ * itself when eager.
15806
+ *
15807
+ * The result is typed {@link DecodedImage}: `unknown` for an entity that
15808
+ * offloads nothing, as before; for one that offloads, its record with each
15809
+ * offloaded field typed by the decode's modes. The error channel carries
15810
+ * `BlobStoreError` only when a mode is eager.
14503
15811
  *
14504
15812
  * Accepts DynamoDB JSON (`{ pk: { S: "…" }, … }`, `B` as bytes or base64) or
14505
15813
  * an already-unmarshalled item. Fails with `ValidationError` if the item does
@@ -14510,9 +15818,18 @@ export const itemSchema = (entity) => entity.schemas.itemSchema;
14510
15818
  * Note: {@link itemSchema} is a pure schema over unmarshalled items and does
14511
15819
  * not unpack — use this for entities with packed fields.
14512
15820
  */
14513
- export const decodeMarshalledItem = (entity, marshalledItem) => {
14514
- if (entity._decodeImage !== undefined)
14515
- return entity._decodeImage(marshalledItem);
15821
+ export const decodeMarshalledItem = (entity, marshalledItem, options) => {
15822
+ const decodeImage = entity._decodeImage ?? definitionImageDecoder(entity);
15823
+ if (decodeImage !== undefined) {
15824
+ // Lazy by default (#179, design §10.1): a pointer costs a GET only when read.
15825
+ const modes = OffloadRead.parseModesOption(options?.offloaded, OffloadRead.LAZY_MODES, {
15826
+ entityType: entity.entityType,
15827
+ operation: "decodeMarshalledItem",
15828
+ });
15829
+ if (modes instanceof ValidationError)
15830
+ return Effect.fail(modes);
15831
+ return decodeImage(marshalledItem, modes);
15832
+ }
14516
15833
  const corruption = entity._versionCorruption?.(marshalledItem, "decodeMarshalledItem");
14517
15834
  if (corruption !== undefined)
14518
15835
  return Effect.fail(corruption);
@@ -14522,4 +15839,76 @@ export const decodeMarshalledItem = (entity, marshalledItem) => {
14522
15839
  cause,
14523
15840
  })));
14524
15841
  };
15842
+ /**
15843
+ * A pure definition's image decoder (#179, design §10.1): the runtime
15844
+ * entity's own — normalise, unpack, pointer dispatch, renames, sparse
15845
+ * rebuild — built once per definition. Before, a definition's image was
15846
+ * decoded by `itemSchema` alone, so its packed fields came back as their
15847
+ * stored form (#147's gap).
15848
+ */
15849
+ const definitionImageDecoder = (entity) => definitionRuntime(entity)?._decodeImage;
15850
+ /** The runtime entity of a pure definition, built once per definition; `undefined` for anything else. */
15851
+ const definitionRuntime = (entity) => {
15852
+ const def = entity;
15853
+ if (def._config === undefined || def._data === undefined)
15854
+ return undefined;
15855
+ let runtime = definitionRuntimes.get(entity);
15856
+ if (runtime === undefined) {
15857
+ runtime = makeImpl(def._config, def._data);
15858
+ definitionRuntimes.set(entity, runtime);
15859
+ }
15860
+ return runtime;
15861
+ };
15862
+ const definitionRuntimes = new WeakMap();
15863
+ /**
15864
+ * Decode a DynamoDB Streams record of an entity (#179, design §3.9, §10.3) —
15865
+ * both images, and what the change did to each offloaded field — as a
15866
+ * change-feed consumer needs it: to index, scan or forward only what changed.
15867
+ *
15868
+ * - **Records.** Structural ({@link StreamRecordLike}): the SDK's `_Record`
15869
+ * (the change feed's), a Lambda `DynamoDBRecord` and an EventBridge Pipes
15870
+ * record fit; images in DynamoDB JSON (`B` as bytes or base64) or
15871
+ * unmarshalled. The stream must be `NEW_AND_OLD_IMAGES`: a record whose
15872
+ * `StreamViewType` is another, or that lacks an image its event has (a
15873
+ * `MODIFY` / `REMOVE` without `OldImage`, a `MODIFY` / `INSERT` without
15874
+ * `NewImage`), fails with a `ValidationError` carrying `[EDD-9119]` —
15875
+ * checked on every record, whatever its entity type.
15876
+ * - **Other types.** `Option.none()` when no image is of this entity type
15877
+ * (another entity's item, a unique-constraint sentinel, an untyped item).
15878
+ * - **Items** decode exactly as {@link decodeMarshalledItem} decodes an image
15879
+ * (packed fields unpacked, renames reversed, sparse maps rebuilt) — lazy by
15880
+ * default: an offloaded field is an `OffloadedValue` / `BlobHandle` that
15881
+ * fetches only when read; `{ offloaded: "eager" }` resolves them.
15882
+ * - **`offloaded`** classifies each offloaded field present in either image
15883
+ * (see {@link EntityChange}) from the stored forms alone — no store I/O in
15884
+ * any mode. `rewritten` means probably identical: treat it as `changed`
15885
+ * where a change must never be missed.
15886
+ *
15887
+ * A handle read long after its record (a lagging consumer) may fail with
15888
+ * `NotFound` once its version was superseded and reaped: the newer record
15889
+ * carries the newer pointer, so treat it as superseded (design §8.7).
15890
+ *
15891
+ * @example
15892
+ * ```ts
15893
+ * const change = yield* Entity.decodeStreamRecord(Documents, record)
15894
+ * if (Option.isSome(change) && change.value.offloaded.body !== "unchanged") {
15895
+ * yield* reindex(change.value.newItem)
15896
+ * }
15897
+ * ```
15898
+ */
15899
+ export const decodeStreamRecord = (entity, record, options) => {
15900
+ const decodeRecord = entity._decodeStreamRecord ?? definitionRuntime(entity)?._decodeStreamRecord;
15901
+ if (decodeRecord === undefined) {
15902
+ // Only untyped code reaches here: the parameter type admits no other value.
15903
+ return Effect.die(new Error("Entity.decodeStreamRecord: expected an entity (Entity.make) or an entity definition " +
15904
+ "(the schema package's Entity.make)."));
15905
+ }
15906
+ const modes = OffloadRead.parseModesOption(options?.offloaded, OffloadRead.LAZY_MODES, {
15907
+ entityType: entity.entityType,
15908
+ operation: "decodeStreamRecord",
15909
+ });
15910
+ if (modes instanceof ValidationError)
15911
+ return Effect.fail(modes);
15912
+ return decodeRecord(record, modes);
15913
+ };
14525
15914
  //# sourceMappingURL=Entity.js.map