fix(kinesis): signal closed shard exhaustion and return child shards (#6716)

Return a terminal iterator and direct child metadata from coherent shard snapshots. Preserve final-batch delivery and prevent replay in Pipes and Firehose without changing checkpoint commit boundaries.
This commit is contained in:
TiM authored and GitHub committed 2026-10-27 10:24:57 -04:00
1 parent 7ca109b595
commit 77f2477641
11 files changed
+615 -44

No files matched your search

@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.firehose;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -17,6 +19,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
@@ -778,6 +781,83 @@ class FirehoseServiceTest {
java.util.List.of(), "KinesisStreamAsSource", kinesisSource(sourceStream));
}
private void closeSourceParent() {
kinesisService.splitShard("src-stream", "shardId-000000000000", "100", "us-east-1");
}
@ParameterizedTest
@ValueSource(ints = {1, 501})
void terminalSourceBatchDoesNotReplayBeforeOrAfterFlushAndRecreation(int count) {
createSourcedDeliveryStream("sourced-stream", "src-stream");
for (int i = 0; i < count; i++) {
kinesisService.putRecord("src-stream", "terminal".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
}
closeSourceParent();
firehoseService.pollKinesisSources();
firehoseService.pollKinesisSources();
firehoseService.flush("sourced-stream");
firehoseService = newService(0);
firehoseService.pollKinesisSources();
firehoseService.flush("sourced-stream");
assertEquals("terminal\n".repeat(count), delivered("sink").text());
}
@Test
void terminalSourceBatchIsRereadWhenServiceIsRecreatedBeforeFlush() {
createSourcedDeliveryStream("sourced-stream", "src-stream");
kinesisService.putRecord("src-stream", "terminal".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
closeSourceParent();
firehoseService.pollKinesisSources();
verifyNothingDelivered();
firehoseService = newService(0);
firehoseService.pollKinesisSources();
firehoseService.flush("sourced-stream");
firehoseService.pollKinesisSources();
firehoseService.flush("sourced-stream");
assertEquals("terminal\n", delivered("sink").text());
}
@Test
void failedTerminalFlushKeepsPendingBatchWithoutCommittingOrDuplicating() {
createSourcedDeliveryStream("sourced-stream", "src-stream");
kinesisService.putRecord("src-stream", "terminal".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
closeSourceParent();
when(s3Service.putObject(anyString(), anyString(), any(byte[].class), anyString(),
anyMap(), any(PutObjectOptions.class))).thenThrow(new RuntimeException("s3 unavailable"));
firehoseService.pollKinesisSources();
firehoseService.flush("sourced-stream");
assertTrue(backends.get("firehose/source-iterators.json").scan(key -> true).isEmpty());
Mockito.reset(s3Service);
firehoseService.pollKinesisSources();
firehoseService.flush("sourced-stream");
firehoseService.pollKinesisSources();
firehoseService.flush("sourced-stream");
assertEquals("terminal\n", delivered("sink").text());
}
@Test
@SuppressWarnings("unchecked")
void committedTerminalCursorSurvivesSerializationRoundTrip() throws Exception {
createSourcedDeliveryStream("sourced-stream", "src-stream");
kinesisService.putRecord("src-stream", "terminal".getBytes(StandardCharsets.UTF_8), "pk", "us-east-1");
closeSourceParent();
firehoseService.pollKinesisSources();
firehoseService.flush("sourced-stream");
AccountAwareStorageBackend<Map<String, String>> cursors =
(AccountAwareStorageBackend<Map<String, String>>) backends.get("firehose/source-iterators.json");
ObjectMapper mapper = new ObjectMapper();
for (String key : cursors.keys()) {
Map<String, String> restored = mapper.readValue(mapper.writeValueAsBytes(cursors.get(key).orElseThrow()),
new TypeReference<Map<String, String>>() {});
cursors.put(key, restored);
}
assertFalse(cursors.keys().isEmpty());
firehoseService = newService(0);
firehoseService.pollKinesisSources();
firehoseService.flush("sourced-stream");
assertEquals("terminal\n", delivered("sink").text());
}
@Test
void kinesisSourceRecordsAreDelivered() {
createSourcedDeliveryStream("sourced-stream", "src-stream");
@@ -17,6 +17,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
@@ -59,6 +60,53 @@ class KinesisJsonHandlerTest {
handler = new KinesisJsonHandler(service, MAPPER, 300_000);
}
@Test
void terminalGetRecordsIsJsonNullWithExactChildMetadata() throws Exception {
createStream("test-stream");
service.putRecord("test-stream", new byte[]{1}, "pk", REGION);
service.splitShard("test-stream", FIRST_SHARD_ID, "100", REGION);
String cursor = service.getShardIterator("test-stream", FIRST_SHARD_ID, "TRIM_HORIZON", null, null, REGION);
ObjectNode request = MAPPER.createObjectNode().put("ShardIterator", cursor);
JsonNode page = MAPPER.readTree(responseEntity(handler.handle("GetRecords", request, REGION)).toString());
assertTrue(page.has("NextShardIterator"));
assertTrue(page.get("NextShardIterator").isNull());
assertEquals(1, page.path("Records").size());
assertEquals(MAPPER.readTree("""
[{"ShardId":"shardId-000000000001","ParentShards":["shardId-000000000000"],
"HashKeyRange":{"StartingHashKey":"0","EndingHashKey":"99"}},
{"ShardId":"shardId-000000000002","ParentShards":["shardId-000000000000"],
"HashKeyRange":{"StartingHashKey":"100","EndingHashKey":"340282366920938463463374607431768211455"}}]
"""), page.path("ChildShards"));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void subscriptionTerminalMetadataDoesNotContinueEvenWithRecords(boolean nonempty) throws Exception {
createStream("test-stream");
if (nonempty) {
service.putRecord("test-stream", new byte[]{1}, "pk", REGION);
}
String arn = service.registerStreamConsumer(STREAM_ARN, "terminal-consumer", REGION).getConsumerArn();
service.splitShard("test-stream", FIRST_SHARD_ID, "100", REGION);
ObjectNode request = MAPPER.createObjectNode().put("ConsumerARN", arn).put("ShardId", FIRST_SHARD_ID);
request.putObject("StartingPosition").put("Type", "TRIM_HORIZON");
byte[] wire = (byte[]) handler.handle("SubscribeToShard", request, REGION).getEntity();
ByteBuffer buffer = ByteBuffer.wrap(wire);
int initialLength = buffer.getInt();
buffer.position(initialLength);
int eventLength = buffer.getInt();
int headerLength = buffer.getInt();
buffer.position(initialLength + 12 + headerLength);
byte[] payload = new byte[eventLength - headerLength - 16];
buffer.get(payload);
JsonNode event = MAPPER.readTree(payload);
assertEquals(nonempty ? 1 : 0, event.path("Records").size());
assertFalse(event.has("ContinuationSequenceNumber"));
assertEquals(2, event.path("ChildShards").size());
assertEquals(FIRST_SHARD_ID, event.path("ChildShards").get(0).path("ParentShards").get(0).asText());
assertEquals("99", event.path("ChildShards").get(0).path("HashKeyRange").path("EndingHashKey").asText());
}
// Retention is measured against the service clock, so a test that plants a fixed arrival
// timestamp pins the clock just after it instead of relying on the wall clock.
private void useClockFixedAt(Instant now) {
@@ -0,0 +1,202 @@
package io.github.hectorvent.floci.services.kinesis;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.kinesis.model.KinesisRecord;
import io.github.hectorvent.floci.services.kinesis.model.KinesisShard;
import io.github.hectorvent.floci.services.kinesis.model.KinesisStream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
class KinesisTerminalReadServiceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String PARENT = "shardId-000000000000";
private final AccountAwareStorageBackend<KinesisStream> streams = AccountAwareStorageBackend.inMemory(ACCOUNT);
private final KinesisService service = new KinesisService(streams, AccountAwareStorageBackend.inMemory(ACCOUNT),
new RegionResolver(REGION, ACCOUNT));
private String iterator(String type, String sequence, Long timestamp) {
return service.getShardIterator("s", PARENT, type, sequence, timestamp, REGION);
}
private Map<String, Object> read(boolean account, String iterator, int limit) {
return account ? service.getRecordsForAccount(ACCOUNT, iterator, limit, REGION)
: service.getRecords(iterator, limit, REGION);
}
private String put(String value) {
return service.putRecord("s", value.getBytes(StandardCharsets.UTF_8), "pk", REGION);
}
private void split() {
service.splitShard("s", PARENT, "170141183460469231731687303715884105728", REGION);
}
@SuppressWarnings("unchecked")
private List<KinesisService.ChildShard> children(Map<String, Object> page) {
return (List<KinesisService.ChildShard>) page.get("ChildShards");
}
@Test
void atSequenceNumberOnClosedShardIncludesTheRequestedRecord() {
service.createStream("s", 1, REGION);
put("first");
String last = put("last");
split();
Map<String, Object> page = service.getRecords(iterator("AT_SEQUENCE_NUMBER", last, null), 10, REGION);
assertEquals(1, ((List<?>) page.get("Records")).size());
assertNull(page.get("NextShardIterator"));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void finalNonemptyPageTerminatesAndOnlyTerminalPagesHaveChildren(boolean account) {
service.createStream("s", 1, REGION);
put("first");
put("last");
split();
Map<String, Object> first = read(account, iterator("TRIM_HORIZON", null, null), 1);
assertEquals(1, ((List<?>) first.get("Records")).size());
assertNotNull(first.get("NextShardIterator"));
assertFalse(first.containsKey("ChildShards"));
Map<String, Object> last = read(account, (String) first.get("NextShardIterator"), 1);
assertEquals(1, ((List<?>) last.get("Records")).size());
assertNull(last.get("NextShardIterator"));
assertEquals(0L, last.get("MillisBehindLatest"));
assertEquals(List.of("shardId-000000000001", "shardId-000000000002"),
children(last).stream().map(KinesisService.ChildShard::shardId).toList());
assertEquals(List.of(PARENT), children(last).getFirst().parentShards());
assertEquals(new KinesisShard.HashKeyRange("0", "170141183460469231731687303715884105727"),
children(last).getFirst().hashKeyRange());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void caughtUpOpenShardRemainsReadableAndClosedPositionsTerminate(boolean account) {
service.createStream("s", 1, REGION);
String sequence = put("last");
String latest = iterator("LATEST", null, null);
Map<String, Object> open = read(account, latest, 10);
assertTrue(((List<?>) open.get("Records")).isEmpty());
assertNotNull(open.get("NextShardIterator"));
assertFalse(open.containsKey("ChildShards"));
split();
for (String cursor : List.of(latest, iterator("AFTER_SEQUENCE_NUMBER", sequence, null),
iterator("AT_TIMESTAMP", null, Instant.now().plusSeconds(60).toEpochMilli()))) {
Map<String, Object> closed = read(account, cursor, 10);
assertTrue(((List<?>) closed.get("Records")).isEmpty());
assertNull(closed.get("NextShardIterator"));
assertEquals(2, children(closed).size());
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void emptyOrRetentionPrunedParentsTerminateWithDirectChildren(boolean account) {
KinesisStream stream = service.createStream("s", 1, REGION);
String cursor = iterator("TRIM_HORIZON", null, null);
split();
assertNull(read(account, cursor, 10).get("NextShardIterator"));
stream.getShards().getFirst().addRecord(new KinesisRecord(new byte[]{1}, "pk", "1",
Instant.now().minusSeconds(172800)));
service.splitShard("s", "shardId-000000000001", "85070591730234615865843651857942052864", REGION);
Map<String, Object> page = read(account, cursor, 10);
assertTrue(((List<?>) page.get("Records")).isEmpty());
assertNull(page.get("NextShardIterator"));
assertEquals(List.of("shardId-000000000001", "shardId-000000000002"),
children(page).stream().map(KinesisService.ChildShard::shardId).toList());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void bothMergeParentsReportBothParentIds(boolean account) {
service.createStream("s", 2, REGION);
String adjacent = "shardId-000000000001";
service.mergeShards("s", PARENT, adjacent, REGION);
for (String parent : List.of(PARENT, adjacent)) {
String cursor = service.getShardIterator("s", parent, "TRIM_HORIZON", null, null, REGION);
Map<String, Object> page = read(account, cursor, 10);
assertNull(page.get("NextShardIterator"));
assertEquals(List.of(new KinesisService.ChildShard("shardId-000000000002", List.of(PARENT, adjacent),
new KinesisShard.HashKeyRange("0", "340282366920938463463374607431768211455"))), children(page));
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void snapshotSerializesWithExplicitAccountAppendsAndResharding(boolean account) throws Exception {
KinesisStream stream = service.createStream("s", 1, REGION);
KinesisShard parent = spy(stream.getShards().getFirst());
stream.getShards().set(0, parent);
put("first");
CountDownLatch captured = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
KinesisShard.RecordsSnapshot snapshot = (KinesisShard.RecordsSnapshot) invocation.callRealMethod();
captured.countDown();
assertTrue(release.await(5, TimeUnit.SECONDS));
return snapshot;
}).when(parent).snapshotRecords();
String cursor = iterator("TRIM_HORIZON", null, null);
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
Future<Map<String, Object>> reading = pool.submit(() -> read(account, cursor, 10));
try {
assertTrue(captured.await(5, TimeUnit.SECONDS));
CountDownLatch writing = new CountDownLatch(1);
Future<?> mutation = pool.submit(() -> {
writing.countDown();
service.putRecordForAccount(ACCOUNT, "s", new byte[]{2}, "pk", REGION);
split();
});
assertTrue(writing.await(5, TimeUnit.SECONDS));
assertThrows(TimeoutException.class, () -> mutation.get(150, TimeUnit.MILLISECONDS));
release.countDown();
Map<String, Object> open = reading.get(5, TimeUnit.SECONDS);
assertNotNull(open.get("NextShardIterator"));
assertEquals(1, ((List<?>) open.get("Records")).size());
mutation.get(5, TimeUnit.SECONDS);
Map<String, Object> terminal = read(account, (String) open.get("NextShardIterator"), 10);
assertEquals(1, ((List<?>) terminal.get("Records")).size());
assertNull(terminal.get("NextShardIterator"));
assertEquals(2, children(terminal).size());
} finally {
release.countDown();
}
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void accountAndRegionResolveTheirOwnTerminalState(boolean closedOther) {
service.createStream("s", 1, REGION);
split();
KinesisStream other = new KinesisStream("s", "arn:aws:kinesis:us-east-1:111111111111:stream/s");
KinesisShard shard = new KinesisShard(PARENT, "0", "100", "0");
shard.setClosed(closedOther);
other.getShards().add(shard);
streams.putForAccount("111111111111", REGION + "::s", other);
String cursor = iterator("TRIM_HORIZON", null, null);
Map<String, Object> page = service.getRecordsForAccount("111111111111", cursor, 10, REGION);
assertEquals(closedOther, page.get("NextShardIterator") == null);
assertNull(service.getRecords(cursor, 10, REGION).get("NextShardIterator"));
service.createStream("s", 1, "eu-west-1");
assertNotNull(service.getRecords(cursor, 10, "eu-west-1").get("NextShardIterator"));
}
}
@@ -30,6 +30,7 @@ import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -125,6 +126,25 @@ class KinesisEventSourcePollerTest {
clock::get);
}
@Test
void finalNonemptyPageWithNullIteratorStillInvokesAndCheckpoints() throws Exception {
stubFunction();
stubStreamWith(List.of(record("123", "pk", "terminal")));
Map<String, Object> terminal = new HashMap<>();
terminal.put("Records", List.of(record("123", "pk", "terminal")));
terminal.put("NextShardIterator", null);
terminal.put("ChildShards", List.of());
when(kinesisService.getRecordsForAccount(eq(ACCOUNT), eq("iter-0"), anyInt(), eq(REGION)))
.thenReturn(terminal);
when(executorService.invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult());
EventSourceMapping mapping = esm();
pollOnce(mapping);
verify(executorService).invoke(any(), any(byte[].class), eq(InvocationType.RequestResponse));
assertEquals("123", mapping.getShardSequenceNumbers().get(SHARD));
verify(esmStore).saveForAccount(eq(ACCOUNT), eq(mapping));
}
private EventSourceMapping esm(String... patterns) {
EventSourceMapping esm = new EventSourceMapping();
esm.setUuid("k-esm");
@@ -0,0 +1,98 @@
package io.github.hectorvent.floci.services.pipes;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.pipes.model.Pipe;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.vertx.core.Vertx;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class PipesKinesisTerminalTest {
@ParameterizedTest
@CsvSource({"true,0,success", "false,0,success", "true,1,success", "false,1,success", "true,2,success", "false,2,success",
"true,1,filtered", "true,2,filtered", "true,1,dlq", "true,2,dlq", "true,1,drop", "true,2,drop"})
void terminalPagesAdvanceBeforeFilteringOrDelivery(boolean account, int recordCount, String outcome) throws Exception {
ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();
StorageFactory factory = mock(StorageFactory.class);
Map<String, AccountAwareStorageBackend<?>> stores = new HashMap<>();
when(factory.create(anyString(), anyString(), any())).thenAnswer(inv -> stores.computeIfAbsent(
inv.getArgument(1), key -> AccountAwareStorageBackend.inMemory("111111111111")));
KinesisService kinesis = spy(new KinesisService(factory, new RegionResolver("eu-west-1", "111111111111")));
kinesis.createStream("s", 1, "eu-west-1");
for (int i = 0; i < recordCount; i++) {
kinesis.putRecord("s", new byte[]{1}, "pk", "eu-west-1");
}
kinesis.splitShard("s", "shardId-000000000000", "100", "eu-west-1");
AtomicInteger terminalRecordPages = new AtomicInteger();
doAnswer(invocation -> {
@SuppressWarnings("unchecked")
Map<String, Object> page = (Map<String, Object>) invocation.callRealMethod();
if (page.get("NextShardIterator") == null && !((List<?>) page.get("Records")).isEmpty()) {
terminalRecordPages.incrementAndGet();
}
return page;
}).when(kinesis).getRecordsForAccount(anyString(), anyString(), any(), anyString());
doAnswer(invocation -> {
@SuppressWarnings("unchecked")
Map<String, Object> page = (Map<String, Object>) invocation.callRealMethod();
if (page.get("NextShardIterator") == null && !((List<?>) page.get("Records")).isEmpty()) {
terminalRecordPages.incrementAndGet();
}
return page;
}).when(kinesis).getRecords(anyString(), any(), anyString());
Pipe pipe = new Pipe();
pipe.setName("terminal");
pipe.setArn("arn:aws:pipes:eu-west-1:111111111111:pipe/terminal");
pipe.setSource("arn:aws:kinesis:eu-west-1:111111111111:stream/s");
pipe.setTarget("arn:aws:lambda:eu-west-1:111111111111:function:target");
pipe.setAccountId(account ? "111111111111" : null);
pipe.setSourceParameters(mapper.readTree("""
{"KinesisStreamParameters":{"BatchSize":1,
"DeadLetterConfig":{"Arn":"arn:aws:sqs:eu-west-1:111111111111:dlq"}}}
"""));
if ("filtered".equals(outcome)) {
pipe.getSourceParameters().withObject("/FilterCriteria").putArray("Filters").addObject()
.put("Pattern", "{\"eventSource\":[\"aws:sqs\"]}");
}
SqsService sqs = mock(SqsService.class);
PipesTargetInvoker target = mock(PipesTargetInvoker.class);
if ("dlq".equals(outcome) || "drop".equals(outcome)) {
doThrow(new RuntimeException("target down")).when(target).invoke(eq(pipe), anyString(), eq("eu-west-1"));
}
if ("drop".equals(outcome)) {
when(sqs.sendMessage(anyString(), anyString(), anyInt(), anyString()))
.thenThrow(new RuntimeException("dlq down"));
}
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
PipesPoller poller = new PipesPoller(mock(Vertx.class), sqs, kinesis, mock(DynamoDbStreamReader.class),
mock(PipesKafkaConsumerManager.class), target, new PipesFilterMatcher(mapper), mapper, config);
try {
for (int i = 0; i < recordCount + 3; i++) {
poller.pollKinesis(pipe, "eu-west-1");
}
verify(target, times("filtered".equals(outcome) ? 0 : recordCount))
.invoke(eq(pipe), anyString(), eq("eu-west-1"));
verify(sqs, times("dlq".equals(outcome) || "drop".equals(outcome) ? recordCount : 0))
.sendMessage(anyString(), anyString(), eq(0), eq("eu-west-1"));
assertEquals(recordCount == 0 ? 0 : 1, terminalRecordPages.get(), "the terminal record page must be consumed once");
} finally {
poller.shutdown();
}
}
}