This is an automated email from the ASF dual-hosted git repository.
o-nikolas pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 37d8acbd5a7 Persist batchoperator deferrable xcom links (#64745)
37d8acbd5a7 is described below
commit 37d8acbd5a738977de904ccafeff8c38081e6a5f
Author: Krishna Kakatur <[email protected]>
AuthorDate: Wed Jun 24 15:57:09 2026 -0700
Persist batchoperator deferrable xcom links (#64745)
When BatchOperator runs with deferrable=True, operator links
(job definition, job queue, CloudWatch logs) were not being
persisted as XCom values, causing ERROR-level logs when the UI
tried to render them.
This change:
- Extracts link persistence logic into _persist_links() method
- Calls _persist_links() from execute_complete() for deferrable tasks
- Refactors monitor_job() to use the same method (DRY principle)
---
.../providers/amazon/aws/operators/batch.py | 133 ++++++++++++-----
.../tests/unit/amazon/aws/operators/test_batch.py | 161 ++++++++++++++++++---
scripts/ci/prek/known_airflow_exceptions.txt | 2 +-
3 files changed, 241 insertions(+), 55 deletions(-)
diff --git
a/providers/amazon/src/airflow/providers/amazon/aws/operators/batch.py
b/providers/amazon/src/airflow/providers/amazon/aws/operators/batch.py
index 26c0f2cabea..2162ebad056 100644
--- a/providers/amazon/src/airflow/providers/amazon/aws/operators/batch.py
+++ b/providers/amazon/src/airflow/providers/amazon/aws/operators/batch.py
@@ -214,20 +214,27 @@ class BatchOperator(AwsBaseOperator[BatchClientHook]):
"""
Submit and monitor an AWS Batch job.
- :raises: AirflowException
+ :raises ValueError: if job_id is not found
+ :raises AirflowException: if job submission fails or job ends in
failure state
"""
self.submit_job(context)
if self.deferrable:
if not self.job_id:
- raise AirflowException("AWS Batch job - job_id was not found")
+ raise ValueError("AWS Batch job - job_id was not found")
- job = self.hook.get_job_description(self.job_id)
+ # Persist operator links before deferring so they're available in
the UI
+ # Reuse job description to reduce API calls
+ job = self._persist_links(context)
job_status = job.get("status")
if job_status == self.hook.SUCCESS_STATE:
+ # Job already completed - persist CloudWatch logs
+ self._persist_cloudwatch_link(context)
self.log.info("Job completed.")
return self.job_id
if job_status == self.hook.FAILURE_STATE:
+ # Job already failed - persist CloudWatch logs
+ self._persist_cloudwatch_link(context)
raise AirflowException(f"Error while running job:
{self.job_id} is in {job_status} state")
if job_status in self.hook.INTERMEDIATE_STATES:
self.defer(
@@ -254,14 +261,36 @@ class BatchOperator(AwsBaseOperator[BatchClientHook]):
def execute_complete(self, context: Context, event: dict[str, Any] | None
= None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job:
{validated_event}")
-
+ # Set job_id first so CloudWatch link can be persisted even on failure
self.job_id = validated_event["job_id"]
# Fetch logs if awslogs_enabled
if self.awslogs_enabled:
- self.monitor_job(context) # fetch logs, no need to return
+ log_fetcher = self._get_batch_log_fetcher(self.job_id)
+ if log_fetcher:
+ self.log.info("Fetching logs for AWS Batch job: %s",
self.job_id)
+ try:
+ # Fetch up to 10,000 messages (CloudWatch limit)
+ log_messages = log_fetcher.get_last_log_messages(10000)
+ for message in log_messages:
+ self.log.info(message)
+ if log_messages:
+ self.log.info("Retrieved %d log messages from
CloudWatch", len(log_messages))
+ else:
+ self.log.info("No logs found in CloudWatch for job:
%s", self.job_id)
+ except Exception:
+ self.log.warning(
+ "Unable to retrieve CloudWatch logs for AWS Batch job:
%s", self.job_id, exc_info=True
+ )
+
+ # Persist CloudWatch logs for both success and failure
+ self._persist_cloudwatch_link(context)
+
+ if validated_event["status"] != "success":
+ raise AirflowException(f"Error while running job:
{validated_event}")
+
+ # Check job success (already know status is "success" from above)
+ self.hook.check_job_success(self.job_id)
self.log.info("Job completed successfully for job_id: %s", self.job_id)
return self.job_id
@@ -332,18 +361,25 @@ class BatchOperator(AwsBaseOperator[BatchClientHook]):
job_id=self.job_id,
)
- def monitor_job(self, context: Context):
+ def _persist_links(
+ self,
+ context: Context,
+ job_description: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
"""
- Monitor an AWS Batch job.
+ Persist job definition and queue links for UI display.
- This can raise an exception or an AirflowTaskTimeout if the task was
- created with ``execution_timeout``.
+ :param context: Task context
+ :param job_description: Optional pre-fetched job description to avoid
redundant API calls
+ :return: Job description dict
"""
if not self.job_id:
- raise AirflowException("AWS Batch job - job_id was not found")
+ raise ValueError("AWS Batch job - job_id was not found")
+
+ # Fetch job description (needed for return value and link persistence)
+ job_desc = job_description or
self.hook.get_job_description(job_id=self.job_id)
try:
- job_desc = self.hook.get_job_description(self.job_id)
job_definition_arn = job_desc["jobDefinition"]
job_queue_arn = job_desc["jobQueue"]
self.log.info(
@@ -370,33 +406,37 @@ class BatchOperator(AwsBaseOperator[BatchClientHook]):
job_queue_arn=job_queue_arn,
)
- if self.awslogs_enabled:
- if self.waiters:
- self.waiters.wait_for_job(self.job_id,
get_batch_log_fetcher=self._get_batch_log_fetcher)
- else:
- self.hook.wait_for_job(self.job_id,
get_batch_log_fetcher=self._get_batch_log_fetcher)
- else:
- if self.waiters:
- self.waiters.wait_for_job(self.job_id)
- else:
- self.hook.wait_for_job(self.job_id)
+ return job_desc
+
+ def _persist_cloudwatch_link(self, context: Context) -> None:
+ """
+ Persist CloudWatch logs link if available.
+
+ :param context: Task context
+ """
+ if not context or "ti" not in context:
+ return
+
+ if not self.do_xcom_push:
+ return
+
+ if not self.job_id:
+ return
- awslogs = []
try:
awslogs = self.hook.get_job_all_awslogs_info(self.job_id)
except AirflowException as ae:
- self.log.warning("Cannot determine where to find the AWS logs for
this Batch job: %s", ae)
+ self.log.warning(
+ "Unable to retrieve CloudWatch log information for AWS Batch
job (%s): %s",
+ self.job_id,
+ ae,
+ )
+ return
if awslogs:
- self.log.info("AWS Batch job (%s) CloudWatch Events details found.
Links to logs:", self.job_id)
- link_builder = CloudWatchEventsLink()
- for log in awslogs:
- self.log.info(link_builder.format_link(**log))
+ self.log.info("AWS Batch job (%s) CloudWatch Events details
found.", self.job_id)
if len(awslogs) > 1:
- # there can be several log streams on multi-node jobs
- self.log.warning(
- "out of all those logs, we can only link to one in the UI.
Using the first one."
- )
+ self.log.warning("Multiple log streams found. Linking to the
first one in the UI.")
CloudWatchEventsLink.persist(
context=context,
@@ -406,6 +446,33 @@ class BatchOperator(AwsBaseOperator[BatchClientHook]):
**awslogs[0],
)
+ def monitor_job(self, context: Context):
+ """
+ Monitor an AWS Batch job.
+
+ This can raise an exception or an AirflowTaskTimeout if the task was
+ created with ``execution_timeout``.
+ """
+ if not self.job_id:
+ raise ValueError("AWS Batch job - job_id was not found")
+
+ # Persist job definition and queue links
+ self._persist_links(context)
+
+ if self.awslogs_enabled:
+ if self.waiters:
+ self.waiters.wait_for_job(self.job_id,
get_batch_log_fetcher=self._get_batch_log_fetcher)
+ else:
+ self.hook.wait_for_job(self.job_id,
get_batch_log_fetcher=self._get_batch_log_fetcher)
+ else:
+ if self.waiters:
+ self.waiters.wait_for_job(self.job_id)
+ else:
+ self.hook.wait_for_job(self.job_id)
+
+ # After job completes, persist CloudWatch logs
+ self._persist_cloudwatch_link(context)
+
self.hook.check_job_success(self.job_id)
self.log.info("AWS Batch job (%s) succeeded", self.job_id)
diff --git a/providers/amazon/tests/unit/amazon/aws/operators/test_batch.py
b/providers/amazon/tests/unit/amazon/aws/operators/test_batch.py
index 996989e9bc2..0a30386329b 100644
--- a/providers/amazon/tests/unit/amazon/aws/operators/test_batch.py
+++ b/providers/amazon/tests/unit/amazon/aws/operators/test_batch.py
@@ -149,16 +149,22 @@ class TestBatchOperator:
def test_template_fields_overrides(self):
validate_template_fields(self.batch)
+ @mock.patch.object(BatchClientHook, "get_job_all_awslogs_info")
@mock.patch.object(BatchClientHook, "get_job_description")
@mock.patch.object(BatchClientHook, "wait_for_job")
@mock.patch.object(BatchClientHook, "check_job_success")
- def test_execute_without_failures(self, check_mock, wait_mock,
job_description_mock):
+ def test_execute_without_failures(
+ self, check_mock, wait_mock, job_description_mock,
get_job_all_awslogs_info_mock
+ ):
# JOB_ID is in RESPONSE_WITHOUT_FAILURES
self.client_mock.submit_job.return_value = RESPONSE_WITHOUT_FAILURES
self.batch.job_id = None
self.batch.waiters = None # use default wait
+ get_job_all_awslogs_info_mock.return_value = []
+ # Use a real dict so "ti" in context works correctly for link
persistence
+ context = {"ti": mock.MagicMock()}
- self.batch.execute(self.mock_context)
+ self.batch.execute(context)
self.client_mock.submit_job.assert_called_once_with(
jobQueue="queue",
@@ -175,9 +181,10 @@ class TestBatchOperator:
wait_mock.assert_called_once_with(JOB_ID)
check_mock.assert_called_once_with(JOB_ID)
- # First Call: Retrieve Batch Queue and Job Definition
- # Second Call: Retrieve CloudWatch information
- assert job_description_mock.call_count == 2
+ # get_job_description called once in _persist_links
+ assert job_description_mock.call_count == 1
+ # get_job_all_awslogs_info called once in _persist_cloudwatch_link
+ get_job_all_awslogs_info_mock.assert_called_once_with(JOB_ID)
def test_execute_with_failures(self):
self.client_mock.submit_job.side_effect = Exception()
@@ -463,7 +470,7 @@ class TestBatchOperator:
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.AwsBaseHook.get_client_type")
def test_defer_but_failed_due_to_job_id_not_found(self, mock_client):
- """Test that an AirflowException is raised if job_id is not set before
deferral."""
+ """Test that a ValueError is raised if job_id is not set before
deferral."""
mock_client.return_value.submit_job.return_value = {
"jobName": JOB_NAME,
"jobId": None,
@@ -477,9 +484,8 @@ class TestBatchOperator:
do_xcom_push=False,
deferrable=True,
)
- with pytest.raises(AirflowException) as exc:
+ with pytest.raises(ValueError, match="AWS Batch job - job_id was not
found"):
batch.execute(self.mock_context)
- assert "AWS Batch job - job_id was not found" in str(exc.value)
@mock.patch.object(BatchClientHook, "get_job_description")
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.AwsBaseHook.get_client_type")
@@ -545,10 +551,29 @@ class TestBatchOperator:
@patch.object(BatchOperator, "log", new_callable=MagicMock)
@patch("airflow.providers.amazon.aws.operators.batch.validate_execute_complete_event")
- @patch.object(BatchOperator, "monitor_job")
- def test_execute_complete_success_with_logs(self, mock_monitor_job,
mock_validate, mock_log):
+ @patch.object(BatchClientHook, "check_job_success")
+ @patch.object(BatchClientHook, "get_job_awslogs_info")
+ @patch.object(BatchClientHook, "get_job_all_awslogs_info")
+
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.AwsBaseHook.get_client_type")
+ def test_execute_complete_success_with_logs(
+ self,
+ mock_client,
+ mock_get_job_all_awslogs_info,
+ mock_get_job_awslogs_info,
+ mock_check_job_success,
+ mock_validate,
+ mock_log,
+ ):
# Setup
mock_validate.return_value = {"status": "success", "job_id": "12345"}
+ mock_get_job_awslogs_info.return_value = {
+ "awslogs_region": "us-east-1",
+ "awslogs_group": "/aws/batch/job",
+ "awslogs_stream_name": "stream1",
+ }
+ mock_get_job_all_awslogs_info.return_value = [
+ {"awslogs_group": "/aws/batch/job", "awslogs_stream_name":
"stream1"}
+ ]
batch = BatchOperator(
task_id="test_task",
job_name=JOB_NAME,
@@ -556,21 +581,47 @@ class TestBatchOperator:
job_definition="dummy_definition",
deferrable=True,
awslogs_enabled=True,
+ do_xcom_push=True, # Enable xcom push so _persist_cloudwatch_link
runs
)
+ # Add task instance to context
+ context = {"ti": mock.MagicMock()}
+
+ # Mock the log fetcher
+ with
patch("airflow.providers.amazon.aws.operators.batch.AwsTaskLogFetcher") as
mock_log_fetcher:
+ mock_fetcher_instance = mock.MagicMock()
+ mock_fetcher_instance.get_last_log_messages.return_value = ["log
line 1", "log line 2"]
+ mock_log_fetcher.return_value = mock_fetcher_instance
+
+ result = batch.execute_complete(context=context, event={"dummy":
"event"})
- result = batch.execute_complete(context={}, event={"dummy": "event"})
+ # Assertion - verify logs were fetched
+ mock_get_job_awslogs_info.assert_called_once_with("12345")
+ mock_log_fetcher.assert_called_once()
+
mock_fetcher_instance.get_last_log_messages.assert_called_once_with(10000)
- # Assertion
assert result == "12345"
- mock_monitor_job.assert_called_once_with({})
+ mock_get_job_all_awslogs_info.assert_called_once_with("12345")
+ mock_check_job_success.assert_called_once_with("12345")
mock_log.info.assert_called_with("Job completed successfully for
job_id: %s", "12345")
@patch.object(BatchOperator, "log", new_callable=MagicMock)
@patch("airflow.providers.amazon.aws.operators.batch.validate_execute_complete_event")
- @patch.object(BatchOperator, "monitor_job")
- def test_execute_complete_success_without_logs(self, mock_monitor_job,
mock_validate, mock_log):
+ @patch.object(BatchClientHook, "check_job_success")
+ @patch.object(BatchClientHook, "get_job_awslogs_info")
+ @patch.object(BatchClientHook, "get_job_all_awslogs_info")
+
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.AwsBaseHook.get_client_type")
+ def test_execute_complete_success_without_logs(
+ self,
+ mock_client,
+ mock_get_job_all_awslogs_info,
+ mock_get_job_awslogs_info,
+ mock_check_job_success,
+ mock_validate,
+ mock_log,
+ ):
# Setup
mock_validate.return_value = {"status": "success", "job_id": "12345"}
+ mock_get_job_all_awslogs_info.return_value = []
batch = BatchOperator(
task_id="test_task",
job_name=JOB_NAME,
@@ -578,19 +629,42 @@ class TestBatchOperator:
job_definition="dummy_definition",
deferrable=True,
awslogs_enabled=False,
+ do_xcom_push=True, # Enable xcom push so _persist_cloudwatch_link
runs
)
+ # Add task instance to context
+ context = {"ti": mock.MagicMock()}
- result = batch.execute_complete(context={}, event={"dummy": "event"})
+ # Mock the log fetcher to ensure it's not called
+ with
patch("airflow.providers.amazon.aws.operators.batch.AwsTaskLogFetcher") as
mock_log_fetcher:
+ result = batch.execute_complete(context=context, event={"dummy":
"event"})
+
+ # Verify logs were NOT fetched when awslogs_enabled=False
+ mock_get_job_awslogs_info.assert_not_called()
+ mock_log_fetcher.assert_not_called()
# Assertions
assert result == "12345"
- mock_monitor_job.assert_not_called()
+ mock_get_job_all_awslogs_info.assert_called_once_with("12345")
+ mock_check_job_success.assert_called_once_with("12345")
mock_log.info.assert_called_with("Job completed successfully for
job_id: %s", "12345")
@patch("airflow.providers.amazon.aws.operators.batch.validate_execute_complete_event")
- def test_execute_complete_failure(self, mock_validate):
+ @patch.object(BatchClientHook, "get_job_awslogs_info")
+ @patch.object(BatchClientHook, "get_job_all_awslogs_info")
+
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.AwsBaseHook.get_client_type")
+ def test_execute_complete_failure(
+ self, mock_client, mock_get_job_all_awslogs_info,
mock_get_job_awslogs_info, mock_validate
+ ):
# Setup
mock_validate.return_value = {"status": "failed", "job_id": "12345"}
+ mock_get_job_awslogs_info.return_value = {
+ "awslogs_region": "us-east-1",
+ "awslogs_group": "/aws/batch/job",
+ "awslogs_stream_name": "stream1",
+ }
+ mock_get_job_all_awslogs_info.return_value = [
+ {"awslogs_group": "/aws/batch/job", "awslogs_stream_name":
"stream1"}
+ ]
batch = BatchOperator(
task_id="test_task",
job_name=JOB_NAME,
@@ -600,9 +674,54 @@ class TestBatchOperator:
awslogs_enabled=True,
)
- # Assertions
- with pytest.raises(AirflowException, match="Error while running job"):
- batch.execute_complete(context={}, event={"dummy": "event"})
+ # Assertions - even on failure, logs should be fetched before raising
+ context = {"ti": mock.MagicMock()}
+ with
patch("airflow.providers.amazon.aws.operators.batch.AwsTaskLogFetcher") as
mock_log_fetcher:
+ mock_fetcher_instance = mock.MagicMock()
+ mock_fetcher_instance.get_last_log_messages.return_value = ["error
log 1", "error log 2"]
+ mock_log_fetcher.return_value = mock_fetcher_instance
+
+ with pytest.raises(AirflowException, match="Error while running
job"):
+ batch.execute_complete(context=context, event={"dummy":
"event"})
+
+ # Verify logs were fetched even on failure
+ mock_get_job_awslogs_info.assert_called_once_with("12345")
+
mock_fetcher_instance.get_last_log_messages.assert_called_once_with(10000)
+
+
@patch("airflow.providers.amazon.aws.operators.batch.validate_execute_complete_event")
+ @patch.object(BatchClientHook, "get_job_awslogs_info")
+ @patch.object(BatchClientHook, "get_job_all_awslogs_info")
+
@mock.patch("airflow.providers.amazon.aws.hooks.batch_client.AwsBaseHook.get_client_type")
+ def test_execute_complete_failure_without_logs(
+ self, mock_client, mock_get_job_all_awslogs_info,
mock_get_job_awslogs_info, mock_validate
+ ):
+ # Setup
+ mock_validate.return_value = {"status": "failed", "job_id": "12345"}
+ mock_get_job_all_awslogs_info.return_value = [
+ {"awslogs_group": "/aws/batch/job", "awslogs_stream_name":
"stream1"}
+ ]
+ batch = BatchOperator(
+ task_id="test_task",
+ job_name=JOB_NAME,
+ job_queue="dummy_queue",
+ job_definition="dummy_definition",
+ deferrable=True,
+ awslogs_enabled=False, # Logs disabled
+ do_xcom_push=True, # Enable xcom push so _persist_cloudwatch_link
runs
+ )
+
+ # Assertions - CloudWatch links should still be persisted even on
failure without logs
+ context = {"ti": mock.MagicMock()}
+ with
patch("airflow.providers.amazon.aws.operators.batch.AwsTaskLogFetcher") as
mock_log_fetcher:
+ with pytest.raises(AirflowException, match="Error while running
job"):
+ batch.execute_complete(context=context, event={"dummy":
"event"})
+
+ # Verify logs were NOT fetched when awslogs_enabled=False
+ mock_get_job_awslogs_info.assert_not_called()
+ mock_log_fetcher.assert_not_called()
+
+ # Verify CloudWatch links were still persisted despite failure
+ mock_get_job_all_awslogs_info.assert_called_once_with("12345")
class TestBatchCreateComputeEnvironmentOperator:
diff --git a/scripts/ci/prek/known_airflow_exceptions.txt
b/scripts/ci/prek/known_airflow_exceptions.txt
index fec615e061f..cf9bb1d8647 100644
--- a/scripts/ci/prek/known_airflow_exceptions.txt
+++ b/scripts/ci/prek/known_airflow_exceptions.txt
@@ -65,7 +65,7 @@
providers/amazon/src/airflow/providers/amazon/aws/hooks/sagemaker_unified_studio
providers/amazon/src/airflow/providers/amazon/aws/links/emr.py::2
providers/amazon/src/airflow/providers/amazon/aws/operators/appflow.py::3
providers/amazon/src/airflow/providers/amazon/aws/operators/athena.py::3
-providers/amazon/src/airflow/providers/amazon/aws/operators/batch.py::7
+providers/amazon/src/airflow/providers/amazon/aws/operators/batch.py::5
providers/amazon/src/airflow/providers/amazon/aws/operators/bedrock.py::6
providers/amazon/src/airflow/providers/amazon/aws/operators/comprehend.py::2
providers/amazon/src/airflow/providers/amazon/aws/operators/datasync.py::10