Skip to content

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

Prerelease/v1.5.23b (#2096)

Nahuel Nucerae2b31289c070
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a18679d6..c40739d8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **DynamoDB — Query and Scan stop each page at 1 MB** — without `Limit`, every matching item came back in one response with no `LastEvaluatedKey`. A page now stops before the item that would take the data read past 1 MB (index pages count the projected entry), before any filter, and returns `LastEvaluatedKey`. Contributed by @DimQ1.
- **DynamoDB — index Query and write cost no longer grow with table size** — a `Query` on a GSI or LSI read every item in the table, and every write recounted the table. Index partitions and `ItemCount` are now maintained per write. Contributed by @DimQ1.
- **DynamoDB — `ClientRequestToken` expires after 10 minutes** — `TransactWriteItems` and `ExecuteTransaction` tokens were kept forever; after 10 minutes a reused token is now a new request, and expired tokens are released. Contributed by @DimQ1.
- **DynamoDB Streams — no record for a write that changes nothing** — a `PutItem` or `UpdateItem` leaving the item unchanged wrote a `MODIFY` record. Contributed by @DimQ1.
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index d347655e..bddfedbb 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -510,6 +510,28 @@ def _attribute_value_size(value: dict) -> int:
return 0
+# A Query/Scan page holds at most 1 MB of items read, before any filter.
+_DDB_PAGE_SIZE_BYTES = 1_048_576
+
+
+def _paginate_evaluated_items(items, limit, table, index_name=None):
+ """One Query/Scan page: up to ``Limit`` items, stopping before the item
+ that would take the data read past 1 MB. Index reads count the index
+ entry (its projected attributes). Returns (page, stopped_at_boundary)."""
+ page = []
+ page_bytes = 0
+ for item in items:
+ entry = _apply_index_projection(item, table, index_name) if index_name else item
+ item_bytes = _item_size_bytes(entry)
+ if page and page_bytes + item_bytes > _DDB_PAGE_SIZE_BYTES:
+ return page, True
+ page.append(item)
+ page_bytes += item_bytes
+ if (limit is not None and len(page) >= int(limit)) or page_bytes >= _DDB_PAGE_SIZE_BYTES:
+ return page, True
+ return page, False
+
+
def _item_size_bytes(item: dict) -> int:
total = 0
if not isinstance(item, dict):
@@ -2388,10 +2410,7 @@ def _query(data):
# AWS returns a LastEvaluatedKey whenever it stopped *because of* the
# limit — including when the results end exactly at the limit, since it
# doesn't look ahead. The follow-up page then returns 0 items and no key.
- has_more = False
- if limit is not None and len(candidates) >= limit:
- has_more = len(candidates) > 0
- candidates = candidates[:limit]
+ candidates, has_more = _paginate_evaluated_items(candidates, limit, table, index_name)
scanned_count = len(candidates)
query_filter = data.get("QueryFilter")
@@ -2611,10 +2630,7 @@ def _scan(data):
# Same LastEvaluatedKey semantics as Query: stopping exactly at the limit
# still yields a key, because AWS doesn't look ahead.
- has_more = False
- if limit is not None and len(all_items) >= limit:
- has_more = len(all_items) > 0
- all_items = all_items[:limit]
+ all_items, has_more = _paginate_evaluated_items(all_items, limit, table, index_name)
scanned_count = len(all_items)
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index cfa8002e..224f59f0 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -7595,3 +7595,32 @@ def test_dynamodb_gsi_multi_attribute_keys(ddb):
assert exc.value.response["Error"]["Message"] == "Query key condition not supported"
finally:
ddb.delete_table(TableName=name)
+
+
+def test_dynamodb_query_and_scan_pages_stop_at_1mb(ddb):
+ name = f"page-1mb-{_uuid_mod.uuid4().hex[:8]}"
+ ddb.create_table(
+ TableName=name, BillingMode="PAY_PER_REQUEST",
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"},
+ {"AttributeName": "sk", "AttributeType": "S"}],
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}, {"AttributeName": "sk", "KeyType": "RANGE"}])
+ try:
+ for i in range(30):
+ ddb.put_item(TableName=name, Item={"pk": {"S": "p"}, "sk": {"S": f"{i:03}"}, "b": {"S": "x" * 100_000}})
+ for op, kwargs in (("query", {"KeyConditionExpression": "pk = :p",
+ "ExpressionAttributeValues": {":p": {"S": "p"}}}),
+ ("scan", {})):
+ pages, start = [], None
+ while True:
+ extra = {"ExclusiveStartKey": start} if start else {}
+ resp = getattr(ddb, op)(TableName=name, **kwargs, **extra)
+ pages.append(resp["Count"])
+ start = resp.get("LastEvaluatedKey")
+ if not start:
+ break
+ assert pages == [10, 10, 10], (op, pages)
+ filtered = ddb.scan(TableName=name, FilterExpression="sk = :none",
+ ExpressionAttributeValues={":none": {"S": "none"}})
+ assert filtered["Count"] == 0 and filtered["ScannedCount"] == 10 and "LastEvaluatedKey" in filtered
+ finally:
+ ddb.delete_table(TableName=name)