fix(stepfunctions): preserve callback token ownership (#6271)

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-22 19:39:20 -04:00
1 parent efc693ad17
commit d3359662e5
6 files changed
+281 -53

No files matched your search

+6
View File
@@ -547,6 +547,12 @@ the wire and the task fails with `Sfn.StateMachineDoesNotExistException`.
| `arn:aws:states:::aws-sdk:scheduler:deleteSchedule` | `{}` | `Scheduler.ResourceNotFoundException` |
| `arn:aws:states:::aws-sdk:sns:publish` | `{MessageId}` | `Sns.NotFoundException` when the topic does not exist |
Callback tokens are owned by the execution account. Foreign callbacks return
`AccessDeniedException`; unknown tokens return `InvalidToken`. Recently closed tokens return
`TaskTimedOut`. Closed-token classification retains at most 1,024 tokens for five minutes; older
or evicted tokens return `InvalidToken`. Invalid JSON output leaves a pending token available
for a corrected callback. Token state remains in memory.
Redshift Data API execution returns a statement `Id` before SQL completes. Follow the
`executeStatement` task with `describeStatement`, a Choice on `Status`, and a Wait state
before polling again. Read results only after `FINISHED`; route `FAILED` and `ABORTED`
@@ -943,7 +943,8 @@ public class AslExecutor {
String credentialsRoleArn = credentials == null ? null : credentials.path("RoleArn").asText(null);
// Registered after the input template resolved, so a template failure leaves no token behind.
CompletableFuture<JsonNode> tokenFuture = needsToken ? sfnService.get().registerPendingToken(taskToken) : null;
CompletableFuture<JsonNode> tokenFuture = needsToken ? sfnService.get().registerPendingToken(taskToken,
AwsArnUtils.parse(sm.getStateMachineArn()).accountId()) : null;
TaskEventProfile profile = taskEventProfile(resource, isActivity);
JsonNode taskResult;
// Read before the scheduled event is built, so a large input or a slow history callback
@@ -1726,8 +1727,10 @@ public class AslExecutor {
*/
private JsonNode invokeAwsSdkSfnSendTaskSuccess(JsonNode input) throws Exception {
String taskToken = input.path("TaskToken").asText(null);
if (!sfnService.get().sendTaskSuccess(taskToken, sdkPayload(input.path("Output")))) {
throw new FailStateException("Sfn.InvalidTokenException", "Invalid Token: 'Invalid token'");
try {
sfnService.get().sendTaskSuccess(taskToken, sdkPayload(input.path("Output")));
} catch (AwsException e) {
throw new FailStateException(sdkExceptionName("Sfn", e.getErrorCode()), e.getMessage());
}
return objectMapper.createObjectNode();
}
@@ -1735,9 +1738,11 @@ public class AslExecutor {
/** AWS SDK integration for {@code sfn:sendTaskFailure}, token semantics as in SendTaskSuccess. */
private JsonNode invokeAwsSdkSfnSendTaskFailure(JsonNode input) {
String taskToken = input.path("TaskToken").asText(null);
if (!sfnService.get().sendTaskFailure(taskToken, input.path("Cause").asText(null),
input.path("Error").asText(null))) {
throw new FailStateException("Sfn.InvalidTokenException", "Invalid Token: 'Invalid token'");
try {
sfnService.get().sendTaskFailure(taskToken, input.path("Cause").asText(null),
input.path("Error").asText(null));
} catch (AwsException e) {
throw new FailStateException(sdkExceptionName("Sfn", e.getErrorCode()), e.getMessage());
}
return objectMapper.createObjectNode();
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -60,7 +61,15 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
private final StorageBackend<String, MapRun> mapRunStore;
private final Map<String, ExecutionHistory> historyCache = new ConcurrentHashMap<>();
private final Map<String, BlockingQueue<ActivityTask>> activityQueues = new ConcurrentHashMap<>();
private final Map<String, CompletableFuture<JsonNode>> pendingTaskTokens = new ConcurrentHashMap<>();
private final Map<String, PendingTask> pendingTaskTokens = new ConcurrentHashMap<>();
// Only recent closures are classified as TaskTimedOut: five minutes, at most 1,024 tokens.
// Evicted/older tokens remain InvalidToken. No task payloads are retained.
private final Map<String, ClosedTask> closedTaskTokens = new LinkedHashMap<>();
private static final long CLOSED_TOKEN_RETENTION_NANOS = TimeUnit.MINUTES.toNanos(5);
private static final int MAX_CLOSED_TOKENS = 1024;
private record PendingTask(String accountId, CompletableFuture<JsonNode> future) {}
private record ClosedTask(String accountId, long closedAtNanos) {}
// When each pending token last showed progress, so a Task's HeartbeatSeconds can bound the gap
// between heartbeats instead of the whole wait.
private final Map<String, Long> taskHeartbeatNanos = new ConcurrentHashMap<>();
@@ -148,8 +157,11 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
public void clear() {
historyCache.clear();
activityQueues.clear();
pendingTaskTokens.values().forEach(f -> f.completeExceptionally(new RuntimeException("StepFunctionsService cleared")));
pendingTaskTokens.values().forEach(f -> f.future().completeExceptionally(new RuntimeException("StepFunctionsService cleared")));
pendingTaskTokens.clear();
synchronized (this) {
closedTaskTokens.clear();
}
taskHeartbeatNanos.clear();
}
@@ -1184,9 +1196,9 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
queue.add(new ActivityTask(taskToken, input));
}
public CompletableFuture<JsonNode> registerPendingToken(String token) {
public synchronized CompletableFuture<JsonNode> registerPendingToken(String token, String accountId) {
CompletableFuture<JsonNode> future = new CompletableFuture<>();
pendingTaskTokens.put(token, future);
pendingTaskTokens.put(token, new PendingTask(Objects.requireNonNull(accountId), future));
taskHeartbeatNanos.put(token, System.nanoTime());
return future;
}
@@ -1201,62 +1213,88 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
return reportedAt != null ? reportedAt : System.nanoTime();
}
/**
* Forgets a token the waiting task has stopped listening for, so a later SendTaskSuccess,
* SendTaskFailure or SendTaskHeartbeat naming it reports no pending task.
*/
public void discardPendingToken(String taskToken) {
if (taskToken == null) {
return;
/** Retires a token when its task stops waiting, including timeout and resource failure. */
public synchronized void discardPendingToken(String taskToken) {
if (taskToken != null) {
PendingTask pending = pendingTaskTokens.remove(taskToken);
taskHeartbeatNanos.remove(taskToken);
if (pending != null) {
rememberClosed(taskToken, pending.accountId());
}
}
pendingTaskTokens.remove(taskToken);
taskHeartbeatNanos.remove(taskToken);
}
// ──────────────────────────── Tasks ────────────────────────────
private void rememberClosed(String token, String accountId) {
long now = System.nanoTime();
closedTaskTokens.entrySet().removeIf(entry -> now - entry.getValue().closedAtNanos()
>= CLOSED_TOKEN_RETENTION_NANOS);
closedTaskTokens.put(token, new ClosedTask(accountId, now));
while (closedTaskTokens.size() > MAX_CLOSED_TOKENS) {
closedTaskTokens.remove(closedTaskTokens.keySet().iterator().next());
}
}
/**
* @return whether the token named a task that was waiting for it. The
* {@code aws-sdk:sfn:sendTaskSuccess} Task integration fails the calling state when it
* did not, the way AWS answers an unknown token with {@code InvalidToken}.
*/
private PendingTask requirePendingTask(String token) {
String accountId = regionResolver.getAccountId();
PendingTask pending = token == null ? null : pendingTaskTokens.get(token);
if (pending != null) {
requireTokenOwner(pending.accountId(), accountId);
return pending;
}
ClosedTask closed = token == null ? null : closedTaskTokens.get(token);
if (closed != null && System.nanoTime() - closed.closedAtNanos() >= CLOSED_TOKEN_RETENTION_NANOS) {
closedTaskTokens.remove(token);
closed = null;
}
if (closed != null) {
requireTokenOwner(closed.accountId(), accountId);
throw new AwsException("TaskTimedOut", "The associated task has already been closed.", 400);
}
throw new AwsException("InvalidToken", "Invalid Token: 'Invalid token'", 400);
}
private void requireTokenOwner(String owner, String caller) {
if (!owner.equals(caller)) {
throw new AwsException("AccessDeniedException", "Not authorized to access this resource.", 400);
}
}
private synchronized CompletableFuture<JsonNode> claimPendingTask(String token) {
PendingTask pending = requirePendingTask(token);
pendingTaskTokens.remove(token);
taskHeartbeatNanos.remove(token);
rememberClosed(token, pending.accountId());
return pending.future();
}
/** Claims an owned callback exactly once; completion runs outside the token lock. */
public boolean sendTaskSuccess(String taskToken, String output) {
CompletableFuture<JsonNode> future = taskToken != null ? pendingTaskTokens.remove(taskToken) : null;
if (future == null) {
LOG.warnv("SendTaskSuccess: no pending task for token {0}", taskToken);
return false;
JsonNode result;
synchronized (this) {
requirePendingTask(taskToken);
}
try {
future.complete(objectMapper.readTree(output));
} catch (Exception e) {
future.completeExceptionally(new RuntimeException("Invalid JSON output: " + e.getMessage()));
result = objectMapper.readTree(output);
} catch (JsonProcessingException | IllegalArgumentException e) {
throw new AwsException("InvalidOutput", "Output is not valid JSON.", 400);
}
if (result == null || result.isMissingNode()) {
throw new AwsException("InvalidOutput", "Output is not valid JSON.", 400);
}
CompletableFuture<JsonNode> future = claimPendingTask(taskToken);
future.complete(result);
return true;
}
/**
* @return whether the token named a task that was waiting for it, as in
* {@link #sendTaskSuccess(String, String)}.
*/
public boolean sendTaskFailure(String taskToken, String cause, String error) {
CompletableFuture<JsonNode> future = taskToken != null ? pendingTaskTokens.remove(taskToken) : null;
if (future == null) {
LOG.warnv("SendTaskFailure: no pending task for token {0}", taskToken);
return false;
}
CompletableFuture<JsonNode> future = claimPendingTask(taskToken);
future.completeExceptionally(new AslExecutor.FailStateException(error, cause));
return true;
}
/**
* Resets the gap a Task's {@code HeartbeatSeconds} allows. A heartbeat for a token nobody is
* waiting for is logged and changes nothing, as in {@link #sendTaskSuccess(String, String)}.
*/
public void sendTaskHeartbeat(String taskToken) {
if (taskToken == null || !pendingTaskTokens.containsKey(taskToken)) {
LOG.warnv("SendTaskHeartbeat: no pending task for token {0}", taskToken);
return;
}
/** A foreign, closed or unknown token cannot refresh a task's heartbeat. */
public synchronized void sendTaskHeartbeat(String taskToken) {
requirePendingTask(taskToken);
taskHeartbeatNanos.put(taskToken, System.nanoTime());
}
@@ -288,7 +288,7 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
@Test
@Order(9)
void sendTaskSuccessOnATokenWhoseResourceInvocationThrewFailsAsInvalid() throws Exception {
void sendTaskSuccessOnATokenWhoseResourceInvocationThrewFailsAsClosed() throws Exception {
// "Leak" registers a task token, then fails invoking its own (unsupported) resource before it
// ever waits on that token. The registration must not outlive the failure: the token is
// recovered from the TaskScheduled event it wrote on its way to failing, and a second
@@ -332,7 +332,7 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
assertEquals("FAILED", describe.jsonPath().getString("status"),
"Leak's token must be discarded once its resource invocation throws, not left pending");
assertEquals("Sfn.InvalidTokenException", describe.jsonPath().getString("error"));
assertEquals("Sfn.TaskTimedOutException", describe.jsonPath().getString("error"));
}
// ──────────────────────────── scheduler:createSchedule / updateSchedule ────────────────────────────
@@ -0,0 +1,176 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class StepFunctionsCallbackTokenTest {
private static final String OWNER = "111111111111";
private final RegionResolver resolver = mock(RegionResolver.class);
private final StepFunctionsService service = new StepFunctionsService(mock(StorageFactory.class),
resolver, mock(AslExecutor.class), new ObjectMapper(), mock(SfnMockLoader.class),
mock(StepFunctionsEventPublisher.class));
@Test
void foreignCallbacksCannotClaimOrRefreshAnOwnedToken() throws Exception {
CompletableFuture<JsonNode> future = service.registerPendingToken("owned", OWNER);
long heartbeat = service.lastTaskHeartbeatNanos("owned");
when(resolver.getAccountId()).thenReturn("222222222222");
refuses("AccessDeniedException", () -> service.sendTaskSuccess("owned", "{}"));
refuses("AccessDeniedException", () -> service.sendTaskFailure("owned", "cause", "error"));
refuses("AccessDeniedException", () -> service.sendTaskHeartbeat("owned"));
assertFalse(future.isDone());
assertEquals(heartbeat, service.lastTaskHeartbeatNanos("owned"));
when(resolver.getAccountId()).thenReturn(OWNER);
service.sendTaskHeartbeat("owned");
assertTrue(service.lastTaskHeartbeatNanos("owned") >= heartbeat);
service.sendTaskSuccess("owned", "{\"first\":true}");
assertTrue(future.get(1, TimeUnit.SECONDS).path("first").asBoolean());
refuses("TaskTimedOut", () -> service.sendTaskSuccess("owned", "{}"));
refuses("TaskTimedOut", () -> service.sendTaskFailure("owned", "cause", "error"));
refuses("TaskTimedOut", () -> service.sendTaskHeartbeat("owned"));
when(resolver.getAccountId()).thenReturn("222222222222");
refuses("AccessDeniedException", () -> service.sendTaskHeartbeat("owned"));
}
@Test
void failureAndDiscardCloseTokensAndUnknownTokensRefuse() {
when(resolver.getAccountId()).thenReturn(OWNER);
CompletableFuture<JsonNode> failed = service.registerPendingToken("failed", OWNER);
service.sendTaskFailure("failed", "cause", "error");
assertTrue(failed.isCompletedExceptionally());
refuses("TaskTimedOut", () -> service.sendTaskSuccess("failed", "{}"));
service.registerPendingToken("expired", OWNER);
service.discardPendingToken("expired");
refuses("TaskTimedOut", () -> service.sendTaskHeartbeat("expired"));
refuses("InvalidToken", () -> service.sendTaskHeartbeat(null));
refuses("InvalidToken", () -> service.sendTaskSuccess("unknown", "{}"));
refuses("InvalidToken", () -> service.sendTaskFailure("unknown", "cause", "error"));
}
@Test
void racingCallbacksCompleteExactlyOnce() throws Exception {
when(resolver.getAccountId()).thenReturn(OWNER);
CompletableFuture<JsonNode> future = service.registerPendingToken("race", OWNER);
CountDownLatch ready = new CountDownLatch(2);
CountDownLatch start = new CountDownLatch(1);
AtomicInteger accepted = new AtomicInteger();
AtomicInteger refused = new AtomicInteger();
AtomicInteger completions = new AtomicInteger();
future.whenComplete((value, error) -> completions.incrementAndGet());
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Runnable callback = () -> {
ready.countDown();
try {
assertTrue(start.await(2, TimeUnit.SECONDS));
service.sendTaskSuccess("race", "{\"once\":true}");
accepted.incrementAndGet();
} catch (AwsException error) {
assertEquals("TaskTimedOut", error.getErrorCode());
refused.incrementAndGet();
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw new AssertionError(error);
}
};
Future<?> first = executor.submit(callback);
Future<?> second = executor.submit(callback);
assertTrue(ready.await(2, TimeUnit.SECONDS));
start.countDown();
first.get(2, TimeUnit.SECONDS);
second.get(2, TimeUnit.SECONDS);
}
assertEquals(1, accepted.get());
assertEquals(1, refused.get());
assertEquals(1, completions.get());
assertTrue(future.get().path("once").asBoolean());
}
@Test
void parsingOutputDoesNotBlockOtherTokensOrClaimAClosedToken() throws Exception {
when(resolver.getAccountId()).thenReturn(OWNER);
ObjectMapper mapper = mock(ObjectMapper.class);
StepFunctionsService callbacks = new StepFunctionsService(mock(StorageFactory.class),
resolver, mock(AslExecutor.class), mapper, mock(SfnMockLoader.class),
mock(StepFunctionsEventPublisher.class));
CountDownLatch parsing = new CountDownLatch(1);
CountDownLatch finishParsing = new CountDownLatch(1);
when(mapper.readTree("{}")).thenAnswer(invocation -> {
parsing.countDown();
assertTrue(finishParsing.await(5, TimeUnit.SECONDS));
return new ObjectMapper().readTree("{}");
});
CompletableFuture<JsonNode> slow = callbacks.registerPendingToken("slow", OWNER);
callbacks.registerPendingToken("other", OWNER);
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<?> success = executor.submit(() -> callbacks.sendTaskSuccess("slow", "{}"));
try {
assertTrue(parsing.await(2, TimeUnit.SECONDS));
executor.submit(() -> {
callbacks.sendTaskHeartbeat("other");
callbacks.sendTaskFailure("slow", "cause", "error");
}).get(2, TimeUnit.SECONDS);
} finally {
finishParsing.countDown();
}
ExecutionException failure = assertThrows(ExecutionException.class,
() -> success.get(2, TimeUnit.SECONDS));
assertEquals("TaskTimedOut", ((AwsException) failure.getCause()).getErrorCode());
}
assertTrue(slow.isCompletedExceptionally());
}
@ParameterizedTest
@ValueSource(strings = {"{invalid", "", "[1,"})
void rejectedOutputDoesNotConsumeTheToken(String output) throws Exception {
when(resolver.getAccountId()).thenReturn(OWNER);
CompletableFuture<JsonNode> future = service.registerPendingToken("output", OWNER);
refuses("InvalidOutput", () -> service.sendTaskSuccess("output", output));
assertFalse(future.isDone());
service.sendTaskHeartbeat("output");
service.sendTaskSuccess("output", "{\"accepted\":true}");
assertTrue(future.get(1, TimeUnit.SECONDS).path("accepted").asBoolean());
refuses("InvalidToken", () -> service.sendTaskSuccess("unknown", output));
}
@Test
void closedTokenClassificationIsBoundedAndClearForgetsIt() {
when(resolver.getAccountId()).thenReturn(OWNER);
for (int index = 0; index <= 1024; index++) {
String token = "closed-" + index;
service.registerPendingToken(token, OWNER);
service.discardPendingToken(token);
}
refuses("InvalidToken", () -> service.sendTaskHeartbeat("closed-0"));
refuses("TaskTimedOut", () -> service.sendTaskHeartbeat("closed-1024"));
service.clear();
refuses("InvalidToken", () -> service.sendTaskHeartbeat("closed-1024"));
}
private static void refuses(String code, Runnable callback) {
AwsException error = assertThrows(AwsException.class, callback::run);
assertEquals(code, error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
@@ -38,6 +39,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
@@ -173,7 +175,8 @@ class StepFunctionsServicePersistenceTest {
List<HistoryEvent> actualHistory = afterRestart.getExecutionHistory(started.getExecutionArn());
aborted.setTimestamp(actualHistory.getLast().getTimestamp());
assertHistoryEquals(expectedHistory, actualHistory);
assertFalse(afterRestart.sendTaskSuccess(taskToken, "{\"done\":true}"));
assertEquals("InvalidToken", assertThrows(AwsException.class,
() -> afterRestart.sendTaskSuccess(taskToken, "{\"done\":true}")).getErrorCode());
} finally {
beforeRestart.abortAbandonedExecutions();
beforeRestart.clear();