fix(emr-serverless): report a Spark job run's total and billed resource utilization (#9187)

GetJobRun gave an ended run no totalResourceUtilization or
billedResourceUtilization, which a cost or usage report reads.

- An ended Spark run gives both, reckoned from the workers it asks for:
  its driver and the executors it starts with, sized as the user
  guide's supported worker configurations size them. A worker has the
  vCPUs its cores ask for, and memory for its Spark memory and its 10%
  overhead, at least 384 MB, rounded up to the sizes its vCPUs allow.
  Unset, a worker has 4 vCPUs, 14G and 20G of disk, and a run starts 3
  executors, as the Spark job properties give them; spark-submit's
  sizing options set over --conf, as Spark takes them. Sizes are read
  as the executors' capacity reads them, which a size too large for a
  long no longer breaks.
- The total covers the time "from the time the job starts to execute,
  until the time the job terminates, rounded up to the nearest second";
  the billed figure includes "a 1-minute minimum usage for workers,
  plus additional storage over 20 GB per worker".
- Its driver's worker counts for the whole attempt. Executors with
  containers of their own count for the time each container ran, as
  they come and go with Spark's target; otherwise the executors it
  starts with count for the whole attempt.
- Each attempt gives its own, and one that never started used nothing.
  A Hive run gives none, its Tez tasks coming and going with its query.
  A Spark run stored before this gets its workers as it ends.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-22 04:00:01 -04:00
1 parent 8bc759420f
commit a1f3379198
13 files changed
+613 -21

No files matched your search

@@ -768,4 +768,19 @@ class EmrServerlessJobRunIntegrationTest {
givenReq().queryParam("shutdownGracePeriodInSeconds", 30).when().delete(run).then().statusCode(200);
givenReq().when().get(run).then().statusCode(200).body("jobRun.state", equalTo("CANCELLED"));
}
@Test
void anEndedSparkRunGivesItsTotalAndBilledResourceUtilization() {
String applicationId = createApplication("");
String jobRunId = startedRunId(applicationId, sparkRun(UUID.randomUUID().toString(), ""));
// Ended as it started, it used nothing, and is billed a minute of its workers and none of their disk.
givenReq().when().get("/applications/" + applicationId + "/jobruns/" + jobRunId).then().statusCode(200)
.body("jobRun.state", equalTo("SUCCESS"))
.body("jobRun.totalResourceUtilization.keySet()",
containsInAnyOrder("vCPUHour", "memoryGBHour", "storageGBHour"))
.body("jobRun.totalResourceUtilization.vCPUHour", equalTo(0.0f))
.body("jobRun.billedResourceUtilization.storageGBHour", equalTo(0.0f))
.body("jobRun.billedResourceUtilization.memoryGBHour", greaterThan(1.0f));
}
}
@@ -1142,6 +1142,64 @@ class EmrServerlessJobRunServiceTest {
assertEquals("SerializationException", refused.getErrorCode());
}
@Test
void anEndedSparkRunGivesItsResourceUtilizationAndAHiveRunNone() {
EmrServerlessJobRunService service = service(90);
StartJobRunRequest sized = request(null, null);
sized.getJobDriver().getSparkSubmit()
.setSparkSubmitParameters("--conf spark.dynamicAllocation.enabled=false"
+ " --conf spark.executor.instances=1 --conf spark.executor.cores=2");
String spark = service.startJobRun(applicationId, sized).getJobRunId();
String hiveApplication = applications.createApplication(applicationRequest("hive", "emr-7.5.0", "HIVE"))
.getApplicationId();
String hive = service.startJobRun(hiveApplication, hiveRequest("s3://bucket/queries/report.sql", null, null))
.getJobRunId();
assertNull(service.getJobRun(applicationId, spark, null).getTotalResourceUtilization(),
"a run still running has used nothing yet");
clock.advance(Duration.ofSeconds(90));
JobRun ended = service.getJobRun(applicationId, spark, null);
// A default driver, 4 vCPUs, 16 GB and 20 GB, and one executor of 2 vCPUs, whose 14G and 1.4G of overhead
// round up to a 2-vCPU worker's largest 16 GB, for 90 seconds.
assertEquals("SUCCESS", ended.getState());
assertEquals(Map.of("vCPUHour", 6 * 90 / 3600.0, "memoryGBHour", 32 * 90 / 3600.0,
"storageGBHour", 40 * 90 / 3600.0), ended.getTotalResourceUtilization());
assertEquals(Map.of("vCPUHour", 6 * 90 / 3600.0, "memoryGBHour", 32 * 90 / 3600.0, "storageGBHour", 0.0),
ended.getBilledResourceUtilization());
JobRun hiveRun = service.getJobRun(hiveApplication, hive, null);
assertEquals("SUCCESS", hiveRun.getState());
assertNull(hiveRun.getTotalResourceUtilization());
}
@Test
void aRunWhoseExecutorsHadContainersCountsTheTimeEachRanAndOneStoredWithoutWorkersGetsThemAsItEnds() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String measured = service.startJobRun(applicationId, request(null, null)).getJobRunId();
runner.whileRunning = () -> clock.advance(Duration.ofSeconds(100));
runner.executorLifetimes = List.of(Duration.ofSeconds(30), Duration.ofMillis(90_500));
runNext();
// The driver for its attempt, a little over 100 seconds as the test's clock ticks, rounded up; the executors
// for 121 seconds between them, each billed a minute at least.
JobRun ended = service.getJobRun(applicationId, measured, null);
long driver = Math.ceilDiv(Duration.between(ended.getStartedAt(), ended.getEndedAt()).toMillis(), 1000);
assertEquals(101, driver);
assertEquals((4 * driver + 4 * 121) / 3600.0, ended.getTotalResourceUtilization().get("vCPUHour"));
assertEquals((4 * driver + 4 * 151) / 3600.0, ended.getBilledResourceUtilization().get("vCPUHour"));
EmrServerlessJobRunService immediate = service(90);
String stored = immediate.startJobRun(applicationId, request(null, null)).getJobRunId();
JobRunRecord record = store.get(stored).orElseThrow();
record.setWorkers(null);
store.put(stored, record);
clock.advance(Duration.ofSeconds(90));
assertEquals(16 * 90 / 3600.0,
immediate.getJobRun(applicationId, stored, null).getTotalResourceUtilization().get("vCPUHour"));
}
@Test
void eachAttemptIsLaunchedWhileItsApplicationCannotBeDeleted() {
FakeRunner runner = new FakeRunner();
@@ -1853,6 +1911,9 @@ class EmrServerlessJobRunServiceTest {
Outcome outcome = Outcome.exitedWith(0);
Runnable whileRunning = () -> { };
Runnable whileTimingOut = () -> { };
// How long its executors' workers ran, told as the run ends, as the Docker runner tells it for executors with
// containers of their own; null for none told.
List<Duration> executorLifetimes;
// The manifest digest each custom image resolves to, told before the driver starts as the Docker runner does,
// and the executors' where their pull resolves another, as a push between the two pulls gives.
final Map<String, String> digests = new HashMap<>();
@@ -1882,6 +1943,9 @@ class EmrServerlessJobRunServiceTest {
progress.timedOut();
whileTimingOut.run();
}
if (executorLifetimes != null) {
progress.executorsRan(executorLifetimes);
}
return stopped.contains(job.runId()) ? Outcome.halted() : outcome;
}
@@ -0,0 +1,132 @@
package io.floci.aws.services.emrserverless;
import io.floci.aws.services.emrserverless.model.JobRun;
import io.floci.aws.services.emrserverless.model.RunWorkers;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class EmrServerlessWorkersTest {
private static final Instant STARTED = Instant.parse("2026-11-22T00:00:00Z");
private static List<Integer> sizes(RunWorkers workers) {
return List.of(workers.getDriverVcpu(), workers.getDriverMemoryGb(), workers.getDriverDiskGb(),
workers.getExecutorVcpu(), workers.getExecutorMemoryGb(), workers.getExecutorDiskGb(),
workers.getExecutors());
}
private static JobRun ran(long millis) {
JobRun run = new JobRun();
run.setStartedAt(STARTED);
run.setEndedAt(STARTED.plusMillis(millis));
return run;
}
@Test
void anUnsetRunHasADefaultDriverAndThreeDefaultExecutors() {
// 14G of Spark memory and its 10% overhead come to 15.4 GB, which a 4-vCPU worker rounds up to 16.
assertEquals(List.of(4, 16, 20, 4, 16, 20, 3), sizes(EmrServerlessWorkers.plan(Map.of(), null)));
}
@Test
void eachWorkerIsSizedToTheMemoryItsVcpusAllow() {
RunWorkers workers = EmrServerlessWorkers.plan(Map.of(
"spark.driver.cores", "2", "spark.driver.memory", "4g",
"spark.executor.cores", "8", "spark.executor.memory", "20480m",
"spark.emr-serverless.executor.disk", "50G"), null);
// 4 GB and 384 MB of overhead round up to 5 GB; 20 GB and 2 GB to 24 GB, in 8 vCPUs' 4 GB steps.
assertEquals(List.of(2, 5, 20, 8, 24, 50, 3), sizes(workers));
assertEquals(List.of(4, 12, 20, 32, 120, 200, 3), sizes(EmrServerlessWorkers.plan(Map.of(
"spark.driver.cores", "3", "spark.driver.memory", "8g", "spark.driver.memoryOverhead", "4096",
"spark.executor.cores", "32", "spark.emr-serverless.executor.disk", "500G"), null)));
}
@Test
void theExecutorsARunStartsWithFollowItsDynamicAllocation() {
assertEquals(5, EmrServerlessWorkers.plan(Map.of("spark.dynamicAllocation.enabled", "false",
"spark.executor.instances", "5"), null).getExecutors());
assertEquals(6, EmrServerlessWorkers.plan(Map.of("spark.executor.instances", "6"), null).getExecutors());
assertEquals(2, EmrServerlessWorkers.plan(Map.of("spark.dynamicAllocation.initialExecutors", "1",
"spark.dynamicAllocation.minExecutors", "2"), null).getExecutors());
assertEquals(1, EmrServerlessWorkers.plan(Map.of("spark.dynamicAllocation.maxExecutors", "1"), null)
.getExecutors());
}
@Test
void anAttemptUsesItsWorkersForItsSecondsAndIsBilledAMinuteAtLeastAndStorageOver20Gb() {
RunWorkers defaults = EmrServerlessWorkers.plan(Map.of(), null);
JobRun ninetySeconds = ran(90_000);
EmrServerlessWorkers.account(ninetySeconds, defaults, null);
// 16 vCPUs, 64 GB and 80 GB of disk for 90 seconds; none of the disk is over 20 GB a worker.
assertEquals(Map.of("vCPUHour", 0.4, "memoryGBHour", 1.6, "storageGBHour", 2.0),
ninetySeconds.getTotalResourceUtilization());
assertEquals(Map.of("vCPUHour", 0.4, "memoryGBHour", 1.6, "storageGBHour", 0.0),
ninetySeconds.getBilledResourceUtilization());
RunWorkers bigDisks = EmrServerlessWorkers.plan(Map.of("spark.emr-serverless.executor.disk", "50g"), null);
JobRun brief = ran(35_400);
EmrServerlessWorkers.account(brief, bigDisks, null);
// Rounded up to 36 seconds; billed for 60, and for 30 GB of each executor's disk.
assertEquals(16 * 36 / 3600.0, brief.getTotalResourceUtilization().get("vCPUHour"));
assertEquals(170 * 36 / 3600.0, brief.getTotalResourceUtilization().get("storageGBHour"));
assertEquals(16 * 60 / 3600.0, brief.getBilledResourceUtilization().get("vCPUHour"));
assertEquals(90 * 60 / 3600.0, brief.getBilledResourceUtilization().get("storageGBHour"));
}
@Test
void anAttemptThatNeverStartedUsedNothingAndOneWithoutWorkersGivesNone() {
JobRun neverStarted = new JobRun();
neverStarted.setEndedAt(STARTED);
EmrServerlessWorkers.account(neverStarted, EmrServerlessWorkers.plan(Map.of(), null), null);
assertEquals(Map.of("vCPUHour", 0.0, "memoryGBHour", 0.0, "storageGBHour", 0.0),
neverStarted.getBilledResourceUtilization());
JobRun hive = ran(60_000);
EmrServerlessWorkers.account(hive, null, null);
assertNull(hive.getTotalResourceUtilization());
assertNull(hive.getBilledResourceUtilization());
}
@Test
void sparkSubmitsSizingOptionsWinOverTheSettingsTheySet() {
// The properties as spark-defaults and --conf give them, which the options then set over.
RunWorkers workers = EmrServerlessWorkers.plan(Map.of("spark.executor.memory", "4g",
"spark.executor.cores", "2", "spark.dynamicAllocation.enabled", "false"),
"--driver-cores 8 --driver-memory=20g --executor-memory 8g --num-executors=5 --class example.Main");
assertEquals(List.of(8, 24, 20, 2, 9, 20, 5), sizes(workers));
}
@Test
void settingsTooLargeForTheirTypesGiveTheLargestWorkersAndNoNegativeUse() {
RunWorkers huge = EmrServerlessWorkers.plan(Map.of("spark.dynamicAllocation.enabled", "false",
"spark.executor.instances", String.valueOf(Integer.MAX_VALUE),
"spark.executor.memory", "99999999999999999999g", "spark.driver.memory", "9007199254740993p"), null);
JobRun run = ran(3_600_000);
EmrServerlessWorkers.account(run, huge, null);
// The memory that does not read as a size takes the default; the executors are what was asked for.
assertEquals(List.of(4, 16, 20, 4, 16, 20, Integer.MAX_VALUE), sizes(huge));
assertEquals(4.0 + 4.0 * Integer.MAX_VALUE, run.getTotalResourceUtilization().get("vCPUHour"));
}
@Test
void executorsWhoseContainersCameAndWentAreCountedForTheTimeEachRan() {
RunWorkers defaults = EmrServerlessWorkers.plan(Map.of(), null);
JobRun run = ran(100_000);
EmrServerlessWorkers.account(run, defaults, List.of(30_000L, 90_500L));
// The driver for 100 seconds and the executors for 121 between them; billed a minute at least each.
assertEquals((4 * 100 + 4 * 121) / 3600.0, run.getTotalResourceUtilization().get("vCPUHour"));
assertEquals((4 * 100 + 4 * 151) / 3600.0, run.getBilledResourceUtilization().get("vCPUHour"));
}
}
@@ -287,6 +287,24 @@ class SparkExecutorsTest {
assertEquals(Amount.NONE, capacity.held());
}
@Test
void eachExecutorsWorkerIsTimedFromItsStartToItsEnd() {
driver.settings(IMAGE_DEFAULTS);
driver.target(2);
SparkExecutors executors = new SparkExecutors(TWO, driver, containers, capacity, nanos::get);
executors.follow();
driver.target(1);
driver.coresUsed(Map.of("10.0.0.1", 4, "10.0.0.2", 0));
advance(SparkExecutors.LOOK_INTERVAL);
executors.follow();
advance(Duration.ofSeconds(10));
executors.removeAll();
assertEquals(List.of(SparkExecutors.LOOK_INTERVAL, SparkExecutors.LOOK_INTERVAL.plusSeconds(10)),
executors.lifetimes());
}
@Test
void sizesReadAsSparkReadsThem() {
assertEquals(14 * 1024, SparkExecutors.mebibytes("14G", 0));
@@ -294,6 +312,9 @@ class SparkExecutorsTest {
assertEquals(512, SparkExecutors.mebibytes("512m", 0));
assertEquals(2048, SparkExecutors.mebibytes("2048", 0));
assertEquals(7, SparkExecutors.mebibytes("not a size", 7));
// Too large for a long, as written or once in MiB.
assertEquals(7, SparkExecutors.mebibytes("99999999999999999999g", 7));
assertEquals(7, SparkExecutors.mebibytes("9007199254740993p", 7));
assertEquals(20, SparkExecutors.gigabytes(null));
assertEquals(200, SparkExecutors.gigabytes("200G"));
}