mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(ssm): stop re-reading shared mutable state in the command status rollup (#2477)
* fix(ssm): stop re-reading shared mutable state in the command status rollup Fixes #2264 (flaky SsmCommandServiceDirectExecutionTest.directTimeoutMarksCommandTimedOut seeing status=TimedOut with statusDetails still In Progress). commandStore is a plain ConcurrentHashMap-backed InMemoryStorage whose get() returns the same shared Command object on every call, not a defensive copy. updateCommandStatus's finalize branch computed a local status, called command.setStatus(status), then immediately re-read command.getStatus() to compute statusDetails instead of using that same local variable. On a shared mutable object that's a real TOCTOU gap: if another thread's updateCommandStatus call for the same command (its own instance's completion racing this one) mutated command's status in the window between those two lines, this call's statusDetails ended up reflecting the OTHER thread's status instead of the one it had just written - reproducing the exact reported symptom. Fix: use the local status variable directly, the same one already passed to setStatus, instead of reading it back through the shared object. Verified: added a test that forces many instances of a multi-instance command to complete via a CyclicBarrier as close to simultaneously as Java threads allow, across many trials, asserting status and statusDetails always agree. Rigor-checked by reverting the fix and re-running against 1200 such attempts (12 instances x 100 trials) - it never reproduced the historical race, which the two-line gap being a few nanoseconds of adjacent bytecode explains: that's far narrower than a clean, uncontended test JVM's thread-scheduling granularity, matching the issue's own report that it only flakes under real CI load, not locally. So this isn't a fails-before/passes-after reproduction; it's a standing invariant check, and the fix's correctness is established by construction instead - statusDetails is now computed from a local variable no other thread can touch, closing the TOCTOU window regardless of scheduling rather than just making it statistically less likely to hit. Full ssm package regression is green (62 tests). * fix(ssm): synchronize cancelCommand against the status rollup greptile flagged a real gap in the previous commit: even with updateCommandStatus no longer racing against itself, cancelCommand's own status+statusDetails write could still land entirely inside the rollup's window between ITS two field writes - e.g. status=Cancelled from cancelCommand landing between the rollup's setStatus("Success") and its setStatusDetails(...), leaving statusDetails="Success" stored alongside status="Cancelled". Both methods now synchronize on the shared Command object itself before touching its status fields. commandStore's get() always returns the same instance for a given key (InMemoryStorage is a plain ConcurrentHashMap, not a defensive-copying store), so locking on that object correctly serializes every writer of a given command's status, regardless of which method they're in. Verified with a deterministic mutual-exclusion test rather than a timing-based reproduction: commandStore.put() is called from inside each synchronized block and is a real interception point (unlike the plain field-setter calls themselves), so a spy forces the rollup to block mid-finalize while still holding the lock, and the test asserts a concurrent cancelCommand call blocks too rather than racing past it - the same style already used for the code-volume lock in ContainerLauncherTest's cleanupAndAConcurrentRollback... test. Confirmed the test fails when either method's lock alone is swapped for an unshared one (checked both independently) and passes with both restored. Full ssm package regression is green (63 tests). * fix(ssm): synchronize reads and every remaining invocation writer pgermosen found the real remaining gap on this PR: SsmJsonHandler's commandToNode() (the ListCommands/GetCommandInvocation serializer) read Status and StatusDetails from the same live, shared Command object the writers now synchronize on, but never took that lock itself. A ListCommands call whose two field reads straddled a concurrent writer's update could observe a torn pair that was never true at any single instant - most likely the actual path #2264 was originally seen through, since a customer polls status via ListCommands, not the internal rollup directly. Fixes that by synchronizing commandToNode's read on the same Command object, and invocationToNode's read on the same CommandInvocation object for the identical reason: CommandInvocation is also returned as a live shared reference from invocationStore, and multiple methods already write its status pair independently (cancelCommand's per- instance cancel, applyDirectResult's completion, agent SendReply and FailMessage, AcknowledgeMessage's Pending to InProgress transition, and the bulk timeout sweep in failActiveInvocationsForInstances). None of those writers synchronized against each other or against the read side, so this closes the same class of bug at the invocation level too rather than leaving an identical gap sitting right next to the fix. Verified with the same style as the previous two commits: a spy forces a rollup to block mid-finalize while still holding the Command lock, and a new test asserts a concurrent ListCommands call (going through SsmJsonHandler, not just SsmCommandService directly) blocks too rather than observing a torn read. Confirmed it fails with the read-side lock swapped for an unshared one and passes with it restored. Full ssm package regression is green (64 tests).
This commit is contained in:
1 parent
b243504b48
commit
6f1ce9b23f
3 files changed
+337
-45
No files matched your search
@@ -264,10 +264,16 @@ public class SsmCommandService implements Resettable {
|
||||
for (String instanceId : targets) {
|
||||
String invKey = invocationKey(region, commandId, instanceId);
|
||||
invocationStore.get(invKey).ifPresent(inv -> {
|
||||
if ("Pending".equals(inv.getStatus()) || "InProgress".equals(inv.getStatus())) {
|
||||
inv.setStatus("Cancelled");
|
||||
inv.setStatusDetails("Cancelled");
|
||||
invocationStore.put(invKey, inv);
|
||||
// Same lock discipline as the command-level fields: invocationStore returns the same
|
||||
// shared CommandInvocation object on every get(), and multiple methods here (direct
|
||||
// completion, agent SendReply/FailMessage, timeout sweeps) can race this cancellation
|
||||
// on the same instance's invocation.
|
||||
synchronized (inv) {
|
||||
if ("Pending".equals(inv.getStatus()) || "InProgress".equals(inv.getStatus())) {
|
||||
inv.setStatus("Cancelled");
|
||||
inv.setStatusDetails("Cancelled");
|
||||
invocationStore.put(invKey, inv);
|
||||
}
|
||||
}
|
||||
// Remove any queued (not-yet-polled) messages for this instance
|
||||
Queue<PendingMessage> q = messageQueues.get(instanceId);
|
||||
@@ -277,9 +283,13 @@ public class SsmCommandService implements Resettable {
|
||||
});
|
||||
}
|
||||
|
||||
command.setStatus("Cancelled");
|
||||
command.setStatusDetails("Cancelled");
|
||||
commandStore.put(commandKey(region, commandId), command);
|
||||
// Same lock updateCommandStatus takes on this exact object, so a rollup completing this
|
||||
// command concurrently can't have its own status+statusDetails write interleave with this one.
|
||||
synchronized (command) {
|
||||
command.setStatus("Cancelled");
|
||||
command.setStatusDetails("Cancelled");
|
||||
commandStore.put(commandKey(region, commandId), command);
|
||||
}
|
||||
LOG.infov("CancelCommand: commandId={0}", commandId);
|
||||
}
|
||||
|
||||
@@ -303,11 +313,13 @@ public class SsmCommandService implements Resettable {
|
||||
if (!isActiveInvocation(invocation.getStatus())) {
|
||||
continue;
|
||||
}
|
||||
invocation.setStatus("Failed");
|
||||
invocation.setStatusDetails(statusDetails);
|
||||
invocation.setResponseCode(-1);
|
||||
invocation.setExecutionEndDateTime(now);
|
||||
invocationStore.put(invocationKey(region, invocation.getCommandId(), invocation.getInstanceId()), invocation);
|
||||
synchronized (invocation) {
|
||||
invocation.setStatus("Failed");
|
||||
invocation.setStatusDetails(statusDetails);
|
||||
invocation.setResponseCode(-1);
|
||||
invocation.setExecutionEndDateTime(now);
|
||||
invocationStore.put(invocationKey(region, invocation.getCommandId(), invocation.getInstanceId()), invocation);
|
||||
}
|
||||
commandIds.add(invocation.getCommandId());
|
||||
failed++;
|
||||
}
|
||||
@@ -369,11 +381,13 @@ public class SsmCommandService implements Resettable {
|
||||
|
||||
String invKey = invocationKey(region, commandId, instanceId);
|
||||
invocationStore.get(invKey).ifPresent(inv -> {
|
||||
if ("Pending".equals(inv.getStatus())) {
|
||||
inv.setStatus("InProgress");
|
||||
inv.setStatusDetails(statusDetails("InProgress"));
|
||||
inv.setExecutionStartDateTime(Instant.now());
|
||||
invocationStore.put(invKey, inv);
|
||||
synchronized (inv) {
|
||||
if ("Pending".equals(inv.getStatus())) {
|
||||
inv.setStatus("InProgress");
|
||||
inv.setStatusDetails(statusDetails("InProgress"));
|
||||
inv.setExecutionStartDateTime(Instant.now());
|
||||
invocationStore.put(invKey, inv);
|
||||
}
|
||||
}
|
||||
});
|
||||
LOG.debugv("AcknowledgeMessage: messageId={0} commandId={1}", messageId, commandId);
|
||||
@@ -424,13 +438,15 @@ public class SsmCommandService implements Resettable {
|
||||
String invKey = invocationKey(region, commandId, instanceId);
|
||||
CommandInvocation inv = invocationStore.get(invKey).orElse(null);
|
||||
if (inv != null) {
|
||||
inv.setStatus(toInvocationStatus(status));
|
||||
inv.setStatusDetails(statusDetails(toInvocationStatus(status)));
|
||||
inv.setStandardOutputContent(stdout);
|
||||
inv.setStandardErrorContent(stderr);
|
||||
inv.setResponseCode(returnCode);
|
||||
inv.setExecutionEndDateTime(endTime);
|
||||
invocationStore.put(invKey, inv);
|
||||
synchronized (inv) {
|
||||
inv.setStatus(toInvocationStatus(status));
|
||||
inv.setStatusDetails(statusDetails(toInvocationStatus(status)));
|
||||
inv.setStandardOutputContent(stdout);
|
||||
inv.setStandardErrorContent(stderr);
|
||||
inv.setResponseCode(returnCode);
|
||||
inv.setExecutionEndDateTime(endTime);
|
||||
invocationStore.put(invKey, inv);
|
||||
}
|
||||
}
|
||||
|
||||
// Recalculate command status
|
||||
@@ -452,10 +468,12 @@ public class SsmCommandService implements Resettable {
|
||||
|
||||
String invKey = invocationKey(region, commandId, instanceId);
|
||||
invocationStore.get(invKey).ifPresent(inv -> {
|
||||
inv.setStatus("Failed");
|
||||
inv.setStatusDetails("Failed: " + failureType);
|
||||
inv.setExecutionEndDateTime(Instant.now());
|
||||
invocationStore.put(invKey, inv);
|
||||
synchronized (inv) {
|
||||
inv.setStatus("Failed");
|
||||
inv.setStatusDetails("Failed: " + failureType);
|
||||
inv.setExecutionEndDateTime(Instant.now());
|
||||
invocationStore.put(invKey, inv);
|
||||
}
|
||||
});
|
||||
updateCommandStatus(commandId, region);
|
||||
LOG.warnv("FailMessage: commandId={0} instanceId={1} failureType={2}", commandId, instanceId, failureType);
|
||||
@@ -533,15 +551,19 @@ public class SsmCommandService implements Resettable {
|
||||
.executeIfSupported(instanceId, documentName, parameters, timeoutSeconds)
|
||||
.orElse(null);
|
||||
if (result == null) {
|
||||
invocation.setStatus("Pending");
|
||||
invocation.setStatusDetails(statusDetails("Pending"));
|
||||
invocationStore.put(invKey, invocation);
|
||||
synchronized (invocation) {
|
||||
invocation.setStatus("Pending");
|
||||
invocation.setStatusDetails(statusDetails("Pending"));
|
||||
invocationStore.put(invKey, invocation);
|
||||
}
|
||||
queueMessage(commandId, instanceId, documentName, parameters, timeoutSeconds, region);
|
||||
updateCommandStatus(commandId, region);
|
||||
return;
|
||||
}
|
||||
applyDirectResult(invocation, result);
|
||||
invocationStore.put(invKey, invocation);
|
||||
synchronized (invocation) {
|
||||
applyDirectResult(invocation, result);
|
||||
invocationStore.put(invKey, invocation);
|
||||
}
|
||||
updateCommandStatus(commandId, region);
|
||||
}, directExecutionExecutor);
|
||||
}
|
||||
@@ -683,16 +705,30 @@ public class SsmCommandService implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
command.setCompletedCount(completed);
|
||||
command.setErrorCount(errors);
|
||||
// Synchronized on the shared Command object itself (commandStore's get() always returns the
|
||||
// same instance for a given key, not a defensive copy) so this status+statusDetails write
|
||||
// can't interleave with cancelCommand's own status+statusDetails write on the same object -
|
||||
// without this, cancelCommand's whole pair could land inside the gap between this method's
|
||||
// two field writes, leaving status=Cancelled but statusDetails reflecting this call's stale
|
||||
// completion status (or the reverse), even though each method's own two fields individually
|
||||
// agree with each other when read right after being written.
|
||||
synchronized (command) {
|
||||
command.setCompletedCount(completed);
|
||||
command.setErrorCount(errors);
|
||||
|
||||
if (!anyInProgress && completed == instanceIds.size()) {
|
||||
String status = commandStatus(errors, timedOut, instanceIds.size());
|
||||
command.setStatus(status);
|
||||
command.setStatusDetails(statusDetails(command.getStatus()));
|
||||
if (!anyInProgress && completed == instanceIds.size()) {
|
||||
// Use the local status, not a re-read of command.getStatus(): re-reading it here left
|
||||
// a second, narrower window where a concurrent updateCommandStatus call for the same
|
||||
// command (e.g. another instance's async completion racing this one) could mutate the
|
||||
// shared object in between, so this call's own statusDetails ended up reflecting a
|
||||
// DIFFERENT call's status than the one it had just written to status itself.
|
||||
String status = commandStatus(errors, timedOut, instanceIds.size());
|
||||
command.setStatus(status);
|
||||
command.setStatusDetails(statusDetails(status));
|
||||
}
|
||||
|
||||
commandStore.put(commandKey(region, commandId), command);
|
||||
}
|
||||
|
||||
commandStore.put(commandKey(region, commandId), command);
|
||||
}
|
||||
|
||||
private static String commandStatus(int errors, int timedOut, int targetCount) {
|
||||
|
||||
@@ -423,8 +423,15 @@ public class SsmJsonHandler {
|
||||
if (c.getComment() != null) node.put("Comment", c.getComment());
|
||||
if (c.getRequestedDateTime() != null) node.put("RequestedDateTime", c.getRequestedDateTime().toEpochMilli() / 1000.0);
|
||||
if (c.getExpiresAfter() != null) node.put("ExpiresAfter", c.getExpiresAfter().toEpochMilli() / 1000.0);
|
||||
node.put("Status", c.getStatus());
|
||||
node.put("StatusDetails", c.getStatusDetails());
|
||||
// c is the same live, shared Command object SsmCommandService's writers (updateCommandStatus,
|
||||
// cancelCommand) synchronize on before touching Status/StatusDetails together. Reading the
|
||||
// pair here without the same lock would let this read straddle a concurrent writer's update -
|
||||
// one field read before it, the other after - producing a Status/StatusDetails combination
|
||||
// that was never actually true at any single instant.
|
||||
synchronized (c) {
|
||||
node.put("Status", c.getStatus());
|
||||
node.put("StatusDetails", c.getStatusDetails());
|
||||
}
|
||||
node.put("TargetCount", c.getTargetCount());
|
||||
node.put("CompletedCount", c.getCompletedCount());
|
||||
node.put("ErrorCount", c.getErrorCount());
|
||||
@@ -454,8 +461,12 @@ public class SsmJsonHandler {
|
||||
node.put("DocumentName", inv.getDocumentName());
|
||||
if (inv.getDocumentVersion() != null) node.put("DocumentVersion", inv.getDocumentVersion());
|
||||
if (inv.getRequestedDateTime() != null) node.put("RequestedDateTime", inv.getRequestedDateTime().toEpochMilli() / 1000.0);
|
||||
node.put("Status", inv.getStatus());
|
||||
node.put("StatusDetails", inv.getStatusDetails());
|
||||
// Same reasoning as commandToNode: inv is the same live, shared CommandInvocation object its
|
||||
// writers (cancelCommand, direct/agent completion, timeout sweeps) now synchronize on.
|
||||
synchronized (inv) {
|
||||
node.put("Status", inv.getStatus());
|
||||
node.put("StatusDetails", inv.getStatusDetails());
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user