fix(bedrock-agentcore): serialize runtime endpoint mutations (#7502)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-04 09:55:00 -04:00
1 parent b551625a62
commit 8f69e81893
4 files changed
+339 -107

No files matched your search

@@ -0,0 +1,21 @@
package io.github.hectorvent.floci.core.common;
/** A bounded set of monitors for callers to synchronize operations sharing a key. */
public final class StripedLocks {
private final Object[] locks;
public StripedLocks(int stripeCount) {
if (stripeCount <= 0) {
throw new IllegalArgumentException("stripeCount must be positive");
}
locks = new Object[stripeCount];
for (int i = 0; i < locks.length; i++) {
locks[i] = new Object();
}
}
public Object lockFor(Object key) {
return locks[Math.floorMod(key.hashCode(), locks.length)];
}
}
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.core.common.StripedLocks;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntime;
@@ -46,9 +47,11 @@ public class BedrockAgentCoreControlService {
private static final String ID_ALPHABET =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final int MAX_PAGE = 100;
private static final int RUNTIME_LOCK_STRIPES = 256;
private final StorageBackend<String, AgentRuntime> storage;
private final RegionResolver regionResolver;
private final StripedLocks runtimeLocks = new StripedLocks(RUNTIME_LOCK_STRIPES);
private final BedrockAgentCoreIdentityService identityService;
// clientToken idempotency: tokens of completed deletes, so a replayed delete succeeds
// instead of 404ing. In-memory only (reset on restart), and each entry expires after
@@ -181,34 +184,36 @@ public class BedrockAgentCoreControlService {
String roleArn, String description, Map<String, String> environmentVariables,
JsonNode authorizerConfiguration, JsonNode protocolConfiguration,
String region) {
if (artifact == null || artifact.isNull()) {
throw new AwsException("ValidationException", "agentRuntimeArtifact is required", 400);
}
if (networkConfiguration == null || networkConfiguration.isNull()) {
throw new AwsException("ValidationException", "networkConfiguration is required", 400);
}
if (roleArn == null || roleArn.isBlank()) {
throw new AwsException("ValidationException", "roleArn is required", 400);
}
validateConfiguration(networkConfiguration, protocolConfiguration);
AgentRuntime runtime = getAgentRuntime(id, region);
Instant now = Instant.now();
synchronized (runtimeLock(region, id)) {
if (artifact == null || artifact.isNull()) {
throw new AwsException("ValidationException", "agentRuntimeArtifact is required", 400);
}
if (networkConfiguration == null || networkConfiguration.isNull()) {
throw new AwsException("ValidationException", "networkConfiguration is required", 400);
}
if (roleArn == null || roleArn.isBlank()) {
throw new AwsException("ValidationException", "roleArn is required", 400);
}
validateConfiguration(networkConfiguration, protocolConfiguration);
AgentRuntime runtime = getAgentRuntime(id, region);
Instant now = Instant.now();
int newVersion = runtime.getLatestVersion() + 1;
runtime.setLatestVersion(newVersion);
runtime.setRoleArn(roleArn);
runtime.setDescription(description);
runtime.setAgentRuntimeArtifact(artifact);
runtime.setNetworkConfiguration(networkConfiguration);
runtime.setAuthorizerConfiguration(authorizerConfiguration);
runtime.setProtocolConfiguration(protocolConfiguration);
runtime.setEnvironmentVariables(environmentVariables != null ? new HashMap<>(environmentVariables) : new HashMap<>());
runtime.setLastUpdatedAt(now);
runtime.getVersions().add(snapshot(runtime, String.valueOf(newVersion), now));
int newVersion = runtime.getLatestVersion() + 1;
runtime.setLatestVersion(newVersion);
runtime.setRoleArn(roleArn);
runtime.setDescription(description);
runtime.setAgentRuntimeArtifact(artifact);
runtime.setNetworkConfiguration(networkConfiguration);
runtime.setAuthorizerConfiguration(authorizerConfiguration);
runtime.setProtocolConfiguration(protocolConfiguration);
runtime.setEnvironmentVariables(environmentVariables != null ? new HashMap<>(environmentVariables) : new HashMap<>());
runtime.setLastUpdatedAt(now);
runtime.getVersions().add(snapshot(runtime, String.valueOf(newVersion), now));
storage.put(key(region, id), runtime);
LOG.infov("Updated AgentCore runtime {0} to version {1}", id, newVersion);
return runtime;
storage.put(key(region, id), runtime);
LOG.infov("Updated AgentCore runtime {0} to version {1}", id, newVersion);
return runtime;
}
}
/**
@@ -236,25 +241,27 @@ public class BedrockAgentCoreControlService {
}
public AgentRuntime deleteAgentRuntime(String id, String clientToken, String region) {
Optional<AgentRuntime> found = storage.get(key(region, id));
if (found.isEmpty()) {
if (clientToken != null && deletedRuntimeTokens.contains(tokenKey(region, clientToken))) {
AgentRuntime marker = new AgentRuntime();
marker.setAgentRuntimeId(id);
marker.setStatus(STATUS_DELETING);
return marker;
synchronized (runtimeLock(region, id)) {
Optional<AgentRuntime> found = storage.get(key(region, id));
if (found.isEmpty()) {
if (clientToken != null && deletedRuntimeTokens.contains(tokenKey(region, clientToken))) {
AgentRuntime marker = new AgentRuntime();
marker.setAgentRuntimeId(id);
marker.setStatus(STATUS_DELETING);
return marker;
}
throw new AwsException("ResourceNotFoundException",
"AgentCore runtime not found: " + id, 404);
}
throw new AwsException("ResourceNotFoundException",
"AgentCore runtime not found: " + id, 404);
AgentRuntime runtime = found.get();
storage.delete(key(region, id));
if (clientToken != null) {
deletedRuntimeTokens.record(tokenKey(region, clientToken));
}
runtime.setStatus(STATUS_DELETING);
LOG.infov("Deleted AgentCore runtime {0}", id);
return runtime;
}
AgentRuntime runtime = found.get();
storage.delete(key(region, id));
if (clientToken != null) {
deletedRuntimeTokens.record(tokenKey(region, clientToken));
}
runtime.setStatus(STATUS_DELETING);
LOG.infov("Deleted AgentCore runtime {0}", id);
return runtime;
}
private static String tokenKey(String region, String clientToken) {
@@ -347,38 +354,42 @@ public class BedrockAgentCoreControlService {
public AgentRuntimeEndpoint createEndpoint(String runtimeId, String name, String agentRuntimeVersion,
String description, String clientToken, String region) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
if (clientToken != null) {
Optional<AgentRuntimeEndpoint> replay = runtime.getEndpoints().stream()
.filter(e -> clientToken.equals(e.getClientToken()))
.findFirst();
if (replay.isPresent()) {
return replay.get();
synchronized (runtimeLock(region, runtimeId)) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
if (clientToken != null) {
Optional<AgentRuntimeEndpoint> replay = runtime.getEndpoints().stream()
.filter(e -> clientToken.equals(e.getClientToken()))
.findFirst();
if (replay.isPresent()) {
return replay.get();
}
}
if (name == null || !NAME_PATTERN.matcher(name).matches()) {
throw new AwsException("ValidationException",
"endpoint name must match [a-zA-Z][a-zA-Z0-9_]{0,47}", 400);
}
boolean exists = runtime.getEndpoints().stream().anyMatch(e -> name.equals(e.getName()));
if (exists) {
throw new AwsException("ConflictException",
"AgentCore runtime endpoint already exists: " + name, 409);
}
String version = agentRuntimeVersion != null ? agentRuntimeVersion
: String.valueOf(runtime.getLatestVersion());
requirePublishedVersion(runtime, version);
AgentRuntimeEndpoint endpoint = newEndpoint(name, version, description, Instant.now());
endpoint.setClientToken(clientToken);
runtime.getEndpoints().add(endpoint);
storage.put(key(region, runtimeId), runtime);
LOG.infov("Created AgentCore endpoint {0} on runtime {1}", name, runtimeId);
return endpoint;
}
if (name == null || !NAME_PATTERN.matcher(name).matches()) {
throw new AwsException("ValidationException",
"endpoint name must match [a-zA-Z][a-zA-Z0-9_]{0,47}", 400);
}
boolean exists = runtime.getEndpoints().stream().anyMatch(e -> name.equals(e.getName()));
if (exists) {
throw new AwsException("ConflictException",
"AgentCore runtime endpoint already exists: " + name, 409);
}
String version = agentRuntimeVersion != null ? agentRuntimeVersion
: String.valueOf(runtime.getLatestVersion());
requirePublishedVersion(runtime, version);
AgentRuntimeEndpoint endpoint = newEndpoint(name, version, description, Instant.now());
endpoint.setClientToken(clientToken);
runtime.getEndpoints().add(endpoint);
storage.put(key(region, runtimeId), runtime);
LOG.infov("Created AgentCore endpoint {0} on runtime {1}", name, runtimeId);
return endpoint;
}
public AgentRuntimeEndpoint getEndpoint(String runtimeId, String name, String region) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
return findEndpoint(runtime, name);
synchronized (runtimeLock(region, runtimeId)) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
return findEndpoint(runtime, name);
}
}
/** UpdateAgentRuntimeEndpoint on the API: a null version or description is left as it is. */
@@ -395,19 +406,21 @@ public class BedrockAgentCoreControlService {
*/
public AgentRuntimeEndpoint updateEndpoint(String runtimeId, String name, String agentRuntimeVersion,
String description, boolean replaceOmitted, String region) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
AgentRuntimeEndpoint endpoint = findEndpoint(runtime, name);
if (agentRuntimeVersion != null) {
requirePublishedVersion(runtime, agentRuntimeVersion);
endpoint.setTargetVersion(agentRuntimeVersion);
endpoint.setLiveVersion(agentRuntimeVersion);
synchronized (runtimeLock(region, runtimeId)) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
AgentRuntimeEndpoint endpoint = findEndpoint(runtime, name);
if (agentRuntimeVersion != null) {
requirePublishedVersion(runtime, agentRuntimeVersion);
endpoint.setTargetVersion(agentRuntimeVersion);
endpoint.setLiveVersion(agentRuntimeVersion);
}
if (description != null || replaceOmitted) {
endpoint.setDescription(description);
}
endpoint.setLastUpdatedAt(Instant.now());
storage.put(key(region, runtimeId), runtime);
return endpoint;
}
if (description != null || replaceOmitted) {
endpoint.setDescription(description);
}
endpoint.setLastUpdatedAt(Instant.now());
storage.put(key(region, runtimeId), runtime);
return endpoint;
}
/**
@@ -424,34 +437,38 @@ public class BedrockAgentCoreControlService {
}
public AgentRuntimeEndpoint deleteEndpoint(String runtimeId, String name, String clientToken, String region) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
Optional<AgentRuntimeEndpoint> found = runtime.getEndpoints().stream()
.filter(e -> e.getName().equals(name)).findFirst();
if (found.isEmpty()) {
if (clientToken != null && deletedEndpointTokens.contains(tokenKey(region, clientToken))) {
AgentRuntimeEndpoint marker = new AgentRuntimeEndpoint();
marker.setName(name);
marker.setStatus(STATUS_DELETING);
return marker;
synchronized (runtimeLock(region, runtimeId)) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
Optional<AgentRuntimeEndpoint> found = runtime.getEndpoints().stream()
.filter(e -> e.getName().equals(name)).findFirst();
if (found.isEmpty()) {
if (clientToken != null && deletedEndpointTokens.contains(tokenKey(region, clientToken))) {
AgentRuntimeEndpoint marker = new AgentRuntimeEndpoint();
marker.setName(name);
marker.setStatus(STATUS_DELETING);
return marker;
}
throw new AwsException("ResourceNotFoundException",
"AgentCore runtime endpoint not found: " + name, 404);
}
throw new AwsException("ResourceNotFoundException",
"AgentCore runtime endpoint not found: " + name, 404);
AgentRuntimeEndpoint endpoint = found.get();
runtime.getEndpoints().removeIf(e -> name.equals(e.getName()));
if (clientToken != null) {
deletedEndpointTokens.record(tokenKey(region, clientToken));
}
endpoint.setStatus(STATUS_DELETING);
storage.put(key(region, runtimeId), runtime);
return endpoint;
}
AgentRuntimeEndpoint endpoint = found.get();
runtime.getEndpoints().removeIf(e -> name.equals(e.getName()));
if (clientToken != null) {
deletedEndpointTokens.record(tokenKey(region, clientToken));
}
endpoint.setStatus(STATUS_DELETING);
storage.put(key(region, runtimeId), runtime);
return endpoint;
}
public PaginatedResult<AgentRuntimeEndpoint> listEndpoints(String runtimeId, Integer maxResults, String nextToken,
String region) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
return Pagination.paginate(runtime.getEndpoints(), AgentRuntimeEndpoint::getName, maxResults, nextToken,
MAX_PAGE, "ValidationException");
synchronized (runtimeLock(region, runtimeId)) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
return Pagination.paginate(runtime.getEndpoints(), AgentRuntimeEndpoint::getName, maxResults, nextToken,
MAX_PAGE, "ValidationException");
}
}
/** An endpoint together with the runtime that holds it. */
@@ -471,15 +488,26 @@ public class BedrockAgentCoreControlService {
String uuid = resource.substring("agentEndpoint/".length());
String prefix = keyPrefix(region);
for (AgentRuntime runtime : storage.scan(k -> k.startsWith(prefix))) {
for (AgentRuntimeEndpoint endpoint : runtime.getEndpoints()) {
if (uuid.equals(endpoint.getUuid())) {
return Optional.of(new EndpointLocation(runtime, endpoint));
synchronized (runtimeLock(region, runtime.getAgentRuntimeId())) {
Optional<AgentRuntime> current = storage.get(key(region, runtime.getAgentRuntimeId()));
if (current.isEmpty()) {
continue;
}
for (AgentRuntimeEndpoint endpoint : current.get().getEndpoints()) {
if (uuid.equals(endpoint.getUuid())) {
return Optional.of(new EndpointLocation(current.get(), endpoint));
}
}
}
}
return Optional.empty();
}
private Object runtimeLock(String region, String runtimeId) {
String lockKey = regionResolver.getAccountId() + ":" + key(region, runtimeId);
return runtimeLocks.lockFor(lockKey);
}
private AgentRuntimeEndpoint findEndpoint(AgentRuntime runtime, String name) {
return runtime.getEndpoints().stream()
.filter(e -> e.getName().equals(name))
@@ -0,0 +1,45 @@
package io.github.hectorvent.floci.core.common;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
class StripedLocksTest {
@Test
void equalKeysShareAMonitor() {
StripedLocks locks = new StripedLocks(256);
assertSame(locks.lockFor("runtime"), locks.lockFor(new String("runtime")));
}
@Test
void aSingleStripeReusesItsMonitorForEveryKey() {
StripedLocks locks = new StripedLocks(1);
assertSame(locks.lockFor("first"), locks.lockFor("second"));
}
@Test
void distinctStripesHaveDifferentMonitors() {
StripedLocks locks = new StripedLocks(4);
assertNotSame(locks.lockFor(0), locks.lockFor(1));
}
@Test
void negativeHashesSelectANonnegativeStripe() {
StripedLocks locks = new StripedLocks(3);
assertSame(locks.lockFor(Integer.MIN_VALUE), locks.lockFor(1));
assertSame(locks.lockFor(-1), locks.lockFor(2));
}
@Test
void requiresAPositiveStripeCount() {
assertThrows(IllegalArgumentException.class, () -> new StripedLocks(0));
assertThrows(IllegalArgumentException.class, () -> new StripedLocks(-1));
}
}
@@ -0,0 +1,138 @@
package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntime;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeEndpoint;
import io.github.hectorvent.floci.testing.ParkingStore;
import io.github.hectorvent.floci.testing.ThreadStates;
import org.junit.jupiter.api.Test;
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.AtomicReference;
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.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BedrockAgentCoreEndpointConcurrencyTest {
private static final String REGION = "us-east-1";
@Test
void concurrentClientTokenReplayWaitsForPublication() throws Exception {
Fixture fixture = new Fixture();
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<AgentRuntimeEndpoint> first = executor.submit(() -> fixture.create("token"));
try {
assertTrue(fixture.storage.awaitParked());
AtomicReference<Thread> secondThread = new AtomicReference<>();
Future<AgentRuntimeEndpoint> second = executor.submit(() -> {
secondThread.set(Thread.currentThread());
return fixture.create("token");
});
ThreadStates.awaitBlockedOrDone(secondThread, second);
assertNotNull(secondThread.get(), "the competing worker must start");
assertEquals(Thread.State.BLOCKED, secondThread.get().getState(),
"the competing worker must overlap the parked publication");
assertFalse(second.isDone(), "replay must await the original publication");
fixture.storage.release();
assertSame(first.get(5, TimeUnit.SECONDS), second.get(5, TimeUnit.SECONDS));
assertEquals(1, fixture.namedEndpointCount());
} finally {
fixture.storage.release();
}
}
}
@Test
void concurrentSameNameGetsConflictAfterPublication() throws Exception {
Fixture fixture = new Fixture();
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<AgentRuntimeEndpoint> first = executor.submit(() -> fixture.create(null));
try {
assertTrue(fixture.storage.awaitParked());
AtomicReference<Thread> secondThread = new AtomicReference<>();
Future<AwsException> second = executor.submit(() -> {
secondThread.set(Thread.currentThread());
return assertThrows(AwsException.class, () -> fixture.create(null));
});
ThreadStates.awaitBlockedOrDone(secondThread, second);
assertNotNull(secondThread.get(), "the competing worker must start");
assertEquals(Thread.State.BLOCKED, secondThread.get().getState(),
"the competing worker must overlap the parked publication");
assertFalse(second.isDone(), "the uniqueness decision must await publication");
fixture.storage.release();
first.get(5, TimeUnit.SECONDS);
assertEquals("ConflictException", second.get(5, TimeUnit.SECONDS).getErrorCode());
assertEquals(1, fixture.namedEndpointCount());
} finally {
fixture.storage.release();
}
}
}
@Test
void deletingRuntimeCannotBeUndoneByEndpointPublication() throws Exception {
Fixture fixture = new Fixture();
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
Future<AgentRuntimeEndpoint> first = executor.submit(() -> fixture.create(null));
try {
assertTrue(fixture.storage.awaitParked());
AtomicReference<Thread> deleteThread = new AtomicReference<>();
Future<AgentRuntime> deletion = executor.submit(() -> {
deleteThread.set(Thread.currentThread());
return fixture.service.deleteAgentRuntime(fixture.runtimeId, null, REGION);
});
ThreadStates.awaitBlockedOrDone(deleteThread, deletion);
assertNotNull(deleteThread.get(), "the competing worker must start");
assertEquals(Thread.State.BLOCKED, deleteThread.get().getState(),
"the competing worker must overlap the parked publication");
assertFalse(deletion.isDone(), "deletion must wait for the in-flight publication");
fixture.storage.release();
first.get(5, TimeUnit.SECONDS);
deletion.get(5, TimeUnit.SECONDS);
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
() -> fixture.service.getAgentRuntime(fixture.runtimeId, REGION)).getErrorCode());
} finally {
fixture.storage.release();
}
}
}
private static final class Fixture {
private final ParkingStore<AgentRuntime> storage = new ParkingStore<>();
private final BedrockAgentCoreControlService service = new BedrockAgentCoreControlService(
storage, new RegionResolver(REGION, "000000000000"));
private final String runtimeId;
private Fixture() {
ObjectMapper mapper = new ObjectMapper();
ObjectNode artifact = mapper.createObjectNode();
artifact.putObject("containerConfiguration").put("containerUri", "example.invalid/probe:1");
ObjectNode network = mapper.createObjectNode().put("networkMode", "PUBLIC");
runtimeId = service.createAgentRuntime("probe", artifact, network,
"arn:aws:iam::000000000000:role/probe", null, null,
null, null, null, REGION).getAgentRuntimeId();
storage.parkNextWrite();
}
private AgentRuntimeEndpoint create(String clientToken) {
return service.createEndpoint(runtimeId, "shared", null, null, clientToken, REGION);
}
private long namedEndpointCount() {
return service.getAgentRuntime(runtimeId, REGION).getEndpoints().stream()
.filter(endpoint -> "shared".equals(endpoint.getName())).count();
}
}
}