diff --git a/docs/services/emr-containers.md b/docs/services/emr-containers.md index 8cbbc47b54..da9d4415d4 100644 --- a/docs/services/emr-containers.md +++ b/docs/services/emr-containers.md @@ -59,7 +59,7 @@ does not refuse a container provider its EKS has no cluster for, nor a second vi namespace: AWS documents no error for either. A `securityConfigurationId` must name a security configuration of the account. `schedulerConfiguration` is stored and returned, an empty object clears it on `UpdateVirtualCluster`, and `DescribeVirtualCluster` adds a `schedulerStatus` with the current queued -and running job run counts; the limits are not enforced on `StartJobRun`. A virtual cluster created on an EKS +and running job run counts. A virtual cluster created on an EKS cluster whose `authenticationMode` admits access entries (`API` or `API_AND_CONFIG_MAP`) is EKS access entry integrated, as the guide's cluster access management setup has it, and `ListVirtualClusters`' `eksAccessEntryIntegrated` keeps the ones that are, or are not; one on a cluster Floci's EKS does not have is @@ -76,6 +76,16 @@ gives it. Otherwise the run is `COMPLETED` at once, or `RUNNING` for `CANCELLED`. A run with a `retryPolicyConfiguration` reports `retryPolicyExecution` with one attempt. The release label is not checked against EMR on EKS's releases. +**Concurrent job limits.** `StartJobRun` applies the virtual cluster's limits, as the development guide's +"Concurrent job limits for virtual clusters" describes them. At most `maxConcurrentJobRuns` runs are +`RUNNING` at once, 1000 when it is not set. A run beyond that waits `PENDING` in the queue, and when a +running slot frees up, the run first in the queue starts. Once `maxInQueueJobRuns` runs wait, `StartJobRun` +refuses another with `ValidationException`. A run still queued 30 minutes after it was submitted is `FAILED`, +as the guide's "buffered jobs fail after 30 minutes if no slot frees up" has it. A higher limit, a cleared +one, or a cancelled run starts queued runs at once. The guide gives neither message, so the refusal's and +the timed-out run's `stateDetails` are Floci's wording. A run takes its slot only while it is `RUNNING`, so +with the default `job-run-duration-seconds` of `0` no run waits. + **Job templates.** `StartJobRun` with a `jobTemplateId` takes `executionRoleArn`, `releaseLabel`, `jobDriver` and `configurationOverrides` from the template where the request leaves them out, and the template's `jobTags` under the request's `tags`, which together keep the 50-tag limit. Every `${name}` in the template is replaced by the diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java index ee10769ed8..69e0f44488 100644 --- a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java +++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java @@ -28,16 +28,24 @@ import jakarta.inject.Inject; import java.math.BigDecimal; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Deque; import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.PriorityQueue; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Predicate; @@ -49,7 +57,8 @@ import java.util.regex.Pattern; * and security configurations, as control-plane records. A job run follows the job run states * without running Spark on Kubernetes: it completes as soon as it is submitted, or after * {@code floci.services.emrcontainers.job-run-duration-seconds}, and fails as AWS documents when - * Floci's EKS has no cluster of the virtual cluster's name. + * Floci's EKS has no cluster of the virtual cluster's name. A virtual cluster's concurrent job + * limits hold a run beyond its running limit in a queue, and refuse one beyond its queue depth. * *

Every resource is stored as the JSON AWS answers for it, under its ARN. Members whose name * starts with {@code _} are Floci's own and never leave the service. @@ -70,16 +79,23 @@ public class EmrContainersService implements Resettable, StoredResourceArns { private static final String CLIENT_TOKEN = "_clientToken"; private static final String DUE_AT = "_dueAt"; + // Where a job run held in its virtual cluster's queue stands in it, the first to start lowest. + private static final String QUEUE_POSITION = "_queuePosition"; private static final String ACCESS_ENTRY_INTEGRATED = "_eksAccessEntryIntegrated"; private static final Set ACCESS_ENTRY_MODES = Set.of("API", "API_AND_CONFIG_MAP"); private static final String RUNNING = "RUNNING"; + private static final String PENDING = "PENDING"; private static final String TERMINATED = "TERMINATED"; private static final String COMPLETED = "COMPLETED"; private static final String CANCELLED = "CANCELLED"; private static final String FAILED = "FAILED"; private static final String ACTIVE = "ACTIVE"; private static final Set FINISHED_JOB_RUN_STATES = Set.of(COMPLETED, CANCELLED, FAILED); - private static final Set QUEUED_JOB_RUN_STATES = Set.of("PENDING", "SUBMITTED"); + private static final Set QUEUED_JOB_RUN_STATES = Set.of(PENDING, "SUBMITTED"); + // The development guide's concurrent job limits: "By default, the per-virtual-cluster concurrency limit is set + // to 1000 concurrent job runs", and "buffered jobs fail after 30 minutes if no slot frees up". + private static final int DEFAULT_MAX_CONCURRENT_JOB_RUNS = 1000; + private static final Duration QUEUE_TIMEOUT = Duration.ofMinutes(30); private static final Set FINISHED_ENDPOINT_STATES = Set.of(TERMINATED, "TERMINATED_WITH_ERRORS"); private static final String TOKEN_CREDENTIAL = "TOKEN"; private static final int DEFAULT_SESSION_SECONDS = 15 * 60; @@ -224,6 +240,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns { EmrContainersRequestShapes.check("UpdateVirtualCluster", request); ObjectNode cluster = virtualCluster(id).orElseThrow(() -> notFound(virtualClusterMissing(id))); requireState(cluster, RUNNING, "VirtualCluster", "update"); + // The runs stand as the limits they had until now left them; the new ones hold from now on. + settledRuns(cluster); ObjectNode updated = cluster.deepCopy(); JsonNode scheduler = request.get("schedulerConfiguration"); if (scheduler != null && !scheduler.isNull()) { @@ -235,6 +253,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns { } } virtualClusters.put(updated.get("arn").textValue(), updated); + // A higher running limit, or none, starts queued runs now. + settledRuns(updated); return wrap("virtualCluster", withSchedulerStatus(updated)); } @@ -313,6 +333,17 @@ public class EmrContainersService implements Resettable, StoredResourceArns { run.set("retryPolicyExecution", object("currentAttemptCount", 1)); } + // Concurrent job limits are "enforced at StartJobRun, before any pods are created": a run beyond the + // running limit waits in the queue, and "once the queue is full, StartJobRun rejects further submissions". + List runs = settledRuns(cluster); + boolean slotFree = count(runs, RUNNING::equals) < maxConcurrentJobRuns(cluster); + long queued = count(runs, QUEUED_JOB_RUN_STATES::contains); + JsonNode maxInQueue = cluster.path("schedulerConfiguration").path("maxInQueueJobRuns"); + if (!slotFree && maxInQueue.isIntegralNumber() && queued >= maxInQueue.longValue()) { + // The guide gives ValidationException, not its message; the wording is Floci's. + throw invalid("Virtual cluster " + virtualClusterId + " has " + queued + " job runs in its queue, its " + + "maxInQueueJobRuns, and accepts no more until one of them starts."); + } String eksCluster = cluster.path("containerProvider").path("id").textValue(); if (eksService.findAuthenticationCluster(regionResolver.getAccountId(), regionResolver.getRegion(), eksCluster) .isEmpty()) { @@ -320,11 +351,13 @@ public class EmrContainersService implements Resettable, StoredResourceArns { finish(run, FAILED, now); run.put("stateDetails", "Cluster " + eksCluster + " does not exist."); run.put("failureReason", "CLUSTER_UNAVAILABLE"); - } else if (jobRunDurationSeconds <= 0) { - finish(run, COMPLETED, now); + } else if (!slotFree) { + // Held before it is submitted to the virtual cluster: "waiting to be submitted to the virtual cluster". + run.put("state", PENDING); + run.put(QUEUE_POSITION, runs.stream().mapToLong(held -> held.path(QUEUE_POSITION).asLong()).max() + .orElse(0) + 1); } else { - run.put("state", RUNNING); - run.put(DUE_AT, now.plusSeconds(jobRunDurationSeconds).toEpochMilli()); + start(run, now); } jobRuns.put(arn, run); return pick(run, "id", "name", "arn", "virtualClusterId"); @@ -340,9 +373,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns { ObjectNode shape = query.shape().put("virtualClusterId", virtualClusterId); putText(shape, "name", name); EmrContainersRequestShapes.check("ListJobRuns", shape); - String prefix = arn(VIRTUAL_CLUSTERS + virtualClusterId + JOB_RUNS); - List matching = jobRuns.scan(key -> key.startsWith(prefix)).stream() - .map(this::advance) + List matching = settledRuns(virtualClusterId).stream() .filter(query::matches) .filter(run -> name == null || name.equals(run.path("name").textValue())) .toList(); @@ -359,6 +390,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns { ObjectNode cancelled = run.deepCopy(); finish(cancelled, CANCELLED, now()); jobRuns.put(cancelled.get("arn").textValue(), cancelled); + // A running slot it frees goes to the queue's first run now. + settledRuns(virtualClusterId); return object("id", id).put("virtualClusterId", virtualClusterId); } @@ -725,7 +758,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns { } private Optional jobRun(String virtualClusterId, String id) { - return jobRuns.get(arn(VIRTUAL_CLUSTERS + virtualClusterId + JOB_RUNS + id)).map(this::advance); + settledRuns(virtualClusterId); + return jobRuns.get(arn(VIRTUAL_CLUSTERS + virtualClusterId + JOB_RUNS + id)); } private Optional endpoint(String virtualClusterId, String id) { @@ -763,8 +797,8 @@ public class EmrContainersService implements Resettable, StoredResourceArns { } Matcher nested = NESTED_ARN.matcher(resource); if (nested.matches() && "jobruns".equals(nested.group(2))) { - ObjectNode run = jobRuns.get(resourceArn).map(this::advance) - .orElseThrow(() -> resourceMissing(resourceArn)); + settledRuns(nested.group(1)); + ObjectNode run = jobRuns.get(resourceArn).orElseThrow(() -> resourceMissing(resourceArn)); return new Taggable(jobRuns, run, !FINISHED_JOB_RUN_STATES.contains(run.path("state").textValue())); } if (nested.matches()) { @@ -847,25 +881,106 @@ public class EmrContainersService implements Resettable, StoredResourceArns { // ── States ─────────────────────────────────────────────────────────────────── - /** Completes a RUNNING job run whose duration has passed, and stores the change. */ - private ObjectNode advance(ObjectNode run) { - if (!RUNNING.equals(run.path("state").textValue()) || !run.has(DUE_AT)) { - return run; + private List settledRuns(String virtualClusterId) { + return virtualCluster(virtualClusterId).map(this::settledRuns).orElseGet(List::of); + } + + /** + * The virtual cluster's job runs as they stand now, each change stored. They are replayed in the order things + * happened: a RUNNING run completes once its duration has passed, and the running slot it frees goes at that + * moment to the run first in the queue, "As running slots free up, queued job runs start automatically"; a run + * still queued 30 minutes after it was submitted fails. A slot free now, once the limit is raised or a run is + * cancelled, goes to the queue now. + */ + private List settledRuns(ObjectNode cluster) { + String prefix = cluster.get("arn").textValue() + JOB_RUNS; + List runs = jobRuns.scan(key -> key.startsWith(prefix)).stream() + .map(ObjectNode::deepCopy) + .toList(); + // The running runs by when they complete, and the queue in order: a run's DUE_AT never changes in there. + PriorityQueue running = new PriorityQueue<>(Comparator.comparing(EmrContainersService::dueAt)); + runs.stream() + .filter(run -> RUNNING.equals(run.path("state").textValue()) && run.has(DUE_AT)) + .forEach(running::add); + Deque queue = new ArrayDeque<>(runs.stream() + .filter(run -> PENDING.equals(run.path("state").textValue()) && run.has(QUEUE_POSITION)) + .sorted(Comparator.comparingLong(run -> run.get(QUEUE_POSITION).longValue())) + .toList()); + int limit = maxConcurrentJobRuns(cluster); + Instant now = now(); + // By identity: a node's equality is its content, which changes here. + Set changed = Collections.newSetFromMap(new IdentityHashMap<>()); + while (true) { + ObjectNode ending = running.peek(); + Instant endsAt = ending != null && !dueAt(ending).isAfter(now) ? dueAt(ending) : null; + ObjectNode first = queue.peekFirst(); + Instant timesOutAt = first != null ? Instant.parse(first.get("createdAt").textValue()).plus(QUEUE_TIMEOUT) + : null; + if (timesOutAt != null && !timesOutAt.isAfter(now) && (endsAt == null || timesOutAt.isBefore(endsAt))) { + queue.pollFirst(); + finish(first, FAILED, timesOutAt); + // No source gives AWS's stateDetails for it; the wording is Floci's. + first.put("stateDetails", "Job run waited " + QUEUE_TIMEOUT.toMinutes() + " minutes in the queue " + + "of virtual cluster " + cluster.get("id").textValue() + " without starting."); + changed.add(first); + } else if (endsAt != null) { + running.poll(); + finish(ending, COMPLETED, endsAt); + changed.add(ending); + startQueued(running, queue, limit, endsAt, changed); + } else { + break; + } } - Instant dueAt = Instant.ofEpochMilli(run.get(DUE_AT).longValue()); - if (now().isBefore(dueAt)) { - return run; + startQueued(running, queue, limit, now, changed); + // In one write: a persistent store rewrites its file on each. + if (!changed.isEmpty()) { + Map writes = new LinkedHashMap<>(); + changed.forEach(run -> writes.put(run.get("arn").textValue(), run)); + jobRuns.putAll(writes); } - ObjectNode completed = run.deepCopy(); - finish(completed, COMPLETED, dueAt); - jobRuns.put(completed.get("arn").textValue(), completed); - return completed; + return runs; + } + + // Starts the queue's first runs at the moment {@code at} while the running limit leaves a slot. + private void startQueued(PriorityQueue running, Deque queue, int limit, Instant at, + Set changed) { + while (running.size() < limit && !queue.isEmpty()) { + ObjectNode run = queue.pollFirst(); + start(run, at); + changed.add(run); + if (run.has(DUE_AT)) { + running.add(run); + } + } + } + + // A run starts: RUNNING for the configured duration, or completed at once without one. + private void start(ObjectNode run, Instant at) { + run.remove(QUEUE_POSITION); + if (jobRunDurationSeconds <= 0) { + finish(run, COMPLETED, at); + } else { + run.put("state", RUNNING); + run.put(DUE_AT, at.plusSeconds(jobRunDurationSeconds).toEpochMilli()); + } + } + + private static Instant dueAt(ObjectNode run) { + return Instant.ofEpochMilli(run.get(DUE_AT).longValue()); + } + + // How many of the virtual cluster's runs may be RUNNING at once: its maxConcurrentJobRuns, or AWS's default. + private static int maxConcurrentJobRuns(ObjectNode cluster) { + JsonNode limit = cluster.path("schedulerConfiguration").path("maxConcurrentJobRuns"); + return limit.isIntegralNumber() ? limit.intValue() : DEFAULT_MAX_CONCURRENT_JOB_RUNS; } private void finish(ObjectNode run, String state, Instant at) { run.put("state", state); run.put("finishedAt", timestamp(at)); run.remove(DUE_AT); + run.remove(QUEUE_POSITION); } /** @@ -885,8 +1000,7 @@ public class EmrContainersService implements Resettable, StoredResourceArns { if (scheduler == null || scheduler.isEmpty()) { return cluster; } - String prefix = cluster.get("arn").textValue() + JOB_RUNS; - List runs = jobRuns.scan(key -> key.startsWith(prefix)).stream().map(this::advance).toList(); + List runs = settledRuns(cluster); ObjectNode status = mapper.createObjectNode(); status.put("currentInQueueJobRuns", count(runs, QUEUED_JOB_RUN_STATES::contains)); status.put("currentConcurrentJobRuns", count(runs, RUNNING::equals)); diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersIntegrationTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersIntegrationTest.java index 92c2aa5e39..e8fcbea94d 100644 --- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersIntegrationTest.java @@ -142,6 +142,31 @@ class EmrContainersIntegrationTest { .body("__type", containsString("ValidationException")); } + /** A run takes a running slot only while it is RUNNING, so runs that complete at once never wait in the queue. */ + @Test + void runsThatCompleteAtOnceNeverWaitBehindTheRunningLimit() { + String clusterId = emr().body(""" + {"name": "limited", "clientToken": "%s", + "containerProvider": {"type": "EKS", "id": "%s", "info": {"eksInfo": {"namespace": "spark"}}}, + "schedulerConfiguration": {"maxConcurrentJobRuns": 1, "maxInQueueJobRuns": 100}} + """.formatted(UUID.randomUUID(), eksCluster())) + .post("/virtualclusters") + .then().statusCode(200) + .extract().path("id"); + String first = startJobRun(clusterId); + String second = startJobRun(clusterId); + + for (String runId : new String[] {first, second}) { + emr().get("/virtualclusters/" + clusterId + "/jobruns/" + runId) + .then().statusCode(200) + .body("jobRun.state", equalTo("COMPLETED")); + } + emr().get("/virtualclusters/" + clusterId) + .then().statusCode(200) + .body("virtualCluster.schedulerStatus.currentConcurrentJobRuns", equalTo(0)) + .body("virtualCluster.schedulerStatus.currentInQueueJobRuns", equalTo(0)); + } + @Test void jobRunOnAMissingVirtualClusterAnswersAwsDocumentedError() { emr().body(""" diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java index b8dd9645b8..e3a6c07a03 100644 --- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java @@ -281,6 +281,150 @@ class EmrContainersServiceTest { assertFalse(cleared.has("schedulerStatus")); } + // A virtual cluster on EKS_CLUSTER with these concurrent job limits. + private String limitedVirtualCluster(EmrContainersService service, String schedulerConfiguration) { + return service.createVirtualCluster(json(""" + {"name": "vc", "clientToken": "%s", "schedulerConfiguration": %s, + "containerProvider": {"type": "EKS", "id": "%s", "info": {"eksInfo": {"namespace": "spark"}}}} + """.formatted(UUID.randomUUID(), schedulerConfiguration, EKS_CLUSTER))).get("id").textValue(); + } + + private JsonNode schedulerStatus(EmrContainersService service, String clusterId) { + return service.describeVirtualCluster(clusterId).at("/virtualCluster/schedulerStatus"); + } + + @Test + void aRunBeyondTheRunningLimitWaitsPendingAndStartsWhenASlotFreesUp() { + EmrContainersService service = service(600); + String clusterId = limitedVirtualCluster(service, "{\"maxConcurrentJobRuns\": 1}"); + String first = startJobRun(service, clusterId).get("id").textValue(); + clock.advance(Duration.ofSeconds(1)); + String second = startJobRun(service, clusterId).get("id").textValue(); + + assertEquals("RUNNING", jobRun(service, clusterId, first).get("state").textValue()); + assertEquals("PENDING", jobRun(service, clusterId, second).get("state").textValue()); + assertEquals(1, schedulerStatus(service, clusterId).get("currentConcurrentJobRuns").intValue()); + assertEquals(1, schedulerStatus(service, clusterId).get("currentInQueueJobRuns").intValue()); + + // Read only after both have ended: the second started the moment the first's slot freed up. + clock.advance(Duration.ofHours(1)); + assertEquals("2026-01-01T00:10:00Z", jobRun(service, clusterId, first).get("finishedAt").textValue()); + JsonNode run = jobRun(service, clusterId, second); + assertEquals("COMPLETED", run.get("state").textValue()); + assertEquals("2026-01-01T00:20:00Z", run.get("finishedAt").textValue()); + assertFalse(run.has("_queuePosition"), "Floci's own members never leave the service"); + assertEquals(0, schedulerStatus(service, clusterId).get("currentInQueueJobRuns").intValue()); + } + + @Test + void aFullQueueRefusesTheRunAndARunQueuedThirtyMinutesFails() { + EmrContainersService service = service(3600); + String clusterId = limitedVirtualCluster(service, "{\"maxConcurrentJobRuns\": 1, \"maxInQueueJobRuns\": 100}"); + startJobRun(service, clusterId); + List queued = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + queued.add(startJobRun(service, clusterId).get("id").textValue()); + } + + AwsException full = assertThrows(AwsException.class, () -> startJobRun(service, clusterId)); + assertEquals("ValidationException", full.getErrorCode()); + assertEquals(400, full.getHttpStatus()); + assertEquals(100, schedulerStatus(service, clusterId).get("currentInQueueJobRuns").intValue()); + + clock.advance(Duration.ofMinutes(30)); + JsonNode timedOut = jobRun(service, clusterId, queued.get(0)); + assertEquals("FAILED", timedOut.get("state").textValue()); + assertEquals("2026-01-01T00:30:00Z", timedOut.get("finishedAt").textValue()); + assertTrue(timedOut.get("stateDetails").textValue().contains("30 minutes"), timedOut.toString()); + assertEquals(0, schedulerStatus(service, clusterId).get("currentInQueueJobRuns").intValue()); + String next = startJobRun(service, clusterId).get("id").textValue(); + assertEquals("PENDING", jobRun(service, clusterId, next).get("state").textValue(), + "the first run still holds the one running slot"); + } + + @Test + void aCancelledRunOrARaisedLimitStartsTheQueuedRunsInOrderAtOnce() { + EmrContainersService service = service(600); + String clusterId = limitedVirtualCluster(service, "{\"maxConcurrentJobRuns\": 1}"); + String first = startJobRun(service, clusterId).get("id").textValue(); + String second = startJobRun(service, clusterId).get("id").textValue(); + String third = startJobRun(service, clusterId).get("id").textValue(); + + clock.advance(Duration.ofMinutes(1)); + service.cancelJobRun(clusterId, first); + assertEquals("RUNNING", jobRun(service, clusterId, second).get("state").textValue()); + assertEquals("PENDING", jobRun(service, clusterId, third).get("state").textValue()); + + clock.advance(Duration.ofMinutes(1)); + JsonNode raised = service.updateVirtualCluster(clusterId, + json("{\"clientToken\": \"u\", \"schedulerConfiguration\": {\"maxConcurrentJobRuns\": 2}}")); + assertEquals(2, raised.at("/virtualCluster/schedulerStatus/currentConcurrentJobRuns").intValue()); + clock.advance(Duration.ofHours(1)); + assertEquals("2026-01-01T00:11:00Z", jobRun(service, clusterId, second).get("finishedAt").textValue()); + assertEquals("2026-01-01T00:12:00Z", jobRun(service, clusterId, third).get("finishedAt").textValue()); + } + + @Test + void withoutLimitsAThousandRunsRunAtOnce() { + EmrContainersService service = service(600); + String clusterId = virtualCluster(service, EKS_CLUSTER); + for (int i = 0; i < 1000; i++) { + startJobRun(service, clusterId); + } + String beyond = startJobRun(service, clusterId).get("id").textValue(); + + assertEquals("PENDING", jobRun(service, clusterId, beyond).get("state").textValue()); + clock.advance(Duration.ofHours(1)); + assertEquals("2026-01-01T00:20:00Z", jobRun(service, clusterId, beyond).get("finishedAt").textValue()); + } + + @Test + void runsThatCompleteAndStartTogetherAreStoredInOneWrite() { + CountingStorage runs = new CountingStorage(); + EmrContainersService service = service(600, REGION, List.of(AccountAwareStorageBackend.inMemory(ACCOUNT_ID), + new AccountAwareStorageBackend<>(runs, null, ACCOUNT_ID), + AccountAwareStorageBackend.inMemory(ACCOUNT_ID), AccountAwareStorageBackend.inMemory(ACCOUNT_ID), + AccountAwareStorageBackend.inMemory(ACCOUNT_ID))); + String clusterId = limitedVirtualCluster(service, "{\"maxConcurrentJobRuns\": 5}"); + for (int i = 0; i < 10; i++) { + startJobRun(service, clusterId); + } + + clock.advance(Duration.ofHours(1)); + int before = runs.writes; + service.describeVirtualCluster(clusterId); + assertEquals(before + 1, runs.writes, "five runs completed, five started and completed"); + List states = service.listJobRuns(clusterId, ListQuery.of(null, null, null, null, null), null) + .findValuesAsText("state"); + assertEquals(List.of("COMPLETED"), states.stream().distinct().toList()); + assertEquals(before + 1, runs.writes, "a read with nothing to settle writes nothing"); + } + + // An in-memory store that counts its writes, a batch as one. + private static final class CountingStorage extends InMemoryStorage { + private int writes; + private boolean inBatch; + + @Override + public synchronized void put(String key, ObjectNode value) { + if (!inBatch) { + writes++; + } + super.put(key, value); + } + + @Override + public synchronized void putAll(Map entries) { + writes++; + inBatch = true; + try { + super.putAll(entries); + } finally { + inBatch = false; + } + } + } + /** * IAM's lookup reads the tags of the virtual cluster, job run or job template the ARN names, as the tag calls * leave them, and nothing for another account's, another Region's, an unknown or another service's ARN.