fix(swf): reject a decision batch whose closing decision is not last

RespondDecisionTaskCompleted accepted a batch with decisions after a closing
decision and silently dropped the remainder. The live service rejects the whole
batch instead:

  HTTP 400
  {"__type":"com.amazon.coral.validate#ValidationException",
   "message":"Close must be last decision in list"}

Silently accepting it hides a decider bug and diverges on both the status code
and the response body, so a decider that ships a malformed batch sees success
locally and a 400 against AWS.

The batch is now validated before any state is mutated, matching the live
service's behaviour of leaving the decision task outstanding so the decider can
retry with a corrected batch. Note this fault is namespaced
com.amazon.coral.validate rather than com.amazonaws.swf.base.model.

Tests assert the status code, both fault spellings, the message, that no
DecisionTaskCompleted event is appended, and that the same task token still
works afterwards. They fail on the previous behaviour with "Expected status code
<400> but was <200>".

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait committed 2026-08-12 20:00:46 +00:00
1 parent 497f96d693
commit 5e8d2e3dc6
5 files changed
+119 -14

No files matched your search

+4 -2
View File
@@ -76,7 +76,9 @@ All 39 modeled operations are implemented.
A decision that cannot be applied appends its `*Failed` event with the AWS cause
(`ACTIVITY_TYPE_DOES_NOT_EXIST`, `ACTIVITY_ID_ALREADY_IN_USE`, `TIMER_ID_UNKNOWN`,
`UNHANDLED_DECISION`, …) instead of failing the request, and the decider is given a
fresh decision task. Decisions that follow a closing decision are dropped.
fresh decision task. A closing decision must be last in the batch: a batch with anything
after it is rejected with `ValidationException` ("Close must be last decision in list") and
no decision is applied.
## Timeouts
@@ -202,7 +204,7 @@ Faults use the AWS codes and messages, so SDK error handling works unchanged:
| `WorkflowExecutionAlreadyStartedFault` | `StartWorkflowExecution` while an execution with that `workflowId` is open |
| `DefaultUndefinedFault` | A required field is absent from both the request and the type's defaults |
| `TooManyTagsFault` | More than 50 tags on a domain |
| `ValidationException` | Missing required member or a value outside an enum |
| `ValidationException` | Missing required member, a value outside an enum, or a closing decision that is not last |
## Limitations
@@ -539,9 +539,9 @@ public class SwfService implements Resettable {
/**
* Applies a decider's decisions in order.
*
* <p>Decisions after a closing decision (Complete/Fail/Cancel/ContinueAsNew) are
* dropped, matching SWF: the execution is already closed, so a later decision has
* nothing to act on.
* <p>A closing decision (Complete/Fail/Cancel/ContinueAsNew) must be last: the live
* service rejects the whole batch with {@code ValidationException} rather than applying
* the prefix, so this is validated before any state changes.
*/
public void respondDecisionTaskCompleted(String taskToken, List<Decision> decisions, String executionContext) {
SwfWorkflowExecution located = executionForDecisionToken(taskToken);
@@ -553,6 +553,10 @@ public class SwfService implements Resettable {
throw SwfFaults.unknownTaskToken();
}
// Rejected before anything is mutated: the live service answers 400 and leaves
// the task outstanding, so the decider can retry with a corrected batch.
requireCloseIsLastDecision(decisions);
SwfHistoryEvent completed = appendEvent(execution, "DecisionTaskCompleted");
completed.attr("executionContext", executionContext)
.attr("scheduledEventId", task.getScheduledEventId())
@@ -576,6 +580,21 @@ public class SwfService implements Resettable {
}
}
/**
* Rejects a batch whose closing decision is not last, with the live service's message.
* The closing decision itself may appear only once and only in final position.
*/
private void requireCloseIsLastDecision(List<Decision> decisions) {
if (decisions == null || decisions.size() < 2) {
return;
}
for (int i = 0; i < decisions.size() - 1; i++) {
if (SwfConstants.CLOSING_DECISIONS.contains(decisions.get(i).type())) {
throw SwfFaults.validation("Close must be last decision in list");
}
}
}
private void applyDecisions(SwfWorkflowExecution execution, List<Decision> decisions, long decisionEventId) {
if (decisions == null) {
return;
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.swf.model;
import java.util.Set;
/**
* Wire-level constants shared by the SWF service and handler.
*
@@ -14,6 +16,16 @@ public final class SwfConstants {
public static final String FAULT_NAMESPACE = "com.amazonaws.swf.base.model#";
public static final String VALIDATION_NAMESPACE = "com.amazon.coral.validate#";
/**
* Decision types that close the execution. SWF requires one of these to be the last
* decision in a batch and rejects the batch outright otherwise.
*/
public static final Set<String> CLOSING_DECISIONS = Set.of(
"CompleteWorkflowExecution",
"FailWorkflowExecution",
"CancelWorkflowExecution",
"ContinueAsNewWorkflowExecution");
public static final String UNKNOWN_RESOURCE = "UnknownResourceFault";
public static final String DOMAIN_ALREADY_EXISTS = "DomainAlreadyExistsFault";
public static final String DOMAIN_DEPRECATED = "DomainDeprecatedFault";
@@ -527,6 +527,53 @@ class SwfIntegrationTest {
.body("__type", equalTo("com.amazonaws.swf.base.model#UnknownResourceFault"));
}
@Test
void respondDecisionTaskCompleted_closeNotLast_returnsCoralValidationException() {
String domain = uniqueName("close-order");
registerDomain(domain);
registerWorkflowType(domain, "TestWf", "1.0");
registerActivityType(domain, "TestAct", "1.0");
String runId = startExecution(domain, "wf-close-order", null);
String token = pollDecisionToken(domain);
// The live service rejects the batch outright instead of applying the prefix, and
// this fault is namespaced com.amazon.coral.validate, not com.amazonaws.swf.base.model.
call("RespondDecisionTaskCompleted", """
{"taskToken": "%s", "decisions": [
{"decisionType": "CompleteWorkflowExecution",
"completeWorkflowExecutionDecisionAttributes": {"result": "early"}},
{"decisionType": "ScheduleActivityTask",
"scheduleActivityTaskDecisionAttributes": {
"activityId": "after-close",
"activityType": {"name": "TestAct", "version": "1.0"}
}}]}
""".formatted(token))
.then()
.statusCode(400)
.body("__type", equalTo("com.amazon.coral.validate#ValidationException"))
.body("message", equalTo("Close must be last decision in list"));
// The execution is untouched and the same token still works for a valid batch.
call("DescribeWorkflowExecution", """
{"domain": "%s", "execution": {"workflowId": "wf-close-order"}}
""".formatted(domain))
.then()
.body("executionInfo.executionStatus", equalTo("OPEN"));
call("RespondDecisionTaskCompleted", """
{"taskToken": "%s", "decisions": [
{"decisionType": "CompleteWorkflowExecution",
"completeWorkflowExecutionDecisionAttributes": {"result": "ok"}}]}
""".formatted(token))
.then().statusCode(200);
call("DescribeWorkflowExecution", """
{"domain": "%s", "execution": {"workflowId": "wf-close-order", "runId": "%s"}}
""".formatted(domain, runId))
.then()
.body("executionInfo.closeStatus", equalTo("COMPLETED"));
}
@Test
void closingDecisionWithOpenActivity_failsWithUnhandledDecision() {
String domain = uniqueName("unhandled");
@@ -133,21 +133,46 @@ class SwfServiceTest {
}
@Test
void respondDecisionTaskCompleted_dropsDecisionsAfterAClosingDecision() {
void respondDecisionTaskCompleted_rejectsABatchWhoseClosingDecisionIsNotLast() {
String runId = start("wf-after-close");
SwfDecisionTask task = service.pollForDecisionTask(DOMAIN, "tl", "d").orElseThrow();
service.respondDecisionTaskCompleted(task.getTaskToken(), List.of(
new Decision("CompleteWorkflowExecution", Map.of("result", "done")),
new Decision("ScheduleActivityTask", Map.of(
"activityId", "too-late",
"activityType", Map.of("name", "A", "version", "1")))), null);
// The live service rejects the whole batch rather than applying the prefix.
AwsException thrown = assertThrows(AwsException.class,
() -> service.respondDecisionTaskCompleted(task.getTaskToken(), List.of(
new Decision("CompleteWorkflowExecution", Map.of("result", "done")),
new Decision("ScheduleActivityTask", Map.of(
"activityId", "too-late",
"activityType", Map.of("name", "A", "version", "1")))), null));
assertEquals("ValidationException", thrown.getErrorCode());
assertEquals("Close must be last decision in list", thrown.getMessage());
assertEquals("com.amazon.coral.validate#ValidationException", thrown.jsonType());
// Nothing was applied and the task is still outstanding, so the decider can retry.
SwfWorkflowExecution execution = service.describeWorkflowExecution(DOMAIN, "wf-after-close", runId);
assertEquals("CLOSED", execution.getExecutionStatus());
assertEquals("OPEN", execution.getExecutionStatus());
assertTrue(execution.getActivities().isEmpty());
assertNull(lastAttribute(execution, "DecisionTaskCompleted", "scheduledEventId"),
"a rejected batch must not append DecisionTaskCompleted");
service.respondDecisionTaskCompleted(task.getTaskToken(), List.of(
new Decision("CompleteWorkflowExecution", Map.of("result", "done"))), null);
assertEquals("COMPLETED",
service.describeWorkflowExecution(DOMAIN, "wf-after-close", runId).getCloseStatus());
}
@Test
void respondDecisionTaskCompleted_acceptsAClosingDecisionInFinalPosition() {
String runId = start("wf-close-last");
SwfDecisionTask task = service.pollForDecisionTask(DOMAIN, "tl", "d").orElseThrow();
service.respondDecisionTaskCompleted(task.getTaskToken(), List.of(
new Decision("RecordMarker", Map.of("markerName", "m-1")),
new Decision("CompleteWorkflowExecution", Map.of("result", "done"))), null);
SwfWorkflowExecution execution = service.describeWorkflowExecution(DOMAIN, "wf-close-last", runId);
assertEquals("m-1", lastAttribute(execution, "MarkerRecorded", "markerName"));
assertEquals("COMPLETED", execution.getCloseStatus());
assertTrue(execution.getActivities().isEmpty(),
"a decision after the closing decision must be dropped");
}
@Test