effect-dynamodb 1.39.0 → 1.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/dist/Aggregate.d.ts +119 -15
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +2021 -379
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/Batch.d.ts +9 -5
  6. package/dist/Batch.d.ts.map +1 -1
  7. package/dist/Batch.js +28 -44
  8. package/dist/Batch.js.map +1 -1
  9. package/dist/Collection.d.ts.map +1 -1
  10. package/dist/Collection.js +12 -5
  11. package/dist/Collection.js.map +1 -1
  12. package/dist/ConsumedCapacity.js +1 -1
  13. package/dist/ConsumedCapacity.js.map +1 -1
  14. package/dist/DynamoClient.d.ts +22 -8
  15. package/dist/DynamoClient.d.ts.map +1 -1
  16. package/dist/DynamoClient.js +243 -87
  17. package/dist/DynamoClient.js.map +1 -1
  18. package/dist/Entity.d.ts +87 -22
  19. package/dist/Entity.d.ts.map +1 -1
  20. package/dist/Entity.js +2750 -514
  21. package/dist/Entity.js.map +1 -1
  22. package/dist/EventStore.d.ts +37 -15
  23. package/dist/EventStore.d.ts.map +1 -1
  24. package/dist/EventStore.js +215 -79
  25. package/dist/EventStore.js.map +1 -1
  26. package/dist/Marshaller.d.ts +39 -9
  27. package/dist/Marshaller.d.ts.map +1 -1
  28. package/dist/Marshaller.js +421 -70
  29. package/dist/Marshaller.js.map +1 -1
  30. package/dist/Query.d.ts +23 -0
  31. package/dist/Query.d.ts.map +1 -1
  32. package/dist/Query.js +49 -3
  33. package/dist/Query.js.map +1 -1
  34. package/dist/StorageEncoding.d.ts +7 -1
  35. package/dist/StorageEncoding.d.ts.map +1 -1
  36. package/dist/StorageEncoding.js +8 -2
  37. package/dist/StorageEncoding.js.map +1 -1
  38. package/dist/Table.d.ts +69 -8
  39. package/dist/Table.d.ts.map +1 -1
  40. package/dist/Transaction.d.ts.map +1 -1
  41. package/dist/Transaction.js +10 -4
  42. package/dist/Transaction.js.map +1 -1
  43. package/dist/change-feed/ChangeFeed.d.ts +8 -3
  44. package/dist/change-feed/ChangeFeed.d.ts.map +1 -1
  45. package/dist/change-feed/ChangeFeed.js +76 -9
  46. package/dist/change-feed/ChangeFeed.js.map +1 -1
  47. package/dist/change-feed/CheckpointStore.js +1 -1
  48. package/dist/change-feed/CheckpointStore.js.map +1 -1
  49. package/dist/change-feed/DynamoStreamsClient.d.ts +12 -5
  50. package/dist/change-feed/DynamoStreamsClient.d.ts.map +1 -1
  51. package/dist/change-feed/DynamoStreamsClient.js +15 -9
  52. package/dist/change-feed/DynamoStreamsClient.js.map +1 -1
  53. package/dist/internal/BoundCrud.d.ts +40 -32
  54. package/dist/internal/BoundCrud.d.ts.map +1 -1
  55. package/dist/internal/BoundCrud.js.map +1 -1
  56. package/dist/internal/BoundQuery.d.ts +1 -1
  57. package/dist/internal/BoundQuery.d.ts.map +1 -1
  58. package/dist/internal/BoundQuery.js +22 -12
  59. package/dist/internal/BoundQuery.js.map +1 -1
  60. package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
  61. package/dist/internal/BoundVectorQuery.js +2 -1
  62. package/dist/internal/BoundVectorQuery.js.map +1 -1
  63. package/dist/internal/Capacity.d.ts +44 -4
  64. package/dist/internal/Capacity.d.ts.map +1 -1
  65. package/dist/internal/Capacity.js +89 -15
  66. package/dist/internal/Capacity.js.map +1 -1
  67. package/dist/internal/ClientOptions.d.ts +72 -0
  68. package/dist/internal/ClientOptions.d.ts.map +1 -0
  69. package/dist/internal/ClientOptions.js +79 -0
  70. package/dist/internal/ClientOptions.js.map +1 -0
  71. package/dist/internal/Cursor.d.ts +19 -10
  72. package/dist/internal/Cursor.d.ts.map +1 -1
  73. package/dist/internal/Cursor.js +25 -10
  74. package/dist/internal/Cursor.js.map +1 -1
  75. package/dist/internal/EntityCombinators.d.ts +22 -7
  76. package/dist/internal/EntityCombinators.d.ts.map +1 -1
  77. package/dist/internal/EntityCombinators.js +6 -2
  78. package/dist/internal/EntityCombinators.js.map +1 -1
  79. package/dist/internal/EntityOps.d.ts +11 -1
  80. package/dist/internal/EntityOps.d.ts.map +1 -1
  81. package/dist/internal/EntityOps.js.map +1 -1
  82. package/dist/internal/EventProjection.d.ts +15 -3
  83. package/dist/internal/EventProjection.d.ts.map +1 -1
  84. package/dist/internal/EventProjection.js +27 -8
  85. package/dist/internal/EventProjection.js.map +1 -1
  86. package/dist/internal/Expr.d.ts.map +1 -1
  87. package/dist/internal/Expr.js +53 -2
  88. package/dist/internal/Expr.js.map +1 -1
  89. package/dist/internal/ExpressionLimits.d.ts +57 -1
  90. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  91. package/dist/internal/ExpressionLimits.js +90 -1
  92. package/dist/internal/ExpressionLimits.js.map +1 -1
  93. package/dist/internal/ItemSize.d.ts +108 -4
  94. package/dist/internal/ItemSize.d.ts.map +1 -1
  95. package/dist/internal/ItemSize.js +190 -3
  96. package/dist/internal/ItemSize.js.map +1 -1
  97. package/dist/internal/MultiProjection.d.ts +7 -2
  98. package/dist/internal/MultiProjection.d.ts.map +1 -1
  99. package/dist/internal/MultiProjection.js +9 -3
  100. package/dist/internal/MultiProjection.js.map +1 -1
  101. package/dist/internal/PathBuilder.d.ts +15 -4
  102. package/dist/internal/PathBuilder.d.ts.map +1 -1
  103. package/dist/internal/PathBuilder.js +20 -10
  104. package/dist/internal/PathBuilder.js.map +1 -1
  105. package/dist/internal/ProjectionEngine.d.ts +76 -2
  106. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  107. package/dist/internal/ProjectionEngine.js +358 -28
  108. package/dist/internal/ProjectionEngine.js.map +1 -1
  109. package/dist/internal/Rekey.d.ts +21 -1
  110. package/dist/internal/Rekey.d.ts.map +1 -1
  111. package/dist/internal/Rekey.js +67 -0
  112. package/dist/internal/Rekey.js.map +1 -1
  113. package/dist/internal/RoundTrip.d.ts +36 -0
  114. package/dist/internal/RoundTrip.d.ts.map +1 -0
  115. package/dist/internal/RoundTrip.js +79 -0
  116. package/dist/internal/RoundTrip.js.map +1 -0
  117. package/dist/internal/SentRequest.d.ts +14 -0
  118. package/dist/internal/SentRequest.d.ts.map +1 -0
  119. package/dist/internal/SentRequest.js +31 -0
  120. package/dist/internal/SentRequest.js.map +1 -0
  121. package/dist/internal/TransactWriteOps.d.ts +69 -15
  122. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  123. package/dist/internal/TransactWriteOps.js +144 -107
  124. package/dist/internal/TransactWriteOps.js.map +1 -1
  125. package/dist/internal/TransactableOps.d.ts +115 -23
  126. package/dist/internal/TransactableOps.d.ts.map +1 -1
  127. package/dist/internal/TransactableOps.js +244 -80
  128. package/dist/internal/TransactableOps.js.map +1 -1
  129. package/dist/internal/WriteDiagnosis.d.ts +31 -3
  130. package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
  131. package/dist/internal/WriteDiagnosis.js +128 -11
  132. package/dist/internal/WriteDiagnosis.js.map +1 -1
  133. package/package.json +2 -2
package/dist/Entity.js CHANGED
@@ -10,30 +10,35 @@ import { getIdentifierField, getSparseFields, isConfiguredModel, isRefField, } f
10
10
  import * as DynamoSchema from "@effect-dynamodb/schema/DynamoSchema.js";
11
11
  import { Embedder } from "@effect-dynamodb/schema/Embedder.js";
12
12
  import { CascadePartialFailure, ConcurrentModification, ConditionalCheckFailed, DeleteAppliedButUnreadable, DynamoError, EmbeddingError, ItemNotDeleted, ItemNotFound, isAwsConditionalCheckFailed, isAwsTransactionCancelled, OptimisticLockError, RefNotFound, StaleAppend, TransactionOverflow, UniqueConstraintViolation, UpdateAppliedButUnreadable, ValidationError, } from "@effect-dynamodb/schema/Errors.js";
13
- import { compositeKeyFormKind, keyFormValueKind, makeCompositeKeyForm, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
13
+ import { compositeKeyFormKind, keyFormValueKind, kindReadingOf, makeCompositeKeyForm, makeCompositeStoredForm, otherNumericKind, readsBackOtherwise, refuseInexact, storedFormOfRead, storedNumericForm, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
14
14
  import { makeDefaultCrypto } from "@effect-dynamodb/schema/internal/DefaultCrypto.js";
15
15
  import { packedIndexRefusal } from "@effect-dynamodb/schema/internal/EntityPacked.js";
16
+ import { failingAsBefore, issueDecoding } from "@effect-dynamodb/schema/internal/FailingAsBefore.js";
16
17
  import * as KeyText136 from "@effect-dynamodb/schema/internal/KeyText136.js";
18
+ import { absentReading, absentStored, pathIsRequired, rowOmits, } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
19
+ import { refuseReadAsSparseEntry } from "@effect-dynamodb/schema/internal/SharedKeyAttribute.js";
20
+ import { sparseKeyRefusal, sparseReader } from "@effect-dynamodb/schema/internal/SparseKey.js";
17
21
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
18
22
  import { normalizeGsiConfig } from "@effect-dynamodb/schema/KeyComposer.js";
19
23
  import { deriveSourceText } from "@effect-dynamodb/schema/VectorIndex.js";
20
- import { Cause, Context, Data, DateTime, Effect, Equal, Option, Schema, Stream, } from "effect";
24
+ import { Cause, Context, Data, DateTime, Effect, Equal, Exit, Option, Schema, SchemaIssue, Stream, } from "effect";
21
25
  import { SecureRandom } from "effect/crypto";
22
26
  import { attributeValueEquals } from "./internal/AttributeValueEquals.js";
23
27
  import { isBoundOp, makeBoundAppend, makeBoundDelete, makeBoundGet, makeBoundPut, makeBoundUpdate, } from "./internal/BoundCrud.js";
24
28
  import { BoundQueryImpl, entityNaming, } from "./internal/BoundQuery.js";
25
29
  import * as Capacity from "./internal/Capacity.js";
26
30
  import { compileExpr, createConditionOps, emptyPartProblem, isExpr, nonEmptyCondition, parseShorthand, parseSimpleShorthand, toExpr, } from "./internal/Expr.js";
27
- import { asReadGuard, countOperators, expressionFits } from "./internal/ExpressionLimits.js";
31
+ import { asReadGuard, countOperators, expressionFits, wholeRowGuard, } from "./internal/ExpressionLimits.js";
28
32
  import { BASE_DELAY_MS, MAX_RETRIES } from "./internal/Hydrate.js";
29
33
  import { decodeImage, imageEntityType, ownRowsRawRow, packAttributeValueSync, packedExprRefusal, packedProjectionRefusal, packItemSync, unpackRow, withRegistry, } from "./internal/Packed.js";
30
34
  import { compilePath, createPathBuilder } from "./internal/PathBuilder.js";
31
35
  import { KEY_MAX, KEY_TOP, keyJustBelow } from "./internal/RangePlanner.js";
32
36
  import * as Rekey from "./internal/Rekey.js";
33
- import { composeKeysOrFail, freshIncarnationToken, generateTimestampPrimitive, INCARNATION_TOKEN, isProjectionTombstone, KEY_TEXT, OUTBOX_CLAIM, OUTBOX_CLAIMED_UNTIL, OUTBOX_ROW_PK, OUTBOX_ROW_SK, overTombstone, UNSENTINELED_DEFAULTS, } from "./internal/TransactableOps.js";
37
+ import { asRead, notReadBack, readBackOf, readBackRefusal, } from "./internal/RoundTrip.js";
38
+ import { 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";
34
39
  import { planWrite } from "./internal/TransactPlan.js";
35
40
  import { batchEntries, diagnosedValidationError, diagnoseFailure, keyAttributesOf, targetsFor, transactItemTarget, } from "./internal/WriteDiagnosis.js";
36
- import { decodeSparseFields, encodeSparseFields, fromAttributeMap, toAttributeMap, toAttributeValue, } from "./Marshaller.js";
41
+ import { decodeSparseFields, encodeSparseFields, fromAttributeMap, hasNoStoredForm, isEmptySet, toAttributeMap, toAttributeValue, UnstorableValue, unstorableIn, } from "./Marshaller.js";
37
42
  import * as Query from "./Query.js";
38
43
  import { filterExpr, selectPaths } from "./Query.js";
39
44
  import { resolveTtlAttributeName } from "./Table.js";
@@ -68,7 +73,13 @@ import { asModel, condition as conditionCombinator, expectedVersion, set, } from
68
73
  */
69
74
  import { buildEntityDefinition, normalizeTtlSeconds, resolveUniqueTtl, zorderInCollection, } from "@effect-dynamodb/schema/Entity.js";
70
75
  export { normalizeTtlSeconds };
71
- const composeUniqueSentinel = (schema, entityType, constraintName, constraintDef, source) => {
76
+ const composeUniqueSentinel = (schema, entityType, constraintName, constraintDef, source,
77
+ /**
78
+ * The value a field held when it was stored (`storedNumericForm`), or `undefined` when it is
79
+ * that already. A sentinel is composed from the Encoded value `put` stores, and a row read back
80
+ * holds a stored `bigint` as a number.
81
+ */
82
+ stored) => {
72
83
  const fields = resolveUniqueFields(constraintDef);
73
84
  // A field holding only a default has no sentinel (#133).
74
85
  const defaulted = source[UNSENTINELED_DEFAULTS];
@@ -80,9 +91,10 @@ const composeUniqueSentinel = (schema, entityType, constraintName, constraintDef
80
91
  const serialized = [];
81
92
  const fieldsRecord = {};
82
93
  for (const f of fields) {
83
- const raw = source[f];
84
- if (raw === undefined || raw === null)
94
+ const given = source[f];
95
+ if (given === undefined || given === null)
85
96
  return undefined;
97
+ const raw = stored(f, given) ?? given;
86
98
  const s = KeyComposer.compositeText(schema, raw);
87
99
  serialized.push(s);
88
100
  fieldsRecord[f] = s;
@@ -125,7 +137,9 @@ const keyFormFor = (target, record) => {
125
137
  const source = t.schemas?.inputSchema ?? t.model;
126
138
  if (source === undefined)
127
139
  return record;
128
- const form = makeCompositeKeyForm(source, (attr, value) => {
140
+ const form = makeCompositeKeyForm(source, (attr, value, reason) => {
141
+ if (reason !== undefined)
142
+ return refuseInexact(`Composite "${attr}"`, value, reason);
129
143
  throw new Error(`[EDD-9050] Composite "${attr}" could not be put into its key form: ` +
130
144
  `${JSON.stringify(String(value))} resolves under neither encode nor decode->encode.`);
131
145
  });
@@ -135,6 +149,19 @@ const keyFormFor = (target, record) => {
135
149
  * @internal A plain update of a complete item found no item: the caller
136
150
  * creates it instead (`updateOrCreate`). Never escapes the update operation.
137
151
  */
152
+ /**
153
+ * What a failed decode says, naming the field when the schema does: `"stock":
154
+ * Expected a value greater than or equal to 0, got -2.`
155
+ */
156
+ const decodeProblem = (cause) => {
157
+ if (!Schema.isSchemaError(cause))
158
+ return `${String(cause)}.`;
159
+ const first = SchemaIssue.makeFormatterStandardSchemaV1()(cause.issue).issues[0];
160
+ if (first === undefined)
161
+ return `${cause.message}.`;
162
+ const path = (first.path ?? []).map((segment) => String(segment)).join(".");
163
+ return path === "" ? `${first.message}.` : `"${path}": ${first.message}.`;
164
+ };
138
165
  class MissingForCreate extends Data.TaggedError("MissingForCreate") {
139
166
  }
140
167
  /** @internal Re-exported for tests: what DynamoDB counts against an expression's 300 operators. */
@@ -372,6 +399,8 @@ const makeImpl = (config, precomputedData) => {
372
399
  // the runtime Entity carries, so the cast is sound.
373
400
  const data = precomputedData ?? buildEntityDefinition(config);
374
401
  const { systemFields, schemas, hasRefs, immutableFields, resolvedIdentifier, generatedIdField, generatedIdVersion, entityType, entityVersion, sparseFields, hasSparseFields, renameToDynamo, renameFromDynamo, resolveDbName, rawModel, isSchemaClass, hasHiddenFields, } = data;
402
+ /** Which stored attributes are this entity's sparse map entries, as a row's reader takes them. */
403
+ const sparseEntries = sparseReader(sparseFields);
375
404
  // Encoders for path-addressed update values (`pathSet`, `pathAppend`, …) and
376
405
  // record-based `append`, which bypass the update schema (#133).
377
406
  const pathValues = makePathValueEncoder(data.modelFields, schemas.writeModelSchema.fields,
@@ -398,6 +427,12 @@ const makeImpl = (config, precomputedData) => {
398
427
  const encoded = pathValues.elements(segments, value);
399
428
  return { encoded, issue: pathValues.validateElements(segments, encoded) };
400
429
  };
430
+ /**
431
+ * A `pathSet` or `pathSubtract` that names another attribute in place of a value: it has no
432
+ * operand of its own. The other path operations always write their `value`, whatever else the
433
+ * operation object holds.
434
+ */
435
+ const isCopy = (op) => Boolean(op.isPath && op.valueSegments);
401
436
  const hasPathOps = (uState) => [
402
437
  uState.pathSets,
403
438
  uState.pathRemoves,
@@ -616,7 +651,7 @@ const makeImpl = (config, precomputedData) => {
616
651
  const named = Object.keys(record).find((field) => isTableKeyAttribute(field));
617
652
  return named === undefined ? undefined : primaryCompositeRefusal(".set()", named);
618
653
  };
619
- /** A record operation writing an attribute of the table's primary key, by its stored name. */
654
+ /** A record operation writing a primary-key composite or an attribute of the table's key. */
620
655
  const refusedRecordOperands = (uState) => {
621
656
  const operands = [
622
657
  [".add()", uState.add],
@@ -625,20 +660,669 @@ const makeImpl = (config, precomputedData) => {
625
660
  [".deleteFromSet()", uState.deleteFromSet],
626
661
  ];
627
662
  for (const [op, record] of operands) {
628
- const named = Object.keys(record ?? {}).find((field) => isTableKeyAttribute(field));
663
+ const named = Object.keys(record ?? {}).find((field) => isTableKeyAttribute(field) || isPrimaryComposite(field));
629
664
  if (named !== undefined)
630
665
  return primaryCompositeRefusal(op, named);
631
666
  }
632
667
  return undefined;
633
668
  };
669
+ const modelFieldSchemas = data.modelFields;
670
+ const isModelField = (name) => Object.hasOwn(modelFieldSchemas, name);
671
+ const modelFieldStoredIn = (attribute) => Object.keys(modelFieldSchemas).find((field) => resolveDbName(field) === attribute);
672
+ const fieldOfAttribute = (attribute) => modelFieldStoredIn(attribute) ?? attribute;
673
+ /**
674
+ * The fields of an encoded payload to judge against what DynamoDB can store. A
675
+ * packed field has its own form, and a `NaN` feeding a key is key composition's to
676
+ * refuse first, with its own code (`refuseUncomposed` has the rest).
677
+ */
678
+ const fieldsToStore = (encoded) => {
679
+ const composites = indexCompositeFields();
680
+ return Object.fromEntries(Object.entries(encoded).filter(([field, value]) => !(field in packedFields) &&
681
+ !(Number.isNaN(value) && (composites.has(field) || isPrimaryComposite(field)))));
682
+ };
683
+ /** What in an encoded payload DynamoDB can't store, as `put` finds it when it marshals. */
684
+ const unstorableOf = (encoded) => unstorableIn(fieldsToStore(encoded));
685
+ /** `inputSchema`'s fields of a key record, once per set of names (`unstorableKey`). */
686
+ const keyRecordSchemas = new Map();
687
+ /**
688
+ * What DynamoDB can't store in a caller's DOMAIN key record, as `put` decides it: the record
689
+ * encoded through `inputSchema`'s own fields as `put` encodes its input, then `unstorableOf`,
690
+ * the check `put` runs on what it encoded. `undefined` when it stores; a value that doesn't
691
+ * encode fails as `put` fails on it, with a `ValidationError`.
692
+ */
693
+ const unstorableKey = (record) => {
694
+ const names = Object.keys(record);
695
+ const id = names.join("\u0000");
696
+ let schema = keyRecordSchemas.get(id);
697
+ if (schema === undefined) {
698
+ const fields = getSchemaFields(schemas.inputSchema) ?? {};
699
+ schema = Schema.Struct(Object.fromEntries(names.map((name) => [name, Object.hasOwn(fields, name) ? fields[name] : Schema.Unknown])));
700
+ keyRecordSchemas.set(id, schema);
701
+ }
702
+ return encodeOrDecodeEncode(schema, record, entityType, "aggregate.create").pipe(Effect.map((encoded) => unstorableOf(encoded)));
703
+ };
704
+ /** Refuses a value DynamoDB can't store, for a path about to read or send something. */
705
+ const refuseUnstorable = (encoded, operation) => {
706
+ const unstorable = unstorableOf(encoded);
707
+ return unstorable === undefined
708
+ ? Effect.void
709
+ : Effect.fail(new ValidationError({
710
+ entityType,
711
+ operation,
712
+ cause: `${unstorable.describe()} Nothing was sent.`,
713
+ }));
714
+ };
715
+ /**
716
+ * For a path that has composed its keys: a `NaN` `fieldsToStore` left to key composition,
717
+ * which didn't refuse it, because it fed a half that wasn't composed.
718
+ */
719
+ const refuseUncomposed = (encoded, operation) => {
720
+ const fields = encoded;
721
+ const left = Object.keys(fields).filter((field) => Number.isNaN(fields[field]));
722
+ const unstorable = unstorableIn(Object.fromEntries(left.map((field) => [field, fields[field]])));
723
+ return unstorable === undefined
724
+ ? Effect.void
725
+ : Effect.fail(new ValidationError({
726
+ entityType,
727
+ operation,
728
+ cause: `${unstorable.describe()} Nothing was sent.`,
729
+ }));
730
+ };
731
+ const writeLacks = () => {
732
+ const omitted = new Map();
733
+ const absent = new Map();
734
+ const omits = (field) => {
735
+ if (!isModelField(field))
736
+ return true;
737
+ const known = omitted.get(field);
738
+ if (known !== undefined)
739
+ return known;
740
+ const judged = rowOmits(modelFieldSchemas[field]);
741
+ omitted.set(field, judged);
742
+ return judged;
743
+ };
744
+ const reading = (field) => {
745
+ if (!isModelField(field))
746
+ return undefined;
747
+ if (absent.has(field))
748
+ return absent.get(field);
749
+ const judged = absentReading(modelFieldSchemas[field]);
750
+ absent.set(field, judged);
751
+ return judged;
752
+ };
753
+ return {
754
+ omits,
755
+ absentReading: reading,
756
+ canLack: (field) => omits(field) || reading(field) !== undefined,
757
+ };
758
+ };
759
+ /**
760
+ * Why an update can't address `name` as a top-level attribute, or `undefined` when it
761
+ * can: it's a model field an update may write, a primary-key composite (refused
762
+ * separately, whichever way it's named), or an attribute the model doesn't know,
763
+ * which stays allowed so an attribute a model no longer declares can be cleaned up.
764
+ */
765
+ const unaddressable = (name, ttlAttribute) => {
766
+ if (isTableKeyAttribute(name) || isPrimaryComposite(name))
767
+ return undefined;
768
+ if (name === systemFields.version ||
769
+ name === systemFields.createdAt ||
770
+ name === systemFields.updatedAt) {
771
+ return `"${name}" is managed by the library`;
772
+ }
773
+ if (isModelField(name)) {
774
+ if (immutableFields.has(name)) {
775
+ return `"${name}" is immutable and cannot be changed by an update`;
776
+ }
777
+ if (Object.hasOwn(sparseFields, name)) {
778
+ return (`"${name}" is a sparse map, stored as one attribute per entry. ` +
779
+ `Use .removeEntries("${name}", [...]) or .clearMap("${name}")`);
780
+ }
781
+ return undefined;
782
+ }
783
+ if (name.startsWith("__edd_"))
784
+ return `"${name}" is an attribute the library manages`;
785
+ const storedBy = modelFieldStoredIn(name);
786
+ if (storedBy !== undefined) {
787
+ return `"${name}" is the attribute "${storedBy}" is stored in. Name the model field: "${storedBy}"`;
788
+ }
789
+ const refId = resolvedRefs.find((ref) => ref.idFieldName === name);
790
+ if (refId !== undefined) {
791
+ return (`"${name}" is the id of the ref "${refId.fieldName}", which a row stores whole as ` +
792
+ `"${refId.fieldName}". Reassign it with .set({ ${name} })`);
793
+ }
794
+ for (const [index, def] of Object.entries(allIndexes)) {
795
+ if (index !== "primary" && (name === def.pk.field || name === def.sk.field)) {
796
+ return (`"${name}" is a key attribute of index "${index}", which the library composes. ` +
797
+ `Remove the composite it's built from instead`);
798
+ }
799
+ }
800
+ if (name === "deletedAt" && config.softDelete)
801
+ return `"${name}" is managed by the library`;
802
+ if (writesTtl() && name === ttlAttribute)
803
+ return `"${name}" is managed by the library`;
804
+ return undefined;
805
+ };
806
+ /** An update naming, in any operation, a top-level attribute it can't address. */
807
+ const refusedAttributeNames = (uState, ttlAttribute) => {
808
+ const heads = (ops = []) => ops.flatMap(({ segments }) => (typeof segments[0] === "string" ? [segments[0]] : []));
809
+ const named = [
810
+ [".remove()", uState.remove ?? []],
811
+ [".add()", Object.keys(uState.add ?? {})],
812
+ [".subtract()", Object.keys(uState.subtract ?? {})],
813
+ [".append()", Object.keys(uState.append ?? {})],
814
+ [".deleteFromSet()", Object.keys(uState.deleteFromSet ?? {})],
815
+ ["pathSet", heads(uState.pathSets)],
816
+ ["pathRemove", heads((uState.pathRemoves ?? []).map((segments) => ({ segments })))],
817
+ ["pathAdd", heads(uState.pathAdds)],
818
+ ["pathSubtract", heads(uState.pathSubtracts)],
819
+ ["pathAppend", heads(uState.pathAppends)],
820
+ ["pathPrepend", heads(uState.pathPrepends)],
821
+ ["pathIfNotExists", heads(uState.pathIfNotExists)],
822
+ ["pathDelete", heads(uState.pathDeletes)],
823
+ ];
824
+ for (const [op, names] of named) {
825
+ for (const name of names) {
826
+ const reason = unaddressable(name, ttlAttribute);
827
+ if (reason !== undefined)
828
+ return `${op} of "${name}": ${reason}. Nothing was sent.`;
829
+ }
830
+ }
831
+ // A sparse map's entries have an operation of their own to clear them. The other
832
+ // path operations address an entry by its stored name, which is how a counter
833
+ // entry is added to, so that name stays open to them.
834
+ const clearedEntries = [
835
+ [".remove()", uState.remove ?? []],
836
+ [
837
+ "pathRemove",
838
+ (uState.pathRemoves ?? []).flatMap((segments) => segments.length === 1 && typeof segments[0] === "string" ? [segments[0]] : []),
839
+ ],
840
+ ];
841
+ for (const [op, names] of clearedEntries) {
842
+ for (const name of names) {
843
+ // The attribute the operation removes decides: `.remove()` names a field, removed where
844
+ // it's stored, and a path's segment holding `#` is the attribute's own name.
845
+ const entry = sparseEntries.entryOf(op === ".remove()" ? resolveDbName(name) : name);
846
+ if (entry === undefined)
847
+ continue;
848
+ return (`${op} of "${name}": "${name}" is an entry of the sparse map "${entry.field}". ` +
849
+ `Use .removeEntries("${entry.field}", ["${entry.key}"]). Nothing was sent.`);
850
+ }
851
+ }
852
+ return undefined;
853
+ };
854
+ /** Clearing a field no row can be without: the row would write, then not be readable. */
855
+ const clearRefusal = (op, field, lacks) => {
856
+ if (isPrimaryComposite(field) || isTableKeyAttribute(field)) {
857
+ return primaryCompositeRefusal(op, field);
858
+ }
859
+ if (immutableFields.has(field) || field === systemFields.version) {
860
+ return `${op} of "${field}": "${field}" cannot be changed by an update. Nothing was sent.`;
861
+ }
862
+ if (field === systemFields.createdAt) {
863
+ return `${op} of "${field}": "${field}" is managed by the library. Nothing was sent.`;
864
+ }
865
+ const ref = resolvedRefs.find((r) => r.fieldName === field || r.idFieldName === field);
866
+ if (ref !== undefined) {
867
+ return (`${op} of "${field}": "${ref.fieldName}" is a ref, so a row without it could not be ` +
868
+ `read. Reassign it with .set({ ${ref.idFieldName} }). Nothing was sent.`);
869
+ }
870
+ if (lacks.canLack(field))
871
+ return undefined;
872
+ return (`${op} of "${field}": the model requires "${field}", so a row without it could not be ` +
873
+ `read. Make it optional in the model, or write a new value with .set({ ${field} }). ` +
874
+ "Nothing was sent.");
875
+ };
876
+ /**
877
+ * A `.set()` value that writes nothing at all, so it clears the field: `undefined`, or
878
+ * what encodes to it or to an empty set. A schema refusing the value (a `.check()` for a
879
+ * non-empty set) isn't a clear, and that schema goes on to refuse it.
880
+ */
881
+ const encodesToNothing = (field, value) => {
882
+ if (value === undefined)
883
+ return !storesUndefined(field);
884
+ if (modelFieldSchemas[field]?.ast.encoding === undefined && !isEmptySet(value))
885
+ return false;
886
+ const updateField = getSchemaFields(schemas.updateSchema)?.[field];
887
+ if (updateField === undefined)
888
+ return false;
889
+ try {
890
+ const encoded = Schema.encodeUnknownExit(Schema.Struct({ [field]: updateField }))({ [field]: value });
891
+ return Exit.isSuccess(encoded) && hasNoStoredForm(encoded.value[field]);
892
+ }
893
+ catch {
894
+ return false;
895
+ }
896
+ };
897
+ /**
898
+ * `.set({ field: undefined })` IS `.remove([field])`: one form, from here on, for
899
+ * everything downstream (sentinel release, the composer's per-half gate and policy,
900
+ * the vector gate, the retain snapshot, the transactional planner). Clearing a field
901
+ * no row can be without is refused. Three names are not clears: a library-generated
902
+ * `updatedAt` (`undefined` means generate it), a sparse map (`.set()` merges entries,
903
+ * and no entries merge nothing), and a name the model doesn't know, which the
904
+ * payload's schema drops as it drops any other unknown name.
905
+ */
906
+ const normalizeClears = (uState, lacks) => {
907
+ if (typeof uState.updates !== "object" || uState.updates === null)
908
+ return uState;
909
+ const record = uState.updates;
910
+ const payload = { ...record };
911
+ const remove = [...(uState.remove ?? [])];
912
+ let cleared = false;
913
+ for (const field of Object.keys(record)) {
914
+ const named = isModelField(field) || resolvedRefs.some((ref) => ref.idFieldName === field);
915
+ if (!named || !encodesToNothing(field, record[field]))
916
+ continue;
917
+ cleared = true;
918
+ delete payload[field];
919
+ if (field === systemFields.updatedAt || Object.hasOwn(sparseFields, field))
920
+ continue;
921
+ const refused = clearRefusal(".set()", field, lacks);
922
+ if (refused !== undefined)
923
+ return refused;
924
+ if (!remove.includes(field))
925
+ remove.push(field);
926
+ }
927
+ return cleared ? { ...uState, updates: payload, remove } : uState;
928
+ };
929
+ /**
930
+ * Whether `undefined` is a value of this field that has a stored form, one a transform
931
+ * writes as `"none"`. Setting it writes that, like any other value.
932
+ */
933
+ const storesUndefined = (field) => {
934
+ const schema = modelFieldSchemas[field];
935
+ if (schema === undefined)
936
+ return false;
937
+ try {
938
+ const encoded = Schema.encodeUnknownExit(schema)(undefined);
939
+ return Exit.isSuccess(encoded) && !hasNoStoredForm(encoded.value);
940
+ }
941
+ catch {
942
+ return false;
943
+ }
944
+ };
634
945
  /**
635
- * A `.remove()` of a primary-key composite: the row would keep its key and lose the
636
- * attribute, so it would stop decoding for every reader. Refused as a `.set()` of one
637
- * is, before a defaulted composite could turn it into one.
946
+ * The other operations holding a value with no stored form, which DynamoDB refuses as
947
+ * an operand. Adding or deleting nothing, or defaulting to nothing, is nothing to do. A
948
+ * `pathSet` of one clears the path, as `.set()` clears a field. A list element is
949
+ * refused: it can't be absent without moving the elements after it.
638
950
  */
639
- const refusedRecordRemove = (fields) => {
640
- const field = fields?.find((name) => isPrimaryComposite(name) || isTableKeyAttribute(name));
641
- return field === undefined ? undefined : primaryCompositeRefusal(".remove()", field);
951
+ const normalizeNoStoredForm = (uState) => {
952
+ const keptValues = (record) => record === undefined
953
+ ? undefined
954
+ : Object.fromEntries(Object.entries(record).filter(([, value]) => !hasNoStoredForm(value)));
955
+ const keptOps = (ops) => ops?.filter((op) => !hasNoStoredForm(op.value));
956
+ const pathRemoves = [...(uState.pathRemoves ?? [])];
957
+ const pathSets = [];
958
+ for (const op of uState.pathSets ?? []) {
959
+ if (op.isPath || !hasNoStoredForm(op.value)) {
960
+ pathSets.push(op);
961
+ continue;
962
+ }
963
+ if (typeof op.segments[op.segments.length - 1] === "number") {
964
+ const path = op.segments.map((segment) => String(segment)).join(".");
965
+ return (`pathSet on "${path}": DynamoDB can't store this value, and a list element can't be ` +
966
+ "left out without moving the elements after it. Use pathRemove to remove the " +
967
+ "element. [EDD-9124] Nothing was sent.");
968
+ }
969
+ pathRemoves.push(op.segments);
970
+ }
971
+ return {
972
+ ...uState,
973
+ add: keptValues(uState.add),
974
+ deleteFromSet: keptValues(uState.deleteFromSet),
975
+ pathAdds: keptOps(uState.pathAdds),
976
+ pathDeletes: keptOps(uState.pathDeletes),
977
+ pathIfNotExists: keptOps(uState.pathIfNotExists),
978
+ pathSets: uState.pathSets === undefined ? undefined : pathSets,
979
+ pathRemoves: pathRemoves.length === 0 ? uState.pathRemoves : pathRemoves,
980
+ };
981
+ };
982
+ /**
983
+ * The fields that can hold a value of a custom declaration, each with what checks one reads back.
984
+ * Empty for a model with none, which pays nothing more on a write.
985
+ */
986
+ const readBacks = new Map(Object.entries(data.modelFields).flatMap(([field, schema]) => {
987
+ // What's packed doesn't go through the marshaller's map, and packing refuses an instance itself.
988
+ const read = field in data.packedFields
989
+ ? undefined
990
+ : getSchemaFields(schemas.recordSchema)?.[field];
991
+ const readBack = read === undefined ? undefined : readBackOf(schema, () => read);
992
+ return readBack === undefined ? [] : [[field, readBack]];
993
+ }));
994
+ /** Refuses a payload holding a value that wouldn't read back, before anything is read or sent. */
995
+ const refuseNotReadBack = (encoded, operation) => readBacks.size === 0
996
+ ? Effect.void
997
+ : Effect.forEach([...readBacks].filter(([field]) => encoded[field] != null), ([field, readBack]) => readBack(encoded[field]).pipe(Effect.mapError((issue) => new ValidationError({
998
+ entityType,
999
+ operation,
1000
+ cause: notReadBack(`Field "${field}"`, issue),
1001
+ }))), { discard: true });
1002
+ /** What composes `field` into key text, in words, or `undefined` when nothing does. */
1003
+ const composedInto = (field) => {
1004
+ for (const [name, def] of Object.entries(allIndexes)) {
1005
+ if (def.pk.composite.includes(field) || def.sk.composite.includes(field)) {
1006
+ return name === "primary" ? "the primary key" : `index "${name}"`;
1007
+ }
1008
+ }
1009
+ for (const [name, def] of Object.entries((config.unique ?? {}))) {
1010
+ if (resolveUniqueFields(def).includes(field))
1011
+ return `unique constraint "${name}"`;
1012
+ }
1013
+ for (const [name, def] of Object.entries(data.vectorIndexes)) {
1014
+ if (def.partition.includes(field))
1015
+ return `vector index "${name}"'s partition`;
1016
+ }
1017
+ const timeSeries = config.timeSeries;
1018
+ return timeSeries?.orderBy === field ? "an event's sort key (timeSeries.orderBy)" : undefined;
1019
+ };
1020
+ /** A composite value's text, as `KeyComposer` composes it; `undefined` when it composes none. */
1021
+ const compositeTextOf = (value) => {
1022
+ if (value === undefined || value === null)
1023
+ return undefined;
1024
+ try {
1025
+ return KeyComposer.compositeText(schema, value);
1026
+ }
1027
+ catch {
1028
+ return undefined;
1029
+ }
1030
+ };
1031
+ /**
1032
+ * The texts a key composite's value is composed into, written and composed again from a row read
1033
+ * back, by what composes it: a key or a vector partition through the key form; a unique sentinel
1034
+ * from the value as stored (`storedSentinelValue`, `readSentinelValue`); and `append`'s event sort
1035
+ * key, with `escapeKeys` and `numericKeyText` off, from the value as given.
1036
+ */
1037
+ const readBackTexts = (field, append) => {
1038
+ const timeSeries = config.timeSeries;
1039
+ const numericOrderBy = schema.escapeKeys === true || schema.numericKeyText === true;
1040
+ const inKey = Object.values(allIndexes).some((def) => def.pk.composite.includes(field) || def.sk.composite.includes(field)) ||
1041
+ Object.values(data.vectorIndexes).some((def) => def.partition.includes(field)) ||
1042
+ (append && timeSeries?.orderBy === field && numericOrderBy);
1043
+ const inSentinel = !append &&
1044
+ Object.values((config.unique ?? {})).some((def) => resolveUniqueFields(def).includes(field));
1045
+ const inEvent = append && timeSeries?.orderBy === field && !numericOrderBy;
1046
+ const keyText = (value) => {
1047
+ try {
1048
+ return compositeTextOf(compositeKeyForm(field, value));
1049
+ }
1050
+ catch {
1051
+ return undefined;
1052
+ }
1053
+ };
1054
+ const readText = (value) => compositeTextOf(readSentinelValue(field, value) ?? value);
1055
+ return [
1056
+ ...(inKey ? [{ written: keyText, read: keyText }] : []),
1057
+ ...(inSentinel
1058
+ ? [
1059
+ {
1060
+ written: (value) => compositeTextOf(storedSentinelValue(field, value) ?? value),
1061
+ read: readText,
1062
+ },
1063
+ ]
1064
+ : []),
1065
+ ...(inEvent ? [{ written: compositeTextOf, read: readText }] : []),
1066
+ ];
1067
+ };
1068
+ /**
1069
+ * The key composites of `fields` (the model's, or `appendInput`'s for `append`) whose read-back
1070
+ * can't be guaranteed at load (`readBackUnsure`: a transformation, or numeric kinds that can't be
1071
+ * read off the schema), each with what composes it and the test of a stored value that reads back
1072
+ * otherwise (`readsBackOtherwise`): read back by the model's field, as every read and every key
1073
+ * composed again from a row reads it. A write giving one such a value is refused (`EDD-9128`). A
1074
+ * field no key composes isn't asked. Empty for a model with none, which pays nothing more on a
1075
+ * write.
1076
+ */
1077
+ const otherKindReadsOf = (fields, append) => new Map(Object.entries(fields).flatMap(([field, schema]) => {
1078
+ const into = composedInto(field);
1079
+ if (into === undefined)
1080
+ return [];
1081
+ const reading = modelFieldSchemas[field] ?? schema;
1082
+ const readsOther = readsBackOtherwise(reading, {
1083
+ asRead,
1084
+ written: schema === reading ? undefined : schema,
1085
+ texts: readBackTexts(field, append),
1086
+ });
1087
+ return readsOther === undefined ? [] : [[field, { into, readsOther }]];
1088
+ }));
1089
+ /**
1090
+ * The model's and, for `append`, which takes its input through `appendInput`, `appendInput`'s own.
1091
+ * Worked out again when `_injectIndex` adds an index, whose composites it composes.
1092
+ */
1093
+ let kindReadsFor;
1094
+ const kindReads = () => {
1095
+ if (kindReadsFor?.indexes === allIndexes)
1096
+ return kindReadsFor;
1097
+ const appendInput = config.timeSeries?.appendInput;
1098
+ const appendFields = appendInput === undefined ? undefined : getSchemaFields(appendInput);
1099
+ kindReadsFor = {
1100
+ indexes: allIndexes,
1101
+ model: otherKindReadsOf(data.modelFields, false),
1102
+ append: appendFields === undefined ? new Map() : otherKindReadsOf(appendFields, true),
1103
+ };
1104
+ return kindReadsFor;
1105
+ };
1106
+ /**
1107
+ * Refuses a payload storing, for a key composite whose read-back can't be guaranteed at load, a
1108
+ * value that reads back otherwise: a stored row would compose other key text (`EDD-9128`).
1109
+ */
1110
+ const refuseOtherKindRead = (encoded, operation, reads = kindReads().model) => {
1111
+ for (const [field, { into, readsOther }] of reads) {
1112
+ const value = encoded[field];
1113
+ const readsAs = value == null ? undefined : readsOther(value);
1114
+ if (readsAs === undefined)
1115
+ continue;
1116
+ return Effect.fail(new ValidationError({
1117
+ entityType,
1118
+ operation,
1119
+ cause: readBackRefusal(`Field "${field}" is composed into ${into}`, value, readsAs),
1120
+ }));
1121
+ }
1122
+ return Effect.void;
1123
+ };
1124
+ /**
1125
+ * A write's payload, encoded (see `encodeOrDecodeEncode`) and refused if it wouldn't read back.
1126
+ * Every write of the entity's own encodes through this.
1127
+ */
1128
+ const encodeForWrite = (schema, input, operation) => {
1129
+ const encoded = encodeOrDecodeEncode(schema, input, entityType, operation);
1130
+ const readBack = readBacks.size === 0
1131
+ ? encoded
1132
+ : encoded.pipe(Effect.tap((value) => refuseNotReadBack(value, operation)));
1133
+ const reads = operation === "append" ? kindReads().append : kindReads().model;
1134
+ return reads.size === 0
1135
+ ? readBack
1136
+ : readBack.pipe(Effect.tap((value) => refuseOtherKindRead(value, operation, reads)));
1137
+ };
1138
+ /**
1139
+ * An update's operand that wouldn't read back. An operand of `.add`, `.subtract` or `.deleteFromSet`
1140
+ * is a number or a set to apply, not a value of the field, so only what's stored as given counts.
1141
+ * `unstorableOperand` goes first, so each of these has already been through the marshaller.
1142
+ */
1143
+ const notReadBackOperand = (uState) => {
1144
+ if (readBacks.size === 0)
1145
+ return undefined;
1146
+ const operands = [
1147
+ [
1148
+ ".append() of",
1149
+ Object.entries(uState.append ?? {}).map(([field, value]) => ({
1150
+ segments: [field],
1151
+ value,
1152
+ })),
1153
+ "elements",
1154
+ ],
1155
+ ["pathSet of", uState.pathSets, "value"],
1156
+ ["pathAppend of", uState.pathAppends, "elements"],
1157
+ ["pathPrepend of", uState.pathPrepends, "elements"],
1158
+ ["pathIfNotExists of", uState.pathIfNotExists, "value"],
1159
+ ];
1160
+ for (const [op, ops, kind] of operands) {
1161
+ for (const operand of ops ?? []) {
1162
+ // A copy writes another attribute's value: it holds no value of its own to read back.
1163
+ if (op === "pathSet of" && isCopy(operand))
1164
+ continue;
1165
+ const { segments, value } = operand;
1166
+ if (!readBacks.has(String(segments[0])))
1167
+ continue;
1168
+ const { encoded } = encodePathValue(segments, value, kind);
1169
+ const read = asRead(encoded);
1170
+ const issue = kind === "value"
1171
+ ? pathValues.validate(segments, read)
1172
+ : pathValues.validateElements(segments, read);
1173
+ if (issue !== undefined)
1174
+ return notReadBack(`${op} "${segments.join(".")}"`, issue);
1175
+ }
1176
+ }
1177
+ return undefined;
1178
+ };
1179
+ /**
1180
+ * A value in an update that DynamoDB can't store, in words, before the update reads or
1181
+ * sends anything: an operand of any operation, in the form it would be written.
1182
+ */
1183
+ const unstorableOperand = (uState, encodedUpdates) => {
1184
+ const refused = (op, unstorable) => `${op} ${unstorable.describe()} Nothing was sent.`;
1185
+ const appended = Object.fromEntries(Object.entries(uState.append ?? {}).map(([field, value]) => [
1186
+ field,
1187
+ encodePathValue([field], value, "elements").encoded,
1188
+ ]));
1189
+ const records = [
1190
+ [".set() of", fieldsToStore(encodedUpdates)],
1191
+ [".add() of", uState.add ?? {}],
1192
+ [".subtract() of", uState.subtract ?? {}],
1193
+ [".append() of", appended],
1194
+ [".deleteFromSet() of", uState.deleteFromSet ?? {}],
1195
+ [".withVector() of", uState.withVectors ?? {}],
1196
+ ];
1197
+ for (const [op, record] of records) {
1198
+ const unstorable = unstorableIn(record);
1199
+ if (unstorable !== undefined)
1200
+ return refused(op, unstorable);
1201
+ }
1202
+ const pathOps = [
1203
+ ["pathSet of", uState.pathSets, "value"],
1204
+ ["pathAdd of", uState.pathAdds, undefined],
1205
+ ["pathSubtract of", uState.pathSubtracts, undefined],
1206
+ ["pathAppend of", uState.pathAppends, "elements"],
1207
+ ["pathPrepend of", uState.pathPrepends, "elements"],
1208
+ ["pathIfNotExists of", uState.pathIfNotExists, "value"],
1209
+ ["pathDelete of", uState.pathDeletes, undefined],
1210
+ ];
1211
+ for (const [op, ops, kind] of pathOps) {
1212
+ for (const operand of ops ?? []) {
1213
+ // A copy, or a subtraction of another attribute's value, writes no value of its own.
1214
+ if ((op === "pathSet of" || op === "pathSubtract of") && isCopy(operand))
1215
+ continue;
1216
+ const value = kind === undefined
1217
+ ? operand.value
1218
+ : encodePathValue(operand.segments, operand.value, kind).encoded;
1219
+ const unstorable = unstorableIn({ value });
1220
+ if (unstorable !== undefined) {
1221
+ return refused(op, new UnstorableValue({
1222
+ path: [...operand.segments, ...unstorable.path.slice(1)],
1223
+ reason: unstorable.reason,
1224
+ }));
1225
+ }
1226
+ }
1227
+ }
1228
+ for (const [attribute, value] of Object.entries(uState.cascade?.filter ?? {})) {
1229
+ const unstorable = isEmptySet(value)
1230
+ ? new UnstorableValue({ path: [attribute], reason: "DynamoDB has no empty set." })
1231
+ : unstorableIn({ [attribute]: value });
1232
+ if (unstorable !== undefined)
1233
+ return refused(".cascade() filter on", unstorable);
1234
+ }
1235
+ return undefined;
1236
+ };
1237
+ /**
1238
+ * An update's operands written as values of its fields — `.append()`'s entries and the values of
1239
+ * `pathSet` (a copy excepted), `pathAppend`, `pathPrepend` and `pathIfNotExists` — in the form
1240
+ * they're written, each checked against the write schema at its path. Decided once, before the
1241
+ * update reads or sends anything: the first one the schema refuses refuses the update, and the
1242
+ * write sends the rest as encoded here. Each path operation's value is at its operation's index.
1243
+ */
1244
+ const encodeOperands = (uState) => {
1245
+ // Keyed by a name the caller supplies: no prototype, so `__proto__` is a key like any other.
1246
+ const append = Object.create(null);
1247
+ for (const [field, value] of Object.entries(uState.append ?? {})) {
1248
+ const { encoded, issue } = encodePathValue([field], value, "elements");
1249
+ if (issue !== undefined)
1250
+ return { operation: "update.append", issue };
1251
+ append[field] = encoded;
1252
+ }
1253
+ const each = (operation, ops, kind,
1254
+ /** Whether the operation can copy another attribute's value: only `pathSet`. */
1255
+ copies = false) => {
1256
+ const values = [];
1257
+ for (const op of ops ?? []) {
1258
+ // A copy writes another attribute's value: there's nothing to encode.
1259
+ if (copies && isCopy(op)) {
1260
+ values.push(undefined);
1261
+ continue;
1262
+ }
1263
+ const { encoded, issue } = encodePathValue(op.segments, op.value, kind);
1264
+ if (issue !== undefined)
1265
+ return { operation, issue };
1266
+ values.push(encoded);
1267
+ }
1268
+ return values;
1269
+ };
1270
+ const pathSets = each("update.pathSet", uState.pathSets, "value", true);
1271
+ if ("issue" in pathSets)
1272
+ return pathSets;
1273
+ const pathAppends = each("update.pathAppend", uState.pathAppends, "elements");
1274
+ if ("issue" in pathAppends)
1275
+ return pathAppends;
1276
+ const pathPrepends = each("update.pathPrepend", uState.pathPrepends, "elements");
1277
+ if ("issue" in pathPrepends)
1278
+ return pathPrepends;
1279
+ const pathIfNotExists = each("update.pathIfNotExists", uState.pathIfNotExists, "value");
1280
+ if ("issue" in pathIfNotExists)
1281
+ return pathIfNotExists;
1282
+ return { append, pathSets, pathAppends, pathPrepends, pathIfNotExists };
1283
+ };
1284
+ /**
1285
+ * A `pathRemove` of a field no row can be without, or of a property below a field
1286
+ * whose schema requires it. Primary-key composites, and paths below a field that
1287
+ * feeds a key or a sentinel, get their refusal from `normalizeDerivedPathOps`.
1288
+ */
1289
+ const refusedPathRemove = (uState, lacks) => {
1290
+ for (const segments of uState.pathRemoves ?? []) {
1291
+ const head = segments[0];
1292
+ if (typeof head !== "string" || !isModelField(head))
1293
+ continue;
1294
+ if (segments.length === 1) {
1295
+ if (isPrimaryComposite(head))
1296
+ continue;
1297
+ const refused = clearRefusal("pathRemove", head, lacks);
1298
+ if (refused !== undefined)
1299
+ return refused;
1300
+ continue;
1301
+ }
1302
+ if (derivedFrom(head) !== undefined)
1303
+ continue;
1304
+ if (pathIsRequired(modelFieldSchemas[head], segments.slice(1))) {
1305
+ const path = segments.map((s) => String(s)).join(".");
1306
+ return (`pathRemove on "${path}": the model requires it, so a row without it could not be ` +
1307
+ "read. Make it optional in the model, or write a new value with .pathSet(). " +
1308
+ "Nothing was sent.");
1309
+ }
1310
+ }
1311
+ return undefined;
1312
+ };
1313
+ /**
1314
+ * A `.remove()` no row could survive. A primary-key composite: the row would keep its
1315
+ * key and lose the attribute, so it would stop decoding for every reader. Refused as a
1316
+ * `.set()` of one is, before a defaulted composite could turn it into one. A required
1317
+ * field, for the same reason.
1318
+ */
1319
+ const refusedRecordRemove = (fields, lacks) => {
1320
+ for (const field of fields ?? []) {
1321
+ const refused = clearRefusal(".remove()", field, lacks);
1322
+ if (refused !== undefined)
1323
+ return refused;
1324
+ }
1325
+ return undefined;
642
1326
  };
643
1327
  /**
644
1328
  * The immutable fields a `.set()` names, in stored form (#133). An update may
@@ -658,6 +1342,9 @@ const makeImpl = (config, precomputedData) => {
658
1342
  if (encoded.issue !== undefined) {
659
1343
  return `.set() of immutable "${field}": ${String(encoded.issue)}`;
660
1344
  }
1345
+ const unstorable = unstorableIn({ [field]: encoded.encoded });
1346
+ if (unstorable !== undefined)
1347
+ return `.set(): ${unstorable.describe()} Nothing was sent.`;
661
1348
  out.push({
662
1349
  field,
663
1350
  attr: resolveDbName(field),
@@ -704,11 +1391,12 @@ const makeImpl = (config, precomputedData) => {
704
1391
  * the item it writes decodes. Anything less on a missing item would leave a
705
1392
  * partial row behind — those updates require the item to exist.
706
1393
  */
707
- const completeUpsertPayload = (updates) => {
1394
+ const completeUpsertPayload = (updates, removed, lacks) => {
708
1395
  if (typeof updates !== "object" || updates === null)
709
1396
  return false;
710
1397
  const record = updates;
711
- const present = (field) => record[field] !== undefined && record[field] !== null;
1398
+ const present = (field) => (record[field] !== undefined && record[field] !== null) ||
1399
+ (removed.includes(field) && lacks.absentReading(field) !== undefined);
712
1400
  const primary = allIndexes.primary;
713
1401
  if (primary && ![...primary.pk.composite, ...primary.sk.composite].every(present))
714
1402
  return false;
@@ -901,6 +1589,9 @@ const makeImpl = (config, precomputedData) => {
901
1589
  */
902
1590
  const toDomainView = (raw) => {
903
1591
  const view = { ...raw };
1592
+ // The order every read of a row uses: sparse entries leave the attribute-keyed row first, so
1593
+ // an entry never stands in for a field of its name whose own attribute the row lacks.
1594
+ deserializeSparseFields(view);
904
1595
  renameFromDynamo(view);
905
1596
  return view;
906
1597
  };
@@ -917,12 +1608,51 @@ const makeImpl = (config, precomputedData) => {
917
1608
  // `composeAllKeys`. The raw model is not equivalent — entity derivation
918
1609
  // substitutes date/Redacted fields with their wire transforms, so reading
919
1610
  // fields off the model would miss encodings the write path applies.
920
- const compositeKeyForm = makeCompositeKeyForm(schemas.inputSchema, (attr, value) => {
1611
+ /**
1612
+ * Every attribute a key, sentinel or partition of this entity is composed from: the composites
1613
+ * of the primary key and of every index (a Z-order half's prefix and dimensions among them, and
1614
+ * the history segments, which are the primary sort key's), shard sources, unique constraint
1615
+ * fields, vector partitions and a time series' `orderBy`. `allIndexes` grows after `make()`.
1616
+ */
1617
+ let keyReaders;
1618
+ const readsKey = (attr) => {
1619
+ if (keyReaders === undefined || keyReaders[0] !== allIndexes) {
1620
+ const readers = new Set();
1621
+ for (const def of Object.values(allIndexes)) {
1622
+ // A shard's `by` and source are composites of the index and the primary key.
1623
+ for (const field of [...def.pk.composite, ...def.sk.composite])
1624
+ readers.add(field);
1625
+ }
1626
+ for (const def of Object.values((config.unique ?? {}))) {
1627
+ for (const field of resolveUniqueFields(def))
1628
+ readers.add(field);
1629
+ }
1630
+ for (const definition of Object.values(data.vectorIndexes)) {
1631
+ for (const field of definition.partition)
1632
+ readers.add(field);
1633
+ }
1634
+ const orderBy = config.timeSeries?.orderBy;
1635
+ if (orderBy !== undefined)
1636
+ readers.add(orderBy);
1637
+ keyReaders = [allIndexes, readers];
1638
+ }
1639
+ return keyReaders[1].has(attr);
1640
+ };
1641
+ const unencodable = (attr, value, reason) => {
1642
+ if (reason !== undefined) {
1643
+ return refuseInexact(`Composite "${attr}" on entity "${entityType}"`, value, reason);
1644
+ }
921
1645
  throw new Error(`[EDD-9050] Composite "${attr}" on entity "${entityType}" could not be encoded to its ` +
922
1646
  `stored form. The attribute's schema carries an encoding transformation, so the ` +
923
1647
  `stored key holds the ENCODED value, but ${JSON.stringify(String(value))} encodes ` +
924
1648
  `under neither encode nor decode->encode. Supply a value of the attribute's own type.`);
925
- });
1649
+ };
1650
+ const compositeKeyForm = makeCompositeKeyForm(schemas.inputSchema, unencodable,
1651
+ // A record handed here can be a whole row read back (restore, a retain update, rekey): what
1652
+ // no key reads is never key text, so a field stored in a form its schema can't take again
1653
+ // is left as it is.
1654
+ { reads: readsKey });
1655
+ const compositeStoredForm = makeCompositeStoredForm(schemas.inputSchema);
926
1656
  /**
927
1657
  * PUBLIC key boundary. Converts a caller-supplied key record from the model's
928
1658
  * **Type** side — the one convention the whole API takes — into the ENCODED
@@ -980,6 +1710,56 @@ const makeImpl = (config, precomputedData) => {
980
1710
  * through `keyForm(...)`.
981
1711
  */
982
1712
  const keyForm = (record) => toCompositeKeyRecord(compositeKeyForm, record);
1713
+ /**
1714
+ * A unique field's value as `put` stored it, from a row read back: sentinels are composed from
1715
+ * the Encoded value, which for a field stored as `N` the unmarshaller may hand back as the other
1716
+ * numeric kind (`storedNumericForm`). `undefined` when the value is already as stored.
1717
+ */
1718
+ const storedSentinelValue = (() => {
1719
+ const fields = getSchemaFields(schemas.inputSchema);
1720
+ const forms = new Map();
1721
+ return (field, value) => {
1722
+ if (!forms.has(field)) {
1723
+ const fieldSchema = fields?.[field];
1724
+ forms.set(field, fieldSchema === undefined ? undefined : storedNumericForm(fieldSchema));
1725
+ }
1726
+ return forms.get(field)?.(value);
1727
+ };
1728
+ })();
1729
+ /**
1730
+ * A unique field's value, or a time-series `orderBy`, as `put` or `append` stored it, from a row
1731
+ * read back: {@link storedSentinelValue}, and for a field whose numeric kinds can't be read off its
1732
+ * schema, the value decoded through the field, as a read decodes it, and encoded again
1733
+ * (`storedFormOfRead`). `Schema.Unknown` decoded to a `Schema.BigInt` stored `5n`, which reads back
1734
+ * as `5`. Only a value read from a row is taken this way: a write's own value is the one it stores.
1735
+ */
1736
+ const readSentinelValue = (() => {
1737
+ const fields = getSchemaFields(schemas.inputSchema);
1738
+ const forms = new Map();
1739
+ return (field, value) => {
1740
+ if (!forms.has(field)) {
1741
+ const fieldSchema = fields?.[field];
1742
+ forms.set(field, fieldSchema === undefined ? undefined : storedFormOfRead(fieldSchema));
1743
+ }
1744
+ return forms.get(field)?.(value);
1745
+ };
1746
+ })();
1747
+ /**
1748
+ * `keyForm` of a caller's DOMAIN key record: each composite first put into
1749
+ * the form `put` stores it in, as `put`'s encode and `get`'s `encodeKey` do,
1750
+ * so a domain value that also reads as its codec's stored text (`"x:MiX"`
1751
+ * for a codec prepending `x:`) composes the key `put` wrote for it. Every
1752
+ * other composite composes exactly what `keyForm` alone does.
1753
+ */
1754
+ const domainKeyForm = (record) => keyForm(compositeStoredForm(record));
1755
+ /**
1756
+ * The key form 1.39.0 composed from a stored record: a codec whose `encode`
1757
+ * takes its own output keyed its stored text encoded once more (`x:x:mix`
1758
+ * for `"MiX"` stored `"x:MiX"`). Only `rekey` composes it, to find a row
1759
+ * 1.39.0 stored under that text and move it to `keyForm`'s.
1760
+ */
1761
+ const compositeKeyForm139 = makeCompositeKeyForm(schemas.inputSchema, unencodable, { text139: true, reads: readsKey });
1762
+ const keyForm139 = (record) => toCompositeKeyRecord(compositeKeyForm139, record);
983
1763
  // -------------------------------------------------------------------------
984
1764
  // Write-limit diagnosis (#144)
985
1765
  //
@@ -1041,6 +1821,41 @@ const makeImpl = (config, precomputedData) => {
1041
1821
  [primary.sk.field]: KeyComposer.composeSk(schema, entityType, entityVersion, primary, recordKeyForm),
1042
1822
  };
1043
1823
  };
1824
+ /**
1825
+ * What a write stamps on an item it builds whole, in wire form: a timestamp the caller didn't
1826
+ * supply, and the first version. Keys are composed after this, so an index can be composed from
1827
+ * any of them (`DESIGN.md` §7, "Composites the library stamps").
1828
+ */
1829
+ const stampsOf = (encoded, times) => ({
1830
+ ...(systemFields.createdAt && encoded[systemFields.createdAt] === undefined
1831
+ ? {
1832
+ [systemFields.createdAt]: generateTimestamp(systemFields.createdAtEncoding, times.createdAt),
1833
+ }
1834
+ : {}),
1835
+ ...(systemFields.updatedAt && encoded[systemFields.updatedAt] === undefined
1836
+ ? {
1837
+ [systemFields.updatedAt]: generateTimestamp(systemFields.updatedAtEncoding, times.updatedAt),
1838
+ }
1839
+ : {}),
1840
+ ...(systemFields.version ? { [systemFields.version]: 1 } : {}),
1841
+ });
1842
+ /**
1843
+ * What an update stamps, by model name: the `updatedAt` it writes, and the next version where the
1844
+ * write read the item to know it. See `KeyComposer.composeGsiKeysForUpdatePolicyAware`.
1845
+ */
1846
+ const writeStamps = (updatedAt, version) => ({
1847
+ ...(systemFields.updatedAt && updatedAt !== undefined
1848
+ ? { [systemFields.updatedAt]: updatedAt }
1849
+ : {}),
1850
+ ...(systemFields.version && version !== undefined ? { [systemFields.version]: version } : {}),
1851
+ });
1852
+ /** The system fields of `item`, by model name: what a guarded put may have carried over from the stored item. */
1853
+ const carriedSystemFields = (item) => ({
1854
+ ...(systemFields.createdAt
1855
+ ? { [systemFields.createdAt]: item[resolveDbName(systemFields.createdAt)] }
1856
+ : {}),
1857
+ ...(systemFields.version ? { [systemFields.version]: item[systemFields.version] } : {}),
1858
+ });
1044
1859
  /**
1045
1860
  * Every index's keys for `record`. A Z-order sort key can fail to place a
1046
1861
  * value (`[EDD-9092]`, #171), and a composite can have no key text (`NaN`,
@@ -1144,13 +1959,12 @@ const makeImpl = (config, precomputedData) => {
1144
1959
  defaulted: removed,
1145
1960
  })), Effect.mapError((cause) => new ValidationError({ entityType, operation: "update.default", cause })));
1146
1961
  };
1147
- const fillDecodingDefaults = (input) => {
1962
+ const fillDecodingDefaults = (input, fills = (field) => indexedDefaultFields().has(field)) => {
1148
1963
  if (defaultedFields.length === 0 || typeof input !== "object" || input === null) {
1149
1964
  return Effect.succeed(input);
1150
1965
  }
1151
1966
  const record = input;
1152
- const keyed = indexedDefaultFields();
1153
- const missing = defaultedFields.filter(([name]) => keyed.has(name) && record[name] === undefined);
1967
+ const missing = defaultedFields.filter(([name]) => fills(name, record) && record[name] === undefined);
1154
1968
  if (missing.length === 0)
1155
1969
  return Effect.succeed(input);
1156
1970
  return Schema.decodeUnknownEffect(Schema.Struct(Object.fromEntries(missing)))({}).pipe(Effect.map((defaults) => ({ ...record, ...defaults })), Effect.mapError((cause) => new ValidationError({ entityType, operation: "put.default", cause })));
@@ -1162,6 +1976,96 @@ const makeImpl = (config, precomputedData) => {
1162
1976
  const record = input;
1163
1977
  return [...indexedDefaultFields()].some((name) => record[name] === undefined);
1164
1978
  };
1979
+ /** A field an upsert keeps from the stored row (`if_not_exists`), where it isn't in the key anyway. */
1980
+ const keptByUpsert = (field) => !isPrimaryComposite(field) && (field === systemFields.createdAt || immutableFields.has(field));
1981
+ /** A secondary index's halves: the key attribute, and what's composed into it. */
1982
+ const halvesOf = (index) => [
1983
+ [index.pk.field, [...index.pk.composite, ...(index.shards?.by ?? [])]],
1984
+ [index.sk.field, index.sk.composite],
1985
+ ];
1986
+ /**
1987
+ * A value with no stored form is an absent attribute, so an upsert's replaces what the row
1988
+ * holds. A field left unset (an optional `undefined`) doesn't, nor does an immutable one.
1989
+ */
1990
+ const upsertClears = (field, value, lacks) => (isEmptySet(value) || (value === undefined && lacks.absentReading(field) !== undefined)) &&
1991
+ !immutableFields.has(field);
1992
+ /**
1993
+ * The keys an upsert writes: `composed`, plus a half of an index it can't compose whole, where the
1994
+ * input has all that half holds and some of it can change. A half of nothing but primary composites
1995
+ * and kept values says what it always said, so it isn't written: an upsert writes no more attributes
1996
+ * than it must.
1997
+ */
1998
+ const upsertKeys = (record, composed) => composeKeysOrFail(entityType, "upsert", () => {
1999
+ const keys = { ...composed };
2000
+ const recordKeyForm = keyForm(record);
2001
+ for (const [indexName, index] of Object.entries(allIndexes)) {
2002
+ if (indexName === "primary" || index.pk.field in composed)
2003
+ continue;
2004
+ const known = KeyComposer.composeKnownHalves(schema, entityType, entityVersion, index, recordKeyForm);
2005
+ for (const [field, composites] of halvesOf(index)) {
2006
+ const value = known[field];
2007
+ if (value !== undefined &&
2008
+ composites.some((attr) => !keptByUpsert(attr) && !isPrimaryComposite(attr))) {
2009
+ keys[field] = value;
2010
+ }
2011
+ }
2012
+ }
2013
+ return keys;
2014
+ });
2015
+ /**
2016
+ * What an upsert does about the secondary keys it can't simply write, because one `UpdateItem`
2017
+ * can't splice what's stored into a key (`DESIGN.md` §7, "An upsert over a value it keeps" and "An
2018
+ * upsert leaving out a composite"). By half:
2019
+ *
2020
+ * - **`keep`**: the key holds a value the upsert keeps (`createdAt`, immutable fields), and stays too
2021
+ * (`if_not_exists`), where nothing else in the half can change or its `createdAt` isn't in the
2022
+ * input, so the key can't be written. The write holds on an existing row only where it has the key
2023
+ * and everything in `same`, what else the half holds, is what the input says: the key is then
2024
+ * already right.
2025
+ * - **`matches`**: the input has every value, so the key is written, and the write holds only where
2026
+ * each kept value is stored as the input has it.
2027
+ * - **`same`** also holds what the input names of a half it can't compose, as that half can only
2028
+ * stay if none of it changes. A value it doesn't name changes nothing: an upsert leaves it, and the
2029
+ * key that says it, as stored. So a stamped `updatedAt` isn't held to this, and the half lags until
2030
+ * a write composes it, as on an update. One the input supplies is, and moves the key.
2031
+ *
2032
+ * A rejected write returns the row at no read, and the upsert composes from that
2033
+ * (`guardedUpsert`, by the per-half policy for what the row can't supply): an input that contradicts
2034
+ * it, a row without the key, or a changed `same`.
2035
+ */
2036
+ const upsertKeyPlan = (composed, input, suppliedCreatedAt) => {
2037
+ const keep = new Set();
2038
+ const same = new Set();
2039
+ const matches = new Set();
2040
+ for (const [indexName, index] of Object.entries(allIndexes)) {
2041
+ if (indexName === "primary")
2042
+ continue;
2043
+ for (const [field, composites] of halvesOf(index)) {
2044
+ const others = composites.filter((attr) => !keptByUpsert(attr) && !isPrimaryComposite(attr));
2045
+ if (!(field in composed)) {
2046
+ for (const attr of others) {
2047
+ if (input[attr] !== undefined)
2048
+ same.add(attr);
2049
+ }
2050
+ continue;
2051
+ }
2052
+ const held = composites.filter(keptByUpsert);
2053
+ if (held.length === 0)
2054
+ continue;
2055
+ if (others.length === 0 ||
2056
+ (!suppliedCreatedAt && held.includes(systemFields.createdAt ?? ""))) {
2057
+ keep.add(field);
2058
+ for (const attr of others)
2059
+ same.add(attr);
2060
+ }
2061
+ else {
2062
+ for (const attr of held)
2063
+ matches.add(attr);
2064
+ }
2065
+ }
2066
+ }
2067
+ return { keep, same, matches };
2068
+ };
1165
2069
  /** Attach the model class prototype to a decoded plain object (when model is Schema.Class). */
1166
2070
  const attachPrototype = (decoded) => isSchemaClass ? Object.assign(Object.create(rawModel.prototype), decoded) : decoded;
1167
2071
  /**
@@ -1189,6 +2093,43 @@ const makeImpl = (config, precomputedData) => {
1189
2093
  const corruption = versionCorruption(item, operation);
1190
2094
  return corruption === undefined ? Effect.void : Effect.fail(corruption);
1191
2095
  };
2096
+ /**
2097
+ * The model field a row is without whose reading of the absence throws, if there is one.
2098
+ *
2099
+ * A field whose absent attribute stands for a value is read as that value, through the
2100
+ * field's own steps (`absentStored`). A step that throws on it kills the read, where 1.39.0,
2101
+ * which read no such value, failed on the missing key. Looked for only once a row's decode
2102
+ * has died, so a read that doesn't die runs nothing more.
2103
+ */
2104
+ const fieldDyingOnAbsence = (raw) => {
2105
+ for (const [field, fieldSchema] of Object.entries(modelFieldSchemas)) {
2106
+ if (Object.hasOwn(raw, field))
2107
+ continue;
2108
+ const absent = absentStored(fieldSchema);
2109
+ if (absent === undefined)
2110
+ continue;
2111
+ try {
2112
+ const read = Schema.decodeUnknownExit(fieldSchema)(absent.stored);
2113
+ if (Exit.isFailure(read) && !Exit.hasFails(read))
2114
+ return field;
2115
+ }
2116
+ catch {
2117
+ return field;
2118
+ }
2119
+ }
2120
+ return undefined;
2121
+ };
2122
+ /**
2123
+ * A row's decode that died reading a field the row is without fails as 1.39.0's did, on the
2124
+ * missing key ({@link fieldDyingOnAbsence}, `failingAsBefore`). Any other defect is the defect
2125
+ * it was.
2126
+ */
2127
+ const missingKeyOnDefect = (raw, operation) => failingAsBefore(() => {
2128
+ const field = fieldDyingOnAbsence(raw);
2129
+ return field === undefined
2130
+ ? undefined
2131
+ : issueDecoding(Schema.Struct({ [field]: Schema.Never }), {});
2132
+ }, (cause) => new ValidationError({ entityType, operation, cause }));
1192
2133
  const decodeRecord = (raw) => {
1193
2134
  const corruption = versionCorruption(raw, "decode");
1194
2135
  if (corruption !== undefined)
@@ -1200,7 +2141,7 @@ const makeImpl = (config, precomputedData) => {
1200
2141
  entityType,
1201
2142
  operation: "decode",
1202
2143
  cause,
1203
- })));
2144
+ })), missingKeyOnDefect(raw, "decode"));
1204
2145
  });
1205
2146
  };
1206
2147
  /** Decode a raw item using the schema selected by mode */
@@ -1232,7 +2173,7 @@ const makeImpl = (config, precomputedData) => {
1232
2173
  entityType,
1233
2174
  operation: "decode",
1234
2175
  cause,
1235
- })));
2176
+ })), missingKeyOnDefect(raw, "decode"));
1236
2177
  });
1237
2178
  };
1238
2179
  /**
@@ -1252,7 +2193,7 @@ const makeImpl = (config, precomputedData) => {
1252
2193
  return yield* corruption;
1253
2194
  deserializeSparseFields(raw);
1254
2195
  renameFromDynamo(raw);
1255
- const decoded = yield* Schema.decodeUnknownEffect(schemas.itemSchema)(raw).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation: "decodeMarshalledItem", cause })));
2196
+ const decoded = yield* Schema.decodeUnknownEffect(schemas.itemSchema)(raw).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation: "decodeMarshalledItem", cause })), missingKeyOnDefect(raw, "decodeMarshalledItem"));
1256
2197
  return attachPrototype(decoded);
1257
2198
  });
1258
2199
  const nowIso = (now) => DateTime.formatIso(now);
@@ -1288,6 +2229,42 @@ const makeImpl = (config, precomputedData) => {
1288
2229
  return undefined;
1289
2230
  return config.softDelete.ttl;
1290
2231
  };
2232
+ // The TTL each kind of row is written with, or `undefined` when the entity writes none there.
2233
+ // The write of each row asks the same function, so what refuses the table's TTL attribute
2234
+ // (`refuseTableAttributes`) is what writes it.
2235
+ /** A retained snapshot's: `versioned: { ttl }` without `retain` writes no snapshot. */
2236
+ const snapshotTtl = () => isRetainEnabled() ? retainTtl() || undefined : undefined;
2237
+ /** A soft-deleted row's. */
2238
+ const tombstoneTtl = () => isSoftDeleteEnabled() ? softDeleteTtl() || undefined : undefined;
2239
+ /** A time series' event's. */
2240
+ const eventTtl = () => timeSeriesConfig?.ttl || undefined;
2241
+ /**
2242
+ * The rows this entity writes the table's TTL attribute on, in words: the one place that says
2243
+ * whether it writes that attribute at all. An update naming the attribute is refused, and a
2244
+ * table whose TTL attribute a sparse map would read as an entry is refused at bind, only then.
2245
+ */
2246
+ const ttlRows = () => [
2247
+ ...(snapshotTtl() !== undefined ? ["retained versions"] : []),
2248
+ ...(tombstoneTtl() !== undefined ? ["soft-deleted rows"] : []),
2249
+ ...(eventTtl() !== undefined ? ["time series events"] : []),
2250
+ ];
2251
+ const writesTtl = () => ttlRows().length > 0;
2252
+ /**
2253
+ * `[EDD-9140]` for what the table's configuration names: the TTL attribute this entity sets on
2254
+ * its rows may not be one a row's reader takes as a sparse map's entry. `Entity.make` checks
2255
+ * every name the definition supplies; this one is known when the table is bound.
2256
+ */
2257
+ const refuseTableAttributes = (tc) => {
2258
+ const rows = ttlRows();
2259
+ if (rows.length === 0)
2260
+ return;
2261
+ refuseReadAsSparseEntry(entityType, [
2262
+ {
2263
+ attribute: resolveTtlAttributeName(tc),
2264
+ what: `the table's TTL attribute, which the entity sets on its ${rows.join(" and ")}`,
2265
+ },
2266
+ ], sparseFields);
2267
+ };
1291
2268
  const preserveUnique = () => {
1292
2269
  if (typeof config.softDelete !== "object" || config.softDelete === null)
1293
2270
  return false;
@@ -1565,6 +2542,7 @@ const makeImpl = (config, precomputedData) => {
1565
2542
  // Packed fields are read by their stored form: the source text is
1566
2543
  // derived from the value, not its JSON string or compressed bytes.
1567
2544
  yield* unpackFields(currentDomain, "update.vector");
2545
+ deserializeSparseFields(currentDomain);
1568
2546
  renameFromDynamo(currentDomain);
1569
2547
  merged = { ...currentDomain, ...merged };
1570
2548
  }
@@ -1780,7 +2758,7 @@ const makeImpl = (config, precomputedData) => {
1780
2758
  const incarnation = incarnationGuard(read, names, values);
1781
2759
  if (incarnation !== undefined)
1782
2760
  parts.push(incarnation);
1783
- return { expression: parts.join(" AND "), names, values, inputs: [] };
2761
+ return { expression: parts.join(" AND "), names, values, inputs: [], proves: true };
1784
2762
  }
1785
2763
  names["#dpk"] = pkField;
1786
2764
  parts.push("attribute_exists(#dpk)");
@@ -1804,41 +2782,49 @@ const makeImpl = (config, precomputedData) => {
1804
2782
  };
1805
2783
  const full = [...parts, ...attrs.map(guardOf)].join(" AND ");
1806
2784
  if (fits(full))
1807
- return { expression: full, names, values, inputs: attrs };
2785
+ return { expression: full, names, values, inputs: attrs, proves: true };
1808
2786
  // Too wide to guard attribute by attribute (a sparse map with hundreds of
1809
2787
  // entries): the strongest guard that fits. Every library write sets
1810
2788
  // `updatedAt`, so with timestamps it alone detects any library update;
1811
2789
  // then as many attributes as fit, those the sentinels derive from first,
1812
- // then the model's own fields, then the rest.
1813
- for (const key of Object.keys(names))
1814
- if (key.startsWith("#dg"))
1815
- delete names[key];
1816
- for (const key of Object.keys(values))
1817
- if (key.startsWith(":dg"))
1818
- delete values[key];
1819
- const uniqueAttrs = Object.values(config.unique ?? {}).flatMap((def) => resolveUniqueFields(def).map(resolveDbName));
1820
- const modelAttrs = Object.keys(data.modelFields).map(resolveDbName);
1821
- const ordered = [
1822
- ...new Set([
1823
- ...(systemFields.updatedAt ? [systemFields.updatedAt] : []),
1824
- ...uniqueAttrs,
1825
- ...modelAttrs,
1826
- ...attrs.slice().sort(),
1827
- ]),
1828
- ].filter((attr) => attrs.includes(attr));
1829
- const inputs = [];
1830
- let expression = parts.join(" AND ");
1831
- for (const attr of ordered) {
1832
- const clause = guardOf(attr, inputs.length);
1833
- if (!fits(`${expression} AND ${clause}`)) {
1834
- delete names[`#dg${inputs.length}`];
1835
- delete values[`:dg${inputs.length}`];
1836
- continue;
2790
+ // then the model's own fields, then the rest. `updatedAt` is named by the
2791
+ // attribute it's stored in: a guard on its model name holds on no row.
2792
+ const updatedAttr = systemFields.updatedAt ? resolveDbName(systemFields.updatedAt) : null;
2793
+ const strongest = () => {
2794
+ for (const key of Object.keys(names))
2795
+ if (key.startsWith("#dg"))
2796
+ delete names[key];
2797
+ for (const key of Object.keys(values))
2798
+ if (key.startsWith(":dg"))
2799
+ delete values[key];
2800
+ const uniqueAttrs = Object.values(config.unique ?? {}).flatMap((def) => resolveUniqueFields(def).map(resolveDbName));
2801
+ const modelAttrs = Object.keys(data.modelFields).map(resolveDbName);
2802
+ const ordered = [
2803
+ ...new Set([
2804
+ ...(updatedAttr !== null ? [updatedAttr] : []),
2805
+ ...uniqueAttrs,
2806
+ ...modelAttrs,
2807
+ ...attrs.slice().sort(),
2808
+ ]),
2809
+ ].filter((attr) => attrs.includes(attr));
2810
+ const inputs = [];
2811
+ let expression = parts.join(" AND ");
2812
+ for (const attr of ordered) {
2813
+ const clause = guardOf(attr, inputs.length);
2814
+ if (!fits(`${expression} AND ${clause}`)) {
2815
+ delete names[`#dg${inputs.length}`];
2816
+ delete values[`:dg${inputs.length}`];
2817
+ continue;
2818
+ }
2819
+ expression = `${expression} AND ${clause}`;
2820
+ inputs.push(attr);
1837
2821
  }
1838
- expression = `${expression} AND ${clause}`;
1839
- inputs.push(attr);
1840
- }
1841
- return { expression, names, values, inputs };
2822
+ // `updatedAt` goes first: guarded, held or absent, it proves the row as far as a stamp does.
2823
+ // Without it, no stamp a write changes is guarded.
2824
+ const proves = updatedAttr !== null && inputs.includes(updatedAttr);
2825
+ return { expression, names, values, inputs, proves };
2826
+ };
2827
+ return strongest();
1842
2828
  };
1843
2829
  /** Which predicate rejected a guarded delete — from the stored item (ALL_OLD). */
1844
2830
  const deleteRejection = (key, read, inputs, stored, userCondition) => {
@@ -1965,21 +2951,42 @@ const makeImpl = (config, precomputedData) => {
1965
2951
  * `updatedNew` → just the written attributes, decoded as a partial.
1966
2952
  */
1967
2953
  const updateResult = (rv, old, next, written, mode, encodedKey) => {
2954
+ const landed = rv === "allOld" || rv === "updatedOld" ? "replaced" : "stored";
1968
2955
  switch (rv) {
1969
2956
  case "none":
1970
2957
  return Effect.succeed(undefined);
1971
2958
  case "updatedOld":
1972
- return decodePartial(old, written, mode);
2959
+ return appliedUpdate(decodePartial(old, written, mode), landed);
1973
2960
  case "updatedNew":
1974
- return decodePartial(next, written, mode);
2961
+ return appliedUpdate(decodePartial(next, written, mode), landed);
1975
2962
  default: {
1976
2963
  const image = rv === "allOld" ? old : next;
1977
2964
  if (image === undefined)
1978
2965
  return Effect.fail(new ItemNotFound({ entityType, key: encodedKey }));
1979
- return decodeAs(fromAttributeMap(image), image, mode);
2966
+ return appliedUpdate(decodeAs(fromAttributeMap(image), image, mode), landed);
1980
2967
  }
1981
2968
  }
1982
2969
  };
2970
+ /**
2971
+ * A row that won't decode after its update has landed. The write can't be judged
2972
+ * before it's sent: `.subtract()`, `.add()`, `.append()` and the path operations are
2973
+ * DynamoDB's to apply to a value only it holds, and a read to check them would cost
2974
+ * every update. So the failure says what happened, or a caller reads "validation
2975
+ * failed" as "nothing changed".
2976
+ */
2977
+ const appliedUpdate = (decoding, row) => Effect.mapError(decoding, (error) => {
2978
+ const problem = decodeProblem(error.cause);
2979
+ return new ValidationError({
2980
+ entityType,
2981
+ operation: "update",
2982
+ cause: row === "stored"
2983
+ ? `The update WAS applied, and the stored row no longer matches the model: ${problem} ` +
2984
+ "An update that changes a value relative to what's stored (.add, .subtract, " +
2985
+ ".append, the path operations) isn't checked against the model. Guard it with " +
2986
+ ".condition()."
2987
+ : `The update WAS applied, but the row it replaced doesn't match the model: ${problem}`,
2988
+ });
2989
+ });
1983
2990
  /**
1984
2991
  * The history keys (version snapshots, soft-delete tombstones) of the item
1985
2992
  * whose live sort key is `liveSk` (#133). An entity whose primary sort key
@@ -2200,7 +3207,7 @@ const makeImpl = (config, precomputedData) => {
2200
3207
  // Replace SK with version SK
2201
3208
  snapshot[tableSkField] = DynamoSchema.composeVersionKey(schema, entityType, version, historyKeyOptions(liveSk));
2202
3209
  // Add optional TTL
2203
- const ttl = retainTtl();
3210
+ const ttl = snapshotTtl();
2204
3211
  if (ttl) {
2205
3212
  snapshot[ttlAttrName] = DateTime.toEpochSeconds(now) + normalizeTtlSeconds(ttl);
2206
3213
  }
@@ -2413,6 +3420,12 @@ const makeImpl = (config, precomputedData) => {
2413
3420
  item[systemFields.version] =
2414
3421
  (yield* highestRetainedVersion(args.tableName, owner.pk, owner.sk)) + 1;
2415
3422
  }
3423
+ // What the put continues is what an index over it holds. A put that carries nothing, or an
3424
+ // entity with no such index, keeps the keys it was built with.
3425
+ const carried = carriedSystemFields(item);
3426
+ if (Object.keys(carried).some((field) => indexCompositeFields().has(field))) {
3427
+ Object.assign(item, yield* args.composeKeys(carried));
3428
+ }
2416
3429
  const marshalled = toAttributeMap(item);
2417
3430
  // The main item. Missing: it must still be missing. Present: still the
2418
3431
  // item read — its version and incarnation, or (unversioned) the unique
@@ -2459,9 +3472,9 @@ const makeImpl = (config, precomputedData) => {
2459
3472
  const changes = [];
2460
3473
  const sameKey = (a, b) => a.pk === b.pk && a.sk === b.sk;
2461
3474
  for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
2462
- const next = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, newSource);
3475
+ const next = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, newSource, storedSentinelValue);
2463
3476
  const prior = oldSource !== undefined
2464
- ? composeUniqueSentinel(schema, entityType, constraintName, constraintDef, oldSource)
3477
+ ? composeUniqueSentinel(schema, entityType, constraintName, constraintDef, oldSource, readSentinelValue)
2465
3478
  : undefined;
2466
3479
  if (next !== undefined && prior !== undefined && sameKey(next.key, prior.key))
2467
3480
  continue;
@@ -2933,37 +3946,52 @@ const makeImpl = (config, precomputedData) => {
2933
3946
  // instances) and the substituted date/Redacted transforms
2934
3947
  // tolerate either form. The subsequent `encode` produces
2935
3948
  // the canonical wire shape.
2936
- const encodedInput = yield* encodeOrDecodeEncode(schemas.inputSchema, inputWithGeneratedId, entityType, operation);
3949
+ const encodedInput = yield* encodeForWrite(schemas.inputSchema, inputWithGeneratedId, operation);
3950
+ // Clock-backed time source resolved once for this write op and
3951
+ // threaded into every timestamp/TTL computation below — deterministic
3952
+ // under `TestClock`, wall-clock in production.
3953
+ const now = yield* DateTime.now;
3954
+ // System fields, before the keys: an index may be composed from one.
3955
+ // When a timestamp field collides with a model-declared field, the
3956
+ // user may have supplied their own value (optional on collision in
3957
+ // `inputSchema`). Respect their value if present (already encoded to
3958
+ // wire); otherwise generate a wire primitive directly.
3959
+ const stamps = stampsOf(encodedInput, {
3960
+ createdAt: opts.createdAt ?? now,
3961
+ updatedAt: now,
3962
+ });
3963
+ const keyValues = { ...encodedInput, ...stamps };
2937
3964
  // Compose all keys from the encoded input (ID fields still present
2938
3965
  // and key composites are wire-format strings/numbers).
2939
- const keys = yield* composeAllKeys(encodedInput, operation);
3966
+ const keys = yield* composeAllKeys(keyValues, operation);
3967
+ // A put that sends something before its write refuses a value DynamoDB can't
3968
+ // store first. Any other put finds out when it marshals, at no extra cost.
3969
+ if (hasRefs ||
3970
+ hasVectorIndexes ||
3971
+ Boolean(systemFields.version) ||
3972
+ Object.keys(config.unique ?? {}).length > 0 ||
3973
+ (opts.putKind === "create" && hasProjectionTombstones(self))) {
3974
+ yield* refuseUnstorable({ ...encodedInput, ...opts.withVectors }, operation);
3975
+ yield* refuseUncomposed(encodedInput, operation);
3976
+ }
3977
+ // A put writes the whole item, so an entry key its flattening refuses is refused in
3978
+ // every case: before the refs are read, where it reads any.
3979
+ if (hasRefs) {
3980
+ const refusedKey = refusedSparseKey(encodedInput, true);
3981
+ if (refusedKey !== undefined) {
3982
+ return yield* new ValidationError({
3983
+ entityType,
3984
+ operation: `${operation}.sparse`,
3985
+ cause: refusedKey,
3986
+ });
3987
+ }
3988
+ }
2940
3989
  // Hydrate refs: replace ID fields with full entity domain data
2941
3990
  const encoded = hasRefs
2942
3991
  ? yield* hydrateRefs(encodedInput)
2943
3992
  : encodedInput;
2944
3993
  // Build the DynamoDB item — already in wire-format after encode
2945
- const item = { ...encoded };
2946
- // Clock-backed time source resolved once for this write op and
2947
- // threaded into every timestamp/TTL computation below — deterministic
2948
- // under `TestClock`, wall-clock in production.
2949
- const now = yield* DateTime.now;
2950
- // Add system fields. When a timestamp field collides with a
2951
- // model-declared field, the user may have supplied their own value
2952
- // (optional on collision in `inputSchema`). Respect their value if
2953
- // present (already encoded to wire); otherwise generate a wire
2954
- // primitive directly.
2955
- if (systemFields.createdAt) {
2956
- if (item[systemFields.createdAt] === undefined) {
2957
- item[systemFields.createdAt] = generateTimestamp(systemFields.createdAtEncoding, opts.createdAt ?? now);
2958
- }
2959
- }
2960
- if (systemFields.updatedAt) {
2961
- if (item[systemFields.updatedAt] === undefined) {
2962
- item[systemFields.updatedAt] = generateTimestamp(systemFields.updatedAtEncoding, now);
2963
- }
2964
- }
2965
- if (systemFields.version)
2966
- item[systemFields.version] = 1;
3994
+ const item = { ...encoded, ...stamps };
2967
3995
  if (stampsIncarnation)
2968
3996
  item[INCARNATION_TOKEN] = yield* freshIncarnation;
2969
3997
  // Add entity type discriminator
@@ -2977,7 +4005,7 @@ const makeImpl = (config, precomputedData) => {
2977
4005
  // value. Sparse — an index whose source or partition composites are
2978
4006
  // absent contributes nothing. See `DESIGN.md §14`.
2979
4007
  if (hasVectorIndexes) {
2980
- const vectorWrite = yield* computeVectorAttributes(encoded, opts.withVectors, "all");
4008
+ const vectorWrite = yield* computeVectorAttributes({ ...encoded, ...stamps }, opts.withVectors, "all");
2981
4009
  Object.assign(item, vectorWrite.sets);
2982
4010
  // `put` writes a whole item, so a REMOVE is just an omission.
2983
4011
  for (const field of vectorWrite.removes)
@@ -3022,7 +4050,7 @@ const makeImpl = (config, precomputedData) => {
3022
4050
  // tombstone's place, its checkpoints and revision carried over, on
3023
4051
  // the condition that tombstone is still there.
3024
4052
  if (opts.putKind === "create" && operation !== "upsert" && !guarded) {
3025
- const over = yield* overTombstone(self, client, tableName, item);
4053
+ const over = yield* overTombstone(self, client, tc, item);
3026
4054
  if (Option.isSome(over)) {
3027
4055
  userCondition = compileCondition(withGuard(over.value, opts.condition), resolveDbName);
3028
4056
  }
@@ -3038,10 +4066,11 @@ const makeImpl = (config, precomputedData) => {
3038
4066
  create: opts.putKind === "create",
3039
4067
  operation,
3040
4068
  key: encoded,
4069
+ composeKeys: (carried) => composeAllKeys({ ...keyValues, ...carried }, operation),
3041
4070
  });
3042
4071
  return yield* decodeAs(plan.item, plan.marshalled, mode);
3043
4072
  }
3044
- const marshalledItem = toAttributeMap(item);
4073
+ const marshalledItem = yield* marshalOrFail(entityType, operation, () => toAttributeMap(item), { fieldOf: fieldOfAttribute });
3045
4074
  {
3046
4075
  // Simple put without unique constraints or versioning
3047
4076
  const putInput = {
@@ -3141,12 +4170,15 @@ const makeImpl = (config, precomputedData) => {
3141
4170
  // ---------------------------------------------------------------------------
3142
4171
  // update operation
3143
4172
  // ---------------------------------------------------------------------------
3144
- const runUpdate = (key, mode, requested,
3145
4173
  /**
3146
- * The item as already read — consistently — by the caller (`upsert`).
3147
- * Used instead of reading it again: the write is guarded on it either way.
4174
+ * What an update decides from its own operands, before reading anything: every refusal of the
4175
+ * names, operands and payload it holds and of the keys the payload composes, and the encoded
4176
+ * payload and key ({@link checkUpdatePayload}). A payload with refs to hydrate has its keys
4177
+ * checked after the reads that hydrate them, in {@link runPreparedUpdate}. `runUpdate` runs this
4178
+ * first; `Transaction.transactWrite` runs it for every op before any op reads (`_prepareUpdate`)
4179
+ * and plans the update from what it returns. `encoded`: the key, already encoded.
3148
4180
  */
3149
- preRead) => Effect.gen(function* () {
4181
+ const prepareUpdate = (key, requested, encoded) => Effect.gen(function* () {
3150
4182
  // A packed field takes only a whole-value .set() / .remove() (#147).
3151
4183
  const packedRefusal = refusedPackedUpdate(requested);
3152
4184
  if (packedRefusal !== undefined) {
@@ -3156,10 +4188,41 @@ const makeImpl = (config, precomputedData) => {
3156
4188
  cause: packedRefusal,
3157
4189
  });
3158
4190
  }
4191
+ const tc = yield* tableTag;
4192
+ const ttlAttrName = resolveTtlAttributeName(tc);
4193
+ // Names first: `.remove(["g"])` is told to name the field stored as `g`.
4194
+ const refusedName = refusedAttributeNames(requested, ttlAttrName);
4195
+ if (refusedName !== undefined) {
4196
+ return yield* new ValidationError({
4197
+ entityType,
4198
+ operation: "update",
4199
+ cause: refusedName,
4200
+ });
4201
+ }
4202
+ // `.set({ field: undefined })` becomes `.remove([field])`, once, here. So does
4203
+ // anything else the update holds that DynamoDB can't store.
4204
+ const lacks = writeLacks();
4205
+ const clearedFields = normalizeClears(requested, lacks);
4206
+ const cleared = typeof clearedFields === "string" ? clearedFields : normalizeNoStoredForm(clearedFields);
4207
+ if (typeof cleared === "string") {
4208
+ return yield* new ValidationError({
4209
+ entityType,
4210
+ operation: "update",
4211
+ cause: cleared,
4212
+ });
4213
+ }
4214
+ const refusedPath = refusedPathRemove(cleared, lacks);
4215
+ if (refusedPath !== undefined) {
4216
+ return yield* new ValidationError({
4217
+ entityType,
4218
+ operation: "update",
4219
+ cause: refusedPath,
4220
+ });
4221
+ }
3159
4222
  // Path operations on a field that feeds a key or a unique sentinel
3160
4223
  // become the record operations they are equivalent to, or are
3161
4224
  // refused (#133) — before anything reads the state.
3162
- const normalized = normalizeDerivedPathOps(requested);
4225
+ const normalized = normalizeDerivedPathOps(cleared);
3163
4226
  if (typeof normalized === "string") {
3164
4227
  return yield* new ValidationError({
3165
4228
  entityType,
@@ -3167,7 +4230,7 @@ const makeImpl = (config, precomputedData) => {
3167
4230
  cause: normalized,
3168
4231
  });
3169
4232
  }
3170
- const refusedRemove = refusedRecordRemove(normalized.remove) ?? refusedRecordOperands(normalized);
4233
+ const refusedRemove = refusedRecordRemove(normalized.remove, lacks) ?? refusedRecordOperands(normalized);
3171
4234
  if (refusedRemove !== undefined) {
3172
4235
  return yield* new ValidationError({
3173
4236
  entityType,
@@ -3194,7 +4257,18 @@ const makeImpl = (config, precomputedData) => {
3194
4257
  cause: immutables,
3195
4258
  });
3196
4259
  }
3197
- const upsertable = completeUpsertPayload(uState.updates);
4260
+ const upsertable = completeUpsertPayload(uState.updates, uState.remove ?? [], lacks);
4261
+ // What `put` takes to create the item on a missing row: a field cleared here whose
4262
+ // absent attribute is one of its values is that value, and `put` requires its key.
4263
+ const createInput = () => {
4264
+ const absent = (uState.remove ?? []).flatMap((field) => {
4265
+ const reading = lacks.absentReading(field);
4266
+ return reading === undefined ? [] : [[field, reading.value]];
4267
+ });
4268
+ return absent.length === 0
4269
+ ? uState.updates
4270
+ : { ...uState.updates, ...Object.fromEntries(absent) };
4271
+ };
3198
4272
  const requestedRv = uState.returnValues ?? "allNew";
3199
4273
  // A cascade propagates the NEW item; a mode returning the OLD one then
3200
4274
  // needs both images exactly — the read-then-write branch has both.
@@ -3215,15 +4289,9 @@ const makeImpl = (config, precomputedData) => {
3215
4289
  // The caller's condition, ANDed onto `patch`'s exists guard — a guard
3216
4290
  // no `.condition()` can replace (#133).
3217
4291
  const userCond = withGuard(uState.patch ? { attributeExists: [config.indexes.primary.pk.field] } : undefined, uState.condition);
3218
- const client = yield* Capacity.client;
3219
- const tc = yield* tableTag;
3220
- const tableName = tc.name;
3221
- const ttlAttrName = resolveTtlAttributeName(tc);
3222
- // Clock-backed time source for the updatedAt timestamp + retain snapshot TTL.
3223
- const now = yield* DateTime.now;
3224
4292
  yield* checkWithVectorNames(uState.withVectors, "update");
3225
4293
  // Caller key: Type side in, ENCODED out (see `encodeKey`).
3226
- const encodedKey = yield* encodeKey(key, "update.decodeKey");
4294
+ const encodedKey = encoded ?? (yield* encodeKey(key, "update.decodeKey"));
3227
4295
  // A missing item: `patch`'s exists guard failed — `ConditionalCheckFailed`,
3228
4296
  // on every path, including those that read first (#134); for `update`,
3229
4297
  // `ItemNotFound`.
@@ -3234,21 +4302,149 @@ const makeImpl = (config, precomputedData) => {
3234
4302
  })
3235
4303
  : new ItemNotFound({ entityType, key: encodedKey });
3236
4304
  // Encode update payload → wire form (see `put` for the strategy).
3237
- const encodedUpdates = yield* encodeOrDecodeEncode(schemas.updateSchema, updates ?? {}, entityType, "update");
3238
- // Hydrate refs in updates: for any ${field}Id present, fetch and embed
3239
- let hydratedUpdates = encodedUpdates;
3240
- if (hasRefs) {
3241
- const refsToHydrate = resolvedRefs.filter((ref) => ref.idFieldName in encodedUpdates &&
3242
- encodedUpdates[ref.idFieldName] !== undefined);
3243
- if (refsToHydrate.length > 0) {
3244
- hydratedUpdates = yield* hydrateRefs(hydratedUpdates, refsToHydrate);
4305
+ const encodedUpdates = yield* encodeForWrite(schemas.updateSchema, updates ?? {}, "update");
4306
+ const unstorable = unstorableOperand(uState, encodedUpdates) ??
4307
+ notReadBackOperand(uState);
4308
+ if (unstorable !== undefined) {
4309
+ return yield* new ValidationError({ entityType, operation: "update", cause: unstorable });
4310
+ }
4311
+ // Refs are hydrated by reading the entities they name: a payload holding any has its keys
4312
+ // checked after those reads.
4313
+ const refsToHydrate = hasRefs
4314
+ ? resolvedRefs.filter((ref) => ref.idFieldName in encodedUpdates &&
4315
+ encodedUpdates[ref.idFieldName] !== undefined)
4316
+ : [];
4317
+ // A payload whose refs are read first has its entry keys judged before that read, by what
4318
+ // is known before it: an update that surely refuses the keys a put refuses
4319
+ // (`refusesPutKeys`, which a path op rules out) refuses them, and any other the keys every
4320
+ // update refuses. `checkUpdatePayload` judges the rest once the refs are in.
4321
+ if (refsToHydrate.length > 0) {
4322
+ const refusedKey = refusedSparseKey(encodedUpdates, (isRetainEnabled() || needsBothImages) && !hasPathOps(uState), everyRowWrites);
4323
+ if (refusedKey !== undefined) {
4324
+ return yield* new ValidationError({
4325
+ entityType,
4326
+ operation: "update.sparse",
4327
+ cause: refusedKey,
4328
+ });
4329
+ }
4330
+ }
4331
+ const checked = refsToHydrate.length === 0
4332
+ ? yield* checkUpdatePayload(uState, needsBothImages, encodedKey, encodedUpdates, encodedUpdates)
4333
+ : undefined;
4334
+ // The operands written as values of a field, in the form they're written: refused here if
4335
+ // the schema refuses one, before anything is read or sent, and written as encoded here.
4336
+ const operands = encodeOperands(uState);
4337
+ if ("issue" in operands) {
4338
+ return yield* new ValidationError({
4339
+ entityType,
4340
+ operation: operands.operation,
4341
+ cause: operands.issue,
4342
+ });
4343
+ }
4344
+ return {
4345
+ uState,
4346
+ operands,
4347
+ removedToDefault,
4348
+ immutables,
4349
+ upsertable,
4350
+ createInput,
4351
+ lacks,
4352
+ requestedRv,
4353
+ needsBothImages,
4354
+ evExpected,
4355
+ userCond,
4356
+ tc,
4357
+ ttlAttrName,
4358
+ encodedKey,
4359
+ missingItem,
4360
+ encodedUpdates,
4361
+ refsToHydrate,
4362
+ checked,
4363
+ };
4364
+ });
4365
+ /**
4366
+ * A payload's sparse entry key its write refuses, in words: decided from the payload alone, so
4367
+ * before anything is read. A write that flattens the whole item (`whole`: a put, and an update
4368
+ * that reads the row and writes it back) refuses the keys the map's writer refuses
4369
+ * (`validateSparseKey`); the row's own entries are written back as they're stored. An update
4370
+ * sent as an expression refuses an empty key and one holding `#`.
4371
+ *
4372
+ * Only a value the operation writes whatever the row holds is judged here. An update never
4373
+ * writes an immutable field, and an upsert writes one only into a row that isn't there: with
4374
+ * the row present it succeeds whatever the immutable map's keys are, so nothing refuses it
4375
+ * before the read.
4376
+ */
4377
+ const refusedSparseKey = (payload, whole,
4378
+ /** Whether the operation writes the field's value whatever the row holds. */
4379
+ writes = () => true) => refusedSparseEntry(payload, whole, writes)?.refusal;
4380
+ /** The entry {@link refusedSparseKey} refuses: its map, its key, and why. */
4381
+ const refusedSparseEntry = (payload, whole, writes) => {
4382
+ if (!hasSparseFields || typeof payload !== "object" || payload === null)
4383
+ return undefined;
4384
+ for (const [field, sparse] of Object.entries(sparseFields)) {
4385
+ if (!writes(field) || !Object.hasOwn(payload, field))
4386
+ continue;
4387
+ const value = payload[field];
4388
+ if (value === null || typeof value !== "object")
4389
+ continue;
4390
+ for (const key of Object.keys(value)) {
4391
+ const refusal = whole
4392
+ ? sparseKeyRefusal(field, sparse.prefix, key)
4393
+ : key.length === 0 || key.includes("#")
4394
+ ? `Sparse map "${field}": invalid key ${JSON.stringify(key)}`
4395
+ : undefined;
4396
+ if (refusal !== undefined)
4397
+ return { field, prefix: sparse.prefix, key, refusal };
3245
4398
  }
3246
4399
  }
4400
+ return undefined;
4401
+ };
4402
+ /** Whether an update or an upsert writes the field's value whatever the row holds. */
4403
+ const everyRowWrites = (field) => !immutableFields.has(field);
4404
+ /**
4405
+ * Whether an update refuses the entry keys a put refuses (`refusedSparseKey`'s `whole`): one that
4406
+ * reads the row and writes it whole for a retained entity, a change to a unique field, a computed
4407
+ * index composite or both images, and carries no path operation, as 1.39.0 decided it. Any other
4408
+ * refuses only an empty key and one holding `#`. An upsert over a row it read is written whole as
4409
+ * well (`rewritesWholeItem`), but 1.39.0 sent it as the update of the upserted fields, so it
4410
+ * refuses what that update refuses.
4411
+ */
4412
+ const refusesPutKeys = (needsBothImages, checked) => (isRetainEnabled() ||
4413
+ checked.touchesUniqueFields ||
4414
+ checked.computedComposites.length > 0 ||
4415
+ needsBothImages) &&
4416
+ !checked.pathOpsPresent;
4417
+ /** Whether an update reads the row and writes it whole, in a transaction, and not as an expression. */
4418
+ const rewritesWholeItem = (uState, needsBothImages, checked) => refusesPutKeys(needsBothImages, checked) ||
4419
+ (uState.upsertOver !== undefined && !checked.pathOpsPresent);
4420
+ /**
4421
+ * Whether an update writes or changes a field one of the entity's unique constraints holds: a
4422
+ * field its payload sets (to anything but `undefined`) or one of its operations names.
4423
+ */
4424
+ const touchesUniqueFieldsOf = (uState, updates) => {
4425
+ if (config.unique == null || Object.keys(config.unique).length === 0)
4426
+ return false;
4427
+ const uniqueFieldSet = new Set(Object.values(config.unique).flatMap((def) => [...resolveUniqueFields(def)]));
4428
+ const allUpdatedFields = new Set([
4429
+ ...Object.keys(updates).filter((k) => updates[k] !== undefined),
4430
+ ...(uState.remove ?? []),
4431
+ ...Object.keys(uState.add ?? {}),
4432
+ ...Object.keys(uState.subtract ?? {}),
4433
+ ...Object.keys(uState.append ?? {}),
4434
+ ...Object.keys(uState.deleteFromSet ?? {}),
4435
+ ]);
4436
+ return [...uniqueFieldSet].some((f) => allUpdatedFields.has(f));
4437
+ };
4438
+ /**
4439
+ * The refusals an update's keys decide, before reading anything: a key its payload composes with
4440
+ * no key text or level, and path operations no read-then-write can carry. Returns the primary key
4441
+ * and what decides the write's path.
4442
+ */
4443
+ const checkUpdatePayload = (uState, needsBothImages, encodedKey, encodedUpdates, hydratedUpdates) => Effect.gen(function* () {
3247
4444
  // The index keys the payload feeds, composed once before anything is
3248
4445
  // marshalled: a composite with no key text (`NaN`, `[EDD-9096]`) or
3249
4446
  // Z-order level (`[EDD-9092]`) fails the update with a
3250
- // `ValidationError`, where the marshaller would refuse the attribute as
3251
- // a defect. Each branch below composes the keys it writes itself.
4447
+ // `ValidationError`. Each branch below composes the keys it writes itself.
3252
4448
  yield* composeKeysOrFail(entityType, "update", () => KeyComposer.composeGsiKeysForUpdatePolicyAware(schema, entityType, entityVersion, allIndexes, keyForm(hydratedUpdates), keyForm(encodedKey),
3253
4449
  // The branches below know more: the retain path reads the whole item
3254
4450
  // first, so a shard it can compute is not refused here (#183).
@@ -3256,24 +4452,12 @@ const makeImpl = (config, precomputedData) => {
3256
4452
  onMissingShardSource: "keep",
3257
4453
  ...(uState.remove === undefined ? {} : { removedSet: new Set(uState.remove) }),
3258
4454
  }));
4455
+ yield* refuseUncomposed(encodedUpdates, "update");
3259
4456
  // Compose primary key
3260
4457
  const primaryKey = composePrimaryKey(encodedKey);
3261
4458
  const marshalledKey = toAttributeMap(primaryKey);
3262
4459
  // Detect whether the update touches any unique constraint fields
3263
- const hasUniqueConstraints = config.unique != null && Object.keys(config.unique).length > 0;
3264
- let touchesUniqueFields = false;
3265
- if (hasUniqueConstraints) {
3266
- const uniqueFieldSet = new Set(Object.values(config.unique).flatMap((def) => [...resolveUniqueFields(def)]));
3267
- const allUpdatedFields = new Set([
3268
- ...Object.keys(hydratedUpdates).filter((k) => hydratedUpdates[k] !== undefined),
3269
- ...(uState.remove ?? []),
3270
- ...Object.keys(uState.add ?? {}),
3271
- ...Object.keys(uState.subtract ?? {}),
3272
- ...Object.keys(uState.append ?? {}),
3273
- ...Object.keys(uState.deleteFromSet ?? {}),
3274
- ]);
3275
- touchesUniqueFields = [...uniqueFieldSet].some((f) => allUpdatedFields.has(f));
3276
- }
4460
+ const touchesUniqueFields = touchesUniqueFieldsOf(uState, hydratedUpdates);
3277
4461
  // `.add()` / `.subtract()` / `.append()` / `.deleteFromSet()` on an
3278
4462
  // index composite: DynamoDB would compute the new value, but the
3279
4463
  // index key is composed from it here — so the item is read, the
@@ -3316,11 +4500,46 @@ const makeImpl = (config, precomputedData) => {
3316
4500
  "`versioned` cannot prove. Drop the path operations, the cascade, or the mode.",
3317
4501
  });
3318
4502
  }
3319
- if ((isRetainEnabled() ||
3320
- touchesUniqueFields ||
3321
- computedComposites.length > 0 ||
3322
- needsBothImages) &&
3323
- !pathOpsPresent) {
4503
+ const checked = {
4504
+ primaryKey,
4505
+ marshalledKey,
4506
+ touchesUniqueFields,
4507
+ computedComposites,
4508
+ pathOpsPresent,
4509
+ };
4510
+ const refused = refusedSparseKey(hydratedUpdates, refusesPutKeys(needsBothImages, checked), everyRowWrites);
4511
+ if (refused !== undefined) {
4512
+ return yield* new ValidationError({
4513
+ entityType,
4514
+ operation: "update.sparse",
4515
+ cause: refused,
4516
+ });
4517
+ }
4518
+ return checked;
4519
+ });
4520
+ /** An update from what {@link prepareUpdate} decided: its reads and its write. */
4521
+ const runPreparedUpdate = (key, prepared, mode,
4522
+ /**
4523
+ * The item as already read — consistently — by the caller (`upsert`).
4524
+ * Used instead of reading it again: the write is guarded on it either way.
4525
+ */
4526
+ preRead) => Effect.gen(function* () {
4527
+ const { uState, removedToDefault, immutables, upsertable, createInput, lacks, requestedRv, needsBothImages, evExpected, userCond, tc, ttlAttrName, encodedKey, missingItem, encodedUpdates, operands, } = prepared;
4528
+ const client = yield* Capacity.client;
4529
+ const tableName = tc.name;
4530
+ // Clock-backed time source for the updatedAt timestamp + retain snapshot TTL.
4531
+ const now = yield* DateTime.now;
4532
+ // Hydrate refs in updates: for any ${field}Id present, fetch and embed
4533
+ const hydratedUpdates = prepared.refsToHydrate.length > 0
4534
+ ? yield* hydrateRefs(encodedUpdates, prepared.refsToHydrate)
4535
+ : encodedUpdates;
4536
+ const { primaryKey, marshalledKey, touchesUniqueFields, computedComposites, pathOpsPresent } = prepared.checked ??
4537
+ (yield* checkUpdatePayload(uState, needsBothImages, encodedKey, encodedUpdates, hydratedUpdates));
4538
+ if (rewritesWholeItem(uState, needsBothImages, {
4539
+ touchesUniqueFields,
4540
+ computedComposites,
4541
+ pathOpsPresent,
4542
+ })) {
3324
4543
  // --- Retain path: read-then-transact ---
3325
4544
  // Read current item (needed to create snapshot of pre-update state)
3326
4545
  const currentResult = preRead !== undefined ? { Item: preRead } : yield* readCurrent(tableName, marshalledKey);
@@ -3350,26 +4569,31 @@ const makeImpl = (config, precomputedData) => {
3350
4569
  const currentDomainItem = {
3351
4570
  ...currentRaw,
3352
4571
  };
3353
- renameFromDynamo(currentDomainItem);
3354
- // Rebuild sparse Map fields from flattened attrs into domain Records.
3355
- // Done in-place on the renamed domain item so subsequent merge logic
3356
- // operates on domain shape and re-flattening happens once at the end.
4572
+ // Read as every read path reads a row: sparse entries are taken from the
4573
+ // attribute-keyed row first, then the names are mapped. The other order
4574
+ // took a field named as an entry (`data#x`, stored as `counter`) for the
4575
+ // entry, once the rename had put it under that name.
3357
4576
  deserializeSparseFields(currentDomainItem);
3358
- const newItem = { ...currentDomainItem };
4577
+ renameFromDynamo(currentDomainItem);
4578
+ const newItem = {
4579
+ ...uState.upsertOver?.fill,
4580
+ ...currentDomainItem,
4581
+ };
3359
4582
  // Apply user updates. For sparse fields, merge bucket-by-bucket
3360
4583
  // rather than whole-field replace — concurrent writers to disjoint
3361
4584
  // buckets must coexist (the version CAS protects against same-bucket
3362
4585
  // races). Non-sparse fields use the existing replace semantics.
3363
4586
  //
3364
- // null and undefined collapse: both mean "absent" under v3's
3365
- // two-way classification (DESIGN.md §7). For the in-memory item
3366
- // we DELETE the attribute (mirrors a DynamoDB REMOVE), so
3367
- // subsequent decode sees the field as absent rather than as a
3368
- // typed null that the model schema may not permit. The composer
4587
+ // null means "absent" under v3's two-way classification (DESIGN.md
4588
+ // §7), unless a row can't lack the field, whose `null` is its value.
4589
+ // For the in-memory item we DELETE the attribute (mirrors a DynamoDB
4590
+ // REMOVE), so subsequent decode sees the field as absent rather than
4591
+ // as a typed null that the model schema may not permit. The composer
3369
4592
  // below sees the attr as absent in `newItem` and applies the
3370
- // structural rule.
4593
+ // structural rule. An `undefined` is an encoded value that writes
4594
+ // nothing: the payload's own `undefined`s are already `.remove()`.
3371
4595
  for (const [attr, val] of Object.entries(hydratedUpdates)) {
3372
- if (val === null || val === undefined) {
4596
+ if (val === undefined || (val === null && lacks.omits(attr))) {
3373
4597
  delete newItem[attr];
3374
4598
  continue;
3375
4599
  }
@@ -3410,37 +4634,66 @@ const makeImpl = (config, precomputedData) => {
3410
4634
  newItem[field] = {};
3411
4635
  }
3412
4636
  }
4637
+ // Where a record operation's attribute is in the row as read: an operation naming a
4638
+ // sparse map's entry by its attribute (`.add({ "data#views": 1 })`) reaches the entry
4639
+ // in the map, as the same operation sent as an expression does. Applied to a key of
4640
+ // its own, it was overwritten by the entry when the map was flattened: the operation
4641
+ // reported success and changed nothing.
4642
+ //
4643
+ // `attr`, and an entry's key, are names the caller supplies: each is read and written as
4644
+ // the holder's OWN property, never as a member every object inherits. `data#constructor`
4645
+ // on an empty map found `Object`'s constructor, and `2` was added to a function.
4646
+ const slot = (attr) => {
4647
+ const entry = isModelField(attr) ? undefined : sparseEntries.entryOf(attr);
4648
+ if (entry === undefined)
4649
+ return [newItem, attr];
4650
+ const map = Object.assign(Object.create(null), newItem[entry.field]);
4651
+ newItem[entry.field] = map;
4652
+ return [map, entry.key];
4653
+ };
4654
+ const held = (holder, key) => Object.hasOwn(holder, key) ? holder[key] : undefined;
4655
+ const hold = (holder, key, value) => {
4656
+ Object.defineProperty(holder, key, {
4657
+ value,
4658
+ enumerable: true,
4659
+ writable: true,
4660
+ configurable: true,
4661
+ });
4662
+ };
3413
4663
  if (uState.add) {
3414
4664
  for (const [attr, val] of Object.entries(uState.add)) {
3415
- newItem[attr] = (newItem[attr] ?? 0) + val;
4665
+ // DynamoDB's ADD: a number adds, a set unions, and a row without the attribute
4666
+ // starts from nothing.
4667
+ const [holder, key] = slot(attr);
4668
+ const before = held(holder, key);
4669
+ hold(holder, key, typeof val === "number"
4670
+ ? (before ?? 0) + val
4671
+ : new Set([...(before instanceof Set ? before : []), ...val]));
3416
4672
  }
3417
4673
  }
3418
4674
  if (uState.subtract) {
3419
4675
  for (const [attr, val] of Object.entries(uState.subtract)) {
3420
- newItem[attr] = (newItem[attr] ?? 0) - val;
4676
+ const [holder, key] = slot(attr);
4677
+ hold(holder, key, (held(holder, key) ?? 0) - val);
3421
4678
  }
3422
4679
  }
3423
4680
  if (uState.append) {
3424
- for (const [attr, val] of Object.entries(uState.append)) {
3425
- const existing = newItem[attr] ?? [];
3426
- const appended = encodePathValue([attr], val, "elements");
3427
- if (appended.issue !== undefined) {
3428
- return yield* new ValidationError({
3429
- entityType,
3430
- operation: "update.append",
3431
- cause: appended.issue,
3432
- });
3433
- }
3434
- newItem[attr] = [...existing, ...appended.encoded];
4681
+ for (const attr of Object.keys(uState.append)) {
4682
+ const [holder, key] = slot(attr);
4683
+ const existing = held(holder, key) ?? [];
4684
+ hold(holder, key, [...existing, ...operands.append[attr]]);
3435
4685
  }
3436
4686
  }
3437
4687
  if (uState.deleteFromSet) {
3438
4688
  for (const [attr, val] of Object.entries(uState.deleteFromSet)) {
3439
- if (newItem[attr] instanceof Set && val instanceof Set) {
3440
- const current = newItem[attr];
4689
+ const [holder, key] = slot(attr);
4690
+ const before = held(holder, key);
4691
+ if (before instanceof Set && val instanceof Set) {
4692
+ const current = new Set(before);
3441
4693
  for (const elem of val) {
3442
4694
  current.delete(elem);
3443
4695
  }
4696
+ hold(holder, key, current);
3444
4697
  }
3445
4698
  }
3446
4699
  }
@@ -3504,7 +4757,10 @@ const makeImpl = (config, precomputedData) => {
3504
4757
  // Z-order value the composer can't place (EDD-9092, #171) fails the
3505
4758
  // update with a `ValidationError`.
3506
4759
  const retainRemovedSet = uState.remove ? new Set(uState.remove) : undefined;
3507
- const gsiUpdate = yield* composeKeysOrFail(entityType, "update", () => KeyComposer.composeGsiKeysForUpdatePolicyAware(schema, entityType, entityVersion, allIndexes, keyForm(hydratedUpdates), keyForm(newItem), retainRemovedSet === undefined ? {} : { removedSet: retainRemovedSet }));
4760
+ const gsiUpdate = yield* composeKeysOrFail(entityType, "update", () => KeyComposer.composeGsiKeysForUpdatePolicyAware(schema, entityType, entityVersion, allIndexes, keyForm(hydratedUpdates), keyForm(newItem), {
4761
+ ...(retainRemovedSet === undefined ? {} : { removedSet: retainRemovedSet }),
4762
+ stamped: keyForm(writeStamps(newItem[systemFields.updatedAt ?? ""], newVersion)),
4763
+ }));
3508
4764
  for (const [field, value] of Object.entries(gsiUpdate.sets)) {
3509
4765
  newItem[field] = value;
3510
4766
  }
@@ -3515,8 +4771,10 @@ const makeImpl = (config, precomputedData) => {
3515
4771
  if (touchesUniqueFields) {
3516
4772
  const currentRawDomain = toDomainView(currentRaw);
3517
4773
  for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
3518
- const oldSentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, currentRawDomain);
3519
- const newSentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, newItem);
4774
+ const oldSentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, currentRawDomain, readSentinelValue);
4775
+ const newSentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, newItem, (field, value) => Object.is(value, currentDomainItem[field])
4776
+ ? readSentinelValue(field, value)
4777
+ : storedSentinelValue(field, value));
3520
4778
  if (!oldSentinel && !newSentinel)
3521
4779
  continue;
3522
4780
  if (oldSentinel &&
@@ -3552,16 +4810,16 @@ const makeImpl = (config, precomputedData) => {
3552
4810
  }
3553
4811
  // Convert back to DynamoDB attribute names for storage
3554
4812
  renameToDynamo(newItem);
3555
- // Flatten sparse Map fields into per-entry top-level attributes.
3556
- try {
3557
- serializeSparseFields(newItem);
3558
- }
3559
- catch (e) {
3560
- return yield* new ValidationError({
3561
- entityType,
3562
- operation: "update.sparse",
3563
- cause: e instanceof Error ? e.message : String(e),
3564
- });
4813
+ // Flatten sparse Map fields into per-entry top-level attributes. The payload's keys were
4814
+ // checked before the read (`checkUpdatePayload`), and the row's own entries go back under
4815
+ // the attributes they were read from, whatever their keys.
4816
+ for (const [field, sparse] of Object.entries(sparseFields)) {
4817
+ const value = newItem[field];
4818
+ delete newItem[field];
4819
+ if (value === null || typeof value !== "object")
4820
+ continue;
4821
+ for (const [key, entry] of Object.entries(value))
4822
+ newItem[`${sparse.prefix}#${key}`] = entry;
3565
4823
  }
3566
4824
  // Pack only the packed fields this update names: the others still
3567
4825
  // hold the stored value read above (a string or bytes), carried
@@ -3676,10 +4934,13 @@ const makeImpl = (config, precomputedData) => {
3676
4934
  for (const [indexName, indexDef] of Object.entries(allIndexes)) {
3677
4935
  if (indexName === "primary")
3678
4936
  continue;
4937
+ // Not what this write stamps: its own value is what it writes, and a concurrent
4938
+ // write that moved it changed nothing this key was composed from.
4939
+ const asRead = (composites) => composites.filter((attr) => attr !== systemFields.updatedAt && attr !== systemFields.version);
3679
4940
  if (written.has(indexDef.pk.field))
3680
- add(indexDef.pk.composite);
4941
+ add(asRead(indexDef.pk.composite));
3681
4942
  if (written.has(indexDef.sk.field))
3682
- add(indexDef.sk.composite);
4943
+ add(asRead(indexDef.sk.composite));
3683
4944
  }
3684
4945
  for (const rotation of sentinelRotations) {
3685
4946
  add(resolveUniqueFields(config.unique[rotation.constraintName]), true);
@@ -3882,7 +5143,7 @@ const makeImpl = (config, precomputedData) => {
3882
5143
  // Execute cascade if configured (retain path) — from the new item.
3883
5144
  if (uState.cascade) {
3884
5145
  const domainData = {
3885
- ...(yield* decodeAs(fromAttributeMap(newImage), newImage, "model")),
5146
+ ...(yield* appliedUpdate(decodeAs(fromAttributeMap(newImage), newImage, "model"), "stored")),
3886
5147
  };
3887
5148
  const sourceId = sourceIdentifierField != null
3888
5149
  ? encodedKey[sourceIdentifierField]
@@ -3904,7 +5165,7 @@ const makeImpl = (config, precomputedData) => {
3904
5165
  // and incarnation, so the read IS the old item and ALL_NEW the new.
3905
5166
  let casRead;
3906
5167
  if (isRetainEnabled() || needsBothImages) {
3907
- const current = preRead !== undefined ? { Item: preRead } : yield* readCurrent(tableName, marshalledKey);
5168
+ const current = yield* readCurrent(tableName, marshalledKey);
3908
5169
  if (!current.Item) {
3909
5170
  return yield* missingItem();
3910
5171
  }
@@ -3950,7 +5211,9 @@ const makeImpl = (config, precomputedData) => {
3950
5211
  // Plain (unread) updates require the item to exist (#133). One that
3951
5212
  // could create a complete item — a plain `.set()` of every required
3952
5213
  // field and key composite — does so on a missing item through `put`
3953
- // (`createOnMissing`), so the item is exactly the one `put` writes.
5214
+ // (`createOnMissing`), so the item is exactly the one `put` writes. A
5215
+ // `.remove()` beside it clears what `put` wouldn't write anyway, which is
5216
+ // what lets a complete `.set({ ..., optional: undefined })` create too.
3954
5217
  const plainWrite = retainSnapshot === undefined && casRead === undefined;
3955
5218
  const createsOnMissing = plainWrite &&
3956
5219
  upsertable &&
@@ -3960,7 +5223,7 @@ const makeImpl = (config, precomputedData) => {
3960
5223
  uState.cascade === undefined &&
3961
5224
  uState.withVectors === undefined &&
3962
5225
  (requestedRv === "allNew" || requestedRv === "none" || requestedRv === "updatedNew") &&
3963
- [uState.remove, uState.sparseRemoveEntries, uState.sparseClearFields].every((ops) => ops === undefined || ops.length === 0) &&
5226
+ [uState.sparseRemoveEntries, uState.sparseClearFields].every((ops) => ops === undefined || ops.length === 0) &&
3964
5227
  [uState.add, uState.subtract, uState.append, uState.deleteFromSet].every((ops) => ops === undefined || Object.keys(ops).length === 0) &&
3965
5228
  !hasPathOps(uState);
3966
5229
  // A restated packed immutable cannot be asserted by a condition on its
@@ -3976,7 +5239,7 @@ const makeImpl = (config, precomputedData) => {
3976
5239
  const stored = yield* readCurrent(tableName, marshalledKey);
3977
5240
  if (stored.Item === undefined) {
3978
5241
  return yield* createsOnMissing
3979
- ? new MissingForCreate({ input: uState.updates })
5242
+ ? new MissingForCreate({ input: createInput() })
3980
5243
  : missingItem();
3981
5244
  }
3982
5245
  const packedChange = yield* packedImmutableMismatch(immutables, stored.Item);
@@ -4004,18 +5267,20 @@ const makeImpl = (config, precomputedData) => {
4004
5267
  updateSystemColliders.add(systemFields.updatedAt);
4005
5268
  // Add user-provided updates. Buffered REMOVE clauses for null
4006
5269
  // payload entries land in `removeClauses` below — under v3,
4007
- // `set({ attr: null | undefined })` REMOVEs the attribute from the
4008
- // item but does NOT separately cascade-drop GSI keys. The structural
4009
- // composer treats the cleared attribute as absent and recomposes
4010
- // (or truncates / drops / no-ops) per the half's policy.
4011
- // EDD-9025 guarantees no composite is nullable, so `set` of `null`
4012
- // is only reachable for non-composite, model-declared-nullable
4013
- // attributes. See DESIGN.md §7.
5270
+ // `set({ attr: null })` REMOVEs the attribute from the item but does
5271
+ // NOT separately cascade-drop GSI keys. The structural composer treats
5272
+ // the cleared attribute as absent and recomposes (or truncates / drops
5273
+ // / no-ops) per the half's policy. EDD-9025 guarantees no composite is
5274
+ // nullable, so `set` of `null` is only reachable for non-composite,
5275
+ // model-declared-nullable attributes. See DESIGN.md §7. A field a row
5276
+ // can't lack keeps its `null`: it's stored, or the row couldn't be read.
4014
5277
  const nullClears = [];
5278
+ // A sparse map's entries with no stored form, by their placeholders.
5279
+ const entryClears = [];
4015
5280
  for (const [attr, val] of Object.entries(encodedUpdatesMap)) {
4016
5281
  if (updateSystemColliders.has(attr))
4017
5282
  continue;
4018
- if (val === null || val === undefined) {
5283
+ if (val === undefined || (val === null && lacks.omits(attr))) {
4019
5284
  // Sparse fields: clearing a sparse field with null is a no-op
4020
5285
  // here — the `.removeEntries` API is the explicit per-key
4021
5286
  // remove. Skip to avoid REMOVE'ing the whole prefix erroneously.
@@ -4039,8 +5304,13 @@ const makeImpl = (config, precomputedData) => {
4039
5304
  });
4040
5305
  }
4041
5306
  const nameKey = `#u${counter}`;
4042
- const valKey = `:u${counter}`;
4043
5307
  names[nameKey] = `${sparse.prefix}#${k}`;
5308
+ if (hasNoStoredForm(v)) {
5309
+ entryClears.push(nameKey);
5310
+ counter++;
5311
+ continue;
5312
+ }
5313
+ const valKey = `:u${counter}`;
4044
5314
  values[valKey] = toAttributeValue(v);
4045
5315
  setClauses.push(`${nameKey} = ${valKey}`);
4046
5316
  counter++;
@@ -4062,14 +5332,15 @@ const makeImpl = (config, precomputedData) => {
4062
5332
  // Add updatedAt timestamp. User-supplied value wins (already in wire
4063
5333
  // form via encode); else fall back to a freshly generated wire
4064
5334
  // primitive.
5335
+ const suppliedUpdatedAt = systemFields.updatedAt === null ? undefined : encodedUpdatesMap[systemFields.updatedAt];
5336
+ const stampedUpdatedAt = suppliedUpdatedAt !== undefined
5337
+ ? suppliedUpdatedAt
5338
+ : generateTimestamp(systemFields.updatedAtEncoding, now);
4065
5339
  if (systemFields.updatedAt) {
4066
- const userSupplied = encodedUpdatesMap[systemFields.updatedAt];
4067
5340
  const nameKey = `#u${counter}`;
4068
5341
  const valKey = `:u${counter}`;
4069
- names[nameKey] = systemFields.updatedAt;
4070
- values[valKey] = toAttributeValue(userSupplied !== undefined
4071
- ? userSupplied
4072
- : generateTimestamp(systemFields.updatedAtEncoding, now));
5342
+ names[nameKey] = resolveDbName(systemFields.updatedAt);
5343
+ values[valKey] = toAttributeValue(stampedUpdatedAt);
4073
5344
  setClauses.push(`${nameKey} = ${valKey}`);
4074
5345
  counter++;
4075
5346
  }
@@ -4101,19 +5372,11 @@ const makeImpl = (config, precomputedData) => {
4101
5372
  }
4102
5373
  // APPEND → synthesize SET #field = list_append(#field, :val)
4103
5374
  if (uState.append) {
4104
- for (const [attr, val] of Object.entries(uState.append)) {
5375
+ for (const attr of Object.keys(uState.append)) {
4105
5376
  const nameKey = `#u${counter}`;
4106
5377
  const valKey = `:u${counter}`;
4107
5378
  names[nameKey] = resolveDbName(attr);
4108
- const appended = encodePathValue([attr], val, "elements");
4109
- if (appended.issue !== undefined) {
4110
- return yield* new ValidationError({
4111
- entityType,
4112
- operation: "update.append",
4113
- cause: appended.issue,
4114
- });
4115
- }
4116
- values[valKey] = toAttributeValue(appended.encoded);
5379
+ values[valKey] = toAttributeValue(operands.append[attr]);
4117
5380
  setClauses.push(`${nameKey} = list_append(${nameKey}, ${valKey})`);
4118
5381
  counter++;
4119
5382
  }
@@ -4143,6 +5406,7 @@ const makeImpl = (config, precomputedData) => {
4143
5406
  names[nameKey] = resolveDbName(attr);
4144
5407
  removeClauses.push(nameKey);
4145
5408
  }
5409
+ removeClauses.push(...entryClears);
4146
5410
  // Policy-aware GSI key composition (v1.7.1 — per-half evaluation
4147
5411
  // gate, structural rule, and per-half cascade). One call covers
4148
5412
  // SETs (full recompose, truncated leading prefix), per-half REMOVEs
@@ -4153,7 +5417,10 @@ const makeImpl = (config, precomputedData) => {
4153
5417
  // EDD-9024 was deprecated in v1.7.1 — hole patterns collapse into the
4154
5418
  // unified can't-compose rule and don't throw. A Z-order value the
4155
5419
  // composer can't place (EDD-9092, #171) fails with a `ValidationError`.
4156
- const gsiUpdate = yield* composeKeysOrFail(entityType, "update", () => KeyComposer.composeGsiKeysForUpdatePolicyAware(schema, entityType, entityVersion, allIndexes, keyForm(hydratedUpdates), keyForm(encodedKey), removedSet === undefined ? {} : { removedSet }));
5420
+ const gsiUpdate = yield* composeKeysOrFail(entityType, "update", () => KeyComposer.composeGsiKeysForUpdatePolicyAware(schema, entityType, entityVersion, allIndexes, keyForm(hydratedUpdates), keyForm(encodedKey), {
5421
+ ...(removedSet === undefined ? {} : { removedSet }),
5422
+ stamped: keyForm(writeStamps(stampedUpdatedAt, retainSnapshot === undefined ? undefined : retainSnapshot.version + 1)),
5423
+ }));
4157
5424
  // The key and vector attributes this update writes — a retain
4158
5425
  // snapshot strips them, so the post-image is rebuilt from these.
4159
5426
  const derivedSets = {};
@@ -4221,7 +5488,7 @@ const makeImpl = (config, precomputedData) => {
4221
5488
  const pathCounter = { value: 0 };
4222
5489
  // Path SET operations
4223
5490
  if (uState.pathSets) {
4224
- for (const op of uState.pathSets) {
5491
+ for (const [i, op] of uState.pathSets.entries()) {
4225
5492
  const pathExpr = compilePath(op.segments, names, "ps", pathCounter, resolveDbName);
4226
5493
  if (op.isPath && op.valueSegments) {
4227
5494
  const srcExpr = compilePath(op.valueSegments, names, "ps", pathCounter, resolveDbName);
@@ -4229,15 +5496,7 @@ const makeImpl = (config, precomputedData) => {
4229
5496
  }
4230
5497
  else {
4231
5498
  const valKey = `:ps${pathCounter.value++}`;
4232
- const set = encodePathValue(op.segments, op.value, "value");
4233
- if (set.issue !== undefined) {
4234
- return yield* new ValidationError({
4235
- entityType,
4236
- operation: "update.pathSet",
4237
- cause: set.issue,
4238
- });
4239
- }
4240
- values[valKey] = toAttributeValue(set.encoded);
5499
+ values[valKey] = toAttributeValue(operands.pathSets[i]);
4241
5500
  setClauses.push(`${pathExpr} = ${valKey}`);
4242
5501
  }
4243
5502
  }
@@ -4259,52 +5518,28 @@ const makeImpl = (config, precomputedData) => {
4259
5518
  }
4260
5519
  // Path APPEND operations
4261
5520
  if (uState.pathAppends) {
4262
- for (const op of uState.pathAppends) {
5521
+ for (const [i, op] of uState.pathAppends.entries()) {
4263
5522
  const pathExpr = compilePath(op.segments, names, "pa", pathCounter, resolveDbName);
4264
5523
  const valKey = `:pa${pathCounter.value++}`;
4265
- const appended = encodePathValue(op.segments, op.value, "elements");
4266
- if (appended.issue !== undefined) {
4267
- return yield* new ValidationError({
4268
- entityType,
4269
- operation: "update.pathAppend",
4270
- cause: appended.issue,
4271
- });
4272
- }
4273
- values[valKey] = toAttributeValue(appended.encoded);
5524
+ values[valKey] = toAttributeValue(operands.pathAppends[i]);
4274
5525
  setClauses.push(`${pathExpr} = list_append(${pathExpr}, ${valKey})`);
4275
5526
  }
4276
5527
  }
4277
5528
  // Path PREPEND operations
4278
5529
  if (uState.pathPrepends) {
4279
- for (const op of uState.pathPrepends) {
5530
+ for (const [i, op] of uState.pathPrepends.entries()) {
4280
5531
  const pathExpr = compilePath(op.segments, names, "pp", pathCounter, resolveDbName);
4281
5532
  const valKey = `:pp${pathCounter.value++}`;
4282
- const prepended = encodePathValue(op.segments, op.value, "elements");
4283
- if (prepended.issue !== undefined) {
4284
- return yield* new ValidationError({
4285
- entityType,
4286
- operation: "update.pathPrepend",
4287
- cause: prepended.issue,
4288
- });
4289
- }
4290
- values[valKey] = toAttributeValue(prepended.encoded);
5533
+ values[valKey] = toAttributeValue(operands.pathPrepends[i]);
4291
5534
  setClauses.push(`${pathExpr} = list_append(${valKey}, ${pathExpr})`);
4292
5535
  }
4293
5536
  }
4294
5537
  // Path if_not_exists operations
4295
5538
  if (uState.pathIfNotExists) {
4296
- for (const op of uState.pathIfNotExists) {
5539
+ for (const [i, op] of uState.pathIfNotExists.entries()) {
4297
5540
  const pathExpr = compilePath(op.segments, names, "pi", pathCounter, resolveDbName);
4298
5541
  const valKey = `:pi${pathCounter.value++}`;
4299
- const ifAbsent = encodePathValue(op.segments, op.value, "value");
4300
- if (ifAbsent.issue !== undefined) {
4301
- return yield* new ValidationError({
4302
- entityType,
4303
- operation: "update.pathIfNotExists",
4304
- cause: ifAbsent.issue,
4305
- });
4306
- }
4307
- values[valKey] = toAttributeValue(ifAbsent.encoded);
5542
+ values[valKey] = toAttributeValue(operands.pathIfNotExists[i]);
4308
5543
  setClauses.push(`${pathExpr} = if_not_exists(${pathExpr}, ${valKey})`);
4309
5544
  }
4310
5545
  }
@@ -4347,11 +5582,14 @@ const makeImpl = (config, precomputedData) => {
4347
5582
  }
4348
5583
  const sparse = sparseFields[op.field];
4349
5584
  for (const k of op.keys) {
4350
- if (typeof k !== "string" || k.length === 0 || k.includes("#")) {
5585
+ // An entry the reader reads under `k`: never `<prefix>#` itself.
5586
+ if (typeof k !== "string" ||
5587
+ sparseEntries.entryOf(`${sparse.prefix}#${k}`)?.field !== op.field) {
4351
5588
  return yield* new ValidationError({
4352
5589
  entityType,
4353
5590
  operation: "update.removeEntries",
4354
- cause: `Sparse map "${op.field}": invalid key ${JSON.stringify(k)}`,
5591
+ cause: `Sparse map "${op.field}": invalid key ${JSON.stringify(k)}: no stored ` +
5592
+ "attribute is read as its entry under it",
4355
5593
  });
4356
5594
  }
4357
5595
  const nameKey = `#sr${removeClauses.length}`;
@@ -4402,10 +5640,9 @@ const makeImpl = (config, precomputedData) => {
4402
5640
  }
4403
5641
  const clearItemKeys = Object.keys(clearGetResult.Item);
4404
5642
  for (const field of uState.sparseClearFields) {
4405
- const sparse = sparseFields[field];
4406
- const prefixWithDelim = `${sparse.prefix}#`;
5643
+ // Exactly the attributes the reader takes as the map's entries.
4407
5644
  for (const attrName of clearItemKeys) {
4408
- if (attrName.startsWith(prefixWithDelim)) {
5645
+ if (sparseEntries.entryOf(attrName)?.field === field) {
4409
5646
  const nameKey = `#sc${removeClauses.length}`;
4410
5647
  names[nameKey] = attrName;
4411
5648
  removeClauses.push(nameKey);
@@ -4501,7 +5738,7 @@ const makeImpl = (config, precomputedData) => {
4501
5738
  : undefined;
4502
5739
  if (sourceId == null)
4503
5740
  return;
4504
- const domainData = yield* decodeAs(fromAttributeMap(image), image, "model");
5741
+ const domainData = yield* appliedUpdate(decodeAs(fromAttributeMap(image), image, "model"), "stored");
4505
5742
  yield* executeCascade(uState.cascade, { ...domainData }, String(sourceId));
4506
5743
  });
4507
5744
  if (retainSnapshot !== undefined) {
@@ -4593,7 +5830,7 @@ const makeImpl = (config, precomputedData) => {
4593
5830
  const stored = err.cause.Item;
4594
5831
  if (stored === undefined && !uState.patch) {
4595
5832
  return createsOnMissing
4596
- ? new MissingForCreate({ input: uState.updates })
5833
+ ? new MissingForCreate({ input: createInput() })
4597
5834
  : new ItemNotFound({ entityType, key: encodedKey });
4598
5835
  }
4599
5836
  const corrupt = versionCorruption(stored, "update");
@@ -4622,26 +5859,36 @@ const makeImpl = (config, precomputedData) => {
4622
5859
  yield* cascadeFrom(newImage);
4623
5860
  return yield* updateResult(rv, casRead !== undefined ? casRead.raw : wantsOld ? result.Attributes : undefined, newImage, written, mode, encodedKey);
4624
5861
  });
5862
+ const runUpdate = (key, mode, requested,
5863
+ /** See {@link runPreparedUpdate}. */
5864
+ preRead) => Effect.flatMap(prepareUpdate(key, requested), (prepared) => runPreparedUpdate(key, prepared, mode, preRead));
4625
5865
  /**
4626
5866
  * An update; on a missing item, a plain `.set()` of a complete item creates
4627
5867
  * it through `create` — exactly the item `put` writes (#133). If another
4628
5868
  * writer creates it first, the update runs once more against that item.
4629
5869
  */
4630
- const updateOrCreate = (key, mode, requested) => runUpdate(key, mode, requested).pipe(Effect.catchIf((e) => e instanceof MissingForCreate, (missing) => Effect.gen(function* () {
4631
- const created = yield* Effect.exit(create(missing.input)._run("native"));
4632
- if (created._tag === "Failure") {
4633
- const raced = Cause.findErrorOption(created.cause).pipe(Option.filter((e) => e instanceof ConditionalCheckFailed));
4634
- if (Option.isNone(raced))
4635
- return yield* created;
4636
- // Created concurrently: now an ordinary update of that item.
4637
- return yield* runUpdate(key, mode, requested).pipe(Effect.catchIf((e) => e instanceof MissingForCreate, () => Effect.fail(new ItemNotFound({
4638
- entityType,
4639
- key: key,
4640
- }))));
4641
- }
4642
- const item = created.value;
4643
- return yield* updateResult(requested.returnValues ?? "allNew", undefined, item, new Set(Object.keys(item)), mode, key);
4644
- })));
5870
+ const updateOrCreate = (key, mode, requested,
5871
+ /** What {@link prepareUpdate} decided of `requested`, when the caller already ran it. */
5872
+ prepared) => {
5873
+ const run = () => prepared === undefined
5874
+ ? runUpdate(key, mode, requested)
5875
+ : runPreparedUpdate(key, prepared, mode);
5876
+ return run().pipe(Effect.catchIf((e) => e instanceof MissingForCreate, (missing) => Effect.gen(function* () {
5877
+ const created = yield* Effect.exit(create(missing.input)._run("native"));
5878
+ if (created._tag === "Failure") {
5879
+ const raced = Cause.findErrorOption(created.cause).pipe(Option.filter((e) => e instanceof ConditionalCheckFailed));
5880
+ if (Option.isNone(raced))
5881
+ return yield* created;
5882
+ // Created concurrently: now an ordinary update of that item.
5883
+ return yield* run().pipe(Effect.catchIf((e) => e instanceof MissingForCreate, () => Effect.fail(new ItemNotFound({
5884
+ entityType,
5885
+ key: key,
5886
+ }))));
5887
+ }
5888
+ const item = created.value;
5889
+ return yield* updateResult(requested.returnValues ?? "allNew", undefined, item, new Set(Object.keys(item)), mode, key);
5890
+ })));
5891
+ };
4645
5892
  const update = (key) => new EntityUpdateImpl((mode, requested) => updateOrCreate(key, mode, requested), emptyUpdateState, self, key);
4646
5893
  /**
4647
5894
  * Run one of this entity's write ops with its write recorded instead of
@@ -4660,10 +5907,11 @@ const makeImpl = (config, precomputedData) => {
4660
5907
  * `payload` is what the caller asked to write. With the op's own read of
4661
5908
  * the row, it lets a reservation say which values it reserves.
4662
5909
  */
4663
- const planned = (operation, key,
5910
+ const planned = (operation,
5911
+ /** The key, through `encodeKey`. */
5912
+ encodedKey,
4664
5913
  /** The op itself — a factory, because a missing row means running it again. */
4665
5914
  op, request) => Effect.gen(function* () {
4666
- const encodedKey = yield* encodeKey(key, `${operation}.decodeKey`);
4667
5915
  const primaryKey = composePrimaryKey(encodedKey);
4668
5916
  const ownKey = toAttributeMap(primaryKey);
4669
5917
  const plan = (rowMissing) => planWrite(operation, op(), ownKey, rowMissing);
@@ -4723,6 +5971,8 @@ const makeImpl = (config, precomputedData) => {
4723
5971
  : { ...read, ...request.payload };
4724
5972
  if (mainPut === undefined) {
4725
5973
  for (const [field, delta] of Object.entries(request.deltas ?? {})) {
5974
+ if (typeof delta !== "number")
5975
+ continue;
4726
5976
  const base = read[field];
4727
5977
  after[field] = (typeof base === "number" ? base : 0) + delta;
4728
5978
  }
@@ -4753,7 +6003,7 @@ const makeImpl = (config, precomputedData) => {
4753
6003
  const constraintDef = config.unique?.[constraintName];
4754
6004
  const reserved = constraintDef === undefined
4755
6005
  ? undefined
4756
- : composeUniqueSentinel(schema, entityType, constraintName, constraintDef, after);
6006
+ : composeUniqueSentinel(schema, entityType, constraintName, constraintDef, after, storedSentinelValue);
4757
6007
  const putKey = fromAttributeMap(item.Put.Item ?? {});
4758
6008
  // Only values that recompose THIS sentinel are reported — never a guess.
4759
6009
  const fields = reserved !== undefined &&
@@ -4849,7 +6099,7 @@ const makeImpl = (config, precomputedData) => {
4849
6099
  };
4850
6100
  });
4851
6101
  /** Compile an update for `Transaction.transactWrite` — see `_planUpdate`. */
4852
- const planUpdate = (key, uState) => planned("transactWrite.update", key, () => updateOrCreate(key, "native", uState), {
6102
+ const planUpdate = (key, uState, prepared) => planned("transactWrite.update", prepared.encodedKey, () => updateOrCreate(key, "native", uState, prepared), {
4853
6103
  payload: (uState.updates ?? {}),
4854
6104
  deltas: {
4855
6105
  ...uState.add,
@@ -4998,7 +6248,7 @@ const makeImpl = (config, precomputedData) => {
4998
6248
  const rawDomain = toDomainView(raw);
4999
6249
  const held = [];
5000
6250
  for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
5001
- const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, rawDomain);
6251
+ const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, rawDomain, readSentinelValue);
5002
6252
  if (!sentinel)
5003
6253
  continue;
5004
6254
  held.push({ ...sentinel.key, constraintName });
@@ -5052,7 +6302,7 @@ const makeImpl = (config, precomputedData) => {
5052
6302
  // Add deletedAt
5053
6303
  deletedItem.deletedAt = now;
5054
6304
  // Add optional TTL
5055
- const sdTtl = softDeleteTtl();
6305
+ const sdTtl = tombstoneTtl();
5056
6306
  if (sdTtl) {
5057
6307
  deletedItem[ttlAttrName] =
5058
6308
  DateTime.toEpochSeconds(dtNow) + normalizeTtlSeconds(sdTtl);
@@ -5219,7 +6469,7 @@ const makeImpl = (config, precomputedData) => {
5219
6469
  // deleteIfExists operation — delete + attribute_exists condition
5220
6470
  // ---------------------------------------------------------------------------
5221
6471
  /** Compile a delete for `Transaction.transactWrite` — see `_planDelete`. */
5222
- const planDelete = (key, opts) => planned("transactWrite.delete", key, () => del(key)._builder({ ...opts, returnValues: undefined }), { payload: {}, callerCondition: opts.condition !== undefined });
6472
+ const planDelete = (key, opts, encodedKey) => planned("transactWrite.delete", encodedKey, () => del(key)._builder({ ...opts, returnValues: undefined }), { payload: {}, callerCondition: opts.condition !== undefined });
5223
6473
  const deleteIfExists = (key) => {
5224
6474
  const op = del(key);
5225
6475
  return new EntityDeleteImpl(op._builder, op._entity, op._key, op._condition, op._returnValues, true);
@@ -5236,21 +6486,29 @@ const makeImpl = (config, precomputedData) => {
5236
6486
  * by `attribute_not_exists`, the retain snapshot, omitted defaults stored).
5237
6487
  * Present: an update of the upserted fields — sentinels rotate for changed
5238
6488
  * values, unchanged ones are left alone, immutable fields, `createdAt` and
5239
- * fields the input omits keep their stored values, retain snapshots the
6489
+ * fields the input omits or leaves unset keep their stored values, retain snapshots the
5240
6490
  * replaced item — under the update's version / incarnation or attribute
5241
6491
  * guards, from that one read. The whole input is validated either way. A
5242
6492
  * concurrent create or delete between the read and the write is retried the
5243
6493
  * other way, and a sentinel release whose reservation changed hands is
5244
6494
  * planned again from a fresh read (as a put's is); a race lost on every
5245
6495
  * attempt fails with the concurrency error. A concurrent change of the item
5246
- * itself fails the upsert, as it fails an update.
6496
+ * itself fails the upsert, as it fails an update. A single-write upsert also ends up here, with the
6497
+ * row its rejected write returned, when one write couldn't get a key right (`upsertKeyPlan`).
5247
6498
  */
5248
- const guardedUpsert = (input, mode, opts) => Effect.gen(function* () {
6499
+ const guardedUpsert = (input, mode, opts,
6500
+ /** The stored item, when the caller has it: a rejected write returned it. */
6501
+ stored) => Effect.gen(function* () {
5249
6502
  const client = yield* Capacity.client;
5250
6503
  const { name: tableName } = yield* tableTag;
6504
+ const now = yield* DateTime.now;
5251
6505
  yield* checkWithVectorNames(opts.withVectors, "upsert");
6506
+ const lacks = writeLacks();
5252
6507
  // Required fields are required whether or not the item exists.
5253
- yield* encodeOrDecodeEncode(schemas.inputSchema, yield* fillDecodingDefaults(input), entityType, "upsert");
6508
+ const encodedInput = (yield* encodeForWrite(schemas.inputSchema, yield* fillDecodingDefaults(input), "upsert"));
6509
+ yield* refuseUnstorable({ ...encodedInput, ...opts.withVectors }, "upsert");
6510
+ yield* composeAllKeys(encodedInput, "upsert");
6511
+ yield* refuseUncomposed(encodedInput, "upsert");
5254
6512
  const record = (input ?? {});
5255
6513
  const primary = config.indexes.primary;
5256
6514
  const keyFields = [...primary.pk.composite, ...primary.sk.composite];
@@ -5263,11 +6521,52 @@ const makeImpl = (config, precomputedData) => {
5263
6521
  ...(systemFields.createdAt ? [systemFields.createdAt] : []),
5264
6522
  ...(systemFields.version ? [systemFields.version] : []),
5265
6523
  ]);
5266
- const updates = Object.fromEntries(Object.entries(record).filter(([field]) => !dropped.has(field)));
6524
+ // An `undefined` means what it means on the single write. A merely optional field is left
6525
+ // unset, and a defaulted index composite is omitted (`omitsIndexedDefault`), so either keeps
6526
+ // what the row holds. Any other default is stored.
6527
+ const keyedDefaults = indexedDefaultFields();
6528
+ const updates = (yield* fillDecodingDefaults(Object.fromEntries(Object.entries(record).filter(([field, value]) => !dropped.has(field) &&
6529
+ !(value === undefined &&
6530
+ (keyedDefaults.has(field) ||
6531
+ (encodedInput[field] === undefined &&
6532
+ lacks.absentReading(field) === undefined))))), (field, given) => field in given));
6533
+ // What the single-write upsert sets with `if_not_exists`: under whatever the row holds.
6534
+ const fill = {
6535
+ ...Object.fromEntries([...immutableFields]
6536
+ .filter((field) => encodedInput[field] !== undefined)
6537
+ .map((field) => [field, encodedInput[field]])),
6538
+ ...(systemFields.createdAt
6539
+ ? {
6540
+ [systemFields.createdAt]: encodedInput[systemFields.createdAt] ??
6541
+ generateTimestamp(systemFields.createdAtEncoding, now),
6542
+ }
6543
+ : {}),
6544
+ };
5267
6545
  const read = () => client
5268
6546
  .getItem({ TableName: tableName, Key: marshalledKey, ConsistentRead: true })
5269
6547
  .pipe(Effect.map((result) => result.Item));
5270
- let current = yield* read();
6548
+ // A row that isn't there is written whole, as a put, and one that is takes the update of the
6549
+ // upserted fields (`updates`), which refuses the entry keys `refusesPutKeys` says. A put
6550
+ // refuses every key that update refuses, so such a key is refused before the read, in the
6551
+ // put's words. Any other is judged by the write the read leads to.
6552
+ const refusedEntry = refusedSparseEntry(Object.fromEntries(Object.keys(updates)
6553
+ .filter((field) => Object.hasOwn(encodedInput, field))
6554
+ .map((field) => [field, encodedInput[field]])), refusesPutKeys(false, {
6555
+ touchesUniqueFields: touchesUniqueFieldsOf(emptyUpdateState, updates),
6556
+ computedComposites: [],
6557
+ pathOpsPresent: false,
6558
+ }), everyRowWrites);
6559
+ const refusedKey = refusedEntry === undefined
6560
+ ? undefined
6561
+ : sparseKeyRefusal(refusedEntry.field, refusedEntry.prefix, refusedEntry.key);
6562
+ if (refusedKey !== undefined) {
6563
+ return yield* new ValidationError({
6564
+ entityType,
6565
+ operation: "upsert.sparse",
6566
+ cause: refusedKey,
6567
+ });
6568
+ }
6569
+ let current = stored ?? (yield* read());
5271
6570
  let expected = 0;
5272
6571
  let lost;
5273
6572
  for (let attempt = 0; attempt < GUARDED_PUT_ATTEMPTS; attempt++) {
@@ -5298,6 +6597,7 @@ const makeImpl = (config, precomputedData) => {
5298
6597
  updates,
5299
6598
  condition: opts.condition,
5300
6599
  withVectors: opts.withVectors,
6600
+ upsertOver: { fill },
5301
6601
  }, current).pipe(
5302
6602
  // Its errors name the upsert, not the update it runs.
5303
6603
  Effect.mapError((e) => e instanceof ValidationError && e.operation.startsWith("update")
@@ -5342,6 +6642,18 @@ const makeImpl = (config, precomputedData) => {
5342
6642
  });
5343
6643
  });
5344
6644
  const upsert = (input) => new EntityPutImpl((mode, opts) => Effect.gen(function* () {
6645
+ const lacks = writeLacks();
6646
+ // A primary key over `createdAt` the input doesn't supply names no item that exists yet.
6647
+ if (systemFields.createdAt !== null &&
6648
+ isPrimaryComposite(systemFields.createdAt) &&
6649
+ input[systemFields.createdAt] === undefined) {
6650
+ return yield* put(input)._builder(mode, {
6651
+ condition: opts.condition,
6652
+ withVectors: opts.withVectors,
6653
+ putKind: "create",
6654
+ operation: "upsert",
6655
+ });
6656
+ }
5345
6657
  if ((config.unique != null && Object.keys(config.unique).length > 0) ||
5346
6658
  isRetainEnabled() ||
5347
6659
  omitsIndexedDefault(input)) {
@@ -5355,17 +6667,39 @@ const makeImpl = (config, precomputedData) => {
5355
6667
  // Encode user input → wire form (see `put` for strategy). An input
5356
6668
  // that omits a defaulted index composite took the guarded path: the
5357
6669
  // default is stored on create, the stored value kept on update.
5358
- const encodedInput = yield* encodeOrDecodeEncode(schemas.inputSchema, input, entityType, "upsert");
6670
+ const encodedInput = yield* encodeForWrite(schemas.inputSchema, input, "upsert");
6671
+ yield* refuseUnstorable({ ...encodedInput, ...opts.withVectors }, "upsert");
6672
+ // Clearing a composite clears what a half says, and one write can't tell what's left of
6673
+ // it: the update's own rule says, and that needs the stored row.
6674
+ if ([...indexCompositeFields()].some((field) => upsertClears(field, encodedInput[field], lacks) &&
6675
+ field !== systemFields.createdAt &&
6676
+ field !== systemFields.updatedAt)) {
6677
+ return yield* guardedUpsert(input, mode, opts);
6678
+ }
5359
6679
  // Hydrate refs: replace ID fields with full entity domain data
5360
6680
  const encoded = hasRefs
5361
6681
  ? yield* hydrateRefs(encodedInput)
5362
6682
  : encodedInput;
5363
6683
  const item = encoded;
6684
+ const suppliedCreatedAt = systemFields.createdAt === null ? undefined : item[systemFields.createdAt];
6685
+ const upsertedCreatedAt = suppliedCreatedAt !== undefined
6686
+ ? suppliedCreatedAt
6687
+ : generateTimestamp(systemFields.createdAtEncoding, now);
6688
+ const suppliedUpdatedAt = systemFields.updatedAt === null ? undefined : item[systemFields.updatedAt];
6689
+ const upsertedUpdatedAt = suppliedUpdatedAt !== undefined
6690
+ ? suppliedUpdatedAt
6691
+ : generateTimestamp(systemFields.updatedAtEncoding, now);
5364
6692
  // Every index's keys, composed before anything is marshalled: a
5365
6693
  // composite with no key text (`NaN`, `[EDD-9096]`) or Z-order level
5366
- // (`[EDD-9092]`) fails the upsert with a `ValidationError`, where the
5367
- // marshaller would refuse the attribute as a defect.
5368
- const allKeys = yield* composeAllKeys(item, "upsert");
6694
+ // (`[EDD-9092]`) fails the upsert with a `ValidationError`.
6695
+ const stamped = {
6696
+ ...item,
6697
+ ...writeStamps(upsertedUpdatedAt, undefined),
6698
+ ...(systemFields.createdAt ? { [systemFields.createdAt]: upsertedCreatedAt } : {}),
6699
+ };
6700
+ const allKeys = yield* upsertKeys(stamped, yield* composeAllKeys(stamped, "upsert"));
6701
+ yield* refuseUncomposed(encodedInput, "upsert");
6702
+ const keyPlan = upsertKeyPlan(allKeys, item, suppliedCreatedAt !== undefined);
5369
6703
  const primaryKey = composePrimaryKey(item);
5370
6704
  const marshalledKey = toAttributeMap(primaryKey);
5371
6705
  // Build UpdateExpression with if_not_exists for immutable fields + createdAt
@@ -5374,6 +6708,8 @@ const makeImpl = (config, precomputedData) => {
5374
6708
  const names = {};
5375
6709
  const values = {};
5376
6710
  let counter = 0;
6711
+ // Each written value's placeholders, for the key guards below.
6712
+ const placeholders = new Map();
5377
6713
  // The physical key attributes (`pk` / `sk`) live in `Key` and cannot
5378
6714
  // appear in an UpdateExpression. The COMPOSITE SOURCE fields are
5379
6715
  // ordinary attributes and must be written like any other model field —
@@ -5401,7 +6737,14 @@ const makeImpl = (config, precomputedData) => {
5401
6737
  continue;
5402
6738
  if (systemColliders.has(attr))
5403
6739
  continue;
5404
- if (val === undefined)
6740
+ if (upsertClears(attr, val, lacks)) {
6741
+ const nameKey = `#u${counter}`;
6742
+ names[nameKey] = resolveDbName(attr);
6743
+ upsertRemoveClauses.push(nameKey);
6744
+ counter++;
6745
+ continue;
6746
+ }
6747
+ if (val === undefined || isEmptySet(val))
5405
6748
  continue;
5406
6749
  // Sparse fields: expand into one SET per bucket. Each bucket
5407
6750
  // attribute is named `<prefix>#<key>` and goes through
@@ -5424,8 +6767,13 @@ const makeImpl = (config, precomputedData) => {
5424
6767
  });
5425
6768
  }
5426
6769
  const nameKey = `#u${counter}`;
5427
- const valKey = `:u${counter}`;
5428
6770
  names[nameKey] = `${sparse.prefix}#${k}`;
6771
+ if (hasNoStoredForm(v)) {
6772
+ upsertRemoveClauses.push(nameKey);
6773
+ counter++;
6774
+ continue;
6775
+ }
6776
+ const valKey = `:u${counter}`;
5429
6777
  values[valKey] = toAttributeValue(v);
5430
6778
  setClauses.push(`${nameKey} = ${valKey}`);
5431
6779
  counter++;
@@ -5441,6 +6789,7 @@ const makeImpl = (config, precomputedData) => {
5441
6789
  attr in packedFields
5442
6790
  ? (yield* packAttribute(storedName, val, "upsert"))
5443
6791
  : toAttributeValue(val);
6792
+ placeholders.set(attr, [nameKey, valKey]);
5444
6793
  // Immutable fields use if_not_exists — only set on first create
5445
6794
  if (immutableFields.has(attr)) {
5446
6795
  setClauses.push(`${nameKey} = if_not_exists(${nameKey}, ${valKey})`);
@@ -5451,6 +6800,7 @@ const makeImpl = (config, precomputedData) => {
5451
6800
  counter++;
5452
6801
  }
5453
6802
  // Add all index keys (including GSIs)
6803
+ const keptKeyNames = [];
5454
6804
  for (const [field, value] of Object.entries(allKeys)) {
5455
6805
  // Skip primary key fields (they're in Key, not UpdateExpression)
5456
6806
  if (field === config.indexes.primary.pk.field ||
@@ -5460,7 +6810,13 @@ const makeImpl = (config, precomputedData) => {
5460
6810
  const valKey = `:u${counter}`;
5461
6811
  names[nameKey] = field;
5462
6812
  values[valKey] = toAttributeValue(value);
5463
- setClauses.push(`${nameKey} = ${valKey}`);
6813
+ if (keyPlan.keep.has(field)) {
6814
+ setClauses.push(`${nameKey} = if_not_exists(${nameKey}, ${valKey})`);
6815
+ keptKeyNames.push(nameKey);
6816
+ }
6817
+ else {
6818
+ setClauses.push(`${nameKey} = ${valKey}`);
6819
+ }
5464
6820
  counter++;
5465
6821
  }
5466
6822
  // Vector search: upsert writes the full item, so it always re-embeds
@@ -5469,7 +6825,7 @@ const makeImpl = (config, precomputedData) => {
5469
6825
  // source fields must overwrite the vector derived from them, or the
5470
6826
  // item would stay searchable under its previous description forever.
5471
6827
  if (hasVectorIndexes) {
5472
- const vectorWrite = yield* computeVectorAttributes(item, opts.withVectors, "all");
6828
+ const vectorWrite = yield* computeVectorAttributes({ ...item, ...writeStamps(upsertedUpdatedAt, undefined) }, opts.withVectors, "all");
5473
6829
  for (const [field, value] of Object.entries(vectorWrite.sets)) {
5474
6830
  const nameKey = `#u${counter}`;
5475
6831
  const valKey = `:u${counter}`;
@@ -5500,26 +6856,22 @@ const makeImpl = (config, precomputedData) => {
5500
6856
  // User-supplied value wins (domain input → already serialized above);
5501
6857
  // else fall back to a freshly generated storage primitive.
5502
6858
  if (systemFields.createdAt) {
5503
- const userSupplied = item[systemFields.createdAt];
5504
6859
  const nameKey = `#u${counter}`;
5505
6860
  const valKey = `:u${counter}`;
5506
- names[nameKey] = systemFields.createdAt;
5507
- values[valKey] = toAttributeValue(userSupplied !== undefined
5508
- ? userSupplied
5509
- : generateTimestamp(systemFields.createdAtEncoding, now));
6861
+ names[nameKey] = resolveDbName(systemFields.createdAt);
6862
+ values[valKey] = toAttributeValue(upsertedCreatedAt);
5510
6863
  setClauses.push(`${nameKey} = if_not_exists(${nameKey}, ${valKey})`);
6864
+ placeholders.set(systemFields.createdAt, [nameKey, valKey]);
5511
6865
  counter++;
5512
6866
  }
5513
6867
  // Add updatedAt — user-supplied wins, else always set to current time.
5514
6868
  if (systemFields.updatedAt) {
5515
- const userSupplied = item[systemFields.updatedAt];
5516
6869
  const nameKey = `#u${counter}`;
5517
6870
  const valKey = `:u${counter}`;
5518
- names[nameKey] = systemFields.updatedAt;
5519
- values[valKey] = toAttributeValue(userSupplied !== undefined
5520
- ? userSupplied
5521
- : generateTimestamp(systemFields.updatedAtEncoding, now));
6871
+ names[nameKey] = resolveDbName(systemFields.updatedAt);
6872
+ values[valKey] = toAttributeValue(upsertedUpdatedAt);
5522
6873
  setClauses.push(`${nameKey} = ${valKey}`);
6874
+ placeholders.set(systemFields.updatedAt, [nameKey, valKey]);
5523
6875
  counter++;
5524
6876
  }
5525
6877
  // Add version: if_not_exists(version, 0) + 1
@@ -5556,6 +6908,27 @@ const makeImpl = (config, precomputedData) => {
5556
6908
  Object.assign(names, uc.names);
5557
6909
  Object.assign(values, uc.values);
5558
6910
  }
6911
+ // The key written holds the input's value of what the upsert keeps: only where that's
6912
+ // what's stored. A row with nothing stored takes the input's, and passes.
6913
+ const keyGuards = [];
6914
+ for (const attr of keyPlan.matches) {
6915
+ const [nameKey, valKey] = placeholders.get(attr);
6916
+ keyGuards.push(`(attribute_not_exists(${nameKey}) OR ${nameKey} = ${valKey})`);
6917
+ }
6918
+ // A new row takes the key. An existing one keeps its own, so it must have one, and one
6919
+ // that still says what this input says.
6920
+ const stays = [
6921
+ ...keptKeyNames.map((nameKey) => `attribute_exists(${nameKey})`),
6922
+ ...[...keyPlan.same].map((attr) => {
6923
+ const [nameKey, valKey] = placeholders.get(attr);
6924
+ return `${nameKey} = ${valKey}`;
6925
+ }),
6926
+ ];
6927
+ if (stays.length > 0) {
6928
+ names["#kpk"] = config.indexes.primary.pk.field;
6929
+ keyGuards.push(`(attribute_not_exists(#kpk) OR (${stays.join(" AND ")}))`);
6930
+ }
6931
+ condParts.push(...keyGuards);
5559
6932
  const upsertInput = {
5560
6933
  TableName: tableName,
5561
6934
  Key: marshalledKey,
@@ -5563,25 +6936,35 @@ const makeImpl = (config, precomputedData) => {
5563
6936
  ExpressionAttributeNames: names,
5564
6937
  ExpressionAttributeValues: values,
5565
6938
  ConditionExpression: condParts.length > 0 ? condParts.join(" AND ") : undefined,
5566
- // Only the corruption guard needs the stored item.
5567
- ...(systemFields.version && {
6939
+ // The corruption guard needs the stored item, and so does a rejected key guard.
6940
+ ...((systemFields.version || keyGuards.length > 0) && {
5568
6941
  ReturnValuesOnConditionCheckFailure: "ALL_OLD",
5569
6942
  }),
5570
6943
  ReturnValues: "ALL_NEW",
5571
6944
  };
6945
+ // The row a key guard's rejection returned: DynamoDB charges no read for it.
6946
+ const rejected = {};
5572
6947
  const mapUpsertFailure = (err) => {
5573
6948
  if (isAwsConditionalCheckFailed(err.cause)) {
5574
6949
  const corrupt = versionCorruption(err.cause.Item, "upsert");
5575
6950
  if (corrupt !== undefined)
5576
6951
  return corrupt;
6952
+ if (keyGuards.length > 0 && err.cause.Item !== undefined) {
6953
+ rejected.row = err.cause.Item;
6954
+ }
5577
6955
  if (opts.condition)
5578
6956
  return new ConditionalCheckFailed({ entityType, key: item });
5579
6957
  }
5580
6958
  return err;
5581
6959
  };
5582
- const result = yield* client.updateItem(upsertInput).pipe(Effect.mapError(mapUpsertFailure), diagnoseItemWrite("upsert", {
6960
+ const written = yield* client.updateItem(upsertInput).pipe(Effect.mapError(mapUpsertFailure), diagnoseItemWrite("upsert", {
5583
6961
  Update: upsertInput,
5584
- }));
6962
+ }), Effect.exit);
6963
+ // One write couldn't get a key right: compose from the row. If it was the caller's
6964
+ // condition that rejected the write, this write is rejected too.
6965
+ if (rejected.row !== undefined)
6966
+ return yield* guardedUpsert(input, mode, opts, rejected.row);
6967
+ const result = yield* written;
5585
6968
  if (!result.Attributes) {
5586
6969
  return yield* new ItemNotFound({ entityType, key: item });
5587
6970
  }
@@ -5664,6 +7047,7 @@ const makeImpl = (config, precomputedData) => {
5664
7047
  // ---------------------------------------------------------------------------
5665
7048
  const timeSeriesConfig = config.timeSeries;
5666
7049
  const appendCore = (input, givenCondition, skipFollowUp = false, removeAttrs) => Effect.gen(function* () {
7050
+ const lacks = writeLacks();
5667
7051
  if (!timeSeriesConfig) {
5668
7052
  return yield* new ValidationError({
5669
7053
  entityType,
@@ -5697,7 +7081,7 @@ const makeImpl = (config, precomputedData) => {
5697
7081
  const tableName = tc.name;
5698
7082
  const ttlAttrName = resolveTtlAttributeName(tc);
5699
7083
  const orderByField = timeSeriesConfig.orderBy;
5700
- const ttlDuration = timeSeriesConfig.ttl;
7084
+ const ttlDuration = eventTtl();
5701
7085
  const appendInputSchema = schemas.appendInputSchema;
5702
7086
  // Clock-backed time source for current-item timestamps + event-item TTL.
5703
7087
  const now = yield* DateTime.now;
@@ -5709,14 +7093,22 @@ const makeImpl = (config, precomputedData) => {
5709
7093
  // composites, and ref fields must not be cleared, and the caller cannot
5710
7094
  // remove enrichment fields outside `appendInput` (that's a `.update()`
5711
7095
  // operation, not an append).
5712
- const removedSet = removeAttrs !== undefined && removeAttrs.length > 0 ? new Set(removeAttrs) : undefined;
5713
- if (removedSet !== undefined) {
7096
+ const requestedRemoves = removeAttrs !== undefined && removeAttrs.length > 0 ? new Set(removeAttrs) : undefined;
7097
+ if (requestedRemoves !== undefined) {
5714
7098
  const primary = config.indexes.primary;
5715
7099
  const pkSkComposites = new Set([...primary.pk.composite, ...primary.sk.composite]);
5716
7100
  const appendInputTop = timeSeriesConfig.appendInput;
5717
7101
  const appendInputFieldSet = new Set(Object.keys(getSchemaFields(appendInputTop) ?? {}));
5718
7102
  const model = config.model;
5719
- for (const attr of removedSet) {
7103
+ for (const attr of requestedRemoves) {
7104
+ const unnamed = unaddressable(attr, ttlAttrName);
7105
+ if (unnamed !== undefined) {
7106
+ return yield* new ValidationError({
7107
+ entityType,
7108
+ operation: "append.remove",
7109
+ cause: `.remove() of "${attr}": ${unnamed}. Nothing was sent.`,
7110
+ });
7111
+ }
5720
7112
  if (!appendInputFieldSet.has(attr)) {
5721
7113
  return yield* new ValidationError({
5722
7114
  entityType,
@@ -5747,18 +7139,45 @@ const makeImpl = (config, precomputedData) => {
5747
7139
  cause: `Attribute "${attr}" is a ref field — refs are create-time denormalisations and cannot be cleared via .append(). Use .update() to reassign.`,
5748
7140
  });
5749
7141
  }
7142
+ const refused = clearRefusal(".remove()", attr, lacks);
7143
+ if (refused !== undefined) {
7144
+ return yield* new ValidationError({
7145
+ entityType,
7146
+ operation: "append.remove",
7147
+ cause: refused,
7148
+ });
7149
+ }
7150
+ }
7151
+ }
7152
+ // Removing a defaulted index composite re-materialises its default, as
7153
+ // an update's `.remove()` does (#133): the row would read back as the
7154
+ // default with its index keys dropped.
7155
+ const removedToDefault = defaultedFields.filter(([name]) => requestedRemoves?.has(name) === true && indexedDefaultFields().has(name));
7156
+ for (const [attr] of removedToDefault) {
7157
+ if (input[attr] !== undefined) {
7158
+ return yield* new ValidationError({
7159
+ entityType,
7160
+ operation: "append.remove",
7161
+ cause: `Attribute "${attr}" appears in both the append payload and .remove(). ` +
7162
+ `Choose one — either set the new value or remove the attribute.`,
7163
+ });
5750
7164
  }
5751
7165
  }
7166
+ const defaulted = removedToDefault.length === 0
7167
+ ? {}
7168
+ : yield* Schema.decodeUnknownEffect(Schema.Struct(Object.fromEntries(removedToDefault)))({}).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation: "append.default", cause })));
7169
+ const removes = [...(requestedRemoves ?? [])].filter((attr) => !removedToDefault.some(([name]) => name === attr));
7170
+ const namedRemoves = removes.length > 0 ? new Set(removes) : undefined;
5752
7171
  // Encode user input via appendInputSchema (see `put` for strategy).
5753
- const encodedInput = yield* encodeOrDecodeEncode(appendInputSchema, input, entityType, "append");
7172
+ const encodedInput = yield* encodeForWrite(appendInputSchema, removedToDefault.length === 0 ? input : { ...input, ...defaulted }, "append");
5754
7173
  const encoded = encodedInput;
5755
7174
  // After encoding, detect SET/REMOVE conflict — DynamoDB rejects an
5756
7175
  // UpdateExpression that touches the same attribute in SET and REMOVE.
5757
7176
  // The SET loop (below) skips entries with `undefined` values, so the
5758
7177
  // conflict is only real when the payload carries a non-undefined value
5759
7178
  // for an attribute also named in `.remove()`.
5760
- if (removedSet !== undefined) {
5761
- for (const attr of removedSet) {
7179
+ if (namedRemoves !== undefined) {
7180
+ for (const attr of namedRemoves) {
5762
7181
  if (attr in encoded &&
5763
7182
  encoded[attr] !== undefined) {
5764
7183
  return yield* new ValidationError({
@@ -5770,11 +7189,28 @@ const makeImpl = (config, precomputedData) => {
5770
7189
  }
5771
7190
  }
5772
7191
  }
7192
+ // A value with no stored form is an absent attribute, on the current item as on
7193
+ // the event item, so it's a `.remove()` of that field. A field left unset (an
7194
+ // optional `undefined`) isn't: it leaves the current item's attribute alone.
7195
+ const absentValues = Object.keys(encoded).filter((attr) => isEmptySet(encoded[attr]) ||
7196
+ (encoded[attr] === undefined && lacks.absentReading(attr) !== undefined));
7197
+ for (const attr of absentValues) {
7198
+ const refused = clearRefusal(".append()", attr, lacks);
7199
+ if (refused !== undefined) {
7200
+ return yield* new ValidationError({
7201
+ entityType,
7202
+ operation: "append",
7203
+ cause: refused,
7204
+ });
7205
+ }
7206
+ }
7207
+ const removedSet = absentValues.length === 0
7208
+ ? namedRemoves
7209
+ : new Set([...(namedRemoves ?? []), ...absentValues]);
5773
7210
  // Compose current-item primary key (pk + sk derived from PK/SK composites),
5774
7211
  // and the event key, before anything is marshalled: a value with no key
5775
- // text (`NaN`, `[EDD-9096]`) fails the append with a `ValidationError`,
5776
- // where the marshaller would refuse it as a defect. The event key's
5777
- // orderBy segment follows the setting, as `.history().where()` and
7212
+ // text (`NaN`, `[EDD-9096]`) fails the append with a `ValidationError`.
7213
+ // The event key's orderBy segment follows the setting, as `.history().where()` and
5778
7214
  // `liveRows` compose it (`eventOrderByValue`): with `escapeKeys: true` a
5779
7215
  // `NumberFromString` orderBy is the number, so events sort numerically;
5780
7216
  // off, the encoded text 1.36 wrote, which sorts "10" before "9".
@@ -5788,6 +7224,10 @@ const makeImpl = (config, precomputedData) => {
5788
7224
  eventSk: KeyComposer.composeEventSk(schema, currentSk, KeyComposer.eventOrderByValue(schema, encoded[orderByField], appendKeyForm[orderByField])),
5789
7225
  };
5790
7226
  });
7227
+ // Before anything is read or sent. `.append` marshals each value twice over
7228
+ // already: the current item's SET and the event item.
7229
+ yield* refuseUnstorable(encoded, "append");
7230
+ yield* refuseUncomposed(encoded, "append");
5791
7231
  const marshalledKey = toAttributeMap({
5792
7232
  [primary.pk.field]: pkValue,
5793
7233
  [primary.sk.field]: currentSk,
@@ -5815,7 +7255,7 @@ const makeImpl = (config, precomputedData) => {
5815
7255
  // never change, writing them on every append makes the first append
5816
7256
  // (where the row doesn't yet exist) materialise the row correctly.
5817
7257
  for (const [attr, val] of Object.entries(serialisedInput)) {
5818
- if (val === undefined)
7258
+ if (val === undefined || isEmptySet(val))
5819
7259
  continue;
5820
7260
  const nameKey = `#a${counter}`;
5821
7261
  const valKey = `:a${counter}`;
@@ -5836,13 +7276,54 @@ const makeImpl = (config, precomputedData) => {
5836
7276
  // it can't place (EDD-9092, #171) fails the append with a `ValidationError`.
5837
7277
  const appendNamed = Object.fromEntries(Object.entries(encoded).filter(([attr]) => !config.indexes.primary.pk.composite.includes(attr) &&
5838
7278
  !config.indexes.primary.sk.composite.includes(attr)));
5839
- const gsiUpdate = yield* composeKeysOrFail(entityType, "append", () => KeyComposer.composeGsiKeysForUpdatePolicyAware(schema, entityType, entityVersion, allIndexes, keyForm(appendNamed), keyForm(encoded), removedSet !== undefined ? { removedSet } : undefined));
7279
+ //
7280
+ // `createdAt` isn't in the input: an append that creates the row stamps it, and any other
7281
+ // keeps what's stored (`if_not_exists` below), which an UpdateItem can't tell apart. A half
7282
+ // holding it keeps its key the same way (`keptKeys`), on a row where what else the half holds
7283
+ // is what this append writes (`keptValues`). Anywhere else the rejected write returns the row
7284
+ // to compose from (`DESIGN.md` §7, "An upsert over a value it keeps").
7285
+ const stampedCreatedAt = generateTimestamp(systemFields.createdAtEncoding, now);
7286
+ const createdAtKeyed = systemFields.createdAt !== null && indexCompositeFields().has(systemFields.createdAt);
7287
+ const composeAppendKeys = (createdAt) => composeKeysOrFail(entityType, "append", () => KeyComposer.composeGsiKeysForUpdatePolicyAware(schema, entityType, entityVersion, allIndexes, keyForm(appendNamed), keyForm(createdAtKeyed ? { ...encoded, [systemFields.createdAt]: createdAt } : encoded), removedSet !== undefined ? { removedSet } : undefined));
7288
+ const gsiUpdate = yield* composeAppendKeys(stampedCreatedAt);
7289
+ const keptKeys = new Set();
7290
+ const keptValues = new Map();
7291
+ if (createdAtKeyed) {
7292
+ for (const [indexName, index] of Object.entries(allIndexes)) {
7293
+ if (indexName === "primary")
7294
+ continue;
7295
+ for (const [field, composites] of halvesOf(index)) {
7296
+ if (!(field in gsiUpdate.sets) || !composites.includes(systemFields.createdAt)) {
7297
+ continue;
7298
+ }
7299
+ keptKeys.add(field);
7300
+ for (const attr of composites) {
7301
+ if (attr !== systemFields.createdAt && !isPrimaryComposite(attr)) {
7302
+ keptValues.set(resolveDbName(attr), toAttributeValue(serialisedInput[attr]));
7303
+ }
7304
+ }
7305
+ }
7306
+ }
7307
+ }
7308
+ const gsiValueNames = {};
7309
+ const keptKeyNames = [];
7310
+ // Composed from the stored row, a kept key is written like any other.
7311
+ const writtenKeyClauses = new Map();
5840
7312
  for (const [field, value] of Object.entries(gsiUpdate.sets)) {
5841
7313
  const nameKey = `#a${counter}`;
5842
7314
  const valKey = `:a${counter}`;
5843
7315
  names[nameKey] = field;
5844
7316
  values[valKey] = toAttributeValue(value);
5845
- setClauses.push(`${nameKey} = ${valKey}`);
7317
+ gsiValueNames[field] = valKey;
7318
+ if (keptKeys.has(field)) {
7319
+ const clause = `${nameKey} = if_not_exists(${nameKey}, ${valKey})`;
7320
+ setClauses.push(clause);
7321
+ writtenKeyClauses.set(clause, `${nameKey} = ${valKey}`);
7322
+ keptKeyNames.push(nameKey);
7323
+ }
7324
+ else {
7325
+ setClauses.push(`${nameKey} = ${valKey}`);
7326
+ }
5846
7327
  counter++;
5847
7328
  }
5848
7329
  const appendRemoveClauses = [];
@@ -5879,8 +7360,8 @@ const makeImpl = (config, precomputedData) => {
5879
7360
  if (systemFields.createdAt) {
5880
7361
  const nameKey = `#a${counter}`;
5881
7362
  const valKey = `:a${counter}`;
5882
- names[nameKey] = systemFields.createdAt;
5883
- values[valKey] = toAttributeValue(generateTimestamp(systemFields.createdAtEncoding, now));
7363
+ names[nameKey] = resolveDbName(systemFields.createdAt);
7364
+ values[valKey] = toAttributeValue(stampedCreatedAt);
5884
7365
  setClauses.push(`${nameKey} = if_not_exists(${nameKey}, ${valKey})`);
5885
7366
  counter++;
5886
7367
  }
@@ -5895,10 +7376,12 @@ const makeImpl = (config, precomputedData) => {
5895
7376
  // The user's condition is ANDed after the CAS, its names and values
5896
7377
  // after the CAS's, as 1.36 sent them.
5897
7378
  const uc = userCondition !== undefined ? compileCondition(userCondition, resolveDbName) : undefined;
5898
- const updateExpression = [
5899
- ...(setClauses.length > 0 ? [`SET ${setClauses.join(", ")}`] : []),
7379
+ const expressionOf = (clauses) => [
7380
+ ...(clauses.length > 0 ? [`SET ${clauses.join(", ")}`] : []),
5900
7381
  ...(appendRemoveClauses.length > 0 ? [`REMOVE ${appendRemoveClauses.join(", ")}`] : []),
5901
7382
  ].join(" ");
7383
+ const updateExpression = expressionOf(setClauses);
7384
+ const composedExpression = expressionOf(setClauses.map((clause) => writtenKeyClauses.get(clause) ?? clause));
5902
7385
  // ---------- Build Put of event item ----------
5903
7386
  // `encoded` is already in wire-form via Schema.encode; no extra
5904
7387
  // serialisation step is required for the Put.
@@ -5931,27 +7414,29 @@ const makeImpl = (config, precomputedData) => {
5931
7414
  // treatment as enrichment fields outside `appendInput`. By design,
5932
7415
  // `appendInput` cannot include sparse fields, so this is defensive.)
5933
7416
  if (hasSparseFields) {
5934
- for (const fieldName of Object.keys(sparseFields)) {
7417
+ for (const fieldName of Object.keys(sparseFields))
5935
7418
  delete eventItem[fieldName];
5936
- // Also strip any flattened bucket attrs that might have leaked in
5937
- // via a future code change — defensive cleanup.
5938
- const prefixWithDelim = `${sparseFields[fieldName].prefix}#`;
5939
- for (const k of Object.keys(eventItem)) {
5940
- if (k.startsWith(prefixWithDelim))
5941
- delete eventItem[k];
5942
- }
7419
+ // Also strip any flattened bucket attrs that might have leaked in
7420
+ // via a future code change — defensive cleanup.
7421
+ for (const k of Object.keys(eventItem)) {
7422
+ if (sparseEntries.entryOf(k) !== undefined)
7423
+ delete eventItem[k];
5943
7424
  }
5944
7425
  }
5945
7426
  const marshalledEventItem = toAttributeMap(eventItem);
5946
7427
  // ---------- Execute TransactWriteItems ----------
5947
7428
  /** One attempt: the UpdateItem guarded by `cas` (and the user's condition), then the event Put. */
5948
- const send = (cas) => {
7429
+ const send = (cas, expression = updateExpression) => {
5949
7430
  const appendItems = [
5950
7431
  {
5951
7432
  Update: {
5952
7433
  TableName: tableName,
5953
7434
  Key: marshalledKey,
5954
- UpdateExpression: updateExpression,
7435
+ UpdateExpression: expression,
7436
+ // A rejection hands back the row a kept key has to be composed from.
7437
+ ...(keptKeyNames.length > 0 && {
7438
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
7439
+ }),
5955
7440
  ConditionExpression: uc
5956
7441
  ? `(${cas.expression}) AND (${uc.expression})`
5957
7442
  : cas.expression,
@@ -6033,8 +7518,10 @@ const makeImpl = (config, precomputedData) => {
6033
7518
  }
6034
7519
  return { current: yield* decodeCurrent(followUp.Item) };
6035
7520
  });
6036
- if (compositeKeyFormKind(schemas.inputSchema, orderByField) ===
6037
- "type-numeric") {
7521
+ const readCurrentRow = () => client
7522
+ .getItem({ TableName: tableName, Key: marshalledKey, ConsistentRead: true })
7523
+ .pipe(Effect.map((result) => result.Item));
7524
+ const appendOverRead = (first) => Effect.gen(function* () {
6038
7525
  // A string-encoded numeric orderBy (`NumberFromString`,
6039
7526
  // `BigIntFromString`) is stored as `S`, and DynamoDB compares `S` as
6040
7527
  // text: `#_tsob < :_tsNewOb` refused 10 after 9 and took 9 after 10
@@ -6043,16 +7530,15 @@ const makeImpl = (config, precomputedData) => {
6043
7530
  // and guards the write on the stored value it read (`=`, exact on
6044
7531
  // text). A concurrent append moves the stored value and cancels the
6045
7532
  // write; the append then reads again and decides again, up to
6046
- // `APPEND_GUARD_ATTEMPTS` attempts in all.
7533
+ // `APPEND_GUARD_ATTEMPTS` attempts in all. A key composed from a stored
7534
+ // `createdAt` needs the same read, and the same guard: an append that found
7535
+ // no item must not write a key for a `createdAt` another writer just created.
6047
7536
  const attempted = appendKeyForm[orderByField];
6048
7537
  const storedKeyForm = (stored) => Effect.try({
6049
7538
  try: () => keyForm({ [orderByField]: fromAttributeMap({ v: stored }).v })[orderByField],
6050
7539
  catch: (cause) => new ValidationError({ entityType, operation: "append", cause }),
6051
7540
  });
6052
- const read = () => client
6053
- .getItem({ TableName: tableName, Key: marshalledKey, ConsistentRead: true })
6054
- .pipe(Effect.map((result) => result.Item));
6055
- let current = yield* read();
7541
+ let current = first ?? (yield* readCurrentRow());
6056
7542
  for (let attempt = 1;; attempt++) {
6057
7543
  const storedOb = current?.[orderByName];
6058
7544
  // The CAS, decided on the numbers: an existing item takes the
@@ -6064,6 +7550,13 @@ const makeImpl = (config, precomputedData) => {
6064
7550
  ? staleAppend(Option.none())
6065
7551
  : staleAppend(Option.some(yield* decodeCurrent(current)));
6066
7552
  }
7553
+ if (createdAtKeyed) {
7554
+ const stored = current?.[resolveDbName(systemFields.createdAt)];
7555
+ const keys = yield* composeAppendKeys(stored === undefined ? stampedCreatedAt : fromAttributeMap({ v: stored }).v);
7556
+ for (const [field, value] of Object.entries(keys.sets)) {
7557
+ values[gsiValueNames[field]] = toAttributeValue(value);
7558
+ }
7559
+ }
6067
7560
  const outcome = yield* send(current === undefined
6068
7561
  ? {
6069
7562
  expression: "attribute_not_exists(#_tspk)",
@@ -6074,10 +7567,10 @@ const makeImpl = (config, precomputedData) => {
6074
7567
  expression: "#_tsob = :_tsObserved",
6075
7568
  names: { "#_tsob": orderByName },
6076
7569
  values: { ":_tsObserved": storedOb },
6077
- });
7570
+ }, composedExpression);
6078
7571
  if (!outcome.stale)
6079
7572
  return yield* applied;
6080
- const again = yield* read();
7573
+ const again = yield* readCurrentRow();
6081
7574
  const moved = (current === undefined) !== (again === undefined) ||
6082
7575
  (again !== undefined && !attributeValueEquals(again[orderByName], storedOb));
6083
7576
  if (!moved) {
@@ -6100,15 +7593,54 @@ const makeImpl = (config, precomputedData) => {
6100
7593
  return yield* Effect.fail(outcome.error);
6101
7594
  current = again;
6102
7595
  }
7596
+ });
7597
+ if (compositeKeyFormKind(schemas.inputSchema, orderByField) ===
7598
+ "type-numeric") {
7599
+ return yield* appendOverRead();
6103
7600
  }
6104
7601
  // Any other orderBy compares in DynamoDB as it orders: numbers as
6105
- // numbers, ISO-8601 dates and strings as text.
7602
+ // numbers, ISO-8601 dates and strings as text. A row whose key stays must have one, or
7603
+ // `if_not_exists` would give it a key composed from this append's stamp, and one that still
7604
+ // says what this append writes.
7605
+ const keptValueGuards = [...keptValues].map(([name, value], index) => ({
7606
+ name,
7607
+ value,
7608
+ nameKey: `#_tsk${index}`,
7609
+ valKey: `:_tsk${index}`,
7610
+ }));
7611
+ const stays = [
7612
+ ...keptKeyNames.map((nameKey) => `attribute_exists(${nameKey})`),
7613
+ ...keptValueGuards.map((guard) => `${guard.nameKey} = ${guard.valKey}`),
7614
+ ];
6106
7615
  const cas = {
6107
- expression: "attribute_not_exists(#_tspk) OR #_tsob < :_tsNewOb",
6108
- names: { "#_tspk": pkName, "#_tsob": orderByName },
6109
- values: { ":_tsNewOb": toAttributeValue(newObValue) },
7616
+ expression: stays.length === 0
7617
+ ? "attribute_not_exists(#_tspk) OR #_tsob < :_tsNewOb"
7618
+ : `attribute_not_exists(#_tspk) OR (#_tsob < :_tsNewOb AND ${stays.join(" AND ")})`,
7619
+ names: {
7620
+ "#_tspk": pkName,
7621
+ "#_tsob": orderByName,
7622
+ ...Object.fromEntries(keptValueGuards.map((guard) => [guard.nameKey, guard.name])),
7623
+ },
7624
+ values: {
7625
+ ":_tsNewOb": toAttributeValue(newObValue),
7626
+ ...Object.fromEntries(keptValueGuards.map((guard) => [guard.valKey, guard.value])),
7627
+ },
6110
7628
  };
6111
7629
  const transactResult = yield* send(cas);
7630
+ // The rejection returned the row, whatever rejected it. One without the key, or whose values
7631
+ // the key can't stay over, has the key composed from its `createdAt`. A row written before the
7632
+ // key could be composed needs that once: from then on it has one.
7633
+ const returnedRow = transactResult.stale && isAwsTransactionCancelled(transactResult.error.cause)
7634
+ ? transactResult.error.cause.CancellationReasons?.[0]?.Item
7635
+ : undefined;
7636
+ const rejectedRow = transactResult.stale && keptKeyNames.length > 0
7637
+ ? (returnedRow ?? (yield* readCurrentRow()))
7638
+ : undefined;
7639
+ if (rejectedRow !== undefined &&
7640
+ ([...keptKeys].some((key) => rejectedRow[key] === undefined) ||
7641
+ keptValueGuards.some((guard) => !attributeValueEquals(rejectedRow[guard.name], guard.value)))) {
7642
+ return yield* appendOverRead(rejectedRow);
7643
+ }
6112
7644
  // -----------------------------------------------------------------
6113
7645
  // skipFollowUp branch — no GetItem, cannot decode current, cannot
6114
7646
  // disambiguate CAS vs user-condition cancellation. Both modes
@@ -6128,11 +7660,13 @@ const makeImpl = (config, precomputedData) => {
6128
7660
  // the CAS fails only over an item, and a read missing one just
6129
7661
  // created would report the user's condition rejecting its creation.
6130
7662
  // -----------------------------------------------------------------
6131
- const followUp = yield* client.getItem({
6132
- TableName: tableName,
6133
- Key: marshalledKey,
6134
- ConsistentRead: true,
6135
- });
7663
+ const followUp = rejectedRow !== undefined
7664
+ ? { Item: rejectedRow }
7665
+ : yield* client.getItem({
7666
+ TableName: tableName,
7667
+ Key: marshalledKey,
7668
+ ConsistentRead: true,
7669
+ });
6136
7670
  if (!followUp.Item) {
6137
7671
  // No item: the CAS holds for a missing one, so with a condition the
6138
7672
  // user's rejected the append creating it — whatever the orderBy type
@@ -6176,7 +7710,7 @@ const makeImpl = (config, precomputedData) => {
6176
7710
  // ---------------------------------------------------------------------------
6177
7711
  // The public `append`: the core as the named operation (consumed capacity, #174).
6178
7712
  const append = (input, givenCondition, skipFollowUp = false, removeAttrs) => Capacity.operation("Entity.append", { target: entityType }, appendCore(input, givenCondition, skipFollowUp, removeAttrs));
6179
- const history = (key) => {
7713
+ const historyQuery = (key) => {
6180
7714
  if (!timeSeriesConfig) {
6181
7715
  throw new Error(`[EDD-9010] Entity "${entityType}": .history() requires timeSeries config on the entity.`);
6182
7716
  }
@@ -6197,7 +7731,7 @@ const makeImpl = (config, precomputedData) => {
6197
7731
  entityType,
6198
7732
  operation: "history.decode",
6199
7733
  cause,
6200
- })));
7734
+ })), missingKeyOnDefect(raw, "history.decode"));
6201
7735
  });
6202
7736
  };
6203
7737
  return Query.make({
@@ -6213,6 +7747,11 @@ const makeImpl = (config, precomputedData) => {
6213
7747
  keyFields: [primary.pk.field, primary.sk.field],
6214
7748
  }).pipe(Query.where({ beginsWith: prefix }));
6215
7749
  };
7750
+ /**
7751
+ * The query `build` makes, or one refused for a key value it can't compose: building
7752
+ * a query has no error channel, so its terminals fail instead.
7753
+ */
7754
+ const refusingQuery = (name, build) => Query.orRefusal({ name, target: entityType }, build, (refusal) => Query.refused(undefined, refusal));
6216
7755
  // ---------------------------------------------------------------------------
6217
7756
  // query namespace
6218
7757
  // ---------------------------------------------------------------------------
@@ -6223,10 +7762,12 @@ const makeImpl = (config, precomputedData) => {
6223
7762
  // The bound definition: a Z-order half carries its layout (#171).
6224
7763
  const indexDef = data.initialIndexes[indexName] ?? config.indexes[indexName];
6225
7764
  const zorder = KeyComposer.isZOrderHalf(indexDef.sk);
6226
- queryNamespace[indexName] = (rawPk) => {
7765
+ const indexQuery = (rawPk) => {
6227
7766
  // Normalise composites to their key form before composing — same rule
6228
- // and same function the write path uses (see `CompositeCodec`).
6229
- const pkKeyForm = keyForm(rawPk);
7767
+ // and same function the write path uses (see `CompositeCodec`). They are
7768
+ // the caller's DOMAIN values: the key `put` wrote for one is the key form
7769
+ // of the value it stores.
7770
+ const pkKeyForm = domainKeyForm(rawPk);
6230
7771
  // One partition, or a sharded index's several (#183).
6231
7772
  const read = KeyComposer.composeReadPartitions(schema, entityType, indexDef, pkKeyForm);
6232
7773
  const pkValue = read.partitions[0];
@@ -6273,6 +7814,7 @@ const makeImpl = (config, precomputedData) => {
6273
7814
  : query;
6274
7815
  return pinned;
6275
7816
  };
7817
+ queryNamespace[indexName] = (rawPk) => Query.orRefusal({ name: "Entity.query", target: entityType }, () => indexQuery(rawPk), (refusal) => Query.refused(indexDef.index, refusal));
6276
7818
  }
6277
7819
  // ---------------------------------------------------------------------------
6278
7820
  // scan operation
@@ -6326,7 +7868,7 @@ const makeImpl = (config, precomputedData) => {
6326
7868
  // ---------------------------------------------------------------------------
6327
7869
  // versions operation
6328
7870
  // ---------------------------------------------------------------------------
6329
- const versions = (key) => {
7871
+ const versionsQuery = (key) => {
6330
7872
  const encodedKey = keyForm(encodeKeySync(key));
6331
7873
  const primary = config.indexes.primary;
6332
7874
  const pkValue = KeyComposer.composePk(schema, entityType, primary, keyForm(encodedKey));
@@ -6437,9 +7979,9 @@ const makeImpl = (config, precomputedData) => {
6437
7979
  entityType,
6438
7980
  operation: "deleted.get.decode",
6439
7981
  cause,
6440
- })));
7982
+ })), missingKeyOnDefect(raw, "deleted.get.decode"));
6441
7983
  }), self, key);
6442
- const deletedList = (key) => {
7984
+ const deletedListQuery = (key) => {
6443
7985
  const encodedKey = keyForm(encodeKeySync(key));
6444
7986
  const primary = config.indexes.primary;
6445
7987
  const pkValue = KeyComposer.composePk(schema, entityType, primary, keyForm(encodedKey));
@@ -6460,7 +8002,7 @@ const makeImpl = (config, precomputedData) => {
6460
8002
  entityType,
6461
8003
  operation: "deleted.list.decode",
6462
8004
  cause,
6463
- })));
8005
+ })), missingKeyOnDefect(raw, "deleted.list.decode"));
6464
8006
  });
6465
8007
  };
6466
8008
  return Query.make({
@@ -6588,7 +8130,7 @@ const makeImpl = (config, precomputedData) => {
6588
8130
  const sentinelConstraints = [];
6589
8131
  if (config.unique && Object.keys(config.unique).length > 0) {
6590
8132
  for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
6591
- const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, restoredDomain);
8133
+ const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, restoredDomain, readSentinelValue);
6592
8134
  if (!sentinel)
6593
8135
  continue;
6594
8136
  sentinelConstraints.push(constraintName);
@@ -6802,7 +8344,7 @@ const makeImpl = (config, precomputedData) => {
6802
8344
  for (const holder of holders) {
6803
8345
  const holderDomain = toDomainView(fromAttributeMap(holder));
6804
8346
  for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
6805
- const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, holderDomain);
8347
+ const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, holderDomain, readSentinelValue);
6806
8348
  if (!sentinel)
6807
8349
  continue;
6808
8350
  held.set(`${sentinel.key.pk}\u0000${sentinel.key.sk}`, sentinel.key);
@@ -6820,7 +8362,9 @@ const makeImpl = (config, precomputedData) => {
6820
8362
  }
6821
8363
  // Batch delete in chunks of 25. `UnprocessedItems` are retried with
6822
8364
  // `Batch.write`'s backoff; what the purge had deleted is always
6823
- // stated exactly, whether a request is rejected or retries run out.
8365
+ // stated exactly, whether a request is rejected or retries run out. By count alone: 25
8366
+ // stored keys (at most 2048 + 1024 bytes each, so at most about 0.5 MB as JSON) can't
8367
+ // reach the 16 MB request limit.
6824
8368
  let deleted = 0;
6825
8369
  const deletedSoFar = () => deleted === 0
6826
8370
  ? "the purge had deleted none of the partition's items"
@@ -6921,14 +8465,67 @@ const makeImpl = (config, precomputedData) => {
6921
8465
  const keyFormsOf = () => Object.entries(allIndexes).some(([name, index]) => name !== "primary" && (isTableKeyField(index.pk.field) || isTableKeyField(index.sk.field)))
6922
8466
  ? [...KeyText136.forms(schema), KeyText136.invertedForm137(schema)]
6923
8467
  : KeyText136.forms(schema);
8468
+ /** The fields the primary key's text is composed from. */
8469
+ const primaryTextFields = [
8470
+ ...new Set([...config.indexes.primary.pk.composite, ...config.indexes.primary.sk.composite]),
8471
+ ];
8472
+ /**
8473
+ * The reading of `record`, a key-form record, whose `compose` gives `stored`: each of `fields`
8474
+ * holding a number or a bigint as its own kind or as the other one, the other read from the
8475
+ * digits `row` stored (`CompositeCodec.kindReadingOf`): a field that stored both kinds composed
8476
+ * each value's own kind's text. Each value stays in key form (`kindKeyForm`), a numeric value
8477
+ * given as the kind a release stored. `record` itself when it composes `stored`, at the cost of
8478
+ * that one composition; otherwise one composition per field, never one per combination.
8479
+ */
8480
+ const kindReading = (row, record, fields, compose, stored) => kindReadingOf(record, fields, (field) => row[resolveDbName(field)]?.N, (reading) => compose(reading.record, reading.asOther), stored);
8481
+ /**
8482
+ * A table key as one text, for {@link kindReading}: both halves, neither running into the other.
8483
+ * {@link keySegments} gives it in its halves.
8484
+ */
8485
+ const storedKeyText = (key) => JSON.stringify([key[rekeyPk], key[rekeySk]]);
8486
+ /**
8487
+ * A key's text ({@link storedKeyText}) in its two halves, which concatenate to it: a composite in
8488
+ * both halves is read as one kind in both (`CompositeCodec.kindReadingOf`).
8489
+ */
8490
+ const keySegments = (pk, sk) => [
8491
+ `[${JSON.stringify(pk)}`,
8492
+ `,${JSON.stringify(sk)}]`,
8493
+ ];
8494
+ /** Bytes as text, one character a byte, for {@link kindReading}. */
8495
+ const bytesText = (bytes) => String.fromCharCode(...bytes);
8496
+ /**
8497
+ * A row's values in the key form, then in 1.39.0's where that differs (`keyForm139`): the
8498
+ * records each key text a row may be stored under is composed from.
8499
+ */
8500
+ const rowKeyForms = (values) => {
8501
+ const rowKeyForm = keyForm(values);
8502
+ const rowKeyForm139 = keyForm139(values);
8503
+ return Object.keys(rowKeyForm139).some((attr) => !Object.is(rowKeyForm139[attr], Object.hasOwn(rowKeyForm, attr) ? rowKeyForm[attr] : undefined))
8504
+ ? [rowKeyForm, rowKeyForm139]
8505
+ : [rowKeyForm];
8506
+ };
8507
+ /** What a row's sort key says it is, for a row whose values compose no key to say it by. */
8508
+ const storedRowKind = (sk) => {
8509
+ const versions = DynamoSchema.composeVersionKeyPrefix(schema, entityType);
8510
+ if (sk.startsWith(versions) && /^(?:.*#)?\d{7,}$/.test(sk.slice(versions.length))) {
8511
+ return "snapshot";
8512
+ }
8513
+ const tombstones = DynamoSchema.composeDeletedKeyPrefix(schema, entityType);
8514
+ if (sk.startsWith(tombstones) &&
8515
+ /^(?:.*#)?\d{4}-\d\d-\d\dT[^#]*$/.test(sk.slice(tombstones.length))) {
8516
+ return "tombstone";
8517
+ }
8518
+ return timeSeriesConfig !== undefined && sk.includes("#e#") ? "event" : "item";
8519
+ };
6924
8520
  /**
6925
8521
  * Where a row of the entity belongs now and whether it is stored where some key text put it,
6926
- * from its values and the layout of its sort key: `undefined` for a row whose values compose no
6927
- * key now (`NaN` under `escapeKeys: true`), or of no layout the entity writes. A history row
6928
- * keeps its layout: one an earlier release wrote without an item segment (#133) moves only its
6929
- * partition key.
8522
+ * from its values and the layout of its sort key: `uncomposable` with what refused them for a
8523
+ * row holding a composite whose value has no key text (`NaN`) or that no form of its schema takes
8524
+ * (`EDD-9050`), and `undefined` for a row missing one, or of no layout the entity writes. A
8525
+ * history row keeps its layout: one an earlier release wrote without an item segment (#133)
8526
+ * moves only its partition key.
6930
8527
  */
6931
- const rowTargets = (row) => {
8528
+ const rowPlaces = (row) => {
6932
8529
  if (row.__edd_e__?.S !== entityType)
6933
8530
  return undefined;
6934
8531
  const stored = storedKeyOf(row);
@@ -6937,60 +8534,128 @@ const makeImpl = (config, precomputedData) => {
6937
8534
  try {
6938
8535
  const primary = config.indexes.primary;
6939
8536
  const values = toDomainView(fromAttributeMap(row));
6940
- const rowKeyForm = keyForm(values);
6941
8537
  const live = composePrimaryKey(values);
6942
- const places = keyFormsOf().flatMap((form) => {
6943
- try {
6944
- const key = KeyText136.composeAt(form, entityType, entityVersion, primary, rowKeyForm);
6945
- return [{ form, key: key }];
6946
- }
6947
- catch {
6948
- // Values with no key text under this form.
6949
- return [];
6950
- }
6951
- });
6952
- const lives = [live, ...places.map((place) => place.key)].filter((key, i, all) => all.findIndex((other) => sameStoredKey(other, key)) === i);
6953
- const targets = (kind, at) => ({
6954
- kind,
6955
- current: at({ pk: schema, sk: schema }, live),
6956
- old: places.some(({ form, key }) => sameStoredKey(stored, at(form, key)))
6957
- ? stored
6958
- : undefined,
6959
- live,
6960
- lives,
8538
+ const rowKeyForm = keyForm(values);
8539
+ // Each reading of the values a key text was composed from: the key form, and the one up to
8540
+ // 1.39.0 (`keyForm139`), which keyed a codec whose `encode` takes its own output by its
8541
+ // stored text encoded once more.
8542
+ const readings = rowKeyForms(values);
8543
+ const now = { pk: schema, sk: schema };
8544
+ /**
8545
+ * Is `key` where `atOf(reading)` puts a row of some kind reading of some reading of the
8546
+ * values, under some form?
8547
+ */
8548
+ const placed = (key, atOf, fields, among = readings) => among.some((reading) => {
8549
+ const at = atOf(reading);
8550
+ return keyFormsOf().some((form) => kindReading(row, reading, fields, (kindKeyForm) => {
8551
+ const placedAt = at(form, KeyText136.composeAt(form, entityType, entityVersion, primary, kindKeyForm), kindKeyForm);
8552
+ return keySegments(placedAt[rekeyPk], placedAt[rekeySk]);
8553
+ }, storedKeyText(key)) !== undefined);
6961
8554
  });
6962
- if (lives.some((key) => sameStoredKey(stored, key))) {
6963
- return targets("item", (_, key) => key);
6964
- }
6965
- const sk = stored[rekeySk];
6966
- const versions = DynamoSchema.composeVersionKeyPrefix(schema, entityType);
6967
- if (sk.startsWith(versions) && /^(?:.*#)?\d{7,}$/.test(sk.slice(versions.length))) {
6968
- if (!sk.slice(versions.length).includes("#")) {
6969
- return targets("snapshot", (_, key) => keyAt(key[rekeyPk], sk));
6970
- }
6971
- const version = versionOfSk(sk);
6972
- return targets("snapshot", (_, key) => keyAt(key[rekeyPk], DynamoSchema.composeVersionKey(schema, entityType, version, historyKeyOptions(key[rekeySk]))));
6973
- }
6974
- const tombstones = DynamoSchema.composeDeletedKeyPrefix(schema, entityType);
6975
- if (sk.startsWith(tombstones) &&
6976
- /^(?:.*#)?\d{4}-\d\d-\d\dT[^#]*$/.test(sk.slice(tombstones.length))) {
6977
- if (!sk.slice(tombstones.length).includes("#")) {
6978
- return targets("tombstone", (_, key) => keyAt(key[rekeyPk], sk));
6979
- }
6980
- const timestamp = sk.slice(sk.lastIndexOf("#") + 1);
6981
- return targets("tombstone", (_, key) => keyAt(key[rekeyPk], DynamoSchema.composeDeletedKey(schema, entityType, timestamp, historyKeyOptions(key[rekeySk]))));
8555
+ const itemAt = () => (_, at) => at;
8556
+ const isLive = (key) => sameStoredKey(key, live) || placed(key, itemAt, primaryTextFields);
8557
+ const targets = (kind, atOf, fields = primaryTextFields) => {
8558
+ const current = atOf(rowKeyForm)(now, live, rowKeyForm);
8559
+ const under139 = readings.length > 1 && !placed(stored, atOf, fields, [rowKeyForm]);
8560
+ return {
8561
+ kind,
8562
+ current,
8563
+ old: sameStoredKey(stored, current) || placed(stored, atOf, fields) ? stored : undefined,
8564
+ live,
8565
+ isLive,
8566
+ elsewhere: !under139
8567
+ ? []
8568
+ : keyFormsOf().flatMap((form) => {
8569
+ try {
8570
+ const at = atOf(rowKeyForm)(form, KeyText136.composeAt(form, entityType, entityVersion, primary, rowKeyForm), rowKeyForm);
8571
+ return sameStoredKey(at, current) || sameStoredKey(at, stored) ? [] : [at];
8572
+ }
8573
+ catch {
8574
+ return [];
8575
+ }
8576
+ }),
8577
+ };
8578
+ };
8579
+ const layoutOf = (reading) => historyLayout(stored[rekeySk], values, reading);
8580
+ const history = layoutOf(rowKeyForm);
8581
+ // A history layout's place, from the reading a key text was composed from.
8582
+ const historyAt = (reading) => layoutOf(reading).at;
8583
+ if (sameStoredKey(stored, live))
8584
+ return targets("item", itemAt);
8585
+ // A history row under its current key, which nothing else composes.
8586
+ if (history !== undefined && sameStoredKey(stored, history.at(now, live, rowKeyForm))) {
8587
+ return targets(history.kind, historyAt, history.fields);
8588
+ }
8589
+ if (isLive(stored))
8590
+ return targets("item", itemAt);
8591
+ return history === undefined ? undefined : targets(history.kind, historyAt, history.fields);
8592
+ }
8593
+ catch (error) {
8594
+ const message = error instanceof Error ? error.message : String(error);
8595
+ return Capacity.isRefusedValue(error) || message.startsWith("[EDD-9050]")
8596
+ ? { uncomposable: message }
8597
+ : undefined;
8598
+ }
8599
+ };
8600
+ /**
8601
+ * A history row's kind by the layout of its sort key `sk`, with where a row of that kind is for
8602
+ * an item at a key ({@link rowPlaces}), and the fields that composes it from; `undefined` for a
8603
+ * sort key of no history layout, or an event missing its `orderBy` value.
8604
+ */
8605
+ const historyLayout = (sk, values, rowKeyForm) => {
8606
+ const versions = DynamoSchema.composeVersionKeyPrefix(schema, entityType);
8607
+ if (sk.startsWith(versions) && /^(?:.*#)?\d{7,}$/.test(sk.slice(versions.length))) {
8608
+ if (!sk.slice(versions.length).includes("#")) {
8609
+ return {
8610
+ kind: "snapshot",
8611
+ at: (_, key) => keyAt(key[rekeyPk], sk),
8612
+ fields: primaryTextFields,
8613
+ };
6982
8614
  }
6983
- if (timeSeriesConfig !== undefined) {
6984
- const orderBy = timeSeriesConfig.orderBy;
6985
- if (values[orderBy] === undefined || values[orderBy] === null)
6986
- return undefined;
6987
- return targets("event", (form, key) => keyAt(key[rekeyPk], KeyComposer.composeEventSk(form.sk, key[rekeySk], KeyComposer.eventOrderByValue(form.sk, values[orderBy], rowKeyForm[orderBy]))));
8615
+ const version = versionOfSk(sk);
8616
+ return {
8617
+ kind: "snapshot",
8618
+ at: (_, key) => keyAt(key[rekeyPk], DynamoSchema.composeVersionKey(schema, entityType, version, historyKeyOptions(key[rekeySk]))),
8619
+ fields: primaryTextFields,
8620
+ };
8621
+ }
8622
+ const tombstones = DynamoSchema.composeDeletedKeyPrefix(schema, entityType);
8623
+ if (sk.startsWith(tombstones) &&
8624
+ /^(?:.*#)?\d{4}-\d\d-\d\dT[^#]*$/.test(sk.slice(tombstones.length))) {
8625
+ if (!sk.slice(tombstones.length).includes("#")) {
8626
+ return {
8627
+ kind: "tombstone",
8628
+ at: (_, key) => keyAt(key[rekeyPk], sk),
8629
+ fields: primaryTextFields,
8630
+ };
6988
8631
  }
6989
- return undefined;
8632
+ const timestamp = sk.slice(sk.lastIndexOf("#") + 1);
8633
+ return {
8634
+ kind: "tombstone",
8635
+ at: (_, key) => keyAt(key[rekeyPk], DynamoSchema.composeDeletedKey(schema, entityType, timestamp, historyKeyOptions(key[rekeySk]))),
8636
+ fields: primaryTextFields,
8637
+ };
6990
8638
  }
6991
- catch {
8639
+ if (timeSeriesConfig === undefined)
6992
8640
  return undefined;
6993
- }
8641
+ const orderBy = timeSeriesConfig.orderBy;
8642
+ if (values[orderBy] === undefined || values[orderBy] === null)
8643
+ return undefined;
8644
+ // What `append` composed the key from: the Encoded value it stored, which a `bigint`
8645
+ // reads back from as a number while it's a safe integer.
8646
+ const appended = readSentinelValue(orderBy, values[orderBy]) ?? values[orderBy];
8647
+ return {
8648
+ kind: "event",
8649
+ at: (form, key, record) => keyAt(key[rekeyPk], KeyComposer.composeEventSk(form.sk, key[rekeySk], KeyComposer.eventOrderByValue(form.sk,
8650
+ // As the other numeric kind, the value is its own Encoded form.
8651
+ record[orderBy] === rowKeyForm[orderBy] ? appended : record[orderBy], record[orderBy]))),
8652
+ fields: [...new Set([...primaryTextFields, orderBy])],
8653
+ };
8654
+ };
8655
+ /** {@link rowPlaces}, for a row whose values compose its keys. */
8656
+ const rowTargets = (row) => {
8657
+ const places = rowPlaces(row);
8658
+ return places === undefined || "uncomposable" in places ? undefined : places;
6994
8659
  };
6995
8660
  /**
6996
8661
  * Who holds `at`, a row's current key: the same row (stored under both
@@ -7041,6 +8706,30 @@ const makeImpl = (config, precomputedData) => {
7041
8706
  ? { unchanged: 1 }
7042
8707
  : {};
7043
8708
  });
8709
+ /**
8710
+ * The first row at one of `elsewhere` that moves to `to`, and that row as it would be there.
8711
+ */
8712
+ const movingThereToo = (ctx, elsewhere, to) => Effect.gen(function* () {
8713
+ const client = yield* Capacity.client;
8714
+ for (const key of elsewhere) {
8715
+ const { Item: row } = yield* client.getItem({
8716
+ TableName: ctx.tableName,
8717
+ Key: toAttributeMap(key),
8718
+ ConsistentRead: true,
8719
+ });
8720
+ if (row === undefined)
8721
+ continue;
8722
+ const plan = isValueless(row) ? valuelessMove(row, { pk: rekeyPk, sk: rekeySk }) : undefined;
8723
+ if (typeof plan === "object" && sameStoredKey(plan.to, to)) {
8724
+ return { row, at: plan.moved(row) };
8725
+ }
8726
+ const targets = plan === undefined ? rowTargets(row) : undefined;
8727
+ if (targets !== undefined && sameStoredKey(targets.current, to)) {
8728
+ return { row, at: { ...row, ...toAttributeMap(to) } };
8729
+ }
8730
+ }
8731
+ return undefined;
8732
+ });
7044
8733
  /** A row is left because what holds its current key has to move first, and can't. */
7045
8734
  const cantMoveHolder = (kind, from, to) => rekeyConflict(kind, "taken", from, to, "A row that can't move holds its current key.");
7046
8735
  /**
@@ -7048,14 +8737,36 @@ const makeImpl = (config, precomputedData) => {
7048
8737
  * under other key text) moves out first. A tally of what moved, or the
7049
8738
  * conflict that leaves the row where it is. `copy`: whether the row at `to`
7050
8739
  * is a copy of the moving one, which the move then only deletes (`twin`).
8740
+ *
8741
+ * `elsewhere` ({@link RowTargets.elsewhere}): a row 1.39.0 keyed by a codec's doubled text moves
8742
+ * to `to` after a row there that moves there too, whichever the scan reaches first, so a read
8743
+ * model's removal tombstone, not the row it removed, ends up at `to`, and the report is the
8744
+ * same in every order. In a dry run nothing moves: that row is judged as if at `to`.
7051
8745
  */
7052
- const clearTarget = (ctx, kind, from, to, depth, copy) => Effect.gen(function* () {
8746
+ const clearTarget = (ctx, kind, from, to, depth, copy, elsewhere = []) => Effect.gen(function* () {
7053
8747
  const client = yield* Capacity.client;
7054
- const { Item: held } = yield* client.getItem({
8748
+ const { Item: atTarget } = yield* client.getItem({
7055
8749
  TableName: ctx.tableName,
7056
8750
  Key: toAttributeMap(to),
7057
8751
  ConsistentRead: true,
7058
8752
  });
8753
+ const first = atTarget === undefined && depth < Rekey.DISPLACE_DEPTH
8754
+ ? yield* movingThereToo(ctx, elsewhere, to)
8755
+ : undefined;
8756
+ if (first !== undefined) {
8757
+ const tally = yield* Rekey.displace(ctx, (under) => rekeyRow(first.row, under, depth + 1));
8758
+ if ((tally.conflicts ?? []).length > 0) {
8759
+ return {
8760
+ cleared: false,
8761
+ tally: Rekey.mergeTallies(tally, cantMoveHolder(kind, from, to)),
8762
+ };
8763
+ }
8764
+ if (!ctx.dryRun) {
8765
+ const after = yield* clearTarget(ctx, kind, from, to, depth, copy);
8766
+ return { ...after, tally: Rekey.mergeTallies(tally, after.tally) };
8767
+ }
8768
+ }
8769
+ const held = atTarget ?? first?.at;
7059
8770
  if (held === undefined)
7060
8771
  return { cleared: true, tally: {} };
7061
8772
  const occupant = occupantOf(held, to);
@@ -7117,13 +8828,22 @@ const makeImpl = (config, precomputedData) => {
7117
8828
  if (targets === undefined || !sameStoredKey(targets.current, to)) {
7118
8829
  return Rekey.mergeTallies(tally, yield* movedAway(ctx, to));
7119
8830
  }
8831
+ // Its Delete is guarded on the row as read: one nothing proves unchanged is the context's.
8832
+ const guard = deleteGuard(read, "item", undefined);
8833
+ if (!guard.proves) {
8834
+ switch (Rekey.unprovableRow(ctx)) {
8835
+ case "report":
8836
+ return Rekey.mergeTallies(tally, rekeyConflict(kind, "unguarded", from, to, Rekey.UNGUARDED_MESSAGE));
8837
+ case "strongest":
8838
+ break;
8839
+ }
8840
+ }
7120
8841
  const same = kind === "snapshot" ? sameSnapshotAs(read) : undefined;
7121
- const room = yield* clearTarget(ctx, kind, from, to, depth, same === undefined ? undefined : (held) => sameSnapshotHeld(held, read));
8842
+ const room = yield* clearTarget(ctx, kind, from, to, depth, same === undefined ? undefined : (held) => sameSnapshotHeld(held, read), targets.elsewhere);
7122
8843
  tally = Rekey.mergeTallies(tally, room.tally);
7123
8844
  if (room.cleared === "twin") {
7124
8845
  if (ctx.dryRun)
7125
8846
  return countMove(ctx, kind, to, tally);
7126
- const guard = deleteGuard(read, "item", undefined);
7127
8847
  const items = [
7128
8848
  {
7129
8849
  ConditionCheck: {
@@ -7158,14 +8878,13 @@ const makeImpl = (config, precomputedData) => {
7158
8878
  return tally;
7159
8879
  const values = toDomainView(fromAttributeMap(read));
7160
8880
  const sentinels = kind === "tombstone"
7161
- ? yield* sentinelRekeys(ctx, kind, values, targets.lives, targets.live, depth)
8881
+ ? yield* sentinelRekeys(ctx, kind, values, read, targets.isLive, targets.live, depth, true)
7162
8882
  : NO_SENTINEL_REKEYS;
7163
8883
  if (ctx.dryRun) {
7164
8884
  return Rekey.mergeTallies(countMove(ctx, kind, to, tally), sentinels.tally, {
7165
8885
  sentinelsMoved: sentinels.count,
7166
8886
  });
7167
8887
  }
7168
- const guard = deleteGuard(read, "item", undefined);
7169
8888
  const items = [
7170
8889
  {
7171
8890
  Put: {
@@ -7198,6 +8917,218 @@ const makeImpl = (config, precomputedData) => {
7198
8917
  }
7199
8918
  return Rekey.mergeTallies(tally, rekeyConflict(kind, "contended", from, to, "Concurrent writes changed it on every attempt."));
7200
8919
  });
8920
+ /** What judging an index key needs of this entity; `allIndexes.primary` never changes. */
8921
+ const indexKeyJudging = (() => {
8922
+ let judging;
8923
+ return () => {
8924
+ if (judging === undefined) {
8925
+ const primary = config.indexes.primary;
8926
+ judging = {
8927
+ schema,
8928
+ entityType,
8929
+ entityVersion,
8930
+ forms: KeyText136.forms(schema),
8931
+ primaryComposites: new Set([...primary.pk.composite, ...primary.sk.composite]),
8932
+ stamped: new Set([systemFields.createdAt, systemFields.updatedAt, systemFields.version].filter((field) => typeof field === "string")),
8933
+ lagTolerated: systemFields.updatedAt,
8934
+ };
8935
+ }
8936
+ return judging;
8937
+ };
8938
+ })();
8939
+ /**
8940
+ * A stored row's values as a `put` composed from them. A `put` is given a ref's id and stores the
8941
+ * ref (`team: { id, ... }`, no `teamId`), so it's read back from there, as `.within()` does.
8942
+ */
8943
+ const putValuesOf = (row) => {
8944
+ const values = toDomainView(fromAttributeMap(row));
8945
+ if (resolvedRefs.length === 0)
8946
+ return values;
8947
+ const withIds = { ...values };
8948
+ for (const ref of resolvedRefs) {
8949
+ const id = values[ref.fieldName]?.[ref.identifierField];
8950
+ if (id !== undefined)
8951
+ withIds[ref.idFieldName] = id;
8952
+ }
8953
+ return withIds;
8954
+ };
8955
+ /** The stored attribute a composite is read from: a ref's id lives in the ref. */
8956
+ const compositeAttribute = (composite) => resolveDbName(resolvedRefs.find((ref) => ref.idFieldName === composite)?.fieldName ?? composite);
8957
+ const NO_INDEX_KEY_WORK = {
8958
+ sets: {},
8959
+ removes: [],
8960
+ composites: [],
8961
+ found: {},
8962
+ keptAbsent: [],
8963
+ };
8964
+ /**
8965
+ * Each index half of a live item against what its values compose (`KeyComposer.judgeIndexHalf`).
8966
+ * Reads nothing and writes nothing. A half in a table key attribute isn't judged: no write names
8967
+ * one, on any path. Halves sharing an attribute have one definition (`EDD-9106`), so it's judged
8968
+ * once.
8969
+ */
8970
+ const judgeIndexKeys = (row) => {
8971
+ let rowKeyForm;
8972
+ try {
8973
+ rowKeyForm = keyForm(putValuesOf(row));
8974
+ }
8975
+ catch {
8976
+ return NO_INDEX_KEY_WORK;
8977
+ }
8978
+ const judging = indexKeyJudging();
8979
+ const sets = {};
8980
+ const removes = [];
8981
+ const composites = new Set();
8982
+ const found = { missing: 0, truncated: 0, lagging: 0, ambiguous: 0 };
8983
+ const keptAbsent = [];
8984
+ const judged = new Set();
8985
+ for (const [name, index] of Object.entries(allIndexes)) {
8986
+ if (name === "primary")
8987
+ continue;
8988
+ for (const half of ["pk", "sk"]) {
8989
+ const { field, composite } = index[half];
8990
+ if (isTableKeyField(field) || judged.has(field))
8991
+ continue;
8992
+ judged.add(field);
8993
+ const attribute = row[field];
8994
+ const stored = attribute === undefined ? undefined : (attribute.S ?? attribute.B);
8995
+ if (attribute !== undefined && stored === undefined)
8996
+ continue;
8997
+ const verdict = KeyComposer.judgeIndexHalf(judging, index, half, stored, rowKeyForm);
8998
+ if (verdict.kind === "fine")
8999
+ continue;
9000
+ if (verdict.kind === "ambiguous") {
9001
+ found.ambiguous++;
9002
+ keptAbsent.push(field);
9003
+ continue;
9004
+ }
9005
+ if (verdict.kind === "remove") {
9006
+ found.lagging++;
9007
+ removes.push(field);
9008
+ }
9009
+ else {
9010
+ found[verdict.drift]++;
9011
+ sets[field] =
9012
+ typeof verdict.value === "string" ? { S: verdict.value } : { B: verdict.value };
9013
+ }
9014
+ for (const attr of composite)
9015
+ composites.add(compositeAttribute(attr));
9016
+ if (half === "pk") {
9017
+ for (const attr of index.shards?.source ?? [])
9018
+ composites.add(compositeAttribute(attr));
9019
+ }
9020
+ }
9021
+ }
9022
+ return { sets, removes, composites: [...composites], found, keptAbsent };
9023
+ };
9024
+ const indexKeyWorkSize = (work) => Object.keys(work.sets).length + work.removes.length;
9025
+ /**
9026
+ * The `UpdateItem` a repair sends for `work`, judged from `row`: guarded on each key it writes and
9027
+ * each composite they're composed from as read, or on their absence, so a writer changing any of
9028
+ * them wins (`rekey-repair.md`).
9029
+ */
9030
+ const repairRequest = (tableName, row, at, work) => {
9031
+ const names = { "#pk": rekeyPk };
9032
+ const operands = {};
9033
+ const guards = ["attribute_exists(#pk)"];
9034
+ const guardAs = (name, operand, attribute) => {
9035
+ names[name] = attribute;
9036
+ const read = row[attribute];
9037
+ if (read === undefined) {
9038
+ guards.push(`attribute_not_exists(${name})`);
9039
+ }
9040
+ else {
9041
+ operands[operand] = read;
9042
+ guards.push(`${name} = ${operand}`);
9043
+ }
9044
+ };
9045
+ const sets = [];
9046
+ for (const [i, [field, value]] of Object.entries(work.sets).entries()) {
9047
+ guardAs(`#k${i}`, `:o${i}`, field);
9048
+ operands[`:n${i}`] = value;
9049
+ sets.push(`#k${i} = :n${i}`);
9050
+ }
9051
+ const removes = [];
9052
+ for (const [i, field] of work.removes.entries()) {
9053
+ guardAs(`#r${i}`, `:r${i}`, field);
9054
+ removes.push(`#r${i}`);
9055
+ }
9056
+ for (const [i, attribute] of work.composites.entries()) {
9057
+ guardAs(`#c${i}`, `:c${i}`, attribute);
9058
+ }
9059
+ return {
9060
+ TableName: tableName,
9061
+ Key: toAttributeMap(at),
9062
+ UpdateExpression: [
9063
+ ...(sets.length > 0 ? [`SET ${sets.join(", ")}`] : []),
9064
+ ...(removes.length > 0 ? [`REMOVE ${removes.join(", ")}`] : []),
9065
+ ].join(" "),
9066
+ ConditionExpression: guards.join(" AND "),
9067
+ ExpressionAttributeNames: names,
9068
+ ...(Object.keys(operands).length > 0 && { ExpressionAttributeValues: operands }),
9069
+ };
9070
+ };
9071
+ /**
9072
+ * Count the index keys of a live item at its current table key that differ, once per run, and with
9073
+ * `repairIndexKeys` write them (`rekey-repair.md`). `row` holds what the run's text rewrite left.
9074
+ * A row with nothing to do costs nothing here, whatever the option says. `wrote` says the row was
9075
+ * acted on, so isn't `unchanged`.
9076
+ */
9077
+ const repairIndexKeys = (ctx, row, at) => Effect.gen(function* () {
9078
+ if (!ctx.claim(`${entityType}\u0000indexKeys\u0000${at[rekeyPk]}\u0000${at[rekeySk]}`)) {
9079
+ return { tally: {}, wrote: false };
9080
+ }
9081
+ let work = judgeIndexKeys(row);
9082
+ const found = work.found;
9083
+ if (!ctx.repairIndexKeys || indexKeyWorkSize(work) === 0) {
9084
+ return { tally: { indexKeys: found }, wrote: false };
9085
+ }
9086
+ if (ctx.dryRun) {
9087
+ return { tally: { indexKeys: { ...found, repaired: indexKeyWorkSize(work) } }, wrote: true };
9088
+ }
9089
+ const client = yield* Capacity.client;
9090
+ let judged = row;
9091
+ for (let attempt = 0;; attempt++) {
9092
+ const request = repairRequest(ctx.tableName, judged, at, work);
9093
+ const outcome = yield* client.updateItem(request).pipe(Effect.as({ _tag: "Done" }), Effect.catch((err) => isAwsConditionalCheckFailed(err.cause)
9094
+ ? Effect.succeed({ _tag: "Raced" })
9095
+ : Effect.fail(err)), diagnoseItemWrite("rekey", {
9096
+ Update: request,
9097
+ }), Effect.catchTag("ValidationError", (error) => Effect.succeed({ _tag: "Refused", error })));
9098
+ if (outcome._tag === "Done") {
9099
+ return {
9100
+ tally: { indexKeys: { ...found, repaired: indexKeyWorkSize(work) } },
9101
+ wrote: true,
9102
+ };
9103
+ }
9104
+ if (outcome._tag === "Refused") {
9105
+ return {
9106
+ tally: Rekey.mergeTallies({ indexKeys: found }, rekeyConflict("item", "failed", at, at, String(outcome.error.cause ?? outcome.error.message))),
9107
+ wrote: true,
9108
+ };
9109
+ }
9110
+ // A writer got there first: judge the item as it is now, and try once more.
9111
+ if (attempt > 0) {
9112
+ return {
9113
+ tally: { indexKeys: { ...found, skipped: indexKeyWorkSize(work) } },
9114
+ wrote: false,
9115
+ };
9116
+ }
9117
+ const { Item: fresh } = yield* client.getItem({
9118
+ TableName: ctx.tableName,
9119
+ Key: toAttributeMap(at),
9120
+ ConsistentRead: true,
9121
+ });
9122
+ const targets = fresh === undefined ? undefined : rowTargets(fresh);
9123
+ if (targets?.kind !== "item" || !sameStoredKey(targets.current, at)) {
9124
+ return { tally: { indexKeys: found }, wrote: false };
9125
+ }
9126
+ judged = fresh;
9127
+ work = judgeIndexKeys(judged);
9128
+ if (indexKeyWorkSize(work) === 0)
9129
+ return { tally: { indexKeys: found }, wrote: false };
9130
+ }
9131
+ });
7201
9132
  /**
7202
9133
  * What a move writes for `read` at its current key `current`: index keys recomposed as
7203
9134
  * an update would, so a half that can't compose keeps its text. Reads nothing and
@@ -7217,6 +9148,10 @@ const makeImpl = (config, precomputedData) => {
7217
9148
  if (!isTableKeyField(field))
7218
9149
  delete moved[field];
7219
9150
  }
9151
+ // A move recomposes as an update naming everything would, which writes a key the row went
9152
+ // without on purpose: it isn't damage (`rekey-repair.md`), so it stays that way.
9153
+ for (const field of judgeIndexKeys(read).keptAbsent)
9154
+ delete moved[field];
7220
9155
  for (const [, definition] of vectorIndexEntries) {
7221
9156
  if (read[definition.vectorField] === undefined)
7222
9157
  continue;
@@ -7248,12 +9183,22 @@ const makeImpl = (config, precomputedData) => {
7248
9183
  if (targets?.kind !== "item" || !sameStoredKey(targets.current, to)) {
7249
9184
  return Rekey.mergeTallies(tally, yield* movedAway(ctx, to));
7250
9185
  }
7251
- const room = yield* clearTarget(ctx, "item", from, to, depth);
9186
+ // Its Delete is guarded on the item as read: one nothing proves unchanged is the context's.
9187
+ const guard = deleteGuard(read, "item", undefined);
9188
+ if (!guard.proves) {
9189
+ switch (Rekey.unprovableRow(ctx)) {
9190
+ case "report":
9191
+ return Rekey.mergeTallies(tally, rekeyConflict("item", "unguarded", from, to, Rekey.UNGUARDED_MESSAGE));
9192
+ case "strongest":
9193
+ break;
9194
+ }
9195
+ }
9196
+ const room = yield* clearTarget(ctx, "item", from, to, depth, undefined, targets.elsewhere);
7252
9197
  tally = Rekey.mergeTallies(tally, room.tally);
7253
9198
  if (!room.cleared)
7254
9199
  return tally;
7255
9200
  const values = toDomainView(fromAttributeMap(read));
7256
- const sentinels = yield* sentinelRekeys(ctx, "item", values, [from], to, depth);
9201
+ const sentinels = yield* sentinelRekeys(ctx, "item", values, read, (key) => sameStoredKey(key, from), to, depth, true);
7257
9202
  tally = Rekey.mergeTallies(tally, sentinels.tally);
7258
9203
  if ((sentinels.tally.conflicts ?? []).length > 0)
7259
9204
  return tally;
@@ -7264,9 +9209,9 @@ const makeImpl = (config, precomputedData) => {
7264
9209
  if (ctx.dryRun) {
7265
9210
  // The real run goes on to rewrite or report what the move leaves on the row.
7266
9211
  const left = staleIndexKeys(moved.row);
7267
- return Rekey.mergeTallies(countMove(ctx, "item", to, tally), { sentinelsMoved: sentinels.moved }, Object.keys(left.sets).length === 0 ? {} : { indexKeysRewritten: 1 }, heldBackIndexKeys(to, left.uncomposable));
9212
+ const repair = yield* repairIndexKeys(ctx, { ...moved.row, ...left.sets }, to);
9213
+ return Rekey.mergeTallies(countMove(ctx, "item", to, tally), { sentinelsMoved: sentinels.moved }, Object.keys(left.sets).length === 0 ? {} : { indexKeysRewritten: 1 }, heldBackIndexKeys(to, left.uncomposable), repair.tally);
7268
9214
  }
7269
- const guard = deleteGuard(read, "item", undefined);
7270
9215
  const items = [
7271
9216
  {
7272
9217
  Put: {
@@ -7311,7 +9256,9 @@ const makeImpl = (config, precomputedData) => {
7311
9256
  * row's values, and never reads a value out of a stored key.
7312
9257
  *
7313
9258
  * An unsharded partition key, a sort key, a Z-order sort key or a vector partition is rewritten
7314
- * only when it is exactly its text under some form, and that isn't the current text. Each half
9259
+ * only when it is exactly its text under some form, and that isn't the current text: the text of
9260
+ * the row's values, or of them with a numeric composite as the other kind ({@link kindReading}),
9261
+ * looked for only behind a key that isn't its current text. Each half
7315
9262
  * is judged by itself and by its bytes: halves in one attribute have the same definition
7316
9263
  * (`EDD-9106`), so none can be another's other text. A sort key missing a trailing composite is
7317
9264
  * judged by the composites before the gap, which is what a row truncated under 1.36 stores.
@@ -7327,7 +9274,10 @@ const makeImpl = (config, precomputedData) => {
7327
9274
  * unless it is already in the current layout.
7328
9275
  */
7329
9276
  const staleIndexKeys = (row) => {
7330
- const rowKeyForm = keyForm(toDomainView(fromAttributeMap(row)));
9277
+ const values = toDomainView(fromAttributeMap(row));
9278
+ const rowKeyForm = keyForm(values);
9279
+ // The texts a key may be stored under: each form's, from the key form and from 1.39.0's.
9280
+ const rowKeyFormsThen = rowKeyForms(values);
7331
9281
  const composing = (compose) => {
7332
9282
  try {
7333
9283
  return compose();
@@ -7349,14 +9299,22 @@ const makeImpl = (config, precomputedData) => {
7349
9299
  composites.add(resolveDbName(attr));
7350
9300
  };
7351
9301
  const forms = KeyText136.forms(schema);
9302
+ /**
9303
+ * Is `stored` what some reading of the row's values composes under some form: the values in
9304
+ * the key form or in 1.39.0's ({@link rowKeyForms}), or either with some of `fields` as the
9305
+ * other numeric kind ({@link kindReading})?
9306
+ */
9307
+ const composedUnder = (fields, under, stored) => rowKeyFormsThen.some((reading) => forms.some((form) => kindReading(row, reading, fields, (record) => under(form, record), stored) !==
9308
+ undefined));
7352
9309
  const consider = (field, attrs, now, under) => {
7353
9310
  const stored = row[field]?.S;
7354
9311
  if (stored === undefined)
7355
9312
  return;
7356
- if (!forms.some((form) => composing(() => under(form)) === stored))
7357
- return;
9313
+ // Its current text, which no other text is looked for behind: nothing to rewrite.
7358
9314
  const text = composing(now);
7359
- if (text !== undefined && text !== stored)
9315
+ if (text === undefined || text === stored)
9316
+ return;
9317
+ if (composedUnder(attrs, under, stored))
7360
9318
  rewrite(field, { S: text }, attrs);
7361
9319
  };
7362
9320
  const sameBytes = (a, b) => b !== undefined && a.length === b.length && a.every((byte, i) => byte === b[i]);
@@ -7379,26 +9337,25 @@ const makeImpl = (config, precomputedData) => {
7379
9337
  }
7380
9338
  }
7381
9339
  else {
7382
- consider(index.pk.field, index.pk.composite, () => KeyComposer.composePk(schema, entityType, index, rowKeyForm), (form) => KeyComposer.composePk(form.pk, entityType, index, rowKeyForm));
9340
+ consider(index.pk.field, index.pk.composite, () => KeyComposer.composePk(schema, entityType, index, rowKeyForm), (form, kindKeyForm) => KeyComposer.composePk(form.pk, entityType, index, kindKeyForm));
7383
9341
  }
7384
9342
  if (KeyComposer.isZOrderHalf(index.sk)) {
7385
9343
  // An address holds no text, its prefix segments do.
7386
9344
  const stored = row[index.sk.field]?.B;
7387
9345
  if (stored === undefined)
7388
9346
  continue;
7389
- const known = forms.some((form) => sameBytes(stored, composing(() => KeyComposer.composeZOrderSk(form.sk, index, rowKeyForm))));
7390
- const bytes = known
7391
- ? composing(() => KeyComposer.composeZOrderSk(schema, index, rowKeyForm))
7392
- : undefined;
7393
- if (bytes !== undefined && !sameBytes(bytes, stored)) {
9347
+ const bytes = composing(() => KeyComposer.composeZOrderSk(schema, index, rowKeyForm));
9348
+ if (bytes === undefined || sameBytes(bytes, stored))
9349
+ continue;
9350
+ const known = composedUnder(index.sk.zorderHalf.prefix.map((segment) => segment.field), (form, kindKeyForm) => bytesText(KeyComposer.composeZOrderSk(form.sk, index, kindKeyForm)), bytesText(stored));
9351
+ if (known)
7394
9352
  rewrite(index.sk.field, { B: bytes }, index.sk.composite);
7395
- }
7396
9353
  continue;
7397
9354
  }
7398
- consider(index.sk.field, index.sk.composite, () => KeyComposer.composeSortKeyPrefix(schema, entityType, entityVersion, index, rowKeyForm), (form) => KeyComposer.composeSortKeyPrefix(form.sk, entityType, entityVersion, index, rowKeyForm));
9355
+ consider(index.sk.field, index.sk.composite, () => KeyComposer.composeSortKeyPrefix(schema, entityType, entityVersion, index, rowKeyForm), (form, kindKeyForm) => KeyComposer.composeSortKeyPrefix(form.sk, entityType, entityVersion, index, kindKeyForm));
7399
9356
  }
7400
9357
  for (const [, definition] of vectorIndexEntries) {
7401
- consider(definition.partitionField, definition.partition, () => KeyComposer.tryComposeVectorPartition(schema, entityType, definition, rowKeyForm), (form) => KeyComposer.tryComposeVectorPartition(form.pk, entityType, definition, rowKeyForm));
9358
+ consider(definition.partitionField, definition.partition, () => KeyComposer.tryComposeVectorPartition(schema, entityType, definition, rowKeyForm), (form, kindKeyForm) => KeyComposer.tryComposeVectorPartition(form.pk, entityType, definition, kindKeyForm));
7402
9359
  }
7403
9360
  return { sets, olds, composites: [...composites], uncomposable };
7404
9361
  };
@@ -7418,9 +9375,12 @@ const makeImpl = (config, precomputedData) => {
7418
9375
  let row = scanned;
7419
9376
  let rewritten = false;
7420
9377
  let uncomposable = [];
9378
+ // What the text rewrite leaves on the row, for judging what's left of its index keys.
9379
+ let left = scanned;
7421
9380
  for (let attempt = 0;; attempt++) {
7422
9381
  const stale = staleIndexKeys(row);
7423
9382
  uncomposable = stale.uncomposable;
9383
+ left = { ...row, ...stale.sets };
7424
9384
  const fields = Object.keys(stale.sets);
7425
9385
  if (fields.length === 0)
7426
9386
  break;
@@ -7475,14 +9435,16 @@ const makeImpl = (config, precomputedData) => {
7475
9435
  return {};
7476
9436
  row = fresh;
7477
9437
  }
7478
- const sentinels = yield* rekeySentinels(ctx, "item", row, [at], at, depth);
9438
+ const repair = yield* repairIndexKeys(ctx, left, at);
9439
+ const sentinels = yield* rekeySentinels(ctx, "item", row, (key) => sameStoredKey(key, at), at, depth, false);
7479
9440
  const refused = heldBackIndexKeys(at, uncomposable);
7480
9441
  return Rekey.mergeTallies(rewritten ||
9442
+ repair.wrote ||
7481
9443
  (refused.conflicts ?? []).length > 0 ||
7482
9444
  (sentinels.sentinelsMoved ?? 0) > 0 ||
7483
9445
  (sentinels.conflicts ?? []).length > 0
7484
9446
  ? {}
7485
- : { unchanged: 1 }, rewritten ? { indexKeysRewritten: 1 } : {}, sentinels, refused);
9447
+ : { unchanged: 1 }, rewritten ? { indexKeysRewritten: 1 } : {}, repair.tally, sentinels, refused);
7486
9448
  });
7487
9449
  /**
7488
9450
  * What a move left on an item (#183): it recomposes index keys as an update would, so a
@@ -7496,8 +9458,11 @@ const makeImpl = (config, precomputedData) => {
7496
9458
  if (predicted === undefined)
7497
9459
  return {};
7498
9460
  const stale = staleIndexKeys(predicted);
7499
- if (Object.keys(stale.sets).length === 0 && stale.uncomposable.length === 0)
7500
- return {};
9461
+ if (Object.keys(stale.sets).length === 0 && stale.uncomposable.length === 0) {
9462
+ // Judged from what the move wrote, with no read: a repair is conditioned on what's judged,
9463
+ // so a prediction that's wrong fails its condition, and the item is read then.
9464
+ return (yield* repairIndexKeys(ctx, predicted, at)).tally;
9465
+ }
7501
9466
  const client = yield* Capacity.client;
7502
9467
  const { Item: moved } = yield* client.getItem({
7503
9468
  TableName: ctx.tableName,
@@ -7511,31 +9476,139 @@ const makeImpl = (config, precomputedData) => {
7511
9476
  return tally;
7512
9477
  });
7513
9478
  const NO_SENTINEL_REKEYS = { items: [], count: 0, moved: 0, tally: {} };
7514
- /** A unique sentinel's key under `under`; `undefined` when the values have none there. */
7515
- const sentinelKeyUnder = (under, constraintName, constraintDef, source) => {
9479
+ /**
9480
+ * A unique sentinel's key under `under`; `undefined` when the values have none there. A field in
9481
+ * `asOther` is composed as given, not lifted to its kind ({@link kindReading}).
9482
+ */
9483
+ const sentinelKeyUnder = (under, constraintName, constraintDef, source, asOther = new Set()) => {
7516
9484
  try {
7517
- return composeUniqueSentinel(under, entityType, constraintName, constraintDef, source)?.key;
9485
+ return composeUniqueSentinel(under, entityType, constraintName, constraintDef, source, (field, value) => (asOther.has(field) ? undefined : readSentinelValue(field, value)))?.key;
7518
9486
  }
7519
9487
  catch {
7520
9488
  return undefined;
7521
9489
  }
7522
9490
  };
7523
- /** The keys a unique sentinel of `source`'s values can be stored under, other than `current`. */
7524
- const otherSentinelKeys = (constraintName, constraintDef, source, current) => {
7525
- const others = [];
7526
- for (const under of [
7527
- KeyText136.schema136(schema),
7528
- KeyText136.schema137(schema),
7529
- KeyText136.schemaEscaped(schema),
7530
- ]) {
7531
- const key = sentinelKeyUnder(under, constraintName, constraintDef, source);
7532
- if (key !== undefined &&
7533
- !(key.pk === current?.pk && key.sk === current?.sk) &&
7534
- !others.some((other) => other.pk === key.pk && other.sk === key.sk)) {
7535
- others.push(key);
9491
+ /** Each of a unique constraint's values as its field's kind, which the other kind is the other of. */
9492
+ const liftedSentinelValues = (constraintDef, source) => {
9493
+ const lifted = { ...source };
9494
+ for (const field of resolveUniqueFields(constraintDef)) {
9495
+ const value = readSentinelValue(field, source[field]);
9496
+ if (value !== undefined)
9497
+ lifted[field] = value;
9498
+ }
9499
+ return lifted;
9500
+ };
9501
+ /** The sentinel texts a unique sentinel's key is looked for under: each setting's. */
9502
+ const sentinelTexts = () => [
9503
+ KeyText136.schema136(schema),
9504
+ KeyText136.schema137(schema),
9505
+ KeyText136.schemaEscaped(schema),
9506
+ ];
9507
+ /**
9508
+ * The reading of a row's values its own stored key was composed from ({@link kindReading}):
9509
+ * which numeric composites it gives as the other kind. `undefined` when no reading under any
9510
+ * form composes it.
9511
+ */
9512
+ const storedKeyReading = (row) => {
9513
+ const stored = storedKeyOf(row);
9514
+ if (stored === undefined)
9515
+ return undefined;
9516
+ const values = toDomainView(fromAttributeMap(row));
9517
+ const rowKeyForm = keyForm(values);
9518
+ const history = historyLayout(stored[rekeySk], values, rowKeyForm);
9519
+ for (const form of keyFormsOf()) {
9520
+ for (const [at, fields] of [
9521
+ [(key) => key, primaryTextFields],
9522
+ ...(history === undefined
9523
+ ? []
9524
+ : [
9525
+ [
9526
+ (key, record) => history.at(form, key, record),
9527
+ history.fields,
9528
+ ],
9529
+ ]),
9530
+ ]) {
9531
+ const reading = kindReading(row, rowKeyForm, fields,
9532
+ // A reading of the row's key form: each numeric field read as the kind it composes.
9533
+ (kindKeyForm) => {
9534
+ const placedAt = at(KeyText136.composeAt(form, entityType, entityVersion, config.indexes.primary, kindKeyForm), kindKeyForm);
9535
+ return keySegments(placedAt[rekeyPk], placedAt[rekeySk]);
9536
+ }, storedKeyText(stored));
9537
+ if (reading !== undefined)
9538
+ return reading;
7536
9539
  }
7537
9540
  }
7538
- return others;
9541
+ return undefined;
9542
+ };
9543
+ const sameSentinelKey = (a, b) => a.pk === b.pk && a.sk === b.sk;
9544
+ /**
9545
+ * The keys a unique sentinel of `source`'s values, read from `row`, can be stored under, other
9546
+ * than `current`: under each text, and with `otherKinds`, with some numeric values as the other
9547
+ * kind. A moving row's sentinel is looked for there, before anything has a key to compare.
9548
+ * `first` reads the values as they are, as `row`'s own key gives them, each alone as the other
9549
+ * kind, and all of them, which is every reading of a constraint over one or two numeric fields.
9550
+ * `mixes` gives every other reading, fewest values as the other kind first: looked at only when
9551
+ * no key of `first`, and not the current key, holds a sentinel, since a moving row's sentinel
9552
+ * names its old key and is moved by nothing else.
9553
+ */
9554
+ const otherSentinelKeys = (constraintName, constraintDef, source, row, current, otherKinds) => {
9555
+ const lifted = liftedSentinelValues(constraintDef, source);
9556
+ const digits = (field) => row[resolveDbName(field)]?.N;
9557
+ const fields = otherKinds
9558
+ ? resolveUniqueFields(constraintDef).filter((field) => otherNumericKind(lifted[field], digits(field)) !== undefined)
9559
+ : [];
9560
+ const readings = [new Set()];
9561
+ if (otherKinds) {
9562
+ const keyed = storedKeyReading(row)?.asOther;
9563
+ if (keyed !== undefined)
9564
+ readings.push(new Set(fields.filter((field) => keyed.has(field))));
9565
+ for (const field of fields)
9566
+ readings.push(new Set([field]));
9567
+ readings.push(new Set(fields));
9568
+ }
9569
+ const seen = new Set(current === undefined ? [] : [`${current.pk}\u0000${current.sk}`]);
9570
+ const keysOf = (mixes) => {
9571
+ const keys = [];
9572
+ for (const under of sentinelTexts()) {
9573
+ for (const asOther of mixes) {
9574
+ const record = { ...lifted };
9575
+ for (const field of asOther)
9576
+ record[field] = otherNumericKind(lifted[field], digits(field));
9577
+ const key = sentinelKeyUnder(under, constraintName, constraintDef, record, asOther);
9578
+ if (key === undefined || seen.has(`${key.pk}\u0000${key.sk}`))
9579
+ continue;
9580
+ seen.add(`${key.pk}\u0000${key.sk}`);
9581
+ keys.push(key);
9582
+ }
9583
+ }
9584
+ return keys;
9585
+ };
9586
+ const first = keysOf(readings);
9587
+ const mixes = () => {
9588
+ const named = new Set(readings.map((asOther) => [...asOther].sort().join("\u0000")));
9589
+ const others = [];
9590
+ for (let mask = 1; mask < 2 ** fields.length; mask++) {
9591
+ const asOther = new Set(fields.filter((_, i) => (mask & (1 << i)) !== 0));
9592
+ if (!named.has([...asOther].sort().join("\u0000")))
9593
+ others.push(asOther);
9594
+ }
9595
+ return keysOf(others.sort((a, b) => a.size - b.size));
9596
+ };
9597
+ return { first, mixes };
9598
+ };
9599
+ /**
9600
+ * Is `key` where a unique sentinel of `source`'s values, read from `row`, is stored: under the
9601
+ * current text or another, and with `otherKinds`, with some numeric values as the other kind,
9602
+ * found from the key itself ({@link kindReading}).
9603
+ */
9604
+ const sentinelHeldAt = (constraintName, constraintDef, source, row, key, otherKinds) => {
9605
+ const lifted = liftedSentinelValues(constraintDef, source);
9606
+ const fields = otherKinds ? resolveUniqueFields(constraintDef) : [];
9607
+ const text = JSON.stringify([key.pk, key.sk]);
9608
+ return [schema, ...sentinelTexts()].some((under) => kindReading(row, lifted, fields, (record, asOther) => {
9609
+ const at = sentinelKeyUnder(under, constraintName, constraintDef, record, asOther);
9610
+ return at === undefined ? undefined : keySegments(at.pk, at.sk);
9611
+ }, text) !== undefined);
7539
9612
  };
7540
9613
  /** The row a sentinel's back-pointer names: the item, or a tombstone keeping its reservation. */
7541
9614
  const sentinelOwnerRow = (tableName, sentinel) => Effect.gen(function* () {
@@ -7553,18 +9626,32 @@ const makeImpl = (config, precomputedData) => {
7553
9626
  });
7554
9627
  /**
7555
9628
  * The writes that bring the unique sentinels of `values` to their current keys, naming `to`,
7556
- * from consistent reads: a sentinel one of `owners` holds under other key text is put under its
7557
- * current key and released under the old one; one under its current key naming another of
7558
- * `owners` is re-pointed to `to`. Each write is conditioned on the sentinel as read. An item's
7559
- * owners are its own key; a tombstone's (`preserveUnique`) are the item's live keys under every
7560
- * text — the sentinels name the item, not the tombstone.
9629
+ * from consistent reads: a sentinel naming a key `owns` holds under other key text is put under
9630
+ * its current key and released under the old one; one under its current key naming another key
9631
+ * `owns` holds is re-pointed to `to`. Each write is conditioned on the sentinel as read. An
9632
+ * item owns its own key; a tombstone (`preserveUnique`) the item's live keys under every text —
9633
+ * the sentinels name the item, not the tombstone.
7561
9634
  *
7562
9635
  * A sentinel's current key can hold another value's sentinel under other key text: the row it
7563
9636
  * names moves first, with its sentinel. Its current key held by anything else is a conflict and
7564
9637
  * the sentinel is left as it is, as is one whose values compose no key now. `count` is the
7565
9638
  * sentinels written, `moved` those whose text changed.
7566
9639
  */
7567
- const sentinelRekeys = (ctx, kind, values, owners, to, depth) => Effect.gen(function* () {
9640
+ const sentinelRekeys = (ctx, kind, values,
9641
+ /** The row `values` were read from. */
9642
+ row,
9643
+ /** Is a key a sentinel names one of its owners'? */
9644
+ owns, to, depth,
9645
+ /**
9646
+ * Look under the other numeric kind's text too ({@link otherSentinelKeys}). A moving row's
9647
+ * sentinels are looked for there, since they name its old key: under the first readings, then,
9648
+ * when none of them nor the current key holds one, under every other mix. One under its current
9649
+ * key leaves it to the scan to find one there ({@link rekeySentinelRow}): each read it costs is
9650
+ * a read of every item, on every run.
9651
+ */
9652
+ otherKinds,
9653
+ /** A sentinel the scan reached, which names the row: looked at first, for its constraint. */
9654
+ scanned) => Effect.gen(function* () {
7568
9655
  if (config.unique === undefined)
7569
9656
  return NO_SENTINEL_REKEYS;
7570
9657
  const client = yield* Capacity.client;
@@ -7573,9 +9660,14 @@ const makeImpl = (config, precomputedData) => {
7573
9660
  Key: toAttributeMap(sentinelKeyRecord(key)),
7574
9661
  ConsistentRead: true,
7575
9662
  }), (result) => result.Item);
7576
- const ownerIn = (held) => held === undefined
7577
- ? undefined
7578
- : owners.find((owner) => held._entity_pk?.S === owner[rekeyPk] && held._entity_sk?.S === owner[rekeySk]);
9663
+ const ownerIn = (held) => {
9664
+ const pk = held?._entity_pk?.S;
9665
+ const sk = held?._entity_sk?.S;
9666
+ if (pk === undefined || sk === undefined)
9667
+ return undefined;
9668
+ const named = keyAt(pk, sk);
9669
+ return owns(named) ? named : undefined;
9670
+ };
7579
9671
  const items = [];
7580
9672
  let count = 0;
7581
9673
  let moved = 0;
@@ -7587,8 +9679,7 @@ const makeImpl = (config, precomputedData) => {
7587
9679
  const now = (() => {
7588
9680
  try {
7589
9681
  return {
7590
- key: composeUniqueSentinel(schema, entityType, constraintName, constraintDef, values)
7591
- ?.key,
9682
+ key: composeUniqueSentinel(schema, entityType, constraintName, constraintDef, values, readSentinelValue)?.key,
7592
9683
  };
7593
9684
  }
7594
9685
  catch {
@@ -7604,13 +9695,27 @@ const makeImpl = (config, precomputedData) => {
7604
9695
  continue;
7605
9696
  const heldNow = yield* readAt(current);
7606
9697
  let found;
7607
- for (const key of otherSentinelKeys(constraintName, constraintDef, values, current)) {
7608
- const held = yield* readAt(key);
7609
- const owner = ownerIn(held);
7610
- if (held !== undefined && owner !== undefined) {
7611
- found = { key, held, owner };
7612
- break;
9698
+ const keys = otherSentinelKeys(constraintName, constraintDef, values, row, current, otherKinds);
9699
+ const at = scanned?.constraintName === constraintName && !sameSentinelKey(scanned.key, current)
9700
+ ? [scanned.key]
9701
+ : [];
9702
+ const lookAt = (among) => Effect.gen(function* () {
9703
+ for (const key of among) {
9704
+ const held = yield* readAt(key);
9705
+ const owner = ownerIn(held);
9706
+ if (held !== undefined && owner !== undefined)
9707
+ return { key, held, owner };
7613
9708
  }
9709
+ return undefined;
9710
+ });
9711
+ found = yield* lookAt([
9712
+ ...at,
9713
+ ...keys.first.filter((key) => !at.some((one) => sameSentinelKey(one, key))),
9714
+ ]);
9715
+ // Under no reading looked at, and none under its current key: the sentinel of a moving row
9716
+ // is moved by nothing else, so every mix of kinds is looked at.
9717
+ if (found === undefined && heldNow === undefined && otherKinds) {
9718
+ found = yield* lookAt(keys.mixes().filter((key) => !at.some((one) => sameSentinelKey(one, key))));
7614
9719
  }
7615
9720
  if (found !== undefined) {
7616
9721
  if (heldNow !== undefined) {
@@ -7689,13 +9794,13 @@ const makeImpl = (config, precomputedData) => {
7689
9794
  * another key — an item's, or a tombstone's — brought to their current keys in one transaction
7690
9795
  * ({@link sentinelRekeys}), read again when a write changed one in between.
7691
9796
  */
7692
- const rekeySentinels = (ctx, kind, row, owners, to, depth) => Effect.gen(function* () {
9797
+ const rekeySentinels = (ctx, kind, row, owns, to, depth, otherKinds, scanned) => Effect.gen(function* () {
7693
9798
  if (config.unique === undefined)
7694
9799
  return {};
7695
9800
  const client = yield* Capacity.client;
7696
9801
  const values = toDomainView(fromAttributeMap(row));
7697
9802
  for (let attempt = 0; attempt < GUARDED_PUT_ATTEMPTS; attempt++) {
7698
- const planned = yield* sentinelRekeys(ctx, kind, values, owners, to, depth);
9803
+ const planned = yield* sentinelRekeys(ctx, kind, values, row, owns, to, depth, otherKinds, scanned);
7699
9804
  const moved = planned.count > 0 ? { sentinelsMoved: planned.count } : {};
7700
9805
  if (planned.items.length === 0 || ctx.dryRun) {
7701
9806
  return Rekey.mergeTallies(planned.tally, moved);
@@ -7719,20 +9824,29 @@ const makeImpl = (config, precomputedData) => {
7719
9824
  const at = storedKeyOf(row);
7720
9825
  if (at === undefined)
7721
9826
  return { skipped: { unrecognizedKey: 1 } };
7722
- const named = (sentinel, owner) => {
9827
+ const keyOf = (sentinel) => {
9828
+ const stored = storedKeyOf(sentinel);
9829
+ return { pk: stored[rekeyPk], sk: stored[rekeySk] };
9830
+ };
9831
+ const named = (sentinel, owner, otherKinds) => {
7723
9832
  if (constraintDef === undefined)
7724
9833
  return false;
7725
9834
  const values = toDomainView(fromAttributeMap(owner));
7726
- const current = sentinelKeyUnder(schema, constraintName, constraintDef, values);
7727
- const stored = storedKeyOf(sentinel);
7728
- return [
7729
- ...(current === undefined ? [] : [current]),
7730
- ...otherSentinelKeys(constraintName, constraintDef, values, current),
7731
- ].some((key) => key.pk === stored[rekeyPk] && key.sk === stored[rekeySk]);
9835
+ return sentinelHeldAt(constraintName, constraintDef, values, owner, keyOf(sentinel), otherKinds);
7732
9836
  };
7733
- const owner = yield* sentinelOwnerRow(ctx.tableName, row);
7734
- if (owner !== undefined && named(row, owner))
7735
- return {};
9837
+ // Its owner's own pass moves it, except from under the other numeric kind's text, which an
9838
+ // owner under its current key doesn't look under: this one moves it from there, from the key
9839
+ // the scan found it at, whatever mix of kinds that is.
9840
+ const judge = (sentinel, owner) => owner === undefined
9841
+ ? Effect.succeed(undefined)
9842
+ : named(sentinel, owner, false)
9843
+ ? Effect.succeed({})
9844
+ : named(sentinel, owner, true)
9845
+ ? sentinelsUnderOtherKind(ctx, owner, { constraintName, key: keyOf(sentinel) })
9846
+ : Effect.succeed(undefined);
9847
+ const judged = yield* judge(row, yield* sentinelOwnerRow(ctx.tableName, row));
9848
+ if (judged !== undefined)
9849
+ return judged;
7736
9850
  const client = yield* Capacity.client;
7737
9851
  const { Item: fresh } = yield* client.getItem({
7738
9852
  TableName: ctx.tableName,
@@ -7741,10 +9855,25 @@ const makeImpl = (config, precomputedData) => {
7741
9855
  });
7742
9856
  if (fresh === undefined)
7743
9857
  return {};
7744
- const freshOwner = yield* sentinelOwnerRow(ctx.tableName, fresh);
7745
- return freshOwner !== undefined && named(fresh, freshOwner)
7746
- ? {}
7747
- : { skipped: { unrecognizedKey: 1 } };
9858
+ return ((yield* judge(fresh, yield* sentinelOwnerRow(ctx.tableName, fresh))) ?? {
9859
+ skipped: { unrecognizedKey: 1 },
9860
+ });
9861
+ });
9862
+ /**
9863
+ * The sentinels of `owner`, a row under its current key, brought from under the other numeric
9864
+ * kind's text ({@link sentinelHeldAt}), `scanned` the one the scan found. A row under an old key
9865
+ * moves them itself when it moves.
9866
+ */
9867
+ const sentinelsUnderOtherKind = (ctx, owner, scanned) => Effect.gen(function* () {
9868
+ const targets = rowTargets(owner);
9869
+ const ownerAt = storedKeyOf(owner);
9870
+ if (targets === undefined || ownerAt === undefined)
9871
+ return {};
9872
+ if (!sameStoredKey(ownerAt, targets.current))
9873
+ return {};
9874
+ return targets.kind === "tombstone"
9875
+ ? yield* rekeySentinels(ctx, "tombstone", owner, targets.isLive, targets.live, 0, true, scanned)
9876
+ : yield* rekeySentinels(ctx, "item", owner, (key) => sameStoredKey(key, ownerAt), ownerAt, 0, true, scanned);
7748
9877
  });
7749
9878
  /** The entity's `rekey` handler: one scanned row — or one displaced by a move. */
7750
9879
  const rekeyRow = (row, ctx, depth = 0) => Effect.gen(function* () {
@@ -7756,10 +9885,14 @@ const makeImpl = (config, precomputedData) => {
7756
9885
  if (type !== entityType)
7757
9886
  return undefined;
7758
9887
  const stored = storedKeyOf(row);
7759
- const targets = rowTargets(row);
9888
+ const targets = rowPlaces(row);
7760
9889
  if (stored === undefined || targets === undefined) {
7761
9890
  return { skipped: { unrecognizedKey: 1 } };
7762
9891
  }
9892
+ // The member's row, with values no key can be composed from: left where it is, and said so.
9893
+ if ("uncomposable" in targets) {
9894
+ return rekeyConflict(storedRowKind(stored[rekeySk]), "uncomposable", stored, undefined, `Its values compose no key: ${targets.uncomposable}`);
9895
+ }
7763
9896
  if (sameStoredKey(stored, targets.current)) {
7764
9897
  // A sentinel in another row's way has this row reached before the scan gets to it, and
7765
9898
  // then it has nothing left to do: `unchanged` counts a row the run didn't touch.
@@ -7771,7 +9904,7 @@ const makeImpl = (config, precomputedData) => {
7771
9904
  return { unchanged: 1 };
7772
9905
  // A tombstone under its current key: its sentinels may still hold
7773
9906
  // other key text or name another of the item's keys.
7774
- const sentinels = yield* rekeySentinels(ctx, "tombstone", row, targets.lives, targets.live, depth);
9907
+ const sentinels = yield* rekeySentinels(ctx, "tombstone", row, targets.isLive, targets.live, depth, false);
7775
9908
  return (sentinels.sentinelsMoved ?? 0) > 0 || (sentinels.conflicts ?? []).length > 0
7776
9909
  ? sentinels
7777
9910
  : { unchanged: 1 };
@@ -7793,6 +9926,37 @@ const makeImpl = (config, precomputedData) => {
7793
9926
  return moved;
7794
9927
  return Rekey.mergeTallies(moved, yield* rekeyAfterMove(ctx, row, targets.current, depth));
7795
9928
  });
9929
+ /**
9930
+ * A key's values read with each numeric composite as its declared kind or the other one, the
9931
+ * one whose value composes that composite's own text again (`KeyText136.readIndexKeys`), then
9932
+ * given as the kind it is declared: a field that stored both composed each value's own kind's
9933
+ * text. One reading, composite by composite, never one per combination. `undefined` when no
9934
+ * reading fits.
9935
+ */
9936
+ const readAsOtherNumericKind = (readAs) => {
9937
+ const read = readAs((attr) => {
9938
+ const kind = primaryKeyKinds.get(attr);
9939
+ return kind === "number"
9940
+ ? ["number", "bigint"]
9941
+ : kind === "bigint"
9942
+ ? ["bigint", "number"]
9943
+ : kind;
9944
+ });
9945
+ if (read === undefined)
9946
+ return undefined;
9947
+ const declared = { ...read };
9948
+ for (const [attr, kind] of primaryKeyKinds) {
9949
+ const value = read[attr];
9950
+ if (kind === "number" && typeof value === "bigint")
9951
+ declared[attr] = Number(value);
9952
+ if (kind === "bigint" && typeof value === "number") {
9953
+ if (!Number.isInteger(value))
9954
+ return undefined;
9955
+ declared[attr] = BigInt(value);
9956
+ }
9957
+ }
9958
+ return declared;
9959
+ };
7796
9960
  /**
7797
9961
  * Where a projection's row tombstone or outbox item belongs now. It holds no values: only the
7798
9962
  * key of the read-model row it was written for — its own, or `__edd_row_pk__` /
@@ -7817,7 +9981,8 @@ const makeImpl = (config, precomputedData) => {
7817
9981
  !storedSk.startsWith(rowSk)) {
7818
9982
  return undefined;
7819
9983
  }
7820
- const readKeyForm = KeyText136.readIndexKeys(KeyText136.formOfMark(schema, row[KEY_TEXT]?.N), entityType, entityVersion, primary, { [primary.pk.field]: rowPk, [primary.sk.field]: rowSk }, (attr) => primaryKeyKinds.get(attr));
9984
+ const readAs = (kindOf) => KeyText136.readIndexKeys(KeyText136.formOfMark(schema, row[KEY_TEXT]?.N), entityType, entityVersion, primary, { [primary.pk.field]: rowPk, [primary.sk.field]: rowSk }, kindOf);
9985
+ const readKeyForm = readAs((attr) => primaryKeyKinds.get(attr)) ?? readAsOtherNumericKind(readAs);
7821
9986
  if (readKeyForm === undefined)
7822
9987
  return undefined;
7823
9988
  const now = (() => {
@@ -7861,12 +10026,29 @@ const makeImpl = (config, precomputedData) => {
7861
10026
  },
7862
10027
  };
7863
10028
  };
10029
+ /**
10030
+ * A projection's row tombstone or outbox item as read, whole, and unclaimed by a drainer since. A
10031
+ * row too wide for that has no stamp to stand in, so `unprovable` decides: `undefined` when it's
10032
+ * reported.
10033
+ */
10034
+ const valuelessGuard = (read, pkField, unprovable) => {
10035
+ const claims = [OUTBOX_CLAIM, OUTBOX_CLAIMED_UNTIL];
10036
+ const whole = wholeRowGuard(read, pkField, [], claims, []);
10037
+ if (whole !== undefined)
10038
+ return whole;
10039
+ switch (unprovable) {
10040
+ case "report":
10041
+ return undefined;
10042
+ case "strongest":
10043
+ return asReadGuard(read, pkField, [], claims);
10044
+ }
10045
+ };
7864
10046
  /**
7865
10047
  * Move a projection's row tombstone or outbox item as a row: one transaction puts `item` at
7866
10048
  * `to`, where nothing may be, and deletes it at `from` while it is as `read`, unclaimed by a
7867
10049
  * drainer since. `false` when either condition failed.
7868
10050
  */
7869
- const moveValueless = (tableName, pkField, from, read, item) => Effect.gen(function* () {
10051
+ const moveValueless = (tableName, pkField, from, guard, item) => Effect.gen(function* () {
7870
10052
  const client = yield* Capacity.client;
7871
10053
  return yield* client
7872
10054
  .transactWriteItems({
@@ -7883,7 +10065,7 @@ const makeImpl = (config, precomputedData) => {
7883
10065
  Delete: {
7884
10066
  TableName: tableName,
7885
10067
  Key: toAttributeMap(from),
7886
- ...asReadGuard(read, pkField, [], [OUTBOX_CLAIM, OUTBOX_CLAIMED_UNTIL]),
10068
+ ...guard,
7887
10069
  },
7888
10070
  },
7889
10071
  ],
@@ -7927,8 +10109,12 @@ const makeImpl = (config, precomputedData) => {
7927
10109
  if (yield* claimedNow(read)) {
7928
10110
  return Rekey.mergeTallies(tally, rekeyConflict(kind, "contended", from, to, "A drainer holds it."));
7929
10111
  }
10112
+ const guard = valuelessGuard(read, keys.pk, Rekey.unprovableRow(ctx));
10113
+ if (guard === undefined) {
10114
+ return Rekey.mergeTallies(tally, rekeyConflict(kind, "unguarded", from, to, Rekey.UNGUARDED_MESSAGE));
10115
+ }
7930
10116
  if (!ctx.dryRun &&
7931
- (yield* moveValueless(ctx.tableName, keys.pk, from, read, plan.moved(read)))) {
10117
+ (yield* moveValueless(ctx.tableName, keys.pk, from, guard, plan.moved(read)))) {
7932
10118
  return countMove(ctx, kind, counted, tally);
7933
10119
  }
7934
10120
  const { Item: there } = yield* client.getItem({
@@ -7939,6 +10125,14 @@ const makeImpl = (config, precomputedData) => {
7939
10125
  if (there !== undefined) {
7940
10126
  // Another value's row left at its current key moves out first.
7941
10127
  if (occupantOf(there, counted) !== "stale") {
10128
+ // Or it is this row, moved there since the read by another row's move (counted then).
10129
+ const { Item: left } = yield* client.getItem({
10130
+ TableName: ctx.tableName,
10131
+ Key: toAttributeMap(from),
10132
+ ConsistentRead: true,
10133
+ });
10134
+ if (left === undefined)
10135
+ return tally;
7942
10136
  return Rekey.mergeTallies(tally, rekeyConflict(kind, "taken", from, to, "Another row holds its current key."));
7943
10137
  }
7944
10138
  if (depth >= Rekey.DISPLACE_DEPTH) {
@@ -8036,6 +10230,7 @@ const makeImpl = (config, precomputedData) => {
8036
10230
  generatedId: config.generatedId,
8037
10231
  vectorIndexes: config.vectorIndexes,
8038
10232
  _vectorIndexes: vectorIndexes,
10233
+ _refuseTableAttributes: refuseTableAttributes,
8039
10234
  _packedFields: Object.keys(packedFields),
8040
10235
  _packFields: packFields,
8041
10236
  _unpackFields: unpackFields,
@@ -8051,26 +10246,34 @@ const makeImpl = (config, precomputedData) => {
8051
10246
  _entityVersion: entityVersion,
8052
10247
  _serializeSparseFields: serializeSparseFields,
8053
10248
  _keyForm: keyForm,
10249
+ _domainKeyForm: domainKeyForm,
10250
+ _unstorableKey: unstorableKey,
8054
10251
  _renameToDynamo: renameToDynamo,
10252
+ _fieldOfAttribute: fieldOfAttribute,
8055
10253
  _incarnationToken: stampsIncarnation,
8056
10254
  _versionCorruption: versionCorruption,
8057
10255
  _fillDecodingDefaults: fillDecodingDefaults,
10256
+ _refuseNotReadBack: (encoded, operation) => kindReads().model.size === 0
10257
+ ? refuseNotReadBack(encoded, operation)
10258
+ : Effect.andThen(refuseNotReadBack(encoded, operation), refuseOtherKindRead(encoded, operation)),
8058
10259
  _unsentineledDefaults: unsentineledDefaults,
8059
10260
  _planPut: planPut,
8060
10261
  _multiItemWriteFeatures: multiItemWriteFeatures(),
8061
- _planUpdate: (key, state) => planUpdate(key, state).pipe(
10262
+ _prepareUpdate: (key, state, encoded) => prepareUpdate(key, state, encoded).pipe(Effect.map((prepared) => prepared)),
10263
+ _planUpdate: (key, state, prepared) => planUpdate(key, state, prepared).pipe(
8062
10264
  // Planning stops at the write, so only what an update raises BEFORE
8063
10265
  // writing can surface; anything else is a defect (`isPlanUpdateError`).
8064
10266
  Effect.catch((e) => (isPlanUpdateError(e) ? Effect.fail(e) : Effect.die(e)))),
8065
- _planDelete: (key, opts) => planDelete(key, opts).pipe(Effect.catch((e) => (isPlanDeleteError(e) ? Effect.fail(e) : Effect.die(e)))),
10267
+ _planDelete: (key, opts, encoded) => planDelete(key, opts, encoded).pipe(Effect.catch((e) => (isPlanDeleteError(e) ? Effect.fail(e) : Effect.die(e)))),
10268
+ _encodeKey: encodeKey,
8066
10269
  _liveRows: liveRows,
8067
10270
  _rekeyProjectionRow: rekeyProjectionRow,
8068
- _keyTextMark: (key) => KeyText136.markOf(schema, entityType, entityVersion, config.indexes.primary, keyForm(key)),
10271
+ _keyTextMark: (key) => KeyText136.markOf(schema, entityType, entityVersion, config.indexes.primary, domainKeyForm(key)),
8069
10272
  [Rekey.RekeyHandler]: rekeyHandler,
8070
10273
  _attachPrototype: attachPrototype,
8071
- _overTombstone: (tableName, item) => Effect.gen(function* () {
10274
+ _overTombstone: (item) => Effect.gen(function* () {
8072
10275
  const client = yield* Capacity.client;
8073
- return yield* overTombstone(self, client, tableName, item);
10276
+ return yield* overTombstone(self, client, yield* tableTag, item);
8074
10277
  }),
8075
10278
  _configure: (injectedSchema, injectedTableTag) => {
8076
10279
  schema = injectedSchema;
@@ -8108,15 +10311,15 @@ const makeImpl = (config, precomputedData) => {
8108
10311
  // Lifecycle ops reuse the get / delete carriers; their builders carry the
8109
10312
  // operation name consumed-capacity reports use (#174).
8110
10313
  getVersion: (key, versionNumber) => namedOp(getVersion(key, versionNumber), "Entity.getVersion"),
8111
- versions,
10314
+ versions: (key) => refusingQuery("Entity.versions", () => versionsQuery(key)),
8112
10315
  restore: (key) => namedOp(restore(key), "Entity.restore"),
8113
10316
  purge: (key) => namedOp(purge(key), "Entity.purge"),
8114
10317
  deleted: {
8115
10318
  get: (key) => namedOp(deletedGet(key), "Entity.deleted.get"),
8116
- list: deletedList,
10319
+ list: (key) => refusingQuery("Entity.deleted.list", () => deletedListQuery(key)),
8117
10320
  },
8118
10321
  append,
8119
- history,
10322
+ history: (key) => refusingQuery("Entity.history", () => historyQuery(key)),
8120
10323
  set,
8121
10324
  expectedVersion,
8122
10325
  query: queryNamespace,
@@ -8227,7 +10430,9 @@ export const bind = (entity) => Effect.gen(function* () {
8227
10430
  const decoded = (yield* entity._decodeRecord(raw));
8228
10431
  // Snapshots / tombstones live in the same partition under a
8229
10432
  // rewritten SK — their SK cannot be recomposed from the record.
8230
- const decodedKeyForm = keyFormFor(entity, decoded);
10433
+ // `decoded` holds domain values: the keys `put` wrote for them
10434
+ // are the key form of the values it stores.
10435
+ const decodedKeyForm = entity._domainKeyForm(decoded);
8231
10436
  const liveSk = KeyComposer.composeSk(boundSchema, entity.entityType, boundEntityVersion, primary, decodedKeyForm);
8232
10437
  if (storedSk !== liveSk)
8233
10438
  return false;
@@ -8358,6 +10563,28 @@ export const bind = (entity) => Effect.gen(function* () {
8358
10563
  const entityInternals = entity;
8359
10564
  const schemaRef = entityInternals._schema;
8360
10565
  const entityTypeRef = entityInternals.entityType;
10566
+ // An orderBy value as its model field stores it, as `append` encodes
10567
+ // it (`encodeForWrite`: encoded, else decoded and encoded) and as the
10568
+ // key form reads it, so a bound names the key an event's row composes;
10569
+ // a value neither takes, as given. Only a bound's key text: nothing is
10570
+ // stored from it.
10571
+ const encodeOrderBy = (() => {
10572
+ const field = orderBy === undefined
10573
+ ? undefined
10574
+ : getSchemaFields(entity.schemas.inputSchema)?.[orderBy];
10575
+ if (field === undefined)
10576
+ return (v) => v;
10577
+ const codec = field;
10578
+ const encode = Schema.encodeUnknownOption(codec);
10579
+ const decode = Schema.decodeUnknownOption(codec);
10580
+ return (v) => {
10581
+ const direct = encode(v);
10582
+ if (Option.isSome(direct))
10583
+ return direct.value;
10584
+ const again = Option.flatMap(decode(v), (decoded) => encode(decoded));
10585
+ return Option.isSome(again) ? again.value : v;
10586
+ };
10587
+ })();
8361
10588
  // composeSkCondition: rewrite user's .where() values by prefixing
8362
10589
  // with `<currentSk>#e#` and applying serialisation, casing and
8363
10590
  // escaping to the user-supplied orderBy value.
@@ -8366,15 +10593,24 @@ export const bind = (entity) => Effect.gen(function* () {
8366
10593
  // We need the `currentSk` + prefix. The user's `key` lets us derive
8367
10594
  // `currentSk` via the same primary SK composer used by `history()`.
8368
10595
  // `key` is the caller's Type-side key; the stored SK was composed
8369
- // from the encoded form, so normalise it the same way
8370
- // `composePrimaryKey` does before recomposing.
8371
- const currentSk = KeyComposer.composeSk(schemaRef, entityTypeRef, 1, primary, keyFormFor(entityInternals, key));
10596
+ // from the encoded form, so compose it as `get` does: the key form of
10597
+ // the value `put` stores (`_domainKeyForm`).
10598
+ const currentSk = KeyComposer.composeSk(schemaRef, entityTypeRef, 1, primary, entity._domainKeyForm(key));
8372
10599
  const prefix = KeyComposer.composeEventSkPrefix(currentSk, schemaRef.casing);
8373
- // Key form first: the event SK is composed from the key form of the
8374
- // orderBy value (`Entity.append` composes from `serialisedInput`), so
8375
- // a transformed orderBy composite must take the same route here.
8376
- const keyFormOf = (v) => orderBy === undefined ? v : keyFormFor(entityInternals, { [orderBy]: v })[orderBy];
8377
- const rewrite = (v) => `${prefix}${KeyComposer.keyValueText(schemaRef, keyFormOf(v), schemaRef.casing)}`;
10600
+ // Exactly as `Entity.append` composes the event's sort key: the value
10601
+ // encoded as `appendInput` encodes it, put into key form from that,
10602
+ // and the one of the two the setting keys on (`eventOrderByValue`).
10603
+ // From the caller's value, a transformed orderBy (`Option(x)`, a
10604
+ // `NumberFromString` with `escapeKeys` off) composed other text.
10605
+ const keyFormOf = (v) => orderBy === undefined ? v : entity._keyForm({ [orderBy]: encodeOrderBy(v) })[orderBy];
10606
+ const rewrite = (v) => {
10607
+ if (orderBy === undefined) {
10608
+ return `${prefix}${KeyComposer.keyValueText(schemaRef, v, schemaRef.casing)}`;
10609
+ }
10610
+ const encoded = encodeOrderBy(v);
10611
+ const value = KeyComposer.eventOrderByValue(schemaRef, encoded, entity._keyForm({ [orderBy]: encoded })[orderBy]);
10612
+ return `${prefix}${KeyComposer.keyValueText(schemaRef, value, schemaRef.casing)}`;
10613
+ };
8378
10614
  // DynamoDB allows ONE sort key condition, and this one replaces the
8379
10615
  // history query's `begins_with(prefix)`. Every operator therefore
8380
10616
  // keeps both ends inside `prefix` — the `.where()` clamp of