fix(dynamodb): mark time-to-live deletions on the stream as AWS does (#4930)

AWS writes a TTL deletion to the table's stream as a REMOVE record whose
userIdentity names the DynamoDB service. A DeleteItem removal has none.
The member names depend on where the record is read:

- The DynamoDB Streams API (GetRecords) capitalises them, as the SDK's
  Identity shape expects:
  {"PrincipalId": "dynamodb.amazonaws.com", "Type": "Service"}.
- The Lambda and EventBridge Pipes event record and the Kinesis Data
  Streams destination payload use lowercase names,
  {"type": "Service", "principalId": "dynamodb.amazonaws.com"}, the
  shape the developer guide's TTL filter pattern matches.

With the DynamoDB Local engine, Floci passed Local's record through as
is: eventName UNKNOWN_TO_SDK_VERSION and no userIdentity.
DynamoDbLocalBackend now rewrites such records in a successful Streams
GetRecords reply to REMOVE with the Streams API identity, the one place
the public API, the Lambda poller, Pipes and the Redshift zero-ETL
consumer all read through.

The native engine wrote REMOVE but no identity, so a TTL deletion could
not be told from a DeleteItem. The sweep now marks its stream records
(a new in-memory DynamoDbStreamRecord flag) and its Kinesis CDC records.
GetRecords writes the Streams API identity, and the Kinesis record the
lowercase one.

The Lambda event source mapping poller and the Pipes poller rename the
Streams API identity to the event record shape before filtering and
delivery. DynamoDbTtlIdentity.Shape holds the member names of every
output. DeleteItem removals are unchanged.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-11 09:42:23 -04:00
1 parent 04621d8444
commit 9a7ec1c9d0
19 files changed
+572 -15

No files matched your search

@@ -13,7 +13,10 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -32,6 +35,9 @@ class DynamoDbKinesisStreamingIntegrationTest {
@Inject
KinesisStreamingForwarder forwarder;
@Inject
DynamoDbService dynamoDbService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
@@ -293,7 +299,7 @@ class DynamoDbKinesisStreamingIntegrationTest {
@Test
@Order(12)
void deleteItemForwardsRemoveEvent() {
void deleteItemForwardsRemoveEvent() throws Exception {
given()
.header("X-Amz-Target", "DynamoDB_20120810.DeleteItem")
.contentType(DYNAMODB_CONTENT_TYPE)
@@ -334,6 +340,8 @@ class DynamoDbKinesisStreamingIntegrationTest {
String lastEncoded = recordsResponse.jsonPath().getString("Records[" + (recordCount - 1) + "].Data");
String lastDecoded = new String(Base64.getDecoder().decode(lastEncoded));
assertTrue(lastDecoded.contains("\"eventName\":\"REMOVE\""), "Expected REMOVE event, got: " + lastDecoded);
assertTrue(new ObjectMapper().readTree(lastDecoded).get("userIdentity").isNull(),
"a DeleteItem removal is not made by the DynamoDB service: " + lastDecoded);
}
@Test
@@ -481,6 +489,77 @@ class DynamoDbKinesisStreamingIntegrationTest {
.body("DestinationStatus", equalTo("ACTIVE"));
}
@Test
@Order(31)
void ttlDeletionForwardsTheDynamoDbServiceIdentity() throws Exception {
given()
.header("X-Amz-Target", "DynamoDB_20120810.UpdateTimeToLive")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("""
{
"TableName": "StreamingTable",
"TimeToLiveSpecification": {"Enabled": true, "AttributeName": "expireAt"}
}
""")
.when()
.post("/")
.then()
.statusCode(200);
long past = Instant.now().getEpochSecond() - 3600;
given()
.header("X-Amz-Target", "DynamoDB_20120810.PutItem")
.contentType(DYNAMODB_CONTENT_TYPE)
.body("{\"TableName\": \"StreamingTable\", \"Item\": {\"pk\": {\"S\": \"expired\"}, "
+ "\"expireAt\": {\"N\": \"" + past + "\"}}}")
.when()
.post("/")
.then()
.statusCode(200);
dynamoDbService.deleteExpiredItems();
awaitCdcDelivery();
JsonNode removal = null;
for (JsonNode payload : kinesisPayloads()) {
if ("REMOVE".equals(payload.path("eventName").asText())
&& "expired".equals(payload.path("dynamodb").path("Keys").path("pk").path("S").asText())) {
removal = payload;
}
}
assertNotNull(removal, "the TTL deletion must be forwarded to Kinesis");
assertEquals(new ObjectMapper().readTree("{\"type\":\"Service\",\"principalId\":\"dynamodb.amazonaws.com\"}"),
removal.get("userIdentity"));
}
private List<JsonNode> kinesisPayloads() throws Exception {
String shardIterator = given()
.header("X-Amz-Target", "Kinesis_20131202.GetShardIterator")
.contentType(KINESIS_CONTENT_TYPE)
.body("""
{"StreamName": "ddb-streaming-test", "ShardId": "shardId-000000000000", "ShardIteratorType": "TRIM_HORIZON"}
""")
.when()
.post("/")
.then()
.statusCode(200)
.extract().jsonPath().getString("ShardIterator");
List<String> encoded = given()
.header("X-Amz-Target", "Kinesis_20131202.GetRecords")
.contentType(KINESIS_CONTENT_TYPE)
.body("{\"ShardIterator\": \"" + shardIterator + "\", \"Limit\": 100}")
.when()
.post("/")
.then()
.statusCode(200)
.extract().jsonPath().getList("Records.Data", String.class);
ObjectMapper mapper = new ObjectMapper();
List<JsonNode> payloads = new ArrayList<>();
for (String data : encoded) {
payloads.add(mapper.readTree(Base64.getDecoder().decode(data)));
}
return payloads;
}
@Test
@Order(40)
void enableLeavesDynamoDbStreamsDisabled() {
@@ -398,4 +398,35 @@ class DynamoDbStreamServiceTest {
assertEquals(1, service.listStreams("ViewTypeTable", "000000000000", "us-east-1").size());
}
@Test
void captureEvent_ttlRemoval_isMarkedAsATtlDeletion() throws Exception {
TableDefinition table = sharedNameTable(ACCOUNT_A);
StreamDescription stream = service.enableStream(SHARED_TABLE, table.getTableArn(), "OLD_IMAGE", "us-east-1");
service.captureEvent("REMOVE", mapper.readTree("{\"userId\":{\"S\":\"a\"}}"), null, table, "us-east-1", true);
DynamoDbStreamRecord record = onlyRecordIn(stream.getStreamArn());
assertEquals("REMOVE", record.getEventName());
assertTrue(record.isTtlDeletion());
}
@Test
void captureEvent_deleteItemRemoval_isNotATtlDeletion() throws Exception {
TableDefinition table = sharedNameTable(ACCOUNT_A);
StreamDescription stream = service.enableStream(SHARED_TABLE, table.getTableArn(), "OLD_IMAGE", "us-east-1");
service.captureEvent("REMOVE", mapper.readTree("{\"userId\":{\"S\":\"a\"}}"), null, table, "us-east-1");
DynamoDbStreamRecord record = onlyRecordIn(stream.getStreamArn());
assertEquals("REMOVE", record.getEventName());
assertFalse(record.isTtlDeletion());
}
private DynamoDbStreamRecord onlyRecordIn(String streamArn) {
String iterator = service.getShardIterator(streamArn, DynamoDbStreamService.SHARD_ID, "TRIM_HORIZON", null);
List<DynamoDbStreamRecord> records = service.getRecords(iterator, 10).records();
assertEquals(1, records.size());
return records.get(0);
}
}
@@ -61,6 +61,11 @@ class DynamoDbTtlForwardingTest {
};
private static final String REGION = "us-east-1";
private static final String KINESIS_TTL_IDENTITY =
"{\"type\":\"Service\",\"principalId\":\"dynamodb.amazonaws.com\"}";
/** The DynamoDB Streams API capitalises the Identity members, as real AWS returns them. */
private static final String STREAMS_TTL_IDENTITY =
"{\"Type\":\"Service\",\"PrincipalId\":\"dynamodb.amazonaws.com\"}";
private final ObjectMapper mapper = new ObjectMapper();
@@ -141,6 +146,8 @@ class DynamoDbTtlForwardingTest {
for (KinesisRecord record : drained) {
JsonNode payload = mapper.readTree(record.getData());
assertEquals("REMOVE", payload.get("eventName").asText(), "TTL deletions forward as REMOVE");
assertEquals(mapper.readTree(KINESIS_TTL_IDENTITY), payload.get("userIdentity"),
"TTL deletions forward as made by the DynamoDB service");
}
assertEquals(0L, forwarder.getForwardFailureCount(), "happy path drops nothing");
@@ -218,7 +225,7 @@ class DynamoDbTtlForwardingTest {
doAnswer(invocation -> {
svc.deleteTable("TtlTable", REGION);
return null;
}).when(streamService).captureEvent(eq("REMOVE"), any(), any(), any(), any());
}).when(streamService).captureEvent(eq("REMOVE"), any(), any(), any(), any(), eq(true));
svc.deleteExpiredItems();
@@ -277,11 +284,11 @@ class DynamoDbTtlForwardingTest {
doAnswer(invocation -> {
svc.deleteTable("TtlTable", REGION);
return null;
}).doNothing().when(streamService).captureEvent(eq("REMOVE"), any(), any(), any(), any());
}).doNothing().when(streamService).captureEvent(eq("REMOVE"), any(), any(), any(), any(), eq(true));
svc.deleteScannedItems(scans);
verify(streamService, times(1)).captureEvent(eq("REMOVE"), any(), any(), any(), any());
verify(streamService, times(1)).captureEvent(eq("REMOVE"), any(), any(), any(), any(), eq(true));
}
@Test
@@ -393,4 +400,58 @@ class DynamoDbTtlForwardingTest {
assertEquals(1, kinesisRemoves.size(), "a skipped delete must not forward a Kinesis REMOVE record");
assertEquals("row-1", kinesisRemoves.get(0).get("dynamodb").get("Keys").get("pk").get("S").asText());
}
@Test
void getRecords_ttlSweepRemoval_carriesTheDynamoDbServiceIdentity() throws Exception {
StreamedTtlTable streamed = streamedTtlTable();
streamed.service().deleteExpiredItems();
JsonNode record = onlyRecord(streamed);
assertEquals("REMOVE", record.path("eventName").asText());
assertEquals("row-0", record.path("dynamodb").path("Keys").path("pk").path("S").asText());
assertEquals(mapper.readTree(STREAMS_TTL_IDENTITY), record.path("userIdentity"));
}
@Test
void getRecords_deleteItemRemoval_carriesNoIdentity() throws Exception {
StreamedTtlTable streamed = streamedTtlTable();
ObjectNode key = mapper.createObjectNode();
key.set("pk", stringAttr("row-0"));
streamed.service().deleteItem("TtlTable", key, REGION);
JsonNode record = onlyRecord(streamed);
assertEquals("REMOVE", record.path("eventName").asText());
assertFalse(record.has("userIdentity"), "a DeleteItem removal is not made by the DynamoDB service");
}
private record StreamedTtlTable(DynamoDbService service, NativeDynamoDbStreamsJsonHandler handler,
String streamArn) {}
/** A TTL table holding one expired item, whose stream starts after the item was written. */
private StreamedTtlTable streamedTtlTable() {
StorageBackend<String, TableDefinition> tableStore = new InMemoryStorage<>();
DynamoDbStreamService streamService = new DynamoDbStreamService(mapper, tableStore);
RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");
DynamoDbService svc = new DynamoDbService(
tableStore, new InMemoryStorage<>(), regionResolver, streamService, null);
seedTtlTable(svc, 1);
TableDefinition table = tableStore.get("us-east-1::TtlTable").orElseThrow();
StreamDescription sd = streamService.enableStream(
table.getTableName(), table.getTableArn(), "NEW_AND_OLD_IMAGES", REGION);
return new StreamedTtlTable(svc,
new NativeDynamoDbStreamsJsonHandler(streamService, svc, regionResolver, mapper), sd.getStreamArn());
}
private JsonNode onlyRecord(StreamedTtlTable streamed) {
ObjectNode iteratorRequest = mapper.createObjectNode()
.put("StreamArn", streamed.streamArn())
.put("ShardId", DynamoDbStreamService.SHARD_ID)
.put("ShardIteratorType", "TRIM_HORIZON");
JsonNode iterator = (JsonNode) streamed.handler().handle("GetShardIterator", iteratorRequest, REGION).getEntity();
ObjectNode recordsRequest = mapper.createObjectNode().put("ShardIterator", iterator.path("ShardIterator").asText());
JsonNode records = ((JsonNode) streamed.handler().handle("GetRecords", recordsRequest, REGION).getEntity())
.path("Records");
assertEquals(1, records.size(), "one stream record: " + records);
return records.get(0);
}
}
@@ -20,6 +20,8 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -27,6 +29,7 @@ import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.endsWith;
@@ -203,6 +206,38 @@ class DynamoDbLocalBackendIntegrationTest {
assertEquals(CheckpointLifetime.STREAM, streamReader.checkpointLifetime());
}
@Test
void aTtlDeletionReadsAsRemoveByTheDynamoDbService() {
String table = tableName("ttl");
String streamArn = createTable(A_WEST, table, STREAMED)
.statusCode(200)
.extract().path("TableDescription.LatestStreamArn");
dynamoDb(A_WEST, "UpdateTimeToLive", "{\"TableName\": \"" + table
+ "\", \"TimeToLiveSpecification\": {\"Enabled\": true, \"AttributeName\": \"expireAt\"}}")
.statusCode(200);
long past = Instant.now().getEpochSecond() - 3600;
dynamoDb(A_WEST, "PutItem", "{\"TableName\": \"" + table + "\", \"Item\": {\"pk\": {\"S\": \"expired\"}, "
+ "\"expireAt\": {\"N\": \"" + past + "\"}}}")
.statusCode(200);
String shardId = streams(A_WEST, "DescribeStream", "{\"StreamArn\": \"" + streamArn + "\"}")
.statusCode(200)
.extract().path("StreamDescription.Shards[0].ShardId");
// DynamoDB Local deleted an expired item within about 15 seconds when measured.
await().atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofSeconds(1)).untilAsserted(() -> {
String iterator = streams(A_WEST, "GetShardIterator", "{\"StreamArn\": \"" + streamArn
+ "\", \"ShardId\": \"" + shardId + "\", \"ShardIteratorType\": \"TRIM_HORIZON\"}")
.statusCode(200)
.extract().path("ShardIterator");
streams(A_WEST, "GetRecords", "{\"ShardIterator\": \"" + iterator + "\"}")
.statusCode(200)
.body("Records.eventName", contains("INSERT", "REMOVE"))
.body("Records[1].dynamodb.Keys.pk.S", equalTo("expired"))
.body("Records[1].userIdentity.Type", equalTo("Service"))
.body("Records[1].userIdentity.PrincipalId", equalTo("dynamodb.amazonaws.com"));
});
}
@Test
void theDirectDeleteRemovesAProtectedTable() {
String table = tableName("protected");
@@ -278,6 +278,32 @@ class DynamoDbLocalBackendTest {
assertEquals(REGION, reply.body().path("Records").path(0).path("awsRegion").asText());
}
@Test
void timeToLiveDeletionReadsAsRemoveByTheDynamoDbService() throws Exception {
answer(Api.DYNAMODB_STREAMS, "GetRecords", 200, "{\"Records\":[{\"eventName\":\"UNKNOWN_TO_SDK_VERSION\","
+ "\"awsRegion\":\"ddblocal\",\"dynamodb\":{\"Keys\":{\"pk\":{\"S\":\"a\"}},"
+ "\"OldImage\":{\"pk\":{\"S\":\"a\"}}}}]}");
Reply reply = execute(Api.DYNAMODB_STREAMS, "GetRecords", "{\"ShardIterator\":\"it\"}");
JsonNode record = reply.body().path("Records").path(0);
assertEquals("REMOVE", record.path("eventName").asText());
assertEquals(json("{\"Type\":\"Service\",\"PrincipalId\":\"dynamodb.amazonaws.com\"}"),
record.path("userIdentity"));
assertEquals("a", record.path("dynamodb").path("OldImage").path("pk").path("S").asText());
}
@Test
void writeRecordsKeepTheirEventNameAndCarryNoIdentity() throws Exception {
String records = "[{\"eventName\":\"INSERT\",\"dynamodb\":{}},{\"eventName\":\"MODIFY\",\"dynamodb\":{}},"
+ "{\"eventName\":\"REMOVE\",\"dynamodb\":{}}]";
answer(Api.DYNAMODB_STREAMS, "GetRecords", 200, "{\"Records\":" + records + "}");
Reply reply = execute(Api.DYNAMODB_STREAMS, "GetRecords", "{\"ShardIterator\":\"it\"}");
assertEquals(json(records), reply.body().path("Records"));
}
@Test
void arnLookingItemAttributeUntouched() throws Exception {
String item = "{\"TableArn\":{\"S\":\"" + LOCAL + "table/x\"},"
@@ -543,6 +543,45 @@ class DynamoDbStreamsEventSourcePollerTest {
assertEquals("s2", esm.getShardSequenceNumbers().get(SHARD_ID));
}
@Test
void userIdentityFilterDeliversOnlyTheTtlDeletion() {
stubTrimHorizon(List.of(
ddbRecord("s1", "INSERT", "{\"status\":{\"S\":\"active\"}}"),
removal("s2", false),
removal("s3", true)));
when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult());
EventSourceMapping esm = filterEsm(
"{\"userIdentity\":{\"type\":[\"Service\"],\"principalId\":[\"dynamodb.amazonaws.com\"]}}");
pollerWith(mock(EsmStore.class)).pollAndInvoke(esm);
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
verify(executorService, timeout(2000)).invoke(any(), payload.capture(), eq(InvocationType.RequestResponse));
JsonNode records = readRecords(payload.getValue());
assertEquals(1, records.size());
assertEquals("s3", records.get(0).path("dynamodb").path("SequenceNumber").asText());
assertEquals("REMOVE", records.get(0).path("eventName").asText());
assertEquals(OBJECT_MAPPER.createObjectNode().put("type", "Service").put("principalId", "dynamodb.amazonaws.com"),
records.get(0).path("userIdentity"));
}
/**
* A REMOVE record as GetRecords returns it. One that time to live made carries the DynamoDB service
* identity with the Streams API's capitalised member names, as AWS writes it.
*/
private DynamoDbStreamReader.Record removal(String seq, boolean byTtl) {
DynamoDbStreamReader.Record record = ddbRecord(seq, "REMOVE", "{\"status\":{\"S\":\"expired\"}}");
ObjectNode dynamodb = (ObjectNode) record.awsRecord().path("dynamodb");
dynamodb.set("OldImage", dynamodb.remove("NewImage"));
if (byTtl) {
((ObjectNode) record.awsRecord()).putObject("userIdentity")
.put("PrincipalId", "dynamodb.amazonaws.com")
.put("Type", "Service");
}
return record;
}
@Test
void partialBatchFailureCheckpointsBeforeLowestFailedRecord() {
stubTrimHorizon(List.of(
@@ -549,6 +549,29 @@ class PipesPollerTest {
assertEquals(original, active.awsRecord(), "the reader's record is never mutated");
}
@Test
void userIdentityFilterDeliversOnlyTheTtlDeletionWithTheEventRecordIdentity() throws Exception {
Pipe pipe = dynamoDbPipe("{}");
pipe.setSourceParameters(MAPPER.readTree("""
{"DynamoDBStreamParameters":{"StartingPosition":"TRIM_HORIZON"},
"FilterCriteria":{"Filters":[{"Pattern":
"{\\"userIdentity\\":{\\"type\\":[\\"Service\\"],\\"principalId\\":[\\"dynamodb.amazonaws.com\\"]}}"}]}}"""));
streams.shard.add(ddbRemoval("001", false));
DynamoDbStreamReader.Record ttlRemoval = ddbRemoval("002", true);
JsonNode original = ttlRemoval.awsRecord().deepCopy();
streams.shard.add(ttlRemoval);
poller.startPolling(pipe);
poller.pollDynamoDbStreams(pipe, "us-east-1");
assertEquals(List.of(List.of("002")), deliveredSequences(pipe));
ArgumentCaptor<String> payload = ArgumentCaptor.forClass(String.class);
verify(targetInvoker).invoke(eq(pipe), payload.capture(), eq("us-east-1"));
assertEquals(MAPPER.createObjectNode().put("type", "Service").put("principalId", "dynamodb.amazonaws.com"),
MAPPER.readTree(payload.getValue()).path("Records").path(0).path("userIdentity"));
assertEquals(original, ttlRemoval.awsRecord(), "the reader's record is never mutated");
}
@Test
void trimmedDynamoDbCheckpointRestartsAtTheTrimHorizon() throws Exception {
Pipe pipe = dynamoDbPipe("{}");
@@ -641,6 +664,22 @@ class PipesPollerTest {
return new DynamoDbStreamReader.Record(sequenceNumber, awsRecord);
}
/**
* A REMOVE record as GetRecords returns it. One that time to live made carries the DynamoDB service
* identity with the Streams API's capitalised member names, as AWS writes it.
*/
private static DynamoDbStreamReader.Record ddbRemoval(String sequenceNumber, boolean byTtl) {
DynamoDbStreamReader.Record record = ddbRecord(sequenceNumber, "expired");
ObjectNode awsRecord = (ObjectNode) record.awsRecord();
awsRecord.put("eventName", "REMOVE");
ObjectNode dynamodb = (ObjectNode) awsRecord.path("dynamodb");
dynamodb.set("OldImage", dynamodb.remove("NewImage"));
if (byTtl) {
awsRecord.putObject("userIdentity").put("PrincipalId", "dynamodb.amazonaws.com").put("Type", "Service");
}
return record;
}
/** The sequence numbers of each batch the Lambda target was invoked with, in invocation order. */
private List<List<String>> deliveredSequences(Pipe pipe) throws Exception {
ArgumentCaptor<String> payloads = ArgumentCaptor.forClass(String.class);