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
DynamoDB Streams — backlogs and ESM read positions leaked, degrading a long-lived container (#1254)
maximoosemineb0cc59b634da
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 112df7b1..553a9660 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -557,6 +557,7 @@ def _ddb_create(logical_id, props, stack_name):def _ddb_delete(physical_id, props):_dynamodb._tables.pop(physical_id, None)+ _dynamodb.drop_stream_records(physical_id)def _ddb_global_table_create(logical_id, props, stack_name):@@ -2513,6 +2514,7 @@ def _lambda_esm_create(logical_id, props, stack_name):def _lambda_esm_delete(physical_id, props):_lambda_svc._esms.pop(physical_id, None)+ _lambda_svc._release_esm_poll_state(physical_id)def _lambda_esm_update(physical_id, old_props, new_props, stack_name):@@ -2527,6 +2529,7 @@ def _lambda_esm_update(physical_id, old_props, new_props, stack_name):if new_props.get(immutable) != old_props.get(immutable):new_id, attrs = _lambda_esm_create(physical_id, new_props, stack_name)_lambda_svc._esms.pop(physical_id, None)+ _lambda_svc._release_esm_poll_state(physical_id)return new_id, attrsfor key in ("BatchSize",diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex b5186443..0fd1d152 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -548,9 +548,105 @@ def _validate_item(item: dict, pk_name: str | None = None, sk_name: str | None =# DynamoDB Streams: table_name -> list of stream records# Each record follows the DynamoDB Streams event format consumed by Lambda ESMs._stream_records = AccountRegionScopedDict()+# Records dropped off the front of each table's stream, so a consumer's read+# position stays an absolute index into the stream rather than an offset into+# the surviving slice.+_stream_trimmed = AccountRegionScopedDict()_stream_seq_counter = 0_stream_seq_lock = threading.Lock()+# AWS DynamoDB Streams keeps records for 24 hours; retention is purely+# time-based, so records are expired by age and by nothing else.+_STREAM_RETENTION_SECONDS = 24 * 60 * 60+++def _record_age_cutoff(record: dict, cutoff: float) -> bool:+ created = (record.get("dynamodb") or {}).get("ApproximateCreationDateTime")+ if not created:+ # No creation time to age against (restored or hand-built records) —+ # keep it rather than treating it as infinitely old.+ return False+ return created < cutoff+++def _trim_stream_records(table_name: str, *, account_id=None, region=None) -> None:+ """Expire a table's stream records older than the retention window.++ Called from the read paths as well as on write, so a stream that stopped+ receiving records still ages out of its retention window.+ """+ if account_id is None or region is None:+ records = _stream_records.get(table_name)+ else:+ records = _stream_records.get_scoped(account_id, region, table_name)+ if not records:+ return+ cutoff = time.time() - _STREAM_RETENTION_SECONDS+ expired = 0+ while expired < len(records) and _record_age_cutoff(records[expired], cutoff):+ expired += 1+ if not expired:+ return+ del records[:expired]+ if account_id is None or region is None:+ _stream_trimmed[table_name] = _stream_trimmed.get(table_name, 0) + expired+ else:+ _stream_trimmed.set_scoped(+ account_id, region, table_name,+ _stream_trimmed.get_scoped(account_id, region, table_name, 0) + expired,+ )+++def _live_stream_records(table_name: str, account_id=None, region=None) -> list[dict]:+ if account_id is None or region is None:+ return _stream_records.get(table_name) or []+ return _stream_records.get_scoped(account_id, region, table_name) or []+++def _trimmed_count(table_name: str, account_id=None, region=None) -> int:+ if account_id is None or region is None:+ return _stream_trimmed.get(table_name, 0)+ return _stream_trimmed.get_scoped(account_id, region, table_name, 0)+++def stream_start_position(table_name: str, *, account_id=None, region=None) -> int:+ """Oldest position still readable from a table's stream (TRIM_HORIZON)."""+ _trim_stream_records(table_name, account_id=account_id, region=region)+ return _trimmed_count(table_name, account_id, region)+++def stream_end_position(table_name: str, *, account_id=None, region=None) -> int:+ """Position just past the newest record in a table's stream (LATEST)."""+ _trim_stream_records(table_name, account_id=account_id, region=region)+ return (+ _trimmed_count(table_name, account_id, region)+ + len(_live_stream_records(table_name, account_id, region))+ )+++def stream_records_since(+ table_name: str, position: int, limit: int, *, account_id=None, region=None+) -> list[dict]:+ """Read up to ``limit`` records from an absolute stream position. A position+ behind the trim horizon resumes at the horizon, as an AWS shard iterator+ does once its records expire."""+ _trim_stream_records(table_name, account_id=account_id, region=region)+ records = _live_stream_records(table_name, account_id, region)+ offset = max(0, position - _trimmed_count(table_name, account_id, region))+ return records[offset:offset + limit]+++def stream_live_records(table_name: str, *, account_id=None, region=None) -> list[dict]:+ """The table's unexpired records, oldest first. Index ``i`` in this list is+ absolute position ``stream_start_position(...) + i``."""+ _trim_stream_records(table_name, account_id=account_id, region=region)+ return _live_stream_records(table_name, account_id, region)+++def drop_stream_records(table_name: str) -> None:+ _stream_records.pop(table_name, None)+ _stream_trimmed.pop(table_name, None)+def _next_stream_seq():global _stream_seq_counter@@ -618,6 +714,7 @@ def _emit_stream_event(table_name: str, event_name: str, old_item: dict | None,if table_name not in _stream_records:_stream_records[table_name] = []_stream_records[table_name].append(record)+ _trim_stream_records(table_name)if has_kinesis:# AWS's Kinesis streaming destination always carries the equivalent of@@ -1155,6 +1252,7 @@ def _delete_table(data):_ttl_settings.pop(name, None)_pitr_settings.pop(name, None)_kinesis_destinations.pop(name, None)+ drop_stream_records(name)return json_response({"TableDescription": desc})@@ -6516,6 +6614,7 @@ def reset():_ttl_settings.clear()_pitr_settings.clear()_stream_records.clear()+ _stream_trimmed.clear()_kinesis_destinations.clear()_backups.clear()_contributor_insights.clear()diff --git a/ministack/services/dynamodb_streams.py b/ministack/services/dynamodb_streams.pyindex f98f4325..3edaf46e 100644--- a/ministack/services/dynamodb_streams.py+++ b/ministack/services/dynamodb_streams.py@@ -134,12 +134,20 @@ def _request_stream_source(stream_arn: str):def _records_for(account_id: str, region: str, table_name: str) -> list:- """Return the raw list of stream records for a table, or an empty list.+ """Return the unexpired stream records for a table, oldest first.Reads directly from the dynamodb module so TransactWriteItems,BatchWriteItem, and the single-item ops all stay in sync automatically.+ Index ``i`` here is absolute stream position ``_horizon(...) + i``: records+ that age out are dropped off the front, so positions handed to clients in a+ shard iterator are always absolute and never shift underneath them."""- return _ddb._stream_records.get_scoped(account_id, region, table_name, [])+ return _ddb.stream_live_records(table_name, account_id=account_id, region=region)+++def _horizon(account_id: str, region: str, table_name: str) -> int:+ """Absolute position of the oldest record still on the stream."""+ return _ddb.stream_start_position(table_name, account_id=account_id, region=region)def _enabled_stream_info(@@ -300,11 +308,12 @@ def _get_shard_iterator(data):)records = _records_for(spec.account_id, spec.region, table_name)- position = 0+ horizon = _horizon(spec.account_id, spec.region, table_name)+ position = horizonif iterator_type == "TRIM_HORIZON":- position = 0+ position = horizonelif iterator_type == "LATEST":- position = len(records)+ position = horizon + len(records)elif iterator_type in ("AT_SEQUENCE_NUMBER", "AFTER_SEQUENCE_NUMBER"):if not seq_number:return error_response_json(@@ -323,7 +332,7 @@ def _get_shard_iterator(data):f"Sequence number {seq_number} not found on stream",400,)- position = idx if iterator_type == "AT_SEQUENCE_NUMBER" else idx + 1+ position = horizon + (idx if iterator_type == "AT_SEQUENCE_NUMBER" else idx + 1)iterator = _encode_iterator(table_name,@@ -372,8 +381,13 @@ def _get_records(data):400,)- records = _records_for(account_id, region, table_name)- page = records[position:position + limit]+ # ``position`` is absolute, so an iterator minted before records expired+ # still lands correctly; one that now points behind the trim horizon+ # resumes at the horizon rather than skipping live records.+ position = max(position, _horizon(account_id, region, table_name))+ page = _ddb.stream_records_since(+ table_name, position, limit, account_id=account_id, region=region+ )next_position = position + len(page)next_iterator = _encode_iterator(table_name,diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 165bd2a3..cb473211 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -5529,9 +5529,19 @@ def _delete_esm(esm_id: str):404,)esm["State"] = "Deleting"+ _release_esm_poll_state(esm_id)return json_response(_esm_response(esm), 202)+def _release_esm_poll_state(esm_id: str) -> None:+ """Drop the poller bookkeeping a deleted ESM leaves behind, so a long-lived+ container does not accumulate one entry per create/delete cycle."""+ with _dynamodb_stream_positions_lock:+ _dynamodb_stream_positions.pop(esm_id, None)+ _kinesis_positions.pop(esm_id, None)+ _esm_backoff_until.pop(esm_id, None)++# ---------------------------------------------------------------------------# ESM Poller (SQS + Kinesis + DynamoDB Streams)# ---------------------------------------------------------------------------@@ -5565,9 +5575,9 @@ def _init_stream_position(esm_id, source_arn, starting):if esm_id in _dynamodb_stream_positions:returnif starting == "TRIM_HORIZON":- _dynamodb_stream_positions[esm_id] = 0+ _dynamodb_stream_positions[esm_id] = _ddb.stream_start_position(table_name)else:- _dynamodb_stream_positions[esm_id] = len(stream_records.get(table_name, []))+ _dynamodb_stream_positions[esm_id] = _ddb.stream_end_position(table_name)def _ensure_poller():@@ -5951,8 +5961,9 @@ def _poll_dynamodb_streams():table = _ddb._tables.get(table_name)if not table or table.get("LatestStreamArn") != source_arn:continue- table_records = stream_records.get(table_name, [])- if not table_records:+ horizon = _ddb.stream_start_position(table_name)+ end = _ddb.stream_end_position(table_name)+ if end == horizon:continueesm_id = esm["UUID"]@@ -5963,13 +5974,16 @@ def _poll_dynamodb_streams():if esm_id not in _dynamodb_stream_positions:starting = esm.get("StartingPosition", "LATEST")if starting == "TRIM_HORIZON":- _dynamodb_stream_positions[esm_id] = 0+ _dynamodb_stream_positions[esm_id] = horizonelse:- _dynamodb_stream_positions[esm_id] = len(table_records)- pos = _dynamodb_stream_positions[esm_id]+ _dynamodb_stream_positions[esm_id] = end+ # Records that expired since the last pass are gone; resume at+ # the trim horizon rather than replaying from a stale offset.+ pos = max(_dynamodb_stream_positions[esm_id], horizon)+ _dynamodb_stream_positions[esm_id] = posbatch_size = esm.get("BatchSize", 100)- batch = table_records[pos:pos + batch_size]+ batch = _ddb.stream_records_since(table_name, pos, batch_size)if not batch:continuediff --git a/ministack/services/pipes.py b/ministack/services/pipes.pyindex 3090c482..a930fb9d 100644--- a/ministack/services/pipes.py+++ b/ministack/services/pipes.py@@ -227,16 +227,16 @@ def _poll_once():if source_spec.account_id != pipe_account_id:continue- records = stream_records.get_scoped(- pipe_account_id, source_spec.region, table_name, []- )- pos = int(_positions.get(pipe["Arn"], 0))- if pos < 0:- pos = 0- if pos >= len(records):+ scope = {"account_id": pipe_account_id, "region": source_spec.region}+ # Positions are absolute stream positions: records expiring off the+ # front of the stream must not shift a pipe's read position.+ horizon = _ddb.stream_start_position(table_name, **scope)+ end = _ddb.stream_end_position(table_name, **scope)+ pos = max(int(_positions.get(pipe["Arn"], 0)), horizon)+ if pos >= end:continue- batch = records[pos:]+ batch = _ddb.stream_records_since(table_name, pos, end - pos, **scope)for rec in batch:_publish_record_to_sns(target_arn, pipe, rec)_positions[pipe["Arn"]] = pos + len(batch)@@ -326,9 +326,7 @@ def _initial_position(pipe: dict) -> int:stream_records = getattr(_ddb, "_stream_records", None)if stream_records is None:return 0- records = stream_records.get_scoped(- pipe_account_id, source_spec.region, table_name, []- )+ scope = {"account_id": pipe_account_id, "region": source_spec.region}if pipe.get("StartingPosition") == "TRIM_HORIZON":- return 0- return len(records)+ return _ddb.stream_start_position(table_name, **scope)+ return _ddb.stream_end_position(table_name, **scope)diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.pyindex 3c7886c0..a06e36d5 100644--- a/tests/test_dynamodb.py+++ b/tests/test_dynamodb.py@@ -6741,3 +6741,101 @@ def test_dynamodb_update_list_append_missing_attr_rejected(ddb):assert item["lst"] == {"L": [{"S": "x"}]}finally:ddb.delete_table(TableName=name)+++# ---------------------------------------------------------------------------+# Stream-record retention (white-box: the backlog lives in-process, so these+# assert against the module rather than over the wire).+# ---------------------------------------------------------------------------+++def ddb_stream_state():+ from ministack.core.responses import set_request_account_id, set_request_region+ from ministack.services import dynamodb as ddb_service++ set_request_account_id("000000000000")+ set_request_region("us-east-1")+ records = dict(ddb_service._stream_records._data)+ trimmed = dict(ddb_service._stream_trimmed._data)+ ddb_service._stream_records._data.clear()+ ddb_service._stream_trimmed._data.clear()+ try:+ yield ddb_service+ finally:+ ddb_service._stream_records._data.clear()+ ddb_service._stream_trimmed._data.clear()+ ddb_service._stream_records._data.update(records)+ ddb_service._stream_trimmed._data.update(trimmed)+++def _stream_record(created_at):+ return {"dynamodb": {"ApproximateCreationDateTime": int(created_at)}}+++def test_dynamodb_stream_records_expire_after_retention_window(ddb_stream_state):+ ddb_service = ddb_stream_state+ name = "retention-table"+ now = time.time()+ ddb_service._stream_records[name] = [+ _stream_record(now - ddb_service._STREAM_RETENTION_SECONDS - 60),+ _stream_record(now - ddb_service._STREAM_RETENTION_SECONDS - 30),+ _stream_record(now),+ ]++ ddb_service._trim_stream_records(name)++ assert len(ddb_service._stream_records[name]) == 1+ assert ddb_service.stream_start_position(name) == 2+ assert ddb_service.stream_end_position(name) == 3+ # A consumer that was behind the horizon resumes at the oldest live record.+ assert ddb_service.stream_records_since(name, 0, 10) == [_stream_record(now)]+++def test_dynamodb_delete_table_releases_stream_records(ddb, ddb_stream_state):+ ddb_service = ddb_stream_state+ name = f"stream-drop-{_uuid_mod.uuid4().hex[:8]}"+ ddb.create_table(+ TableName=name,+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"},+ )+ ddb.put_item(TableName=name, Item={"pk": {"S": "k1"}})+ ddb.delete_table(TableName=name)++ # The emulator under test is the container, so assert through the API the+ # backlog is gone with the table: recreating it starts from an empty stream.+ ddb.create_table(+ TableName=name,+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"},+ )+ try:+ stream_arn = ddb.describe_table(TableName=name)["Table"]["LatestStreamArn"]+ streams = _ddb_streams_client("us-east-1")+ shard = streams.describe_stream(StreamArn=stream_arn)["StreamDescription"]["Shards"][0]+ it = streams.get_shard_iterator(+ StreamArn=stream_arn,+ ShardId=shard["ShardId"],+ ShardIteratorType="TRIM_HORIZON",+ )["ShardIterator"]+ assert streams.get_records(ShardIterator=it)["Records"] == []+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_delete_table_in_process_drops_backlog(ddb_stream_state):+ ddb_service = ddb_stream_state+ name = "in-process-drop"+ ddb_service._stream_records[name] = [_stream_record(time.time())]+ ddb_service._stream_trimmed[name] = 3++ ddb_service.drop_stream_records(name)++ assert name not in ddb_service._stream_records+ assert ddb_service.stream_start_position(name) == 0+ assert ddb_service.stream_end_position(name) == 0diff --git a/tests/test_dynamodb_streams.py b/tests/test_dynamodb_streams.pyindex 94b3e7fa..41c26560 100644--- a/tests/test_dynamodb_streams.py+++ b/tests/test_dynamodb_streams.py@@ -364,3 +364,179 @@ def test_terraform_list_streams_filters_by_table(ddb, ddb_streams):assert any(s["StreamArn"] == arn and s["TableName"] == tname for s in listed)finally:ddb.delete_table(TableName=tname)+++# ---------------------------------------------------------------------------+# Retention (white-box: records expire by wall-clock age, and the backlog lives+# in-process, so these drive the service module directly rather than the wire).+# ---------------------------------------------------------------------------++def streams_state():+ import time++ from ministack.core.responses import set_request_account_id, set_request_region+ from ministack.services import dynamodb as ddb_service+ from ministack.services import dynamodb_streams as streams_service++ set_request_account_id("000000000000")+ set_request_region("us-east-1")+ saved = (+ dict(ddb_service._tables._data),+ dict(ddb_service._stream_records._data),+ dict(ddb_service._stream_trimmed._data),+ )+ ddb_service._stream_records._data.clear()+ ddb_service._stream_trimmed._data.clear()+ try:+ yield ddb_service, streams_service, time+ finally:+ for store, snapshot in zip(+ (ddb_service._tables, ddb_service._stream_records, ddb_service._stream_trimmed),+ saved,+ ):+ store._data.clear()+ store._data.update(snapshot)+++def _streamed_table(ddb_service, name):+ arn = f"arn:aws:dynamodb:us-east-1:000000000000:table/{name}/stream/2026-01-01T00:00:00.000"+ ddb_service._tables[name] = {+ "TableName": name,+ "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],+ "LatestStreamArn": arn,+ "LatestStreamLabel": "2026-01-01T00:00:00.000",+ "StreamSpecification": {"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"},+ }+ return arn+++def _record(seq, created_at):+ return {+ "eventID": str(seq),+ "eventName": "INSERT",+ "dynamodb": {+ "ApproximateCreationDateTime": int(created_at),+ "Keys": {"pk": {"S": str(seq)}},+ "SequenceNumber": str(seq),+ },+ }+++def _json(response):+ import json as _json_mod++ _status, _headers, body = response+ return _json_mod.loads(body)+++def _iterator(streams_service, arn, iterator_type, **kwargs):+ resp = streams_service._get_shard_iterator({+ "StreamArn": arn,+ "ShardId": _DEFAULT_SHARD_ID,+ "ShardIteratorType": iterator_type,+ **kwargs,+ })+ return _json(resp)["ShardIterator"]+++def _seqs(payload):+ return [r["dynamodb"]["SequenceNumber"] for r in payload["Records"]]+++def test_get_records_iterator_position_survives_record_expiry(streams_state):+ """A shard iterator carries an absolute stream position, so records aging+ off the front of the stream must not shift what a held iterator reads."""+ ddb_service, streams_service, time = streams_state+ name = "streams-retention"+ arn = _streamed_table(ddb_service, name)+ now = time.time()+ ddb_service._stream_records[name] = [_record(i, now) for i in range(3)]++ first = _json(streams_service._get_records({+ "ShardIterator": _iterator(streams_service, arn, "TRIM_HORIZON"),+ "Limit": 1,+ }))+ assert _seqs(first) == ["0"]++ # Records 0 and 1 age out while the caller holds the iterator it got back.+ expired = now - ddb_service._STREAM_RETENTION_SECONDS - 60+ for record in ddb_service._stream_records[name][:2]:+ record["dynamodb"]["ApproximateCreationDateTime"] = int(expired)++ second = _json(streams_service._get_records({"ShardIterator": first["NextShardIterator"]}))+ assert _seqs(second) == ["2"]+ assert ddb_service.stream_start_position(name) == 2+ # And the iterator it hands back is past the end, not back inside the list.+ assert _seqs(_json(streams_service._get_records({+ "ShardIterator": second["NextShardIterator"],+ }))) == []+++def test_shard_iterators_are_absolute_after_a_trim(streams_state):+ """TRIM_HORIZON, LATEST, and AT/AFTER_SEQUENCE_NUMBER all resolve against+ the trim horizon rather than an offset into the surviving records."""+ ddb_service, streams_service, time = streams_state+ name = "streams-retention-iters"+ arn = _streamed_table(ddb_service, name)+ now = time.time()+ expired = now - ddb_service._STREAM_RETENTION_SECONDS - 60+ ddb_service._stream_records[name] = [+ _record(0, expired), _record(1, expired), _record(2, now), _record(3, now),+ ]++ horizon = _iterator(streams_service, arn, "TRIM_HORIZON")+ assert _seqs(_json(streams_service._get_records({"ShardIterator": horizon}))) == ["2", "3"]+ assert ddb_service.stream_start_position(name) == 2++ latest = _iterator(streams_service, arn, "LATEST")+ assert _seqs(_json(streams_service._get_records({"ShardIterator": latest}))) == []+ ddb_service._stream_records[name].append(_record(4, now))+ assert _seqs(_json(streams_service._get_records({"ShardIterator": latest}))) == ["4"]++ at = _iterator(streams_service, arn, "AT_SEQUENCE_NUMBER", SequenceNumber="3")+ assert _seqs(_json(streams_service._get_records({"ShardIterator": at}))) == ["3", "4"]+ after = _iterator(streams_service, arn, "AFTER_SEQUENCE_NUMBER", SequenceNumber="3")+ assert _seqs(_json(streams_service._get_records({"ShardIterator": after}))) == ["4"]+++def test_expired_sequence_number_is_no_longer_addressable(streams_state):+ """Once a record expires its sequence number is gone from the stream, as on+ AWS, so an iterator anchored to it is a TrimmedDataAccessException."""+ ddb_service, streams_service, time = streams_state+ name = "streams-retention-seq"+ arn = _streamed_table(ddb_service, name)+ now = time.time()+ ddb_service._stream_records[name] = [+ _record(0, now - ddb_service._STREAM_RETENTION_SECONDS - 60),+ _record(1, now),+ ]++ resp = streams_service._get_shard_iterator({+ "StreamArn": arn,+ "ShardId": _DEFAULT_SHARD_ID,+ "ShardIteratorType": "AT_SEQUENCE_NUMBER",+ "SequenceNumber": "0",+ })+ assert resp[0] == 400+ assert _json(resp)["__type"].endswith("TrimmedDataAccessException")+++def test_records_expire_on_read_without_further_writes(streams_state):+ """Retention is wall-clock, not write-driven: a stream that stopped taking+ writes still ages out, and DescribeStream's starting sequence follows."""+ ddb_service, streams_service, time = streams_state+ name = "streams-retention-idle"+ arn = _streamed_table(ddb_service, name)+ now = time.time()+ ddb_service._stream_records[name] = [+ _record(0, now - ddb_service._STREAM_RETENTION_SECONDS - 120),+ _record(1, now),+ ]++ described = _json(streams_service._describe_stream({"StreamArn": arn}))["StreamDescription"]+ seq_range = described["Shards"][0]["SequenceNumberRange"]+ assert seq_range["StartingSequenceNumber"] == "1"+ assert _seqs(_json(streams_service._get_records({+ "ShardIterator": _iterator(streams_service, arn, "TRIM_HORIZON"),+ }))) == ["1"]diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 6720b82b..18eb1fbc 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -4659,6 +4659,7 @@ def esm_poll_state(tmp_path, monkeypatch):kinesis_state = _kin.get_state()dynamodb_state = _ddb.get_state()stream_records = dict(_ddb._stream_records._data)+ trimmed = dict(_ddb._stream_trimmed._data)def _clear_all():lsvc._functions._data.clear()@@ -4670,6 +4671,7 @@ def esm_poll_state(tmp_path, monkeypatch):_kin._streams._data.clear()_ddb._tables._data.clear()_ddb._stream_records._data.clear()+ _ddb._stream_trimmed._data.clear()_clear_all()try:@@ -4681,6 +4683,7 @@ def esm_poll_state(tmp_path, monkeypatch):_kin.restore_state(kinesis_state)_ddb.restore_state(dynamodb_state)_ddb._stream_records._data.update(stream_records)+ _ddb._stream_trimmed._data.update(trimmed)def test_poll_sqs_returns_true_when_batch_processed(esm_poll_state, monkeypatch):@@ -8668,6 +8671,112 @@ def test_invoke_rie_rewrites_custom_resource_response_url():assert event["ResponseURL"] == "http://localhost:4566/_ministack/cfn-response/tok"+def _ddb_stream_record(seq, stream_arn, created_at=None):+ return {+ "eventID": str(seq),+ "eventName": "INSERT",+ "eventSource": "aws:dynamodb",+ "dynamodb": {+ "ApproximateCreationDateTime": int(created_at if created_at is not None else time.time()),+ "Keys": {},+ "SequenceNumber": str(seq),+ "SizeBytes": 1,+ "StreamViewType": "NEW_AND_OLD_IMAGES",+ },+ "eventSourceARN": stream_arn,+ }+++def test_delete_esm_releases_poller_state(esm_poll_state):+ """A deleted ESM's poller bookkeeping is dropped, so a container that+ cycles ESMs doesn't accumulate one entry per create/delete."""+ _lsvc, _sqs, _kin, _ddb = esm_poll_state++ esm_id = "esm-release-poll-state"+ _lsvc._esms[esm_id] = {+ "UUID": esm_id,+ "EventSourceArn": "arn:aws:dynamodb:us-east-1:000000000000:table/t/stream/2024-01-01T00:00:00.000",+ "FunctionName": "fn",+ "State": "Enabled",+ "Enabled": True,+ }+ _lsvc._dynamodb_stream_positions[esm_id] = 7+ _lsvc._kinesis_positions[esm_id] = {"shard-0": 3}+ _lsvc._esm_backoff_until[esm_id] = time.time() + 60++ _lsvc._delete_esm(esm_id)++ assert esm_id not in _lsvc._dynamodb_stream_positions+ assert esm_id not in _lsvc._kinesis_positions+ assert esm_id not in _lsvc._esm_backoff_until+++def test_poll_dynamodb_streams_resumes_at_trim_horizon(esm_poll_state, monkeypatch):+ """Records that expired since the last pass are gone; a consumer sitting+ behind the trim horizon resumes at the horizon instead of replaying a+ stale offset into the surviving slice."""+ _lsvc, _sqs, _kin, _ddb = esm_poll_state++ table_name = "esm-ddb-trim-horizon"+ stream_arn = f"arn:aws:dynamodb:us-east-1:000000000000:table/{table_name}/stream/2024-01-01T00:00:00.000"+ function_name = "esm-ddb-trim-horizon-fn"+ esm_id = "esm-ddb-trim-horizon"++ _lsvc._functions[function_name] = {+ "config": {+ "FunctionName": function_name,+ "FunctionArn": f"arn:aws:lambda:us-east-1:000000000000:function:{function_name}",+ },+ "versions": {},+ "aliases": {},+ }+ _ddb._tables[table_name] = {"LatestStreamArn": stream_arn}+ _ddb._stream_records[table_name] = [_ddb_stream_record(i, stream_arn) for i in range(3)]+ # Ten records already aged out of this stream.+ _ddb._stream_trimmed[table_name] = 10++ _lsvc._esms[esm_id] = {+ "UUID": esm_id,+ "EventSourceArn": stream_arn,+ "FunctionName": function_name,+ "State": "Enabled",+ "Enabled": True,+ "BatchSize": 10,+ "StartingPosition": "TRIM_HORIZON",+ }+ _lsvc._dynamodb_stream_positions[esm_id] = 2++ seen = []+ monkeypatch.setattr(+ _lsvc, "_execute_function",+ lambda _func, event: seen.append(event) or {"body": {}},+ )++ assert _lsvc._poll_dynamodb_streams() is True+ assert [r["dynamodb"]["SequenceNumber"] for r in seen[0]["Records"]] == ["0", "1", "2"]+ assert _lsvc._dynamodb_stream_positions[esm_id] == 13+ assert _lsvc._poll_dynamodb_streams() is False+++def test_poll_dynamodb_streams_latest_anchors_past_trimmed_records(esm_poll_state):+ """LATEST anchors past every record the stream still holds, counting the+ ones already trimmed — otherwise a trimmed stream replays its backlog."""+ _lsvc, _sqs, _kin, _ddb = esm_poll_state++ table_name = "esm-ddb-latest-anchor"+ stream_arn = f"arn:aws:dynamodb:us-east-1:000000000000:table/{table_name}/stream/2024-01-01T00:00:00.000"+ esm_id = "esm-ddb-latest-anchor"++ _ddb._tables[table_name] = {"LatestStreamArn": stream_arn}+ _ddb._stream_records[table_name] = [_ddb_stream_record(i, stream_arn) for i in range(2)]+ _ddb._stream_trimmed[table_name] = 5++ _lsvc._init_stream_position(esm_id, stream_arn, "LATEST")+ assert _lsvc._dynamodb_stream_positions[esm_id] == 7++ _lsvc._dynamodb_stream_positions.pop(esm_id, None)+ _lsvc._init_stream_position(esm_id, stream_arn, "TRIM_HORIZON")+ assert _lsvc._dynamodb_stream_positions[esm_id] == 5# ---------------------------------------------------------------------------# Function URL data plane# ---------------------------------------------------------------------------diff --git a/tests/test_pipes.py b/tests/test_pipes.pyindex 8cbc5ea3..43da1bc6 100644--- a/tests/test_pipes.py+++ b/tests/test_pipes.py@@ -342,3 +342,73 @@ def test_pipes_restore_legacy_account_scoped_state_uses_pipe_arn_region():_pipes.reset()set_request_account_id(original_account)set_request_region(original_region)+++def test_pipes_position_is_absolute_across_record_expiry(monkeypatch):+ """A pipe's read position is an absolute stream position: records aging off+ the front of the stream must not shift where the pipe resumes."""+ import time++ from ministack.core.responses import set_request_account_id++ _pipes.reset()+ _ddb._stream_records.clear()+ _ddb._stream_trimmed.clear()+ region_token = _request_region.set("us-east-1")+ try:+ set_request_account_id("000000000000")+ table_name = "PipeTable"+ source_arn = _stream_arn("us-east-1")+ target_arn = _topic_arn("us-east-1")+ pipe_arn = "arn:aws:pipes:us-east-1:000000000000:pipe/PipeName"++ now = time.time()+ expired = now - _ddb._STREAM_RETENTION_SECONDS - 60++ def _record(seq, created_at):+ return {+ "eventID": f"evt-{seq}",+ "eventSource": "aws:dynamodb",+ "dynamodb": {"ApproximateCreationDateTime": int(created_at)},+ }++ _ddb._stream_records[table_name] = [+ _record(0, expired), _record(1, expired), _record(2, now),+ ]+ _pipes._pipes["PipeName"] = {+ "Name": "PipeName",+ "Arn": pipe_arn,+ "Source": source_arn,+ "Target": target_arn,+ "CurrentState": "RUNNING",+ "StartingPosition": "TRIM_HORIZON",+ }+ # The pipe had consumed the first record before the other two expired.+ _pipes._positions[pipe_arn] = 1++ delivered = []+ monkeypatch.setattr(+ _pipes, "_publish_record_to_sns",+ lambda _topic, _pipe, record: delivered.append(record["eventID"]),+ )++ _pipes._poll_once()++ # Resumes at the trim horizon; the surviving record is delivered once.+ assert delivered == ["evt-2"]+ assert _pipes._positions[pipe_arn] == 3+ _pipes._poll_once()+ assert delivered == ["evt-2"]++ # A pipe starting now anchors past everything, trimmed records included.+ assert _pipes._initial_position({+ "Source": source_arn, "StartingPosition": "LATEST",+ }) == 3+ assert _pipes._initial_position({+ "Source": source_arn, "StartingPosition": "TRIM_HORIZON",+ }) == 2+ finally:+ _request_region.reset(region_token)+ _pipes.reset()+ _ddb._stream_records.clear()+ _ddb._stream_trimmed.clear()