Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(dynamodb): follow DynamoDB's check order in TransactWriteItems (#2413)

jun-ut48a73649aa42
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ccd96918..b586695c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **DynamoDB — `TransactWriteItems` follows DynamoDB's check order** — an `Update` whose `ConditionExpression` failed was cancelled with `ValidationError` when its `UpdateExpression` could not be applied to the item (for example `SET #c = #c + :one` on a missing item); it now cancels with `ConditionalCheckFailed`, as `UpdateItem` answers `ConditionalCheckFailedException` for the same request. Such an update-expression error on one member no longer hides a failed condition on another: both reasons are returned, while wrong-typed keys and index keys still cancel before any condition. A missing table answers `ResourceNotFoundException` even when another member has a `ValidationError`, and a `begins_with` condition with a number operand answers `ValidationException` instead of an internal error, as on AWS. Contributed by @jun-ut.
- **ALB — instance and IP targets receive the path as the client sent it** — the data plane forwarded the decoded path, so `%20` became a space and the request was refused with 502 (`URL can't contain control characters`), and `%2F` became `/`. The path now reaches the target with its percent-encoding, as AWS sends it; rules still match the decoded path. Contributed by @skialpine.
- **ALB — `authenticate-oidc` on a 443 listener names its callback without the client's port** — the `redirect_uri` kept a port the client sent in `Host`. On a 443 listener it is now `https://<host>/oauth2/idpresponse`, as AWS sends it. Contributed by @skialpine.
- **ALB — a redirect action's `Location` fills its placeholders as AWS does** — `#{protocol}` was always `http`, `#{port}` was dropped and `#{query}` was not applied, so the request's query string was lost. `#{protocol}` and `#{port}` are now the listener's, the port is always written (`http://host:80/path`), and the default `#{query}` keeps the request's query string; a configured `Query`, which was not stored, now applies and is described. Contributed by @skialpine.
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 17db027d..1a921216 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -4664,14 +4664,16 @@ def _transact_write_items(data):
# Phase 1: wrong-typed keys and update-expression type errors surface as a
# per-item ValidationError cancellation reason, not a top-level exception.
+ # Update-expression errors (expr_reasons) wait for the conditions, as in UpdateItem.
val_reasons = {}
+ expr_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
+ return error_response_json("ResourceNotFoundException", "Requested resource not found", 400)
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:
@@ -4694,7 +4696,7 @@ def _transact_write_items(data):
try:
probe, _ = _apply_update_expression(probe, ue, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {}))
except ValueError as exc:
- val_reasons[idx] = str(exc)
+ expr_reasons[idx] = str(exc)
else:
imsg = _index_key_type_reason(tbl, probe)
if imsg:
@@ -4713,21 +4715,26 @@ def _transact_write_items(data):
op_type, op = _extract_transact_op(transact)
if op is None:
continue
- tbl = _tables.get(op.get("TableName", ""))
- if not tbl:
- return error_response_json("ResourceNotFoundException", "Requested resource not found", 400)
+ tbl = _tables[op.get("TableName", "")]
cond = op.get("ConditionExpression", "")
if cond:
if op_type == "Put":
existing = _get_item_by_key(tbl, _extract_key_from_item(tbl, op.get("Item", {})))
else:
existing = _get_item_by_key(tbl, op.get("Key", {}))
- if not _evaluate_condition(cond, existing or {}, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {})):
+ try:
+ holds = _evaluate_condition(cond, existing or {}, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {}))
+ except ValueError as exc:
+ # e.g. begins_with on a number operand
+ return error_response_json("ValidationException", str(exc), 400)
+ if not holds:
fail_item = existing if op.get("ReturnValuesOnConditionCheckFailure") == "ALL_OLD" else None
failures[idx] = fail_item
- if failures:
- return _transact_cancel_response(len(items_list), failures)
+ # A failed condition wins over the member's own update-expression error.
+ expr_reasons = {i: msg for i, msg in expr_reasons.items() if i not in failures}
+ if failures or expr_reasons:
+ return _transact_cancel_response(len(items_list), failures, expr_reasons)
_txn_write_effects: dict = {}
@@ -5075,17 +5082,20 @@ def _extract_transact_op(transact):
return None, None
-def _transact_cancel_response(total, failures):
+def _transact_cancel_response(total, failures, val_reasons):
"""Build a TransactionCanceledException response.
*failures* is a dict mapping failed item indices to the existing item
(or ``None`` if ``ReturnValuesOnConditionCheckFailure`` was not ``ALL_OLD``).
All entries in the dict are marked ``ConditionalCheckFailed``; the rest are
- ``None``. AWS returns a reason entry for every item in the transaction.
+ ``None``, or ``ValidationError`` for the indices in *val_reasons*. AWS
+ returns a reason entry for every item in the transaction.
"""
reasons = []
for i in range(total):
- if i in failures:
+ if i in val_reasons:
+ reasons.append({"Code": "ValidationError", "Message": val_reasons[i]})
+ elif i in failures:
entry = {"Code": "ConditionalCheckFailed", "Message": "The conditional request failed"}
if failures[i] is not None:
entry["Item"] = failures[i]
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index 7e954f45..e3b3c187 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -2025,6 +2025,67 @@ def test_dynamodb_transact_write_condition_cancel(ddb):
resp = ddb.get_item(TableName="qa-ddb-transact", Key={"pk": {"S": "new-item"}})
assert "Item" not in resp
+def test_dynamodb_transact_write_condition_checked_before_update_expression(ddb):
+ """A failed condition on a missing item cancels with ConditionalCheckFailed, as
+ UpdateItem does, even when the update expression reads an attribute the
+ missing item does not have. Reasons and their order match real DynamoDB."""
+ table = "qa-ddb-transact-cond-order"
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ update = {
+ "TableName": table,
+ "Key": {"pk": {"S": "missing"}},
+ "UpdateExpression": "SET #c = #c + :one",
+ "ConditionExpression": "attribute_exists(#pk)",
+ "ExpressionAttributeNames": {"#c": "count", "#pk": "pk"},
+ "ExpressionAttributeValues": {":one": {"N": "1"}},
+ }
+ with pytest.raises(ClientError) as exc:
+ ddb.update_item(**update)
+ assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException"
+
+ with pytest.raises(ClientError) as exc:
+ ddb.transact_write_items(TransactItems=[{"Update": update}])
+ assert exc.value.response["Error"]["Code"] == "TransactionCanceledException"
+ assert [r["Code"] for r in exc.value.response["CancellationReasons"]] == ["ConditionalCheckFailed"]
+ assert "Item" not in ddb.get_item(TableName=table, Key={"pk": {"S": "missing"}})
+
+ # An update-expression error on another member does not hide the failed condition.
+ no_condition = {
+ "TableName": table,
+ "Key": {"pk": {"S": "missing2"}},
+ "UpdateExpression": "SET #c = #c + :one",
+ "ExpressionAttributeNames": {"#c": "count"},
+ "ExpressionAttributeValues": {":one": {"N": "1"}},
+ }
+ with pytest.raises(ClientError) as exc:
+ ddb.transact_write_items(TransactItems=[{"Update": update}, {"Update": no_condition}])
+ assert [r["Code"] for r in exc.value.response["CancellationReasons"]] == ["ConditionalCheckFailed", "ValidationError"]
+
+ # A wrong-typed key still cancels before any condition is evaluated.
+ wrong_key = {**no_condition, "Key": {"pk": {"N": "1"}}}
+ with pytest.raises(ClientError) as exc:
+ ddb.transact_write_items(TransactItems=[{"Update": wrong_key}, {"Update": update}])
+ assert [r["Code"] for r in exc.value.response["CancellationReasons"]] == ["ValidationError", "None"]
+
+ # A missing table is reported before the update-expression error.
+ with pytest.raises(ClientError) as exc:
+ ddb.transact_write_items(TransactItems=[{"Update": no_condition}, {"Update": {**no_condition, "TableName": f"{table}-missing"}}])
+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ assert ddb.scan(TableName=table)["Count"] == 0
+
+ # begins_with with a number operand is a ValidationException, not an internal error.
+ ddb.put_item(TableName=table, Item={"pk": {"S": "e"}, "count": {"S": "x"}})
+ with pytest.raises(ClientError) as exc:
+ ddb.transact_write_items(TransactItems=[{"ConditionCheck": {
+ "TableName": table, "Key": {"pk": {"S": "e"}}, "ConditionExpression": "begins_with(#c, :n)",
+ "ExpressionAttributeNames": {"#c": "count"}, "ExpressionAttributeValues": {":n": {"N": "1"}}}}])
+ assert exc.value.response["Error"]["Code"] == "ValidationException"
+
def test_dynamodb_transact_write_multiple_failures_all_returned(ddb):
"""TransactWriteItems returns CancellationReasons for ALL failed conditions, not just the first."""
table = "qa-ddb-transact"