Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add four aws batch tables (#116963)

Tom Owers9ff733f1c460
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index dcae3bf83848..6d980a3e40db 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -1080,14 +1080,14 @@ Note: The wiki.awin.com URLs in the source config are dead - they now 302 to the
## AWS Batch — gaps
-Today (4): `compute_environments`, `job_definitions`, `job_queues`, `jobs`
+Today (8): `compute_environments`, `consumable_resources`, `job_children`, `job_definitions`, `job_queues`, `jobs`, `scheduling_policies`, `service_jobs`
Diffed against: <https://raw.githubusercontent.com/boto/botocore/develop/botocore/data/batch/2016-08-10/service-2.json>
-- [ ] `Scheduling policies (ListSchedulingPolicies, POST /v1/listschedulingpolicies; DescribeSchedulingPolicies, POST /v1/describeschedulingpolicies)` — resolves schedulingPolicyArn in job queues and explains fair-share allocation (high)
-- [ ] `Consumable resources (ListConsumableResources, POST /v1/listconsumableresources; DescribeConsumableResource, POST /v1/describeconsumableresource)` — resolves resource references in jobs and measures total, available, and in-use capacity (high)
-- [ ] `Array children and parallel job nodes (ListJobs, POST /v1/listjobs, arrayJobId or multiNodeJobId)` — exposes child failures, runtime, and resource use hidden behind parent jobs (high)
-- [ ] `Service jobs (ListServiceJobs, POST /v1/listservicejobs; DescribeServiceJob, POST /v1/describeservicejob)` — tracks service job status and execution detail missing from standard Batch job imports (medium)
+- [x] `Scheduling policies (ListSchedulingPolicies, POST /v1/listschedulingpolicies; DescribeSchedulingPolicies, POST /v1/describeschedulingpolicies)` — resolves schedulingPolicyArn in job queues and explains fair-share allocation (high)
+- [x] `Consumable resources (ListConsumableResources, POST /v1/listconsumableresources; DescribeConsumableResource, POST /v1/describeconsumableresource)` — resolves resource references in jobs and measures total, available, and in-use capacity (high)
+- [x] `Array children and parallel job nodes (ListJobs, POST /v1/listjobs, arrayJobId or multiNodeJobId)` — exposes child failures, runtime, and resource use hidden behind parent jobs (high) — the `job_children` table describes children by their derived IDs (`parentId:index`, `parentId#node`) with DescribeJobs, because ListJobs ignores its all-status filter for children and would need one walk per status
+- [x] `Service jobs (ListServiceJobs, POST /v1/listservicejobs; DescribeServiceJob, POST /v1/describeservicejob)` — tracks service job status and execution detail missing from standard Batch job imports (medium) — the `service_jobs` table uses the ListServiceJobs summaries; DescribeServiceJob takes one request per job, so it is not called
- [ ] `Job queue snapshots (GetJobQueueSnapshot, POST /v1/getjobqueuesnapshot)` — measures queued demand, dispatch order, and capacity utilization over time (medium)
Note: Parsed read operations, request fields, and response shapes in the official botocore service model. AWS reads mainly use POST; existing jobs already call DescribeJobs, but child discovery needs arrayJobId or multiNodeJobId. Scheduling policies and consumable resources need detail reads, and queue snapshots need retained timestamps. Excluded writes and tag plumbing.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/aws_batch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/aws_batch.py
index 3655d2433045..af1314b1c41b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/aws_batch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/aws_batch.py
@@ -1,7 +1,7 @@
import re
import json
import datetime as dt
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from dataclasses import replace
from typing import Any
@@ -30,6 +30,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
_REGION = re.compile(r"(?:af|ap|ca|cn|eu|il|me|mx|sa|us)-(?:gov-)?[a-z]+-\d+")
+# A name wildcard includes every status without seven separate status walks.
+ALL_JOBS_FILTER = [{"name": "JOB_NAME", "values": ["*"]}]
+QUEUED_ENDPOINTS = ("jobs", "service_jobs")
TRANSPORT_RETRY = BoundedRetry(
total=3,
@@ -46,6 +49,10 @@ class AwsBatchResumeConfig:
queue_arns: list[str] | None = None
queue_index: int = 0
complete: bool = False
+ child_prefixes: list[str] | None = None
+ child_counts: list[int] | None = None
+ parent_index: int = 0
+ child_offset: int = 0
class AwsBatchError(Exception):
@@ -149,7 +156,15 @@ def next_page_token(body: dict[str, Any], previous_token: str | None) -> str | N
return token
-def discover_queues(client: AwsBatchClient, manager: ResumableSourceManager[AwsBatchResumeConfig]) -> list[str]:
+def is_service_queue(queue: dict[str, Any]) -> bool:
+ return bool(queue.get("serviceEnvironmentOrder"))
+
+
+def discover_queues(
+ client: AwsBatchClient,
+ manager: ResumableSourceManager[AwsBatchResumeConfig],
+ include: Callable[[dict[str, Any]], bool] = lambda queue: True,
+) -> list[str]:
queues: list[str] = []
token = None
while True:
@@ -157,13 +172,132 @@ def discover_queues(client: AwsBatchClient, manager: ResumableSourceManager[AwsB
if token:
payload["nextToken"] = token
body = client.request("DescribeJobQueues", payload)
- queues.extend(queue["jobQueueArn"] for queue in body.get("jobQueues", []))
+ queues.extend(queue["jobQueueArn"] for queue in body.get("jobQueues", []) if include(queue))
token = next_page_token(body, token)
manager.safe_point()
if token is None:
return list(dict.fromkeys(queues))
+def first_queue(client: AwsBatchClient, include: Callable[[dict[str, Any]], bool]) -> str | None:
+ token = None
+ while True:
+ payload: dict[str, Any] = {"maxResults": PAGE_SIZE}
+ if token:
+ payload["nextToken"] = token
+ body = client.request("DescribeJobQueues", payload)
+ for queue in body.get("jobQueues", []):
+ if include(queue):
+ return queue["jobQueueArn"]
+ token = next_page_token(body, token)
+ if token is None:
+ return None
+
+
+def child_prefix(summary: dict[str, Any]) -> tuple[str, int] | None:
+ job_id = summary["jobId"]
+ # Child IDs are derived from the parent ID because ListJobs ignores the status filter for children.
+ size = (summary.get("arrayProperties") or {}).get("size")
+ if size and ":" not in job_id:
+ return f"{job_id}:", size
+ nodes = (summary.get("nodeProperties") or {}).get("numNodes")
+ if nodes and "#" not in job_id:
+ return f"{job_id}#", nodes
+ return None
+
+
+def get_child_rows(
+ client: AwsBatchClient,
+ region: str,
+ manager: ResumableSourceManager[AwsBatchResumeConfig],
+ state: AwsBatchResumeConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ if state.queue_arns is None:
+ state = replace(
+ state, queue_arns=discover_queues(client, manager, include=lambda queue: not is_service_queue(queue))
+ )
+ queues = state.queue_arns or []
+ while state.queue_index < len(queues):
+ rows: list[dict[str, Any]] = []
+ prefixes, counts = state.child_prefixes, state.child_counts or []
+ if prefixes is None:
+ payload: dict[str, Any] = {
+ "maxResults": PAGE_SIZE,
+ "jobQueue": queues[state.queue_index],
+ "filters": ALL_JOBS_FILTER,
+ }
+ if state.next_token:
+ payload["nextToken"] = state.next_token
+ body = client.request("ListJobs", payload)
+ token = next_page_token(body, state.next_token)
+ parents = [parent for parent in map(child_prefix, body.get("jobSummaryList", [])) if parent]
+ state = replace(
+ state,
+ next_token=token,
+ child_prefixes=[prefix for prefix, _ in parents],
+ child_counts=[count for _, count in parents],
+ parent_index=0,
+ child_offset=0,
+ )
+ elif state.parent_index >= len(prefixes):
+ last_page = state.next_token is None
+ state = replace(
+ state,
+ queue_index=state.queue_index + last_page,
+ child_prefixes=None,
+ child_counts=None,
+ )
+ else:
+ prefix, count = prefixes[state.parent_index], counts[state.parent_index]
+ end = min(state.child_offset + PAGE_SIZE, count)
+ job_ids = [f"{prefix}{index}" for index in range(state.child_offset, end)]
+ jobs = client.request("DescribeJobs", {"jobs": job_ids}).get("jobs", [])
+ rows = [{**normalize_row(job, region), "parent_job_id": prefix[:-1]} for job in jobs]
+ state = (
+ replace(state, parent_index=state.parent_index + 1, child_offset=0)
+ if end >= count
+ else replace(state, child_offset=end)
+ )
+ manager.save_state(state)
+ if rows:
+ yield rows
+ manager.safe_point()
+ manager.save_state(replace(state, complete=True))
+ manager.safe_point()
+
+
+def describe_page(
+ client: AwsBatchClient,
+ endpoint: str,
+ items: list[dict[str, Any]],
+ manager: ResumableSourceManager[AwsBatchResumeConfig] | None = None,
+) -> list[dict[str, Any]]:
+ if endpoint == "jobs":
+ job_ids = [item["jobId"] for item in items]
+ described: list[dict[str, Any]] = []
+ for offset in range(0, len(job_ids), PAGE_SIZE):
+ described.extend(
+ client.request("DescribeJobs", {"jobs": job_ids[offset : offset + PAGE_SIZE]}).get("jobs", [])
+ )
+ return described
+ if endpoint == "scheduling_policies":
+ arns = [item["arn"] for item in items]
+ if not arns:
+ return []
+ return client.request("DescribeSchedulingPolicies", {"arns": arns}).get("schedulingPolicies", [])
+ if endpoint == "consumable_resources":
+ described = []
+ for item in items:
+ described.append(
+ client.request("DescribeConsumableResource", {"consumableResource": item["consumableResourceArn"]})
+ )
+ # The staged cursor still points at this page, so a hand-off here reads the page again.
+ if manager is not None:
+ manager.safe_point()
+ return described
+ return items
+
+
def get_rows(
config: AwsBatchSourceConfig,
endpoint: str,
@@ -177,36 +311,39 @@ def get_rows(
return
client = AwsBatchClient(config, api_version)
try:
- if endpoint == "jobs" and state.queue_arns is None:
- state = replace(state, queue_arns=discover_queues(client, manager))
+ if endpoint == "job_children":
+ yield from get_child_rows(client, config.region, manager, state)
+ return
+ queued = endpoint in QUEUED_ENDPOINTS
+ if queued and state.queue_arns is None:
+ include = is_service_queue if endpoint == "service_jobs" else lambda queue: True
+ state = replace(state, queue_arns=discover_queues(client, manager, include))
while not state.complete:
payload: dict[str, Any] = {"maxResults": PAGE_SIZE}
- if endpoint == "jobs":
+ queue = None
+ if queued:
queues = state.queue_arns or []
if state.queue_index >= len(queues):
manager.save_state(replace(state, complete=True))
manager.safe_point()
return
- payload["jobQueue"] = queues[state.queue_index]
- # A name wildcard includes every status without seven separate status walks.
- payload["filters"] = [{"name": "JOB_NAME", "values": ["*"]}]
+ queue = queues[state.queue_index]
+ payload["jobQueue"] = queue
+ payload["filters"] = ALL_JOBS_FILTER
if state.next_token:
payload["nextToken"] = state.next_token
body = client.request(endpoint_config.operation, payload)
items = body.get(endpoint_config.result_key, [])
token = next_page_token(body, state.next_token)
- if endpoint == "jobs":
- job_ids = [item["jobId"] for item in items]
- items = []
- for offset in range(0, len(job_ids), PAGE_SIZE):
- items.extend(
- client.request("DescribeJobs", {"jobs": job_ids[offset : offset + PAGE_SIZE]}).get("jobs", [])
- )
+ items = describe_page(client, endpoint, items, manager)
+ if queued:
queue_index = state.queue_index + (token is None)
state = replace(state, next_token=token, queue_index=queue_index, complete=queue_index >= len(queues))
else:
state = replace(state, next_token=token, complete=token is None)
rows = [normalize_row(item, config.region) for item in items]
+ if endpoint == "service_jobs":
+ rows = [{**row, "job_queue": queue} for row in rows]
manager.save_state(state)
if rows:
yield rows
@@ -237,19 +374,30 @@ def validate_credentials(
return False, str(error)
try:
operation = AWS_BATCH_ENDPOINTS[schema_name].operation if schema_name else "DescribeJobQueues"
- if schema_name == "jobs":
- queues = client.request("DescribeJobQueues", {"maxResults": 1}).get("jobQueues", [])
- if queues:
+ if schema_name in ("jobs", "job_children"):
+ if schema_name == "jobs":
+ queues = client.request("DescribeJobQueues", {"maxResults": 1}).get("jobQueues", [])
+ queue = queues[0]["jobQueueArn"] if queues else None
+ else:
+ queue = first_queue(client, lambda queue: not is_service_queue(queue))
+ if queue:
jobs = client.request(
"ListJobs",
{
- "jobQueue": queues[0]["jobQueueArn"],
+ "jobQueue": queue,
"maxResults": 1,
- "filters": [{"name": "JOB_NAME", "values": ["*"]}],
+ "filters": ALL_JOBS_FILTER,
},
).get("jobSummaryList", [])
if jobs:
client.request("DescribeJobs", {"jobs": [jobs[0]["jobId"]]})
+ elif schema_name == "service_jobs":
+ queue = first_queue(client, is_service_queue)
+ if queue:
+ client.request(operation, {"jobQueue": queue, "maxResults": 1, "filters": ALL_JOBS_FILTER})
+ elif schema_name in ("scheduling_policies", "consumable_resources"):
+ items = client.request(operation, {"maxResults": 1}).get(AWS_BATCH_ENDPOINTS[schema_name].result_key, [])
+ describe_page(client, schema_name, items[:1])
else:
client.request(operation, {"maxResults": 1})
except AwsBatchError as error:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/canonical_descriptions.py
index 84a634748ee1..8b49baa66356 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/canonical_descriptions.py
@@ -64,4 +64,68 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"region": "AWS region selected for this source.",
},
},
+ "job_children": {
+ "description": "Child jobs of AWS Batch array jobs and nodes of multi-node parallel jobs.",
+ "docs_url": "https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeJobs.html",
+ "columns": {
+ "job_arn": "ARN that identifies the child job or node.",
+ "job_id": "Child job ID, formed from the parent job ID and the array index or node index.",
+ "parent_job_id": "ID of the array job or multi-node parallel job that owns this child.",
+ "status": "Current state of the child job, such as RUNNING, SUCCEEDED, or FAILED.",
+ "status_reason": "Reason for the current child job state.",
+ "array_properties": "Array index of the child job. Null for multi-node parallel nodes.",
+ "node_details": "Node index and main-node flag of a multi-node parallel node.",
+ "created_at": "Time when the child job was created, converted from milliseconds to a UTC timestamp.",
+ "started_at": "Time when the child job started, converted to UTC. Null if it has not started.",
+ "stopped_at": "Time when the child job stopped, converted to UTC. Null if it has not stopped.",
+ "attempts": "Execution attempts, including timing, container details, and failure reasons.",
+ "container": "Container configuration, resource requirements, and exit details for the child job.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+ "service_jobs": {
+ "description": "AWS Batch service jobs, such as SageMaker training jobs, from service job queues.",
+ "docs_url": "https://docs.aws.amazon.com/batch/latest/APIReference/API_ListServiceJobs.html",
+ "columns": {
+ "job_arn": "ARN that identifies the service job.",
+ "job_id": "Identifier assigned to the service job by AWS Batch.",
+ "job_name": "Name supplied when the service job was submitted.",
+ "job_queue": "ARN of the queue that holds the service job.",
+ "service_job_type": "Type of service job, such as SAGEMAKER_TRAINING.",
+ "share_identifier": "Fair-share identifier of the service job.",
+ "status": "Current state of the service job, such as RUNNING, SUCCEEDED, or FAILED.",
+ "status_reason": "Reason for the current service job state.",
+ "latest_attempt": "Details of the most recent attempt, including the service resource ID.",
+ "created_at": "Time when the service job was created, converted from milliseconds to a UTC timestamp.",
+ "started_at": "Time when the service job started, converted to UTC. Null if it has not started.",
+ "stopped_at": "Time when the service job stopped, converted to UTC. Null if it has not stopped.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+ "scheduling_policies": {
+ "description": "AWS Batch scheduling policies that control fair-share scheduling for job queues.",
+ "docs_url": "https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeSchedulingPolicies.html",
+ "columns": {
+ "arn": "ARN of the scheduling policy. Job queues reference it in scheduling_policy_arn.",
+ "name": "Name of the scheduling policy.",
+ "fairshare_policy": "Fair-share settings, including share decay, compute reservation, and share weights.",
+ "tags": "Tags applied to the scheduling policy.",
+ "region": "AWS region selected for this source.",
+ },
+ },
+ "consumable_resources": {
+ "description": "AWS Batch consumable resources that limit how many jobs can use a shared resource at once.",
+ "docs_url": "https://docs.aws.amazon.com/batch/latest/APIReference/API_DescribeConsumableResource.html",
+ "columns": {
+ "consumable_resource_arn": "ARN of the consumable resource.",
+ "consumable_resource_name": "Name of the consumable resource.",
+ "resource_type": "Whether the resource is REPLENISHABLE or NON_REPLENISHABLE.",
+ "total_quantity": "Total amount of the resource.",
+ "in_use_quantity": "Amount of the resource that running jobs use.",
+ "available_quantity": "Amount of the resource that is available to jobs.",
+ "created_at": "Time when the consumable resource was created, converted to UTC.",
+ "tags": "Tags applied to the consumable resource.",
+ "region": "AWS region selected for this source.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/settings.py
index ab211483d487..40c518e6395e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/settings.py
@@ -19,7 +19,19 @@ AWS_BATCH_ENDPOINTS: dict[str, AwsBatchEndpoint] = {
operation="ListJobs",
result_key="jobSummaryList",
primary_key="job_arn",
- description="Jobs in each queue, with their status, attempts, and execution details. Array children are not expanded.",
+ description="Jobs in each queue, with their status, attempts, and execution details. Array children and nodes are in the job_children table.",
+ ),
+ "job_children": AwsBatchEndpoint(
+ operation="DescribeJobs",
+ result_key="jobs",
+ primary_key="job_arn",
+ description="Child jobs of array jobs and nodes of multi-node parallel jobs, with their execution details.",
+ ),
+ "service_jobs": AwsBatchEndpoint(
+ operation="ListServiceJobs",
+ result_key="jobSummaryList",
+ primary_key="job_arn",
+ description="Service jobs, such as SageMaker training jobs, in each service job queue.",
),
"job_queues": AwsBatchEndpoint(
operation="DescribeJobQueues",
@@ -39,6 +51,18 @@ AWS_BATCH_ENDPOINTS: dict[str, AwsBatchEndpoint] = {
primary_key="job_definition_arn",
description="Job definition revisions, including their resource requirements and container settings.",
),
+ "scheduling_policies": AwsBatchEndpoint(
+ operation="ListSchedulingPolicies",
+ result_key="schedulingPolicies",
+ primary_key="arn",
+ description="Scheduling policies and their fair-share settings.",
+ ),
+ "consumable_resources": AwsBatchEndpoint(
+ operation="ListConsumableResources",
+ result_key="consumableResources",
+ primary_key="consumable_resource_arn",
+ description="Consumable resources with their total, in-use, and available quantities.",
+ ),
}
ENDPOINTS = tuple(AWS_BATCH_ENDPOINTS)
ENDPOINT_DESCRIPTIONS = {name: endpoint.description for name, endpoint in AWS_BATCH_ENDPOINTS.items()}
@@ -48,7 +72,9 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
PERMISSION_MESSAGE = (
"AWS denied access to Batch. Grant batch:DescribeJobQueues, batch:ListJobs, batch:DescribeJobs, "
- "batch:DescribeComputeEnvironments, and batch:DescribeJobDefinitions for the tables you select."
+ "batch:ListServiceJobs, batch:DescribeComputeEnvironments, batch:DescribeJobDefinitions, "
+ "batch:ListSchedulingPolicies, batch:DescribeSchedulingPolicies, batch:ListConsumableResources, "
+ "and batch:DescribeConsumableResource for the tables you select."
)
CREDENTIAL_MESSAGE = "AWS rejected the credentials. Check the access key ID, secret access key, and session token."
NON_RETRYABLE_ERRORS: dict[str, str] = {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/source.py
index 8d0d24541ef4..f645a07da343 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/source.py
@@ -97,12 +97,15 @@ class AwsBatchSource(ResumableSource[AwsBatchSourceConfig, AwsBatchResumeConfig]
label="AWS Batch",
caption=(
"Sync AWS Batch jobs and resources from one region. "
- "Grant `batch:DescribeJobQueues`, `batch:ListJobs`, and `batch:DescribeJobs` to read jobs. "
+ "Grant `batch:DescribeJobQueues`, `batch:ListJobs`, and `batch:DescribeJobs` to read jobs and job children. "
+ "Grant `batch:DescribeJobQueues` and `batch:ListServiceJobs` to read service jobs. "
"Grant `batch:DescribeComputeEnvironments` and `batch:DescribeJobDefinitions` to read those tables. "
+ "Grant `batch:ListSchedulingPolicies` and `batch:DescribeSchedulingPolicies` to read scheduling policies. "
+ "Grant `batch:ListConsumableResources` and `batch:DescribeConsumableResource` to read consumable resources. "
"Enter an access key ID and secret access key. Add a session token for temporary credentials. "
"All tables use full refresh so later job status changes remain visible. "
- "The jobs table includes jobs that AWS still retains in existing queues. "
- "Array children and individual nodes are not expanded."
+ "The jobs and service jobs tables include jobs that AWS still retains in existing queues. "
+ "The job children table includes the children of array jobs and the nodes of multi-node parallel jobs."
),
iconPath="/static/services/aws_batch.png",
releaseStatus=ReleaseStatus.ALPHA,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/tests/test_aws_batch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/tests/test_aws_batch.py
index c9725d6ef92a..bc0d8f1db824 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/tests/test_aws_batch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aws_batch/tests/test_aws_batch.py
@@ -233,6 +233,157 @@ def test_jobs_discover_queues_and_hydrate_all_statuses(config: AwsBatchSourceCon
assert result.response is not None and result.response.sort_mode is None
+def test_job_children_describe_array_children_and_nodes(config: AwsBatchSourceConfig) -> None:
+ def send(request: RecordedRequest) -> ScriptedResponse:
+ payload = request.json()
+ if request.path.endswith("describejobqueues"):
+ return ScriptedResponse(
+ json={
+ "jobQueues": [
+ {"jobQueueArn": "arn:queue:ecs", "computeEnvironmentOrder": [{"order": 1}]},
+ {"jobQueueArn": "arn:queue:service", "serviceEnvironmentOrder": [{"order": 1}]},
+ ]
+ }
+ )
+ if request.path.endswith("listjobs"):
+ assert payload["jobQueue"] == "arn:queue:ecs"
+ assert payload["filters"] == [{"name": "JOB_NAME", "values": ["*"]}]
+ if "nextToken" not in payload:
+ return ScriptedResponse(
+ json={
+ "jobSummaryList": [{"jobId": "plain"}, {"jobId": "array", "arrayProperties": {"size": 101}}],
+ "nextToken": "page-two",
+ }
+ )
+ return ScriptedResponse(json={"jobSummaryList": [{"jobId": "mnp", "nodeProperties": {"numNodes": 2}}]})
+ return ScriptedResponse(
+ json={"jobs": [{"jobArn": f"arn:job/{job_id}", "createdAt": 1735689600000} for job_id in payload["jobs"]]}
+ )
+
+ result = driver(config).run("job_children", send)
+ assert result.raised is None
+ described = [request.json()["jobs"] for request in result.requests if request.path.endswith("describejobs")]
+ assert described == [[f"array:{i}" for i in range(100)], ["array:100"], ["mnp#0", "mnp#1"]]
+ rows = result.rows
+ assert len(rows) == 103
+ assert {row["parent_job_id"] for row in rows} == {"array", "mnp"}
+ assert rows[-1] == {
+ "job_arn": "arn:job/mnp#1",
+ "created_at": dt.datetime(2025, 1, 1, tzinfo=dt.UTC),
+ "region": "eu-west-1",
+ "parent_job_id": "mnp",
+ }
+ assert result.saved_states[-1].complete
+
+
+def test_job_children_resume_mid_parent_and_finish_queue(config: AwsBatchSourceConfig) -> None:
+ result = driver(config).run(
+ "job_children",
+ [ScriptedResponse(json={"jobs": []}), ScriptedResponse(json={"jobSummaryList": []})],
+ resume_state=AwsBatchResumeConfig(
+ queue_arns=["arn:queue"],
+ next_token="page-two",
+ child_prefixes=["done:", "array:"],
+ child_counts=[5, 150],
+ parent_index=1,
+ child_offset=100,
+ ),
+ )
+ assert result.raised is None
+ assert result.requests[0].json() == {"jobs": [f"array:{i}" for i in range(100, 150)]}
+ assert result.requests[1].json()["nextToken"] == "page-two"
+ assert len(result.requests) == 2
+ assert result.saved_states[-1].complete
+
+
+def test_service_jobs_read_only_service_queues(config: AwsBatchSourceConfig) -> None:
+ def send(request: RecordedRequest) -> ScriptedResponse:
+ if request.path.endswith("describejobqueues"):
+ return ScriptedResponse(
+ json={
+ "jobQueues": [
+ {"jobQueueArn": "arn:queue:ecs", "computeEnvironmentOrder": [{"order": 1}]},
+ {"jobQueueArn": "arn:queue:service", "serviceEnvironmentOrder": [{"order": 1}]},
+ ]
+ }
+ )
+ payload = request.json()
+ assert payload["jobQueue"] == "arn:queue:service"
+ assert payload["filters"] == [{"name": "JOB_NAME", "values": ["*"]}]
+ return ScriptedResponse(
+ json={"jobSummaryList": [{"jobArn": "arn:service-job", "status": "FAILED", "stoppedAt": 1735689600000}]}
+ )
+
+ result = driver(config).run("service_jobs", send)
+ assert result.raised is None
+ assert [request.path for request in result.requests] == ["/v1/describejobqueues", "/v1/listservicejobs"]
+ assert result.rows == [
+ {
+ "job_arn": "arn:service-job",
+ "status": "FAILED",
+ "stopped_at": dt.datetime(2025, 1, 1, tzinfo=dt.UTC),
+ "region": "eu-west-1",
+ "job_queue": "arn:queue:service",
+ }
+ ]
+ assert result.saved_states[-1].complete
+
+
+ "endpoint,list_key,item_key,detail_path,expected_details",
+ [
+ (
+ "scheduling_policies",
+ "schedulingPolicies",
+ "arn",
+ "/v1/describeschedulingpolicies",
+ [{"arns": ["arn:one"]}, {"arns": ["arn:two", "arn:three"]}],
+ ),
+ (
+ "consumable_resources",
+ "consumableResources",
+ "consumableResourceArn",
+ "/v1/describeconsumableresource",
+ [{"consumableResource": arn} for arn in ("arn:one", "arn:two", "arn:three")],
+ ),
+ ],
+)
+def test_listed_resources_are_described_page_by_page(
+ config: AwsBatchSourceConfig,
+ endpoint: str,
+ list_key: str,
+ item_key: str,
+ detail_path: str,
+ expected_details: list[dict[str, Any]],
+) -> None:
+ def send(request: RecordedRequest) -> ScriptedResponse:
+ payload = request.json()
+ if request.path == detail_path:
+ if endpoint == "scheduling_policies":
+ return ScriptedResponse(
+ json={"schedulingPolicies": [{"arn": arn, "fairsharePolicy": {}} for arn in payload["arns"]]}
+ )
+ return ScriptedResponse(
+ json={"consumableResourceArn": payload["consumableResource"], "availableQuantity": 3, "createdAt": 0}
+ )
+ if "nextToken" not in payload:
+ return ScriptedResponse(json={list_key: [{item_key: "arn:one"}], "nextToken": "next"})
+ return ScriptedResponse(json={list_key: [{item_key: "arn:two"}, {item_key: "arn:three"}]})
+
+ result = driver(config).run(endpoint, send)
+ assert result.raised is None
+ assert [request.json() for request in result.requests if request.path == detail_path] == expected_details
+ rows = result.rows
+ assert result.response is not None and result.response.primary_keys is not None
+ assert [row[result.response.primary_keys[0]] for row in rows] == ["arn:one", "arn:two", "arn:three"]
+ if endpoint == "scheduling_policies":
+ assert rows[0]["fairshare_policy"] == {}
+ else:
+ assert rows[0]["available_quantity"] == 3
+ assert rows[0]["created_at"] is None
+ assert result.saved_states[-1].complete
+
+
@pytest.mark.parametrize("job_count", [0, 100, 101])
def test_job_descriptions_respect_batch_limit(config: AwsBatchSourceConfig, job_count: int) -> None:
result = driver(config).run(
@@ -399,19 +550,54 @@ def test_connection_error_is_actionable(config: AwsBatchSourceConfig, exception:
assert {request.path for request in network.requests_log} == {"/v1/describejobqueues"}
[email protected]("schema_name", [None, "job_queues", "compute_environments", "job_definitions", "jobs"])
-def test_validation_probes_only_required_operations(config: AwsBatchSourceConfig, schema_name: str | None) -> None:
- with scripted_network(
- [
- ScriptedResponse(json={"jobQueues": [{"jobQueueArn": "arn:queue"}]}),
- ScriptedResponse(json={"jobSummaryList": [{"jobId": "job-one"}]}),
- ScriptedResponse(json={"jobs": []}),
- ]
- ) as network:
+ "schema_name,paths",
+ [
+ (None, ["describejobqueues"]),
+ ("job_queues", ["describejobqueues"]),
+ ("compute_environments", ["describecomputeenvironments"]),
+ ("job_definitions", ["describejobdefinitions"]),
+ ("jobs", ["describejobqueues", "listjobs", "describejobs"]),
+ ("job_children", ["describejobqueues", "describejobqueues", "listjobs", "describejobs"]),
+ ("service_jobs", ["describejobqueues", "listservicejobs"]),
+ ("scheduling_policies", ["listschedulingpolicies", "describeschedulingpolicies"]),
+ ("consumable_resources", ["listconsumableresources", "describeconsumableresource"]),
+ ],
+)
+def test_validation_probes_only_required_operations(
+ config: AwsBatchSourceConfig, schema_name: str | None, paths: list[str]
+) -> None:
+ def send(request: RecordedRequest) -> ScriptedResponse:
+ if request.path.endswith("describejobqueues"):
+ if "nextToken" not in request.json():
+ return ScriptedResponse(
+ json={
+ "jobQueues": [{"jobQueueArn": "arn:service-queue", "serviceEnvironmentOrder": [{"order": 1}]}],
+ "nextToken": "queues-next",
+ }
+ )
+ return ScriptedResponse(
+ json={"jobQueues": [{"jobQueueArn": "arn:queue", "computeEnvironmentOrder": [{"order": 1}]}]}
+ )
+ return ScriptedResponse(
+ json={
+ "jobSummaryList": [{"jobId": "job-one"}],
+ "jobs": [],
+ "schedulingPolicies": [{"arn": "arn:policy"}],
+ "consumableResources": [{"consumableResourceArn": "arn:resource"}],
+ }
+ )
+
+ with scripted_network(send) as network:
assert validate_credentials(config, schema_name) == (True, None)
- assert len(network.requests_log) == (3 if schema_name == "jobs" else 1)
- assert network.requests_log[0].json() == {"maxResults": 1}
- if schema_name == "jobs":
+ assert [request.path.removeprefix("/v1/") for request in network.requests_log] == paths
+ probed_queues = {"job_children": "arn:queue", "service_jobs": "arn:service-queue"}
+ if schema_name in probed_queues:
+ assert (
+ network.requests_log[-1 if schema_name == "service_jobs" else -2].json()["jobQueue"]
+ == probed_queues[schema_name]
+ )
+ if schema_name in ("jobs", "job_children"):
assert network.requests_log[-1].json() == {"jobs": ["job-one"]}