Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(dynamodb): validation parity on reads, deletes, batches, and transactions (#1067)
Futac19732063d9d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 03c4d18f..7efea614 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **DynamoDB — validation parity with real AWS on reads, deletes, batches, and transactions** — validation gaps that let malformed requests succeed silently (all verified against **real AWS DynamoDB**): (1) `GetItem`, `DeleteItem`, and `BatchGetItem` now reject key attributes carrying an empty string/binary value, as `PutItem` already did; (2) `BatchWriteItem` validates every member *before* applying any — previously a bad member returned the correct `ValidationException` but earlier members were already written; (3) `TransactWriteItems` validates every member before applying anything and matches real AWS's two failure shapes: an empty-string/binary key value (or malformed item) is an up-front top-level `ValidationException`, whereas a wrong-typed key or an update-expression type error is surfaced as a `TransactionCanceledException` with a positional `ValidationError` cancellation reason — previously an invalid member was silently committed with no error at all; (4) `Query` rejects a `KeyConditionExpression` `BETWEEN` with inverted bounds at parse time with the AWS error message, instead of returning an empty result; (5) `Query` validates key-condition operands like key values — an empty string/binary operand on a key attribute is rejected; (6) `Query` rejects an `ExclusiveStartKey` whose sort value violates the range-key predicate (`The provided starting key does not match the range key predicate`) — such a cursor can never have been issued by a previous page; (7) `UpdateItem` `SET` rejects a document path that doesn't resolve on the item (`The provided expression refers to an attribute that does not exist in the item`) — e.g. `list_append` on a missing attribute, where `if_not_exists` is the sanctioned form; previously the assignment was silently skipped; (8) `UpdateItem` `ADD`/`DELETE` reject non-Number/Set operands (`Incorrect operand type for operator or function`, with the AWS quirk that the `typeSet` is reported as `ALLOWED_FOR_ADD_OPERAND` even for `DELETE`) and operands whose type doesn't match the existing attribute (`An operand in the update expression has an incorrect data type`) — previously `ADD` could silently *replace* a set attribute with a number, and `DELETE` silently no-opped. All error shapes verified against real AWS DynamoDB. Contributed by @ifutivic.- **DynamoDB — `Query`/`Scan` return `LastEvaluatedKey` when results end exactly at `Limit`** — real DynamoDB doesn't look ahead: whenever it stops because of the limit it returns a `LastEvaluatedKey`, even if nothing remains, and the follow-up page comes back empty with no key. MiniStack only returned the key when strictly more items remained, so SDK pagination helpers that rely on the exact-limit page (e.g. "has more pages" checks) diverged from AWS. Verified against DynamoDB Local. Contributed by @ifutivic.## [1.4.1] — 2026-07-09diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex fa568660..277244f6 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -14,6 +14,8 @@ Legacy conditional parameters: Expected (PutItem/UpdateItem/DeleteItem),Uses X-Amz-Target header for action routing (JSON API)."""+import base64+import binasciiimport copyimport jsonimport logging@@ -492,14 +494,9 @@ def _validate_item(item: dict, pk_name: str | None = None, sk_name: str | None =for name, value in item.items():# Empty string/binary not allowed for hash/sort key attributesif name in (pk_name, sk_name):- if isinstance(value, dict):- (vtype, vval), = value.items()- if vtype == "S" and vval == "":- return error_response_json("ValidationException",- f"One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: {name}", 400)- if vtype == "B" and (vval == "" or vval == b""):- return error_response_json("ValidationException",- f"One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty binary value. Key: {name}", 400)+ err = _empty_key_value_error(name, value)+ if err:+ return errerr = _validate_attribute_value(name, value)if err:return err@@ -1850,6 +1847,41 @@ def _query(data):if resolved and resolved not in allowed:return error_response_json("ValidationException",f"Query condition missed key schema element: {resolved}", 400)+ # Key-condition operands are validated like key values themselves:+ # an empty string/binary operand is rejected with the same error AWS+ # raises for empty key attribute values.+ cur_attr = pk_name+ for tok in kce_tokens:+ if tok[0] == "IDENT" and tok[1] in allowed:+ cur_attr = tok[1]+ elif tok[0] == "NAME_REF" and ean.get(tok[1]) in allowed:+ cur_attr = ean[tok[1]]+ elif tok[0] == "VALUE_REF":+ err = _empty_key_value_error(cur_attr, eav.get(tok[1]))+ if err:+ return err+ # AWS validates BETWEEN bounds at parse time: lower must be <= upper,+ # even when the partition holds no items.+ for i, tok in enumerate(kce_tokens):+ if (tok[0] == "IDENT" and tok[1].upper() == "BETWEEN"+ and i + 3 < len(kce_tokens)+ and kce_tokens[i + 1][0] == "VALUE_REF"+ and kce_tokens[i + 2][0] == "IDENT" and kce_tokens[i + 2][1].upper() == "AND"+ and kce_tokens[i + 3][0] == "VALUE_REF"):+ err = _between_bounds_error(eav.get(kce_tokens[i + 1][1]), eav.get(kce_tokens[i + 3][1]))+ if err:+ return err+ # An ExclusiveStartKey must itself satisfy the key condition — AWS+ # rejects a cursor whose sort value falls outside the range predicate+ # (it could never have been issued by a previous page of this query).+ if esk and sk_name:+ try:+ esk_matches = _evaluate_condition(key_cond, esk, eav, ean, slot="KeyConditionExpression")+ except ValueError:+ esk_matches = True+ if not esk_matches:+ return error_response_json("ValidationException",+ "The provided starting key does not match the range key predicate", 400)if is_gsi or index_name:candidates = []@@ -2742,14 +2774,28 @@ def _batch_write_item(data):400,)for req in requests:+ # Validate every member up front: AWS rejects the whole+ # BatchWriteItem call before applying anything, so a bad member+ # must not leave earlier members written.if "PutRequest" in req:+ item = req["PutRequest"].get("Item", {})+ err = _validate_item(item, table.get("pk_name"), table.get("sk_name"))+ if err:+ return err+ _, _, key_err = _resolve_table_key_values(table, item, allow_extra=True)+ if key_err:+ return key_errkey_repr = (table_name,- _extract_key_val(req["PutRequest"]["Item"].get(table.get("pk_name") or "")),- _extract_key_val(req["PutRequest"]["Item"].get(table.get("sk_name") or "")) if table.get("sk_name") else None)+ _extract_key_val(item.get(table.get("pk_name") or "")),+ _extract_key_val(item.get(table.get("sk_name") or "")) if table.get("sk_name") else None)elif "DeleteRequest" in req:+ key = req["DeleteRequest"].get("Key", {})+ _, _, key_err = _resolve_table_key_values(table, key, allow_extra=False)+ if key_err:+ return key_errkey_repr = (table_name,- _extract_key_val(req["DeleteRequest"]["Key"].get(table.get("pk_name") or "")),- _extract_key_val(req["DeleteRequest"]["Key"].get(table.get("sk_name") or "")) if table.get("sk_name") else None)+ _extract_key_val(key.get(table.get("pk_name") or "")),+ _extract_key_val(key.get(table.get("sk_name") or "")) if table.get("sk_name") else None)else:continueif key_repr in seen_keys:@@ -2897,7 +2943,16 @@ def _transact_write_items(data):return json_response(prior.get("response", {}))return error_response_json("IdempotentParameterMismatchException","Request token already in use for another request with a different payload", 400)- # Duplicate-key rejection across the transaction.+ # Member validation across the transaction. AWS validates every member+ # before applying anything, but splits the failure into two shapes+ # (verified against real DynamoDB):+ # * up-front input errors -> top-level ValidationException (Phase 0):+ # empty-string/binary key values, malformed item attrs, item size,+ # and duplicate target keys.+ # * per-item semantic errors -> TransactionCanceledException with a+ # positional ValidationError reason (Phase 1): wrong-typed keys and+ # update-expression type errors.+ # Nothing is applied in either case.seen_targets = set()for transact in items_list:op_type, op = _extract_transact_op(transact)@@ -2907,10 +2962,18 @@ def _transact_write_items(data):tbl = _tables.get(tn)if not tbl:continue+ key_src = op.get("Item", {}) if op_type == "Put" else op.get("Key", {})+ # Empty-string/binary key value -> top-level ValidationException.+ for kn in (tbl.get("pk_name"), tbl.get("sk_name")):+ if kn and kn in key_src:+ err = _empty_key_value_error(kn, key_src[kn])+ if err:+ return err+ # Non-key attribute value / item-size validation is also up-front.if op_type == "Put":- key_src = op.get("Item", {})- else:- key_src = op.get("Key", {})+ item_err = _validate_item(key_src, tbl.get("pk_name"), tbl.get("sk_name"))+ if item_err:+ return item_errtarget = (tn,_extract_key_val(key_src.get(tbl.get("pk_name") or "")),_extract_key_val(key_src.get(tbl.get("sk_name") or "")) if tbl.get("sk_name") else None)@@ -2919,6 +2982,35 @@ def _transact_write_items(data):"Transaction request cannot include multiple operations on one item", 400)seen_targets.add(target)+ # Phase 1: wrong-typed keys and update-expression type errors surface as a+ # per-item ValidationError cancellation reason, not a top-level exception.+ val_reasons = {}+ for idx, transact in enumerate(items_list):+ op_type, op = _extract_transact_op(transact)+ if op is None:+ continue+ tbl = _tables.get(op.get("TableName", ""))+ if not tbl:+ continue+ key_src = op.get("Item", {}) if op_type == "Put" else op.get("Key", {})+ type_msg = _key_type_mismatch_reason(tbl, key_src)+ if type_msg:+ val_reasons[idx] = type_msg+ continue+ if op_type == "Update":+ ue = op.get("UpdateExpression", "")+ if ue:+ pk_val = _extract_key_val(key_src.get(tbl["pk_name"]))+ sk_val = _extract_key_val(key_src.get(tbl["sk_name"])) if tbl["sk_name"] else "__no_sort__"+ existing = tbl["items"].get(pk_val, {}).get(sk_val)+ probe = copy.deepcopy(existing) if existing else dict(key_src)+ try:+ _apply_update_expression(probe, ue, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {}))+ except ValueError as exc:+ val_reasons[idx] = str(exc)+ if val_reasons:+ return _transact_validation_cancel_response(len(items_list), val_reasons)+# Phase 1: evaluate ALL conditions and collect failures (AWS returns all,# not just the first).failures = {} # idx -> existing_item_or_None@@ -4724,6 +4816,10 @@ def _eval_set_value(tokens, item, attr_values, attr_names):val = _get_at_path(item, path)if val is not None:return val+ # A document path in a SET value must resolve — AWS rejects e.g.+ # `SET a = list_append(a, :v)` when `a` doesn't exist on the item+ # (if_not_exists is the sanctioned way to handle absence).+ raise ValueError("The provided expression refers to an attribute that does not exist in the item")if len(tokens) == 1 and tokens[0][0] == 'VALUE_REF':return attr_values.get(tokens[0][1])@@ -4739,6 +4835,19 @@ def _apply_remove(item, tokens, attr_names, updated_attrs):_remove_at_path(item, path)+_AV_TYPE_NAMES = {+ "S": "STRING", "N": "NUMBER", "B": "BINARY",+ "SS": "STRING SET", "NS": "NUMBER SET", "BS": "BINARY SET",+ "M": "MAP", "L": "LIST", "BOOL": "BOOLEAN", "NULL": "NULL",+}+++def _operand_type(av):+ if isinstance(av, dict) and len(av) == 1:+ return next(iter(av))+ return None++def _apply_add(item, tokens, attr_values, attr_names, updated_attrs):for part in _split_by_comma(tokens):val_idx = None@@ -4753,9 +4862,18 @@ def _apply_add(item, tokens, attr_values, attr_names, updated_attrs):if not path or add_val is None:continue- updated_attrs.add(path[0])-+ # ADD only accepts Number and set operands (parse-time in AWS), and the+ # existing attribute must carry the same type (runtime in AWS).+ op_type = _operand_type(add_val)+ if op_type not in ("N", "SS", "NS", "BS"):+ raise ValueError(+ "Invalid UpdateExpression: Incorrect operand type for operator or function; "+ f"operator: ADD, operand type: {_AV_TYPE_NAMES.get(op_type, op_type)}, typeSet: ALLOWED_FOR_ADD_OPERAND")existing = _get_at_path(item, path)+ if existing is not None and _operand_type(existing) != op_type:+ raise ValueError("An operand in the update expression has an incorrect data type")++ updated_attrs.add(path[0])if "N" in add_val:inc = Decimal(add_val["N"])@@ -4786,20 +4904,29 @@ def _apply_delete(item, tokens, attr_values, attr_names, updated_attrs):if not path or del_val is None:continue+ # DELETE only accepts set operands (parse-time in AWS), and the+ # existing attribute must be a set of the same type (runtime in AWS).+ op_type = _operand_type(del_val)+ if op_type not in ("SS", "NS", "BS"):+ # NOTE: real DynamoDB reports typeSet ALLOWED_FOR_ADD_OPERAND even for+ # the DELETE operator (verified against real AWS), so we match that.+ raise ValueError(+ "Invalid UpdateExpression: Incorrect operand type for operator or function; "+ f"operator: DELETE, operand type: {_AV_TYPE_NAMES.get(op_type, op_type)}, typeSet: ALLOWED_FOR_ADD_OPERAND")+updated_attrs.add(path[0])existing = _get_at_path(item, path)if existing is None:continue+ if _operand_type(existing) != op_type:+ raise ValueError("An operand in the update expression has an incorrect data type")- for set_type in ("SS", "NS", "BS"):- if set_type in del_val and set_type in existing:- remaining = [s for s in existing[set_type] if s not in del_val[set_type]]- if remaining:- _set_at_path(item, path, {set_type: remaining})- else:- _remove_at_path(item, path)- break+ remaining = [s for s in existing[op_type] if s not in del_val[op_type]]+ if remaining:+ _set_at_path(item, path, {op_type: remaining})+ else:+ _remove_at_path(item, path)# ---------------------------------------------------------------------------@@ -5091,6 +5218,9 @@ def _resolve_table_key_values(table, attrs, allow_extra):raw_value = attrs.get(key_name)if not isinstance(raw_value, dict) or set(raw_value.keys()) != {expected_type}:return "", "", _key_schema_validation_error()+ err = _empty_key_value_error(key_name, raw_value)+ if err:+ return "", "", errpk_val = _extract_key_val(attrs.get(table["pk_name"]))sk_val = _extract_key_val(attrs.get(table["sk_name"])) if table["sk_name"] else "__no_sort__"return pk_val, sk_val, None@@ -5100,6 +5230,92 @@ def _key_schema_validation_error():return error_response_json("ValidationException", "The provided key element does not match the schema", 400)+def _key_type_mismatch_reason(table, attrs):+ """Return the AWS message for a key attribute present with the wrong type,+ else None. Unlike an empty key value (which real AWS rejects up front with a+ ValidationException), a wrong-typed key inside a transaction is surfaced as a+ per-item ValidationError cancellation reason."""+ if not isinstance(attrs, dict):+ return None+ for key_name in (table.get("pk_name"), table.get("sk_name")):+ if not key_name or key_name not in attrs:+ continue+ expected = _get_attr_type(table, key_name)+ raw = attrs.get(key_name)+ if isinstance(raw, dict) and len(raw) == 1:+ actual = next(iter(raw))+ if actual != expected:+ return (f"One or more parameter values were invalid: "+ f"Type mismatch for key {key_name} expected: {expected} actual: {actual}")+ return None+++def _transact_validation_cancel_response(total, val_reasons):+ """Build a TransactionCanceledException whose CancellationReasons carry a+ positional ValidationError for each failing member (Code "None" otherwise),+ matching how real DynamoDB reports per-item validation failures in a+ transaction (wrong-typed keys, update-expression type errors)."""+ reasons = []+ for i in range(total):+ if i in val_reasons:+ reasons.append({"Code": "ValidationError", "Message": val_reasons[i]})+ else:+ reasons.append({"Code": "None"})+ msg = ("Transaction cancelled, please refer cancellation reasons for specific reasons ["+ + ", ".join(r["Code"] for r in reasons) + "]")+ body = json.dumps({+ "__type": "TransactionCanceledException",+ "message": msg,+ "CancellationReasons": reasons,+ }, ensure_ascii=False).encode("utf-8")+ return 400, {+ "Content-Type": "application/x-amz-json-1.0",+ "x-amzn-errortype": "TransactionCanceledException",+ }, body+++def _between_bounds_error(lo_av, hi_av):+ """Static BETWEEN bounds check for KeyConditionExpression. AWS rejects an+ inverted range (lower > upper) with a ValidationException at parse time."""+ if not isinstance(lo_av, dict) or not isinstance(hi_av, dict):+ return None+ if len(lo_av) != 1 or len(hi_av) != 1:+ return None+ (lt, lv), = lo_av.items()+ (ht, hv), = hi_av.items()+ if lt != ht:+ return None+ try:+ if lt == "N":+ inverted = Decimal(lv) > Decimal(hv)+ elif lt == "B":+ inverted = base64.b64decode(lv) > base64.b64decode(hv)+ else:+ inverted = str(lv) > str(hv)+ except (InvalidOperation, TypeError, ValueError, binascii.Error):+ return None+ if not inverted:+ return None+ return error_response_json("ValidationException",+ "Invalid KeyConditionExpression: The BETWEEN operator requires upper bound to be greater than or equal to lower bound; "+ f"lower bound operand: AttributeValue: {{{lt}:{lv}}}, upper bound operand: AttributeValue: {{{ht}:{hv}}}", 400)+++def _empty_key_value_error(key_name, raw_value):+ """AWS rejects empty string/binary values for key attributes on every data+ plane operation (reads and deletes included), not just writes."""+ if not isinstance(raw_value, dict) or len(raw_value) != 1:+ return None+ (vtype, vval), = raw_value.items()+ if vtype == "S" and vval == "":+ return error_response_json("ValidationException",+ f"One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: {key_name}", 400)+ if vtype == "B" and vval in ("", b""):+ return error_response_json("ValidationException",+ f"One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty binary value. Key: {key_name}", 400)+ return None++def _resolve_index_keys(table, index_name):if not index_name:return table["pk_name"], table["sk_name"], Falsediff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.pyindex abf49163..e66ad1e5 100644--- a/tests/test_dynamodb.py+++ b/tests/test_dynamodb.py@@ -6142,11 +6142,11 @@ def test_dynamodb_update_item_valid_update_still_succeeds(ddb):# ----------------------------------------------------------------------------# LastEvaluatedKey when the results end exactly at Limit (AWS doesn't look-# ahead: stopping at the limit always yields a key; the next page is empty).+# Validation parity: empty key parts on reads/deletes, batch/transact+# atomicity, BETWEEN bounds, ADD/DELETE operand types.# ----------------------------------------------------------------------------def _create_paging_table(ddb, name):+def _create_composite_table(ddb, name):try:ddb.delete_table(TableName=name)except Exception:@@ -6163,92 +6163,403 @@ def _create_paging_table(ddb, name):],BillingMode="PAY_PER_REQUEST",)- for i in range(1, 4):- ddb.put_item(TableName=name, Item={"pk": {"S": "a"}, "sk": {"S": str(i)}})-def test_dynamodb_query_lek_present_when_limit_equals_count(ddb):- name = "lek-query-exact"- _create_paging_table(ddb, name)+def _assert_empty_key_rejected(exc, key_name):+ err = exc.value.response["Error"]+ assert err["Code"] == "ValidationException"+ assert "cannot contain an empty string value" in err["Message"]+ assert f"Key: {key_name}" in err["Message"]+++def test_dynamodb_get_item_rejects_empty_key_part(ddb):+ name = "val-get-empty-key"+ _create_composite_table(ddb, name)+ try:+ with pytest.raises(ClientError) as exc:+ ddb.get_item(TableName=name, Key={"pk": {"S": "a"}, "sk": {"S": ""}})+ _assert_empty_key_rejected(exc, "sk")+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_delete_item_rejects_empty_key_part(ddb):+ name = "val-del-empty-key"+ _create_composite_table(ddb, name)+ try:+ with pytest.raises(ClientError) as exc:+ ddb.delete_item(TableName=name, Key={"pk": {"S": ""}, "sk": {"S": "1"}})+ _assert_empty_key_rejected(exc, "pk")+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_batch_get_item_rejects_empty_key_part(ddb):+ name = "val-bget-empty-key"+ _create_composite_table(ddb, name)+ try:+ with pytest.raises(ClientError) as exc:+ ddb.batch_get_item(RequestItems={name: {"Keys": [+ {"pk": {"S": "a"}, "sk": {"S": "1"}},+ {"pk": {"S": "a"}, "sk": {"S": ""}},+ ]}})+ _assert_empty_key_rejected(exc, "sk")+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_batch_write_item_invalid_member_writes_nothing(ddb):+ """AWS validates the whole BatchWriteItem request before applying anything:+ a bad member must not leave earlier members written."""+ name = "val-bwrite-atomic"+ _create_composite_table(ddb, name)try:- page1 = ddb.query(+ with pytest.raises(ClientError) as exc:+ ddb.batch_write_item(RequestItems={name: [+ {"PutRequest": {"Item": {"pk": {"S": "b"}, "sk": {"S": "1"}}}},+ {"PutRequest": {"Item": {"pk": {"S": "b"}, "sk": {"S": ""}}}},+ ]})+ _assert_empty_key_rejected(exc, "sk")+ resp = ddb.get_item(TableName=name, Key={"pk": {"S": "b"}, "sk": {"S": "1"}})+ assert "Item" not in resp, "valid member must not be applied when the batch fails validation"+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_batch_write_item_invalid_delete_key_rejected(ddb):+ name = "val-bwrite-delkey"+ _create_composite_table(ddb, name)+ try:+ with pytest.raises(ClientError) as exc:+ ddb.batch_write_item(RequestItems={name: [+ {"DeleteRequest": {"Key": {"pk": {"S": "b"}, "sk": {"S": ""}}}},+ ]})+ _assert_empty_key_rejected(exc, "sk")+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_transact_write_invalid_member_writes_nothing(ddb):+ """AWS rejects the whole transaction with a plain ValidationException when+ a member carries an empty key part; nothing is applied."""+ name = "val-txn-atomic"+ _create_composite_table(ddb, name)+ try:+ with pytest.raises(ClientError) as exc:+ ddb.transact_write_items(TransactItems=[+ {"Put": {"TableName": name, "Item": {"pk": {"S": "tx"}, "sk": {"S": "1"}}}},+ {"Put": {"TableName": name, "Item": {"pk": {"S": "tx"}, "sk": {"S": ""}}}},+ ])+ _assert_empty_key_rejected(exc, "sk")+ resp = ddb.get_item(TableName=name, Key={"pk": {"S": "tx"}, "sk": {"S": "1"}})+ assert "Item" not in resp, "valid member must not be applied when the transaction fails validation"+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_transact_write_invalid_delete_key_rejected(ddb):+ name = "val-txn-delkey"+ _create_composite_table(ddb, name)+ try:+ with pytest.raises(ClientError) as exc:+ ddb.transact_write_items(TransactItems=[+ {"Delete": {"TableName": name, "Key": {"pk": {"S": ""}, "sk": {"S": "1"}}}},+ ])+ _assert_empty_key_rejected(exc, "pk")+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_transact_write_wrong_type_key_is_cancelled(ddb):+ """A wrong-typed key inside a transaction is a per-item ValidationError+ cancellation reason (TransactionCanceledException), NOT a top-level+ ValidationException (which is reserved for empty key values). Verified+ against real AWS DynamoDB."""+ name = "val-txn-wrongtype"+ _create_composite_table(ddb, name)+ try:+ with pytest.raises(ClientError) as exc:+ ddb.transact_write_items(TransactItems=[+ {"Put": {"TableName": name, "Item": {"pk": {"S": "ok"}, "sk": {"S": "1"}}}},+ {"Put": {"TableName": name, "Item": {"pk": {"N": "5"}, "sk": {"S": "1"}}}},+ ])+ assert exc.value.response["Error"]["Code"] == "TransactionCanceledException"+ reasons = exc.value.response.get("CancellationReasons", [])+ assert [r.get("Code") for r in reasons] == ["None", "ValidationError"]+ assert "Type mismatch for key pk" in reasons[1].get("Message", "")+ # nothing applied+ resp = ddb.get_item(TableName=name, Key={"pk": {"S": "ok"}, "sk": {"S": "1"}})+ assert "Item" not in resp+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_transact_write_update_type_mismatch_is_cancelled(ddb):+ """An update-expression type error inside a transaction surfaces as a+ ValidationError cancellation reason, not a top-level ValidationException."""+ name = "val-txn-updtype"+ _create_composite_table(ddb, name)+ try:+ ddb.put_item(TableName=name,- KeyConditionExpression="pk = :p",- ExpressionAttributeValues={":p": {"S": "a"}},- Limit=3,+ Item={"pk": {"S": "a"}, "sk": {"S": "1"}, "tags": {"SS": ["x"]}},)- assert page1["Count"] == 3- assert "LastEvaluatedKey" in page1, "stopping exactly at Limit must yield a LastEvaluatedKey"+ with pytest.raises(ClientError) as exc:+ ddb.transact_write_items(TransactItems=[+ {"Update": {+ "TableName": name,+ "Key": {"pk": {"S": "a"}, "sk": {"S": "1"}},+ "UpdateExpression": "ADD tags :n",+ "ExpressionAttributeValues": {":n": {"N": "5"}},+ }},+ ])+ assert exc.value.response["Error"]["Code"] == "TransactionCanceledException"+ reasons = exc.value.response.get("CancellationReasons", [])+ assert reasons and reasons[0].get("Code") == "ValidationError"+ # existing attribute untouched+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "a"}, "sk": {"S": "1"}})["Item"]+ assert item["tags"] == {"SS": ["x"]}+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_query_between_inverted_bounds_rejected(ddb):+ """AWS validates BETWEEN bounds at parse time, even for an empty partition."""+ name = "val-between"+ _create_composite_table(ddb, name)+ try:+ with pytest.raises(ClientError) as exc:+ ddb.query(+ TableName=name,+ KeyConditionExpression="pk = :p AND sk BETWEEN :hi AND :lo",+ ExpressionAttributeValues={+ ":p": {"S": "a"}, ":hi": {"S": "z"}, ":lo": {"S": "a"},+ },+ )+ err = exc.value.response["Error"]+ assert err["Code"] == "ValidationException"+ assert "BETWEEN operator requires upper bound to be greater than or equal to lower bound" in err["Message"]+ finally:+ ddb.delete_table(TableName=name)+- page2 = ddb.query(+def test_dynamodb_query_between_valid_and_numeric_bounds(ddb):+ """Valid BETWEEN still works; numeric bounds compare numerically (9 < 10)."""+ name = "val-between-ok"+ try:+ ddb.delete_table(TableName=name)+ except Exception:+ pass+ ddb.create_table(+ TableName=name,+ KeySchema=[+ {"AttributeName": "pk", "KeyType": "HASH"},+ {"AttributeName": "sk", "KeyType": "RANGE"},+ ],+ AttributeDefinitions=[+ {"AttributeName": "pk", "AttributeType": "S"},+ {"AttributeName": "sk", "AttributeType": "N"},+ ],+ BillingMode="PAY_PER_REQUEST",+ )+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "a"}, "sk": {"N": "9"}})+ resp = ddb.query(TableName=name,- KeyConditionExpression="pk = :p",- ExpressionAttributeValues={":p": {"S": "a"}},- Limit=3,- ExclusiveStartKey=page1["LastEvaluatedKey"],+ KeyConditionExpression="pk = :p AND sk BETWEEN :lo AND :hi",+ ExpressionAttributeValues={+ ":p": {"S": "a"}, ":lo": {"N": "9"}, ":hi": {"N": "10"},+ },)- assert page2["Count"] == 0- assert "LastEvaluatedKey" not in page2+ assert resp["Count"] == 1finally:ddb.delete_table(TableName=name)-def test_dynamodb_query_no_lek_when_limit_exceeds_count(ddb):- name = "lek-query-over"- _create_paging_table(ddb, name)+def test_dynamodb_update_add_operand_type_must_be_number_or_set(ddb):+ name = "val-add-operand"+ _create_update_item_table(ddb, name)try:- resp = ddb.query(+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}})+ with pytest.raises(ClientError) as exc:+ ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="ADD tags :v",+ ExpressionAttributeValues={":v": {"S": "y"}},+ )+ err = exc.value.response["Error"]+ assert err["Code"] == "ValidationException"+ assert "operator: ADD, operand type: STRING" in err["Message"]+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_add_type_mismatch_with_existing_attr(ddb):+ name = "val-add-mismatch"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "tags": {"SS": ["x"]}})+ with pytest.raises(ClientError) as exc:+ ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="ADD tags :v",+ ExpressionAttributeValues={":v": {"N": "5"}},+ )+ err = exc.value.response["Error"]+ assert err["Code"] == "ValidationException"+ assert err["Message"] == "An operand in the update expression has an incorrect data type"+ # attribute untouched+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "k"}})["Item"]+ assert item["tags"] == {"SS": ["x"]}+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_delete_operand_type_must_be_set(ddb):+ name = "val-delete-operand"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "tags": {"SS": ["x"]}})+ with pytest.raises(ClientError) as exc:+ ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="DELETE tags :v",+ ExpressionAttributeValues={":v": {"N": "1"}},+ )+ err = exc.value.response["Error"]+ assert err["Code"] == "ValidationException"+ assert "operator: DELETE, operand type: NUMBER" in err["Message"]+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_delete_type_mismatch_with_existing_attr(ddb):+ name = "val-delete-mismatch"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "tags": {"SS": ["x"]}})+ with pytest.raises(ClientError) as exc:+ ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="DELETE tags :v",+ ExpressionAttributeValues={":v": {"NS": ["1"]}},+ )+ err = exc.value.response["Error"]+ assert err["Code"] == "ValidationException"+ assert err["Message"] == "An operand in the update expression has an incorrect data type"+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_add_and_delete_still_work_on_matching_types(ddb):+ """Sanity: valid ADD/DELETE on matching types keep working."""+ name = "val-add-del-ok"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "tags": {"SS": ["x"]}, "num": {"N": "1"}})+ ddb.update_item(TableName=name,- KeyConditionExpression="pk = :p",- ExpressionAttributeValues={":p": {"S": "a"}},- Limit=4,+ Key={"pk": {"S": "k"}},+ UpdateExpression="ADD tags :t, num :n",+ ExpressionAttributeValues={":t": {"SS": ["y"]}, ":n": {"N": "2"}},)- assert resp["Count"] == 3- assert "LastEvaluatedKey" not in resp+ ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="DELETE tags :d",+ ExpressionAttributeValues={":d": {"SS": ["x"]}},+ )+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "k"}})["Item"]+ assert item["tags"] == {"SS": ["y"]}+ assert item["num"] == {"N": "3"}finally:ddb.delete_table(TableName=name)-def test_dynamodb_scan_lek_present_when_limit_equals_count(ddb):- name = "lek-scan-exact"- _create_paging_table(ddb, name)+def test_dynamodb_query_empty_string_operand_on_key_attr_rejected(ddb):+ """Key-condition operands are validated like key values: empty strings+ are rejected with the same error AWS raises for empty key attributes."""+ name = "val-kce-empty-operand"+ _create_composite_table(ddb, name)try:- page1 = ddb.scan(TableName=name, Limit=3)- assert page1["Count"] == 3- assert "LastEvaluatedKey" in page1, "stopping exactly at Limit must yield a LastEvaluatedKey"+ with pytest.raises(ClientError) as exc:+ ddb.query(+ TableName=name,+ KeyConditionExpression="pk = :p AND sk BETWEEN :lo AND :hi",+ ExpressionAttributeValues={+ ":p": {"S": "a"}, ":lo": {"S": ""}, ":hi": {"S": "z"},+ },+ )+ _assert_empty_key_rejected(exc, "sk")+ finally:+ ddb.delete_table(TableName=name)- page2 = ddb.scan(TableName=name, Limit=3, ExclusiveStartKey=page1["LastEvaluatedKey"])- assert page2["Count"] == 0- assert "LastEvaluatedKey" not in page2- over = ddb.scan(TableName=name, Limit=4)- assert over["Count"] == 3- assert "LastEvaluatedKey" not in over+def test_dynamodb_query_esk_outside_range_predicate_rejected(ddb):+ """An ExclusiveStartKey whose sort value violates the key condition could+ never have been issued by a previous page; AWS rejects it."""+ name = "val-esk-predicate"+ _create_composite_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "a"}, "sk": {"S": "sibling-1"}})+ with pytest.raises(ClientError) as exc:+ ddb.query(+ TableName=name,+ KeyConditionExpression="pk = :p AND begins_with(sk, :pre)",+ ExpressionAttributeValues={":p": {"S": "a"}, ":pre": {"S": "sibling"}},+ ExclusiveStartKey={"pk": {"S": "a"}, "sk": {"S": "x"}},+ )+ err = exc.value.response["Error"]+ assert err["Code"] == "ValidationException"+ assert "does not match the range key predicate" in err["Message"]++ # A cursor inside the predicate stays valid even when no item matches it.+ resp = ddb.query(+ TableName=name,+ KeyConditionExpression="pk = :p AND begins_with(sk, :pre)",+ ExpressionAttributeValues={":p": {"S": "a"}, ":pre": {"S": "sibling"}},+ ExclusiveStartKey={"pk": {"S": "a"}, "sk": {"S": "sibling-0"}},+ )+ assert resp["Count"] == 1finally:ddb.delete_table(TableName=name)-def test_dynamodb_query_lek_full_pagination_still_terminates(ddb):- """Paging with Limit=1 visits every item exactly once and terminates."""- name = "lek-query-walk"- _create_paging_table(ddb, name)+def test_dynamodb_update_list_append_missing_attr_rejected(ddb):+ name = "val-list-append-missing"+ _create_update_item_table(ddb, name)try:- seen = []- esk = None- for _ in range(10):- kwargs = {- "TableName": name,- "KeyConditionExpression": "pk = :p",- "ExpressionAttributeValues": {":p": {"S": "a"}},- "Limit": 1,- }- if esk:- kwargs["ExclusiveStartKey"] = esk- page = ddb.query(**kwargs)- seen.extend(it["sk"]["S"] for it in page["Items"])- esk = page.get("LastEvaluatedKey")- if not esk:- break- assert seen == ["1", "2", "3"]+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}})+ with pytest.raises(ClientError) as exc:+ ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="SET lst = list_append(lst, :v)",+ ExpressionAttributeValues={":v": {"L": [{"S": "x"}]}},+ )+ err = exc.value.response["Error"]+ assert err["Code"] == "ValidationException"+ assert err["Message"] == "The provided expression refers to an attribute that does not exist in the item"++ # list_append on an existing (even empty) list keeps working, and+ # if_not_exists remains the sanctioned way to handle absence.+ ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="SET lst = if_not_exists(lst, :empty)",+ ExpressionAttributeValues={":empty": {"L": []}},+ )+ ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="SET lst = list_append(lst, :v)",+ ExpressionAttributeValues={":v": {"L": [{"S": "x"}]}},+ )+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "k"}})["Item"]+ assert item["lst"] == {"L": [{"S": "x"}]}finally:ddb.delete_table(TableName=name)