fix(codepipeline): serialize failure writes with stop publication (#8073)

Take the execution monitor when an action, stage or condition records a
failure. A concurrent stop can no longer replace a Failed write between
its terminal check and its Stopping transition.

Port the remaining failure transitions and regression coverage from
AndreKurait/floci#710. The stop handler already landed in upstream #7939.

Hold the execution monitor across the approval completion check, result
updates and persistence so stop cannot interleave with a rejected result.

Share the held-monitor stop helper and cover rejection before a waiting
stop. Wait for approval polling after token persistence in the existing
stop-completion fixture.

Signed-off-by: Andre Kurait <akurait@amazon.com>
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
Co-authored-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Jackson PriceandAndre Kurait authored and GitHub committed 2026-11-11 23:29:19 -04:00
1 parent 2e97c50ca8
commit 589e1e58b4
2 files changed
+232 -37

No files matched your search

@@ -861,22 +861,24 @@ public class CodePipelineService {
throw new AwsException("InvalidApprovalTokenException", "Approval token is invalid", 400);
}
if (!"InProgress".equals(approval.getStatus())) {
throw new AwsException("ApprovalAlreadyCompletedException",
"The approval action has already been approved or rejected.", 400);
}
synchronized (execution) {
if (!"InProgress".equals(approval.getStatus())) {
throw new AwsException("ApprovalAlreadyCompletedException",
"The approval action has already been approved or rejected.", 400);
}
boolean approved = "Approved".equals(status);
approval.setStatus(approved ? "Succeeded" : "Failed");
approval.setSummary(summary);
approval.setLastUpdateTime(now());
if (!approved) {
execution.setStatus("Failed");
execution.setStatusSummary("Action " + actionName + " failed: " + summary);
execution.getStageExecutionStatuses().put(stageName, "Failed");
execution.setLastUpdateTime(now());
boolean approved = "Approved".equals(status);
approval.setStatus(approved ? "Succeeded" : "Failed");
approval.setSummary(summary);
approval.setLastUpdateTime(now());
if (!approved) {
execution.setStatus("Failed");
execution.setStatusSummary("Action " + actionName + " failed: " + summary);
execution.getStageExecutionStatuses().put(stageName, "Failed");
execution.setLastUpdateTime(now());
}
putExecution(execution);
}
putExecution(execution);
return mapper.createObjectNode().put("approvedAt", now());
}
@@ -1884,10 +1886,12 @@ public class CodePipelineService {
}
private void failForCondition(CodePipelineExecution execution, String stageName, String conditionType) {
execution.setStatus("Failed");
execution.setStatusSummary(
"Condition " + conditionType + " failed in stage " + stageName + ".");
putExecution(execution);
synchronized (execution) {
execution.setStatus("Failed");
execution.setStatusSummary(
"Condition " + conditionType + " failed in stage " + stageName + ".");
putExecution(execution);
}
}
private void finishExecutionRun(CodePipelineExecution execution) {
@@ -1984,7 +1988,9 @@ public class CodePipelineService {
.toList();
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
if (futures.stream().anyMatch(CompletableFuture::isCompletedExceptionally)) {
execution.setStatus("Failed");
synchronized (execution) {
execution.setStatus("Failed");
}
}
});
}
@@ -2029,8 +2035,10 @@ public class CodePipelineService {
state.setErrorDetails(Map.of(
"code", e instanceof AwsException aws ? aws.getErrorCode() : "ActionExecutionFailed",
"message", Objects.toString(e.getMessage(), "Action failed")));
execution.setStatus("Failed");
execution.setStatusSummary("Action " + state.getActionName() + " failed: " + state.getSummary());
synchronized (execution) {
execution.setStatus("Failed");
execution.setStatusSummary("Action " + state.getActionName() + " failed: " + state.getSummary());
}
} finally {
state.setLastUpdateTime(now());
putExecution(execution);
@@ -1259,6 +1259,7 @@ class CodePipelineServiceTest {
void workerCompletionCannotBeOverwrittenByStopPublication(boolean abandon) throws Exception {
String pipeline = "stop-publication";
String executionId = "stopping-execution";
CountDownLatch approvalPolling = new CountDownLatch(1);
CountDownLatch stopPublished = new CountDownLatch(1);
CountDownLatch releaseStop = new CountDownLatch(1);
AtomicReference<Thread> requester = new AtomicReference<>();
@@ -1273,6 +1274,12 @@ class CodePipelineServiceTest {
boolean requested = (boolean) invocation.callRealMethod();
if (requested && Thread.currentThread() != requester.get()) {
worker.compareAndSet(null, Thread.currentThread());
} else if (!requested && approvalPolling.getCount() > 0) {
synchronized (execution) {
if (execution.getActionExecutions().stream().anyMatch(action -> action.getToken() != null)) {
approvalPolling.countDown();
}
}
}
return requested;
}).when(execution).isStopRequested();
@@ -1286,10 +1293,8 @@ class CodePipelineServiceTest {
}).when(execution).setStopRequested(anyBoolean());
storage.executionStore.putForAccount(ACCOUNT, REGION + ":" + pipeline + ":" + executionId, execution);
service.resumePersistedExecutions();
await().atMost(Duration.ofSeconds(3)).untilAsserted(() ->
assertFalse(handle("ListActionExecutions", """
{"pipelineName":"%s","filter":{"pipelineExecutionId":"%s"}}
""".formatted(pipeline, executionId)).path("actionExecutionDetails").isEmpty()));
assertTrue(approvalPolling.await(5, TimeUnit.SECONDS),
"Approval worker must enter polling before stop holds the execution monitor");
Future<?> stopped = requests.submit(() -> {
requester.set(Thread.currentThread());
stopExecution(service, pipeline, executionId, abandon);
@@ -1327,20 +1332,9 @@ class CodePipelineServiceTest {
execution.getActionExecutions().add(completed);
ActionExecution registering = new ActionExecution();
registering.setStatus("InProgress");
AtomicReference<Thread> stoppingThread = new AtomicReference<>();
Future<JsonNode> stopped;
synchronized (execution) {
stopped = requests.submit(() -> {
stoppingThread.set(Thread.currentThread());
return handle("StopPipelineExecution", """
{
"pipelineName": "%s",
"pipelineExecutionId": "%s",
"abandon": true
}
""".formatted(pipeline, executionId));
});
ThreadStates.awaitBlockedOrDone(stoppingThread, stopped);
stopped = stopWaitingForExecutionMonitor(requests, execution, true);
// The worker registers actions under this monitor before the stop can traverse them.
execution.getActionExecutions().add(registering);
}
@@ -1354,6 +1348,181 @@ class CodePipelineServiceTest {
}
}
@Test
void actionFailureWaitsForStopPublicationBeforeEndingTheExecution() throws Exception {
String pipeline = "action-failure-during-stop";
String executionId = "failing-execution";
CountDownLatch actionEntered = new CountDownLatch(1);
CountDownLatch releaseAction = new CountDownLatch(1);
CountDownLatch stopChecked = new CountDownLatch(1);
CountDownLatch releaseStop = new CountDownLatch(1);
AtomicReference<Thread> actionThread = new AtomicReference<>();
AtomicReference<Thread> stoppingThread = new AtomicReference<>();
CodeBuildService codeBuild = mock(CodeBuildService.class);
when(codeBuild.startBuild(anyString(), anyString(), anyString(),
any(), any(), any(), any(), any(), any(), any())).thenAnswer(invocation -> {
actionThread.set(Thread.currentThread());
actionEntered.countDown();
assertTrue(releaseAction.await(5, TimeUnit.SECONDS));
throw new AwsException("ResourceNotFoundException", "Build project is missing", 400);
});
CapturingStorageFactory captured = new CapturingStorageFactory();
CodePipelineService pipelineService = new CodePipelineService(captured, mapper, codeBuild,
mock(CodeDeployService.class), mock(LambdaService.class), mock(S3Service.class),
configWithPollInterval(500L));
try (ExecutorService requests = Executors.newSingleThreadExecutor()) {
createExternalActionPipeline(pipelineService, pipeline, """
{
"name": "BuildAction",
"actionTypeId": {
"category": "Build",
"owner": "AWS",
"provider": "CodeBuild",
"version": "1"
},
"configuration": {
"ProjectName": "missing-project"
}
}
""");
CodePipelineExecution execution = spy(waitingExecution(captured, pipeline, executionId, 1, null));
doAnswer(invocation -> {
String status = (String) invocation.callRealMethod();
if (Thread.currentThread() == stoppingThread.get()) {
stopChecked.countDown();
assertTrue(releaseStop.await(5, TimeUnit.SECONDS));
}
return status;
}).when(execution).getStatus();
captured.executionStore.putForAccount(ACCOUNT, REGION + ":" + pipeline + ":" + executionId, execution);
pipelineService.resumePersistedExecutions();
assertTrue(actionEntered.await(5, TimeUnit.SECONDS));
Future<?> stopped = requests.submit(() -> {
stoppingThread.set(Thread.currentThread());
stopExecution(pipelineService, pipeline, executionId, false);
return null;
});
try {
assertTrue(stopChecked.await(5, TimeUnit.SECONDS));
releaseAction.countDown();
ThreadStates.awaitBlockedOrDone(actionThread.get());
assertEquals(Thread.State.BLOCKED, actionThread.get().getState());
assertEquals("InProgress", execution.getStatus());
assertFalse(execution.isStopRequested());
} finally {
releaseStop.countDown();
}
stopped.get(5, TimeUnit.SECONDS);
await().atMost(Duration.ofSeconds(5))
.until(() -> !pipelineService.activeRuns.contains(ACCOUNT + ":" + executionId));
assertEquals("Failed", execution.getStatus());
assertEquals("Failed", execution.getActionExecutions().getFirst().getStatus());
assertTrue(execution.getStatusSummary().contains("Build project is missing"));
} finally {
releaseAction.countDown();
releaseStop.countDown();
pipelineService.shutdown();
}
}
@Test
void aStopThatLosesToTheRunsOwnEndingIsRefusedInsteadOfReplacingIt() throws Exception {
// A run ends under its execution's monitor, Stopped in answer to the stop signal or Failed
// or Succeeded on its own, and then leaves. A stop that raised its signal or checked the
// status outside that monitor could write Stopping after the ending, where it stood for
// good: no run was left to finish it.
String pipeline = "stop-losing-to-the-run-ending";
String executionId = "ending-execution";
try (ExecutorService requests = Executors.newSingleThreadExecutor()) {
createExternalActionPipeline(service, pipeline, """
{
"name": "Approve",
"actionTypeId": {
"category": "Approval",
"owner": "AWS",
"provider": "Manual",
"version": "1"
}
}
""");
CodePipelineExecution execution = waitingExecution(storage, pipeline, executionId, 1, "External");
Future<JsonNode> stopped;
synchronized (execution) {
stopped = stopWaitingForExecutionMonitor(requests, execution, true);
assertFalse(execution.isStopRequested());
assertEquals("InProgress", execution.getStatus());
// The run ends here, as it does under this monitor.
execution.setStatus("Succeeded");
}
ExecutionException refused = assertThrows(ExecutionException.class,
() -> stopped.get(5, TimeUnit.SECONDS));
AwsException cause = (AwsException) refused.getCause();
assertEquals("PipelineExecutionNotStoppableException", cause.getErrorCode());
assertEquals("Succeeded", execution.getStatus());
assertFalse(execution.isStopRequested());
} finally {
service.shutdown();
}
}
@Test
void rejectedApprovalCompletesBeforeAStopWaitingOnItsMonitor() throws Exception {
String pipeline = "rejection-during-stop";
CountDownLatch approvalChecked = new CountDownLatch(1);
CountDownLatch releaseApproval = new CountDownLatch(1);
AtomicReference<Thread> approvalThread = new AtomicReference<>();
try (ExecutorService requests = Executors.newFixedThreadPool(2)) {
CodePipelineExecution execution = createWaitingApprovalExecution(pipeline);
ActionExecution approval = spy(approvalAction());
doAnswer(invocation -> {
String status = (String) invocation.callRealMethod();
if (Thread.currentThread() == approvalThread.get()) {
approvalChecked.countDown();
assertTrue(releaseApproval.await(5, TimeUnit.SECONDS));
}
return status;
}).when(approval).getStatus();
execution.getActionExecutions().add(approval);
Future<JsonNode> rejected = requests.submit(() -> {
approvalThread.set(Thread.currentThread());
return handle("PutApprovalResult", """
{
"pipelineName": "%s",
"stageName": "External",
"actionName": "Approve",
"token": "%s",
"result": {
"status": "Rejected",
"summary": "rejected by test"
}
}
""".formatted(pipeline, approval.getToken()));
});
Future<JsonNode> stopped;
try {
assertTrue(approvalChecked.await(5, TimeUnit.SECONDS));
stopped = stopWaitingForExecutionMonitor(requests, execution, false);
assertFalse(execution.isStopRequested(), "Stop must wait for the approval result to be written");
assertEquals("InProgress", execution.getStatus());
} finally {
releaseApproval.countDown();
}
assertTrue(rejected.get(5, TimeUnit.SECONDS).path("approvedAt").isNumber());
ExecutionException refused = assertThrows(ExecutionException.class,
() -> stopped.get(5, TimeUnit.SECONDS));
AwsException cause = (AwsException) refused.getCause();
assertEquals("PipelineExecutionNotStoppableException", cause.getErrorCode());
assertEquals("Failed", approval.getStatus());
assertEquals("Failed", execution.getStatus());
assertEquals("Failed", execution.getStageExecutionStatuses().get("External"));
assertEquals("Action Approve failed: rejected by test", execution.getStatusSummary());
assertFalse(execution.isStopRequested());
} finally {
releaseApproval.countDown();
service.shutdown();
}
}
@Test
void listActionsIncludesAnActionRegisteredWhileTheRequestWaits() throws Exception {
String pipeline = "list-during-action-registration";
@@ -1435,6 +1604,24 @@ class CodePipelineServiceTest {
}
}
private Future<JsonNode> stopWaitingForExecutionMonitor(ExecutorService requests,
CodePipelineExecution execution,
boolean abandon) throws Exception {
AtomicReference<Thread> stoppingThread = new AtomicReference<>();
Future<JsonNode> stopped = requests.submit(() -> {
stoppingThread.set(Thread.currentThread());
return handle("StopPipelineExecution", """
{
"pipelineName": "%s",
"pipelineExecutionId": "%s",
"abandon": %s
}
""".formatted(execution.getPipelineName(), execution.getPipelineExecutionId(), abandon));
});
ThreadStates.awaitBlockedOrDone(stoppingThread, stopped);
return stopped;
}
private CodePipelineExecution createWaitingApprovalExecution(String pipeline) throws Exception {
createExternalActionPipeline(service, pipeline, """
{"name":"Approve","actionTypeId":{